From ef8e709ecc35333ec5583bf845148efbce5805a4 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Fri, 20 Sep 2024 13:54:08 -0400 Subject: [PATCH 01/15] applied fixer for drect assignment from null --- .editorconfig | 3 + .../CSharp/CSharpDecompiler.cs | 16 ++--- ICSharpCode.Decompiler/CSharp/CallBuilder.cs | 54 ++++++++-------- .../CSharp/ExpressionBuilder.cs | 26 ++++---- .../CSharp/OutputVisitor/CSharpAmbience.cs | 2 +- .../OutputVisitor/CSharpOutputVisitor.cs | 16 ++--- .../InsertMissingTokensDecorator.cs | 10 +-- .../OutputVisitor/InsertParenthesesVisitor.cs | 10 +-- .../ProjectDecompiler/TargetServices.cs | 6 +- .../WholeProjectDecompiler.cs | 6 +- .../CSharp/RecordDecompiler.cs | 14 ++-- .../CSharp/RequiredNamespaceCollector.cs | 4 +- .../CSharp/Resolver/CSharpConversions.cs | 28 ++++---- .../Resolver/CSharpInvocationResolveResult.cs | 8 +-- .../CSharp/Resolver/CSharpResolver.cs | 64 +++++++++---------- .../DynamicInvocationResolveResult.cs | 2 +- .../CSharp/Resolver/MemberLookup.cs | 30 ++++----- .../Resolver/MethodGroupResolveResult.cs | 6 +- .../CSharp/Resolver/OverloadResolution.cs | 34 +++++----- .../CSharp/Resolver/TypeInference.cs | 48 +++++++------- .../CSharp/StatementBuilder.cs | 16 ++--- .../CSharp/Syntax/AstNodeCollection.cs | 6 +- .../CSharp/Syntax/AstType.cs | 6 +- .../CSharp/Syntax/CSharpModifierToken.cs | 2 +- .../CSharp/Syntax/CSharpTokenNode.cs | 2 +- .../CSharp/Syntax/ComposedType.cs | 6 +- .../CSharp/Syntax/DocumentationReference.cs | 2 +- .../Expressions/AnonymousMethodExpression.cs | 4 +- .../Expressions/ArrayCreateExpression.cs | 2 +- .../Expressions/ArrayInitializerExpression.cs | 2 +- .../CSharp/Syntax/Expressions/AsExpression.cs | 2 +- .../Expressions/AssignmentExpression.cs | 2 +- .../Expressions/BaseReferenceExpression.cs | 2 +- .../Expressions/BinaryOperatorExpression.cs | 2 +- .../Syntax/Expressions/CastExpression.cs | 2 +- .../Syntax/Expressions/CheckedExpression.cs | 2 +- .../Expressions/ConditionalExpression.cs | 2 +- .../Expressions/DefaultValueExpression.cs | 2 +- .../Syntax/Expressions/DirectionExpression.cs | 2 +- .../Expressions/IdentifierExpression.cs | 2 +- .../Syntax/Expressions/IndexerExpression.cs | 8 +-- .../InterpolatedStringExpression.cs | 8 +-- .../Expressions/InvocationExpression.cs | 2 +- .../CSharp/Syntax/Expressions/IsExpression.cs | 2 +- .../Syntax/Expressions/LambdaExpression.cs | 2 +- .../Expressions/MemberReferenceExpression.cs | 4 +- .../Expressions/NamedArgumentExpression.cs | 2 +- .../Expressions/NullReferenceExpression.cs | 2 +- .../Expressions/ObjectCreateExpression.cs | 4 +- .../Expressions/ParenthesizedExpression.cs | 2 +- .../Expressions/PointerReferenceExpression.cs | 2 +- .../Syntax/Expressions/PrimitiveExpression.cs | 2 +- .../Syntax/Expressions/QueryExpression.cs | 20 +++--- .../Syntax/Expressions/SizeOfExpression.cs | 2 +- .../Expressions/StackAllocExpression.cs | 2 +- .../Syntax/Expressions/SwitchExpression.cs | 4 +- .../Expressions/ThisReferenceExpression.cs | 2 +- .../Syntax/Expressions/ThrowExpression.cs | 2 +- .../Syntax/Expressions/TypeOfExpression.cs | 2 +- .../Expressions/TypeReferenceExpression.cs | 2 +- .../Expressions/UnaryOperatorExpression.cs | 2 +- .../Syntax/Expressions/UncheckedExpression.cs | 2 +- .../Expressions/UndocumentedExpression.cs | 2 +- .../CSharp/Syntax/FunctionPointerAstType.cs | 2 +- .../CSharp/Syntax/GeneralScope/Attribute.cs | 2 +- .../Syntax/GeneralScope/AttributeSection.cs | 2 +- .../CSharp/Syntax/GeneralScope/Comment.cs | 2 +- .../CSharp/Syntax/GeneralScope/Constraint.cs | 2 +- .../GeneralScope/DelegateDeclaration.cs | 2 +- .../GeneralScope/NamespaceDeclaration.cs | 4 +- .../GeneralScope/PreProcessorDirective.cs | 8 +-- .../Syntax/GeneralScope/TypeDeclaration.cs | 2 +- .../GeneralScope/TypeParameterDeclaration.cs | 2 +- .../GeneralScope/UsingAliasDeclaration.cs | 2 +- .../Syntax/GeneralScope/UsingDeclaration.cs | 2 +- .../CSharp/Syntax/IAnnotatable.cs | 18 +++--- .../CSharp/Syntax/Identifier.cs | 2 +- .../IdentifierExpressionBackreference.cs | 2 +- .../CSharp/Syntax/InvocationAstType.cs | 2 +- .../CSharp/Syntax/MemberType.cs | 8 +-- .../CSharp/Syntax/PatternMatching/AnyNode.cs | 2 +- .../Syntax/PatternMatching/AnyNodeOrNull.cs | 2 +- .../CSharp/Syntax/PrimitiveType.cs | 4 +- .../CSharp/Syntax/SimpleType.cs | 4 +- .../Syntax/Statements/BlockStatement.cs | 2 +- .../Syntax/Statements/BreakStatement.cs | 2 +- .../Syntax/Statements/CheckedStatement.cs | 2 +- .../Syntax/Statements/ContinueStatement.cs | 2 +- .../Syntax/Statements/DoWhileStatement.cs | 2 +- .../Syntax/Statements/EmptyStatement.cs | 2 +- .../Syntax/Statements/ExpressionStatement.cs | 2 +- .../Syntax/Statements/FixedStatement.cs | 2 +- .../CSharp/Syntax/Statements/ForStatement.cs | 2 +- .../Syntax/Statements/ForeachStatement.cs | 2 +- .../CSharp/Syntax/Statements/GotoStatement.cs | 6 +- .../Syntax/Statements/IfElseStatement.cs | 4 +- .../Syntax/Statements/LabelStatement.cs | 2 +- .../CSharp/Syntax/Statements/LockStatement.cs | 2 +- .../Syntax/Statements/ReturnStatement.cs | 2 +- .../Syntax/Statements/SwitchStatement.cs | 6 +- .../Syntax/Statements/ThrowStatement.cs | 2 +- .../Syntax/Statements/TryCatchStatement.cs | 4 +- .../Syntax/Statements/UncheckedStatement.cs | 2 +- .../Syntax/Statements/UnsafeStatement.cs | 2 +- .../Syntax/Statements/UsingStatement.cs | 2 +- .../VariableDeclarationStatement.cs | 4 +- .../Syntax/Statements/WhileStatement.cs | 2 +- .../Syntax/Statements/YieldBreakStatement.cs | 2 +- .../Syntax/Statements/YieldReturnStatement.cs | 2 +- .../CSharp/Syntax/SyntaxTree.cs | 4 +- .../CSharp/Syntax/TupleAstType.cs | 2 +- .../CSharp/Syntax/TypeMembers/Accessor.cs | 2 +- .../TypeMembers/ConstructorDeclaration.cs | 4 +- .../TypeMembers/DestructorDeclaration.cs | 2 +- .../TypeMembers/EnumMemberDeclaration.cs | 2 +- .../Syntax/TypeMembers/EventDeclaration.cs | 4 +- .../Syntax/TypeMembers/FieldDeclaration.cs | 2 +- .../TypeMembers/FixedVariableInitializer.cs | 2 +- .../Syntax/TypeMembers/IndexerDeclaration.cs | 2 +- .../Syntax/TypeMembers/MethodDeclaration.cs | 2 +- .../Syntax/TypeMembers/OperatorDeclaration.cs | 2 +- .../Syntax/TypeMembers/PropertyDeclaration.cs | 2 +- .../Syntax/TypeMembers/VariableInitializer.cs | 4 +- .../CSharp/Syntax/TypeSystemAstBuilder.cs | 26 ++++---- .../CSharp/Transforms/AddCheckedBlocks.cs | 16 ++--- .../Transforms/CombineQueryExpressions.cs | 12 ++-- .../CSharp/Transforms/CustomPatterns.cs | 6 +- .../CSharp/Transforms/DeclareVariables.cs | 4 +- .../Transforms/IntroduceExtensionMethods.cs | 8 +-- .../Transforms/IntroduceQueryExpressions.cs | 12 ++-- .../Transforms/IntroduceUnsafeModifier.cs | 2 +- .../Transforms/IntroduceUsingDeclarations.cs | 2 +- .../Transforms/PatternStatementTransform.cs | 16 ++--- .../CSharp/Transforms/PrettifyAssignments.cs | 8 +-- .../ReplaceMethodCallsWithOperators.cs | 2 +- ...ransformFieldAndConstructorInitializers.cs | 8 +-- .../CSharp/TranslatedExpression.cs | 2 +- .../TypeSystem/AliasNamespaceReference.cs | 2 +- .../TypeSystem/CSharpTypeResolveContext.cs | 2 +- .../MemberTypeOrNamespaceReference.cs | 4 +- .../SimpleTypeOrNamespaceReference.cs | 4 +- .../TypeSystem/TypeOrNamespaceReference.cs | 2 +- .../CSharp/TypeSystem/UsingScope.cs | 2 +- .../DebugInfo/PortablePdbWriter.cs | 4 +- ICSharpCode.Decompiler/DecompilerException.cs | 4 +- ICSharpCode.Decompiler/DecompilerSettings.cs | 2 +- .../Disassembler/DisassemblerHelpers.cs | 4 +- .../Disassembler/MethodBodyDisassembler.cs | 2 +- .../Disassembler/ReflectionDisassembler.cs | 12 ++-- .../Documentation/IdStringProvider.cs | 6 +- .../Documentation/XmlDocumentationProvider.cs | 2 +- .../FlowAnalysis/Dominance.cs | 2 +- .../ICSharpCode.Decompiler.csproj | 1 + .../IL/ControlFlow/AsyncAwaitDecompiler.cs | 18 +++--- .../IL/ControlFlow/AwaitInCatchTransform.cs | 18 +++--- .../IL/ControlFlow/ConditionDetection.cs | 4 +- .../ControlFlow/ControlFlowSimplification.cs | 2 +- .../IL/ControlFlow/DetectPinnedRegions.cs | 20 +++--- .../IL/ControlFlow/LoopDetection.cs | 8 +-- .../IL/ControlFlow/SwitchDetection.cs | 2 +- .../IL/ControlFlow/YieldReturnDecompiler.cs | 6 +- .../IL/Instructions/DeconstructInstruction.cs | 4 +- .../IL/Transforms/AssignVariableNames.cs | 6 +- .../CachedDelegateInitialization.cs | 8 +-- .../IL/Transforms/CopyPropagation.cs | 2 +- .../IL/Transforms/DeconstructionTransform.cs | 12 ++-- .../IL/Transforms/DelegateConstruction.cs | 6 +- .../DetectCatchWhenConditionBlocks.cs | 4 +- .../IL/Transforms/DynamicCallSiteTransform.cs | 4 +- .../DynamicIsEventAssignmentTransform.cs | 4 +- .../Transforms/EarlyExpressionTransforms.cs | 2 +- .../IL/Transforms/ExpressionTransforms.cs | 16 ++--- .../IL/Transforms/HighLevelLoopTransform.cs | 8 +-- .../IL/Transforms/ILInlining.cs | 6 +- .../IL/Transforms/IndexRangeTransform.cs | 8 +-- .../Transforms/InterpolatedStringTransform.cs | 2 +- .../IL/Transforms/LocalFunctionDecompiler.cs | 6 +- .../IL/Transforms/LockTransform.cs | 6 +- .../IL/Transforms/NullPropagationTransform.cs | 10 +-- .../IL/Transforms/NullableLiftingTransform.cs | 16 ++--- .../IL/Transforms/ProxyCallReplacer.cs | 2 +- .../IL/Transforms/ReduceNestingTransform.cs | 2 +- .../IL/Transforms/RemoveDeadVariableInit.cs | 2 +- .../Transforms/SwitchOnNullableTransform.cs | 4 +- .../IL/Transforms/SwitchOnStringTransform.cs | 44 ++++++------- .../Transforms/TransformArrayInitializers.cs | 22 +++---- .../IL/Transforms/TransformAssignment.cs | 18 +++--- .../Transforms/TransformDisplayClassUsage.cs | 18 +++--- .../IL/Transforms/TransformExpressionTrees.cs | 34 +++++----- .../IL/Transforms/TupleTransform.cs | 2 +- .../Transforms/UserDefinedLogicTransform.cs | 4 +- .../IL/Transforms/UsingTransform.cs | 4 +- .../Metadata/DotNetCorePathFinder.cs | 4 +- .../DotNetCorePathFinderExtensions.cs | 2 +- .../Metadata/MetadataExtensions.cs | 4 +- ICSharpCode.Decompiler/SRMExtensions.cs | 2 +- .../Semantics/Conversion.cs | 8 +-- .../Semantics/InvocationResolveResult.cs | 6 +- .../Semantics/LocalResolveResult.cs | 2 +- .../Semantics/MemberResolveResult.cs | 16 ++--- .../Semantics/NamedArgumentResolveResult.cs | 2 +- .../Semantics/ResolveResult.cs | 2 +- .../Semantics/TupleResolveResult.cs | 2 +- .../TypeSystem/ApplyAttributeTypeVisitor.cs | 10 +-- .../TypeSystem/ArrayType.cs | 16 ++--- .../TypeSystem/ByReferenceType.cs | 4 +- .../TypeSystem/FunctionPointerType.cs | 2 +- .../Implementation/AbstractFreezable.cs | 2 +- .../TypeSystem/Implementation/AbstractType.cs | 20 +++--- .../Implementation/AbstractTypeParameter.cs | 46 ++++++------- .../DefaultAssemblyReference.cs | 2 +- .../Implementation/DefaultParameter.cs | 4 +- .../Implementation/DefaultTypeParameter.cs | 14 ++-- .../Implementation/DefaultVariable.cs | 2 +- .../Implementation/GetClassTypeReference.cs | 6 +- .../Implementation/GetMembersHelper.cs | 22 +++---- .../Implementation/MergedNamespace.cs | 4 +- .../Implementation/MetadataMethod.cs | 2 +- .../Implementation/MetadataTypeDefinition.cs | 22 +++---- .../Implementation/NestedTypeReference.cs | 4 +- .../Implementation/SpecializedMember.cs | 6 +- .../Implementation/SpecializedMethod.cs | 6 +- .../Implementation/TypeParameterReference.cs | 2 +- .../TypeSystem/Implementation/UnknownType.cs | 2 +- .../TypeSystem/InheritanceHelper.cs | 4 +- .../TypeSystem/IntersectionType.cs | 2 +- .../TypeSystem/MetadataModule.cs | 8 +-- .../TypeSystem/ModifiedType.cs | 20 +++--- .../TypeSystem/NullableType.cs | 4 +- .../TypeSystem/ParameterListComparer.cs | 12 ++-- .../TypeSystem/ParameterizedType.cs | 32 +++++----- .../TypeSystem/PointerType.cs | 4 +- .../TypeSystem/ReflectionHelper.cs | 6 +- ICSharpCode.Decompiler/TypeSystem/TaskType.cs | 2 +- .../TypeSystem/TupleType.cs | 26 ++++---- .../TypeSystem/TypeParameterSubstitution.cs | 20 +++--- .../TypeSystem/TypeSystemExtensions.cs | 6 +- .../TypeSystem/VarArgInstanceMethod.cs | 4 +- ILSpy/ILSpy.csproj | 1 + ILSpy/TreeNodes/DerivedTypesTreeNode.cs | 3 +- 240 files changed, 833 insertions(+), 825 deletions(-) diff --git a/.editorconfig b/.editorconfig index 1ea262ade4..3de3e13f37 100644 --- a/.editorconfig +++ b/.editorconfig @@ -147,3 +147,6 @@ dotnet_naming_rule.private_fields_rule.symbols = private_fields_symbols # MEF006: No importing constructor dotnet_diagnostic.MEF006.severity = silent + + +dotnet_diagnostic.IDE2003.severity = silent \ No newline at end of file diff --git a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs index 5206197874..20cecc2ce3 100644 --- a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs @@ -406,7 +406,7 @@ static bool IsSwitchOnStringCache(SRM.FieldDefinition field, MetadataReader meta static readonly Regex automaticPropertyBackingFieldRegex = new Regex(@"^<(.*)>k__BackingField$", RegexOptions.Compiled | RegexOptions.CultureInvariant); - static bool IsAutomaticPropertyBackingField(FieldDefinition field, MetadataReader metadata, out string propertyName) + static bool IsAutomaticPropertyBackingField(FieldDefinition field, MetadataReader metadata, out string? propertyName) { propertyName = null; var name = metadata.GetString(field.Name); @@ -631,8 +631,8 @@ void DoDecompileModuleAndAssemblyAttributes(DecompileRun decompileRun, ITypeReso void DoDecompileTypes(IEnumerable types, DecompileRun decompileRun, ITypeResolveContext decompilationContext, SyntaxTree syntaxTree) { - string currentNamespace = null; - AstNode groupNode = null; + string? currentNamespace = null; + AstNode? groupNode = null; foreach (var typeDefHandle in types) { var typeDef = module.GetDefinition(typeDefHandle); @@ -1027,7 +1027,7 @@ public SyntaxTree Decompile(IEnumerable definitions) } bool first = true; - ITypeDefinition parentTypeDef = null; + ITypeDefinition? parentTypeDef = null; foreach (var entity in definitions) { @@ -1315,7 +1315,7 @@ EntityDeclaration DoDecompile(ITypeDefinition typeDef, DecompileRun decompileRun TypeKind.Struct => (settings.RecordStructs && typeDef.IsRecord) || settings.UsePrimaryConstructorSyntaxForNonRecordTypes, _ => false, }; - RecordDecompiler recordDecompiler = isRecordLike ? new RecordDecompiler(typeSystem, typeDef, settings, CancellationToken) : null; + RecordDecompiler? recordDecompiler = isRecordLike ? new RecordDecompiler(typeSystem, typeDef, settings, CancellationToken) : null; if (recordDecompiler != null) decompileRun.RecordDecompilers.Add(typeDef, recordDecompiler); @@ -1779,7 +1779,7 @@ void DecompileBody(IMethod method, EntityDeclaration entityDecl, DecompileRun de ); body = statementBuilder.ConvertAsBlock(function.Body); - Comment prev = null; + Comment? prev = null; foreach (string warning in function.Warnings) { body.InsertChildAfter(prev, prev = new Comment(warning), Roles.Comment); @@ -1916,7 +1916,7 @@ internal static bool RemoveObsoleteAttribute(EntityDeclaration entityDecl, strin return found; } - bool FindAttribute(EntityDeclaration entityDecl, KnownAttribute attributeType, out Syntax.Attribute attribute) + bool FindAttribute(EntityDeclaration entityDecl, KnownAttribute attributeType, out Syntax.Attribute? attribute) { attribute = null; foreach (var section in entityDecl.Attributes) @@ -2016,7 +2016,7 @@ EntityDeclaration DoDecompile(IField field, DecompileRun decompileRun, ITypeReso } } - internal static bool IsFixedField(IField field, out IType type, out int elementCount) + internal static bool IsFixedField(IField field, out IType? type, out int elementCount) { type = null; elementCount = 0; diff --git a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs index 56f420e076..c2dd6a7135 100644 --- a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs @@ -20,6 +20,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; @@ -47,7 +48,7 @@ struct ArgumentList public TranslatedExpression[] Arguments; public IParameter[] ExpectedParameters; public string[] ParameterNames; - public string[] ArgumentNames; + public string[]? ArgumentNames; public int FirstOptionalArgumentIndex; public BitSet IsPrimitiveValue; public IReadOnlyList ArgumentToParameterMap; @@ -146,7 +147,7 @@ public bool CanInferAnonymousTypePropertyNamesFromArguments() { for (int i = 0; i < Arguments.Length; i++) { - string inferredName; + string? inferredName; switch (Arguments[i].Expression) { case IdentifierExpression identifier: @@ -188,13 +189,13 @@ public CallBuilder(ExpressionBuilder expressionBuilder, IDecompilerTypeSystem ty this.typeSystem = typeSystem; } - public TranslatedExpression Build(CallInstruction inst, IType typeHint = null) + public TranslatedExpression Build(CallInstruction inst, IType? typeHint = null) { if (inst is NewObj newobj && IL.Transforms.DelegateConstruction.MatchDelegateConstruction(newobj, out _, out _, out _)) { return HandleDelegateConstruction(newobj); } - if (settings.TupleTypes && TupleTransform.MatchTupleConstruction(inst as NewObj, out var tupleElements) && tupleElements.Length >= 2) + if (settings.TupleTypes && TupleTransform.MatchTupleConstruction(inst as NewObj, out var tupleElements) && tupleElements?.Length >= 2) { var elementTypes = TupleType.GetTupleElementTypes(inst.Method.DeclaringType); var elementNames = typeHint is TupleType tt ? tt.ElementNames : default; @@ -247,7 +248,8 @@ private ExpressionWithResolveResult BuildStringConcat(IMethod method, List<(ILIn return result; } - static bool IsSpanBasedStringConcat(CallInstruction call, out List<(ILInstruction, KnownTypeCode)> operands) + + static bool IsSpanBasedStringConcat(CallInstruction call, [NotNullWhen(true)] out List<(ILInstruction, KnownTypeCode)>? operands) { operands = null; @@ -313,8 +315,8 @@ internal static bool IsStringToReadOnlySpanCharImplicitConversion(IMethod method public ExpressionWithResolveResult Build(OpCode callOpCode, IMethod method, IReadOnlyList callArguments, - IReadOnlyList argumentToParameterMap = null, - IType constrainedTo = null) + IReadOnlyList? argumentToParameterMap = null, + IType? constrainedTo = null) { if (method.IsExplicitInterfaceImplementation && callOpCode == OpCode.Call) { @@ -332,7 +334,7 @@ public ExpressionWithResolveResult Build(OpCode callOpCode, IMethod method, var expectedTargetDetails = new ExpectedTargetDetails { CallOpCode = callOpCode }; - ILFunction localFunction = null; + ILFunction? localFunction = null; if (method.IsLocalFunction) { localFunction = expressionBuilder.ResolveLocalFunction(method); @@ -523,7 +525,7 @@ public ExpressionWithResolveResult Build(OpCode callOpCode, IMethod method, private ExpressionWithResolveResult HandleStringInterpolation(IMethod method, ArgumentList argumentList) { - if (!TryGetStringInterpolationTokens(argumentList, out string format, out var tokens)) + if (!TryGetStringInterpolationTokens(argumentList, out string? format, out var tokens)) return default; var arguments = argumentList.Arguments; @@ -543,7 +545,7 @@ void UnpackSingleElementArray(ref TranslatedExpression argument) argument = new TranslatedExpression(element, arrayCreationRR.InitializerElements.First()); } - if (tokens.Count == 0) + if (tokens == null || tokens.Count == 0) { return default; } @@ -655,7 +657,7 @@ public ExpressionWithResolveResult BuildCollectionInitializerExpression(OpCode c } public ExpressionWithResolveResult BuildDictionaryInitializerExpression(OpCode callOpCode, IMethod method, - InitializedObjectResolveResult target, IReadOnlyList indices, ILInstruction value = null) + InitializedObjectResolveResult target, IReadOnlyList indices, ILInstruction? value = null) { if (method is null) throw new ArgumentNullException(nameof(method)); @@ -696,7 +698,7 @@ private static bool IsInterpolatedStringCreation(IMethod method, ArgumentList ar ); } - private bool TryGetStringInterpolationTokens(ArgumentList argumentList, out string format, out List<(TokenKind Kind, int Index, int Alignment, string Format)> tokens) + private bool TryGetStringInterpolationTokens(ArgumentList argumentList, out string? format, out List<(TokenKind Kind, int Index, int Alignment, string? Format)>? tokens) { tokens = null; format = null; @@ -707,7 +709,7 @@ private bool TryGetStringInterpolationTokens(ArgumentList argumentList, out stri return false; if (!arguments.Skip(1).All(a => !a.Expression.DescendantsAndSelf.OfType().Any(p => p.Value is string))) return false; - tokens = new List<(TokenKind Kind, int Index, int Alignment, string Format)>(); + tokens = new List<(TokenKind Kind, int Index, int Alignment, string? Format)>(); int i = 0; format = (string)crr.ConstantValue; foreach (var (kind, data) in TokenizeFormatString(format)) @@ -867,14 +869,14 @@ int Next() } } - private ArgumentList BuildArgumentList(ExpectedTargetDetails expectedTargetDetails, ResolveResult target, IMethod method, - int firstParamIndex, IReadOnlyList callArguments, IReadOnlyList argumentToParameterMap) + private ArgumentList BuildArgumentList(ExpectedTargetDetails expectedTargetDetails, ResolveResult? target, IMethod method, + int firstParamIndex, IReadOnlyList callArguments, IReadOnlyList? argumentToParameterMap) { ArgumentList list = new ArgumentList(); // Translate arguments to the expected parameter types var arguments = new List(method.Parameters.Count); - string[] argumentNames = null; + string[]? argumentNames = null; Debug.Assert(callArguments.Count == firstParamIndex + method.Parameters.Count); var expectedParameters = new List(method.Parameters.Count); // parameters, but in argument order bool isExpandedForm = false; @@ -978,11 +980,11 @@ private bool IsPrimitiveValueThatShouldBeNamedArgument(TranslatedExpression arg, return p.Type.IsKnownType(KnownTypeCode.Boolean); } - private bool TransformParamsArgument(ExpectedTargetDetails expectedTargetDetails, ResolveResult targetResolveResult, + private bool TransformParamsArgument(ExpectedTargetDetails expectedTargetDetails, ResolveResult? targetResolveResult, IMethod method, IParameter parameter, TranslatedExpression arg, ref List expectedParameters, ref List arguments) { - if (CheckArgument(out int length, out IType elementType)) + if (CheckArgument(out int length, out IType? elementType)) { var expandedParameters = new List(expectedParameters); var expandedArguments = new List(arguments); @@ -1010,7 +1012,7 @@ private bool TransformParamsArgument(ExpectedTargetDetails expectedTargetDetails } return false; - bool CheckArgument(out int len, out IType t) + bool CheckArgument(out int len, [NotNullWhen(true)] out IType? t) { len = 0; t = null; @@ -1069,7 +1071,7 @@ private CallTransformation GetRequiredTransformationsForCall(ExpectedTargetDetai // initialize requireTarget flag bool requireTarget; - ResolveResult targetResolveResult; + ResolveResult? targetResolveResult; if ((allowedTransforms & CallTransformation.RequireTarget) != 0) { if (settings.AlwaysQualifyMemberReferences || expressionBuilder.HidesVariableWithName(method.Name)) @@ -1394,8 +1396,8 @@ private ExpressionWithResolveResult HandleImplicitConversion(IMethod method, Tra OverloadResolutionErrors IsUnambiguousCall(ExpectedTargetDetails expectedTargetDetails, IMethod method, ResolveResult target, IType[] typeArguments, ResolveResult[] arguments, - string[] argumentNames, int firstOptionalArgumentIndex, - out IParameterizedMember foundMember, out bool bestCandidateIsExpandedForm) + string[]? argumentNames, int firstOptionalArgumentIndex, + out IParameterizedMember? foundMember, out bool bestCandidateIsExpandedForm) { foundMember = null; bestCandidateIsExpandedForm = false; @@ -1504,7 +1506,7 @@ OverloadResolutionErrors IsUnambiguousCall(ExpectedTargetDetails expectedTargetD } bool IsUnambiguousAccess(ExpectedTargetDetails expectedTargetDetails, ResolveResult target, IMethod method, - IList arguments, string[] argumentNames, out IMember foundMember) + IList arguments, string[] argumentNames, out IMember? foundMember) { Log.WriteLine("IsUnambiguousAccess: Performing overload resolution for " + method); Log.WriteCollection(" Arguments: ", arguments.Select(a => a.ResolveResult)); @@ -1551,7 +1553,7 @@ bool IsUnambiguousAccess(ExpectedTargetDetails expectedTargetDetails, ResolveRes } ExpressionWithResolveResult HandleAccessorCall(ExpectedTargetDetails expectedTargetDetails, IMethod method, - TranslatedExpression target, List arguments, string[] argumentNames) + TranslatedExpression target, List arguments, string[]? argumentNames) { bool requireTarget; if (settings.AlwaysQualifyMemberReferences || method.AccessorOwner.SymbolKind == SymbolKind.Indexer || expressionBuilder.HidesVariableWithName(method.AccessorOwner.Name)) @@ -1715,7 +1717,7 @@ ExpressionWithResolveResult HandleConstructorCall(ExpectedTargetDetails expected CastArguments(argumentList.Arguments, argumentList.ExpectedParameters); break; // make sure that we don't not end up in an infinite loop } - IType returnTypeOverride = null; + IType? returnTypeOverride = null; if (typeSystem.MainModule.TypeSystemOptions.HasFlag(TypeSystemOptions.NativeIntegersWithoutAttribute)) { // For DeclaringType, we don't use nint/nuint (so that DeclaringType.GetConstructors etc. works), @@ -1932,7 +1934,7 @@ ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod invok bool targetCasted = false; bool addTypeArguments = false; // Initial inputs for IsUnambiguousMethodReference: - ResolveResult targetResolveResult = targetAdded ? target.ResolveResult : null; + ResolveResult? targetResolveResult = targetAdded ? target.ResolveResult : null; IReadOnlyList typeArguments = EmptyList.Instance; // Find somewhat minimal solution: ResolveResult result; diff --git a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs index 0f629f38e0..41fb3870e4 100644 --- a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs @@ -153,7 +153,7 @@ public ExpressionWithResolveResult ConvertConstantValue(ResolveResult rr, } } - public TranslatedExpression Translate(ILInstruction inst, IType typeHint = null) + public TranslatedExpression Translate(ILInstruction inst, IType? typeHint = null) { Debug.Assert(inst != null); cancellationToken.ThrowIfCancellationRequested(); @@ -289,7 +289,7 @@ bool RequiresQualifier(IMember member, TranslatedExpression target) return !(target.Expression is ThisReferenceExpression || target.Expression is BaseReferenceExpression); } - ExpressionWithResolveResult ConvertField(IField field, ILInstruction targetInstruction = null) + ExpressionWithResolveResult ConvertField(IField field, ILInstruction? targetInstruction = null) { var target = TranslateTarget(targetInstruction, nonVirtualInvocation: true, @@ -328,7 +328,7 @@ bool IsAmbiguousAccess(out MemberResolveResult result) return result == null || result.IsError || !result.Member.Equals(field, NormalizeTypeVisitor.TypeErasure); } - MemberResolveResult mrr; + MemberResolveResult? mrr; while (IsAmbiguousAccess(out mrr)) { if (!requireTarget) @@ -486,7 +486,7 @@ StackAllocExpression TranslateLocAllocSpan(LocAllocSpan inst, IType typeHint, ou StackAllocExpression TranslateLocAlloc(LocAlloc inst, IType typeHint, out IType elementType) { TranslatedExpression countExpression; - PointerType pointerType; + PointerType? pointerType; if (inst.Argument.MatchBinaryNumericInstruction(BinaryNumericOperator.Mul, out var left, out var right) && right.UnwrapConv(ConversionKind.SignExtend).UnwrapConv(ConversionKind.ZeroExtend).MatchSizeOf(out elementType)) { @@ -638,7 +638,7 @@ internal ExpressionWithResolveResult GetDefaultValueExpression(IType type) { Expression expr; IType constantType; - object constantValue; + object? constantValue; if (type.IsReferenceType == true || type.IsKnownType(KnownTypeCode.NullableOfT)) { expr = new NullReferenceExpression(); @@ -960,7 +960,7 @@ TranslatedExpression TranslateCeq(Comp inst, out bool negateOutput) .WithILInstruction(inst); } - OperatorResolveResult rr = resolver.ResolveBinaryOperator(inst.Kind.ToBinaryOperatorType(), left.ResolveResult, right.ResolveResult) as OperatorResolveResult; + OperatorResolveResult? rr = resolver.ResolveBinaryOperator(inst.Kind.ToBinaryOperatorType(), left.ResolveResult, right.ResolveResult) as OperatorResolveResult; if (rr == null || rr.IsError || rr.UserDefinedOperatorMethod != null || NullableType.GetUnderlyingType(rr.Operands[0].Type).GetStackType() != inst.InputType || !rr.Type.IsKnownType(KnownTypeCode.Boolean)) @@ -1387,7 +1387,7 @@ ByReferenceType GetReferenceType(IType type) } } - internal TranslatedExpression CallUnsafeIntrinsic(string name, Expression[] arguments, IType returnType, ILInstruction inst = null, IEnumerable typeArguments = null) + internal TranslatedExpression CallUnsafeIntrinsic(string name, Expression[] arguments, IType returnType, ILInstruction? inst = null, IEnumerable? typeArguments = null) { var target = new MemberReferenceExpression { Target = new TypeReferenceExpression(astBuilder.ConvertType(compilation.FindType(KnownTypeCode.Unsafe))), @@ -1458,7 +1458,7 @@ TranslatedExpression EnsureIntegerType(TranslatedExpression expr) if (sub.CheckForOverflow) return null; // First, attempt to parse the 'sizeof' on the RHS - IType elementType; + IType? elementType; if (inst.Right.MatchLdcI(out long elementSize)) { elementType = null; @@ -2397,7 +2397,7 @@ internal ExpressionWithResolveResult TranslateFunction(IType delegateType, ILFun ); var body = builder.ConvertAsBlock(function.Body); - Comment prev = null; + Comment? prev = null; foreach (string warning in function.Warnings) { body.InsertChildAfter(prev, prev = new Comment(warning), Roles.Comment); @@ -2612,7 +2612,7 @@ protected internal override TranslatedExpression VisitBlockContainer(BlockContai } } - internal TranslatedExpression TranslateTarget(ILInstruction target, bool nonVirtualInvocation, + internal TranslatedExpression TranslateTarget(ILInstruction? target, bool nonVirtualInvocation, bool memberStatic, IType memberDeclaringType) { // If references are missing member.IsStatic might not be set correctly. @@ -3393,7 +3393,7 @@ private ArrayInitializerExpression BuildArrayInitializerExpression(Block block, var elementsStack = new Stack>(); var elements = new List(block.Instructions.Count); elementsStack.Push(elements); - List currentPath = null; + List? currentPath = null; var indexVariables = new Dictionary(); foreach (var inst in block.Instructions.Skip(1)) { @@ -3602,7 +3602,7 @@ TranslatedExpression TranslateArrayInitializer(Block block) } } ArraySpecifier[] additionalSpecifiers; - AstType typeExpression; + AstType? typeExpression; if (settings.AnonymousTypes && type.ContainsAnonymousType()) { typeExpression = null; @@ -4023,7 +4023,7 @@ bool CanIgnoreCopy() protected internal override TranslatedExpression VisitAwait(Await inst, TranslationContext context) { - IType expectedType = null; + IType? expectedType = null; if (inst.GetAwaiterMethod != null) { if (inst.GetAwaiterMethod.IsStatic) diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs index beac7989c8..97e92e15b1 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs @@ -58,7 +58,7 @@ public void ConvertSymbol(ISymbol symbol, TokenWriter writer, CSharpFormattingOp TypeSystemAstBuilder astBuilder = CreateAstBuilder(); AstNode node = astBuilder.ConvertSymbol(symbol); writer.StartNode(node); - EntityDeclaration entityDecl = node as EntityDeclaration; + EntityDeclaration? entityDecl = node as EntityDeclaration; if (entityDecl != null) PrintModifiers(entityDecl.Modifiers, writer); diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs index 96d591dab6..2ed3cec002 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs @@ -200,7 +200,7 @@ protected virtual void WriteKeyword(TokenRole tokenRole) WriteKeyword(tokenRole.Token, tokenRole); } - protected virtual void WriteKeyword(string token, Role tokenRole = null) + protected virtual void WriteKeyword(string token, Role? tokenRole = null) { writer.WriteKeyword(tokenRole, token); isAtStartOfLine = false; @@ -529,7 +529,7 @@ protected virtual void WriteEmbeddedStatement(Statement embeddedStatement, NewLi NewLine(); return; } - BlockStatement block = embeddedStatement as BlockStatement; + BlockStatement? block = embeddedStatement as BlockStatement; if (block != null) { WriteBlock(block, policy.StatementBraceStyle); @@ -672,7 +672,7 @@ protected bool CanBeConfusedWithObjectInitializer(Expression expr) { // "int a; new List { a = 1 };" is an object initalizers and invalid, but // "int a; new List { { a = 1 } };" is a valid collection initializer. - AssignmentExpression ae = expr as AssignmentExpression; + AssignmentExpression? ae = expr as AssignmentExpression; return ae != null && ae.Operator == AssignmentOperatorType.Assign; } @@ -703,7 +703,7 @@ protected virtual void PrintInitializerElements(AstNodeCollection el OpenBrace(wrap ? policy.ArrayInitializerBraceStyle : BraceStyle.EndOfLine, newLine: wrap); if (!wrap) Space(); - AstNode last = null; + AstNode? last = null; foreach (var (idx, node) in elements.WithIndex()) { if (idx > 0) @@ -1658,7 +1658,7 @@ public virtual void VisitTypeDeclaration(TypeDeclaration typeDeclaration) if (typeDeclaration.ClassType == ClassType.Enum) { bool first = true; - AstNode last = null; + AstNode? last = null; foreach (var member in typeDeclaration.Members) { if (first) @@ -2340,7 +2340,7 @@ public virtual void VisitConstructorDeclaration(ConstructorDeclaration construct StartNode(constructorDeclaration); WriteAttributes(constructorDeclaration.Attributes); WriteModifiers(constructorDeclaration.ModifierTokens); - TypeDeclaration type = constructorDeclaration.Parent as TypeDeclaration; + TypeDeclaration? type = constructorDeclaration.Parent as TypeDeclaration; if (type != null && type.Name != constructorDeclaration.Name) WriteIdentifier((Identifier)type.NameToken.Clone()); else @@ -2386,7 +2386,7 @@ public virtual void VisitDestructorDeclaration(DestructorDeclaration destructorD Space(); } WriteToken(DestructorDeclaration.TildeRole); - TypeDeclaration type = destructorDeclaration.Parent as TypeDeclaration; + TypeDeclaration? type = destructorDeclaration.Parent as TypeDeclaration; if (type != null && type.Name != destructorDeclaration.Name) WriteIdentifier((Identifier)type.NameToken.Clone()); else @@ -2949,7 +2949,7 @@ public virtual void VisitConstraint(Constraint constraint) public virtual void VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode) { - CSharpModifierToken mod = cSharpTokenNode as CSharpModifierToken; + CSharpModifierToken? mod = cSharpTokenNode as CSharpModifierToken; if (mod != null) { // ITokenWriter assumes that each node processed between a diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs index 8b637218da..d115f75727 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs @@ -105,20 +105,20 @@ public override void WriteToken(Role role, string token) public override void WriteKeyword(Role role, string keyword) { TextLocation start = locationProvider.Location; - CSharpTokenNode t = null; + CSharpTokenNode? t = null; if (role is TokenRole) t = new CSharpTokenNode(start, (TokenRole)role); else if (role == EntityDeclaration.ModifierRole) t = new CSharpModifierToken(start, CSharpModifierToken.GetModifierValue(keyword)); else if (keyword == "this") { - ThisReferenceExpression node = nodes.Peek().LastOrDefault() as ThisReferenceExpression; + ThisReferenceExpression? node = nodes.Peek().LastOrDefault() as ThisReferenceExpression; if (node != null) node.Location = start; } else if (keyword == "base") { - BaseReferenceExpression node = nodes.Peek().LastOrDefault() as BaseReferenceExpression; + BaseReferenceExpression? node = nodes.Peek().LastOrDefault() as BaseReferenceExpression; if (node != null) node.Location = start; } @@ -140,7 +140,7 @@ public override void WriteIdentifier(Identifier identifier) public override void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None) { - Expression node = nodes.Peek().LastOrDefault() as Expression; + Expression? node = nodes.Peek().LastOrDefault() as Expression; var startLocation = locationProvider.Location; base.WritePrimitiveValue(value, format); if (node is PrimitiveExpression) @@ -155,7 +155,7 @@ public override void WritePrimitiveValue(object value, LiteralFormat format = Li public override void WritePrimitiveType(string type) { - PrimitiveType node = nodes.Peek().LastOrDefault() as PrimitiveType; + PrimitiveType? node = nodes.Peek().LastOrDefault() as PrimitiveType; if (node != null) node.SetStartLocation(locationProvider.Location); base.WritePrimitiveType(type); diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertParenthesesVisitor.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertParenthesesVisitor.cs index 2fb3a45460..e99715fec5 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertParenthesesVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertParenthesesVisitor.cs @@ -218,7 +218,7 @@ public override void VisitIndexerExpression(IndexerExpression indexerExpression) public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression) { ParenthesizeIfRequired(unaryOperatorExpression.Expression, GetPrecedence(unaryOperatorExpression)); - UnaryOperatorExpression child = unaryOperatorExpression.Expression as UnaryOperatorExpression; + UnaryOperatorExpression? child = unaryOperatorExpression.Expression as UnaryOperatorExpression; if (child != null && InsertParenthesesForReadability) Parenthesize(child); base.VisitUnaryOperatorExpression(unaryOperatorExpression); @@ -233,7 +233,7 @@ public override void VisitCastExpression(CastExpression castExpression) } // There's a nasty issue in the C# grammar: cast expressions including certain operators are ambiguous in some cases // "(int)-1" is fine, but "(A)-b" is not a cast. - UnaryOperatorExpression uoe = castExpression.Expression as UnaryOperatorExpression; + UnaryOperatorExpression? uoe = castExpression.Expression as UnaryOperatorExpression; if (uoe != null && !(uoe.Operator == UnaryOperatorType.BitNot || uoe.Operator == UnaryOperatorType.Not)) { if (TypeCanBeMisinterpretedAsExpression(castExpression.Type)) @@ -242,7 +242,7 @@ public override void VisitCastExpression(CastExpression castExpression) } } // The above issue can also happen with PrimitiveExpressions representing negative values: - PrimitiveExpression pe = castExpression.Expression as PrimitiveExpression; + PrimitiveExpression? pe = castExpression.Expression as PrimitiveExpression; if (pe != null && pe.Value != null && TypeCanBeMisinterpretedAsExpression(castExpression.Type)) { TypeCode typeCode = Type.GetTypeCode(pe.Value.GetType()); @@ -286,7 +286,7 @@ static bool TypeCanBeMisinterpretedAsExpression(AstType type) // SimpleTypes can always be misinterpreted as IdentifierExpressions // MemberTypes can be misinterpreted as MemberReferenceExpressions if they don't use double colon // PrimitiveTypes or ComposedTypes can never be misinterpreted as expressions. - MemberType mt = type as MemberType; + MemberType? mt = type as MemberType; if (mt != null) return !mt.IsDoubleColon; else @@ -354,7 +354,7 @@ static bool IsBitwise(BinaryOperatorType op) BinaryOperatorType? GetBinaryOperatorType(Expression expr) { - BinaryOperatorExpression boe = expr as BinaryOperatorExpression; + BinaryOperatorExpression? boe = expr as BinaryOperatorExpression; if (boe != null) return boe.Operator; else diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs index adbf96fc45..e2458b8021 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs @@ -66,8 +66,8 @@ public static TargetFramework DetectTargetFramework(MetadataFile module) break; } - string targetFrameworkIdentifier = null; - string targetFrameworkProfile = null; + string? targetFrameworkIdentifier = null; + string? targetFrameworkProfile = null; string targetFramework = module.DetectTargetFrameworkId(); if (!string.IsNullOrEmpty(targetFramework)) @@ -245,7 +245,7 @@ static void GetFrameworkVersionNET20(MetadataFile module, IAssemblyResolver asse break; } - MetadataFile resolvedReference; + MetadataFile? resolvedReference; try { resolvedReference = assemblyResolver.Resolve(reference); diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs index f8b687b73b..a61a71459e 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs @@ -636,7 +636,7 @@ static string CleanUpName(string text, bool separateAtDots, bool treatAsFileName if (pos > 0) text = text.Substring(0, pos); text = text.Trim(); - string extension = null; + string? extension = null; int currentSegmentLength = 0; if (treatAsFileName) { @@ -781,9 +781,9 @@ public static bool CanUseSdkStyleProjectFormat(MetadataFile module) public record struct ProjectItemInfo(string ItemType, string FileName) { - public List PartialTypes { get; set; } = null; + public List? PartialTypes { get; set; } = null; - public Dictionary AdditionalProperties { get; set; } = null; + public Dictionary? AdditionalProperties { get; set; } = null; public ProjectItemInfo With(string name, string value) { diff --git a/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs b/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs index 1ddc179b33..8fda6e1f00 100644 --- a/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs @@ -75,7 +75,7 @@ void DetectAutomaticProperties() } } - bool IsAutoProperty(IProperty p, out IField field) + bool IsAutoProperty(IProperty p, out IField? field) { field = null; if (p.IsStatic) @@ -108,7 +108,7 @@ bool IsAutoProperty(IProperty p, out IField field) return field.Name == $"<{p.Name}>k__BackingField"; } - bool IsAutoGetter(IMethod method, out IField field) + bool IsAutoGetter(IMethod method, out IField? field) { field = null; var body = DecompileBody(method); @@ -129,7 +129,7 @@ bool IsAutoGetter(IMethod method, out IField field) } } - bool IsAutoSetter(IMethod method, out IField field) + bool IsAutoSetter(IMethod method, out IField? field) { field = null; Debug.Assert(!method.IsStatic); @@ -672,7 +672,7 @@ bool IsPrintedMember(IMember member) return true; } - bool MatchStringBuilderAppendConstant(out string text) + bool MatchStringBuilderAppendConstant(out string? text) { text = null; while (MatchStringBuilderAppend(body.Instructions[pos], builder, out var val) && val.MatchLdStr(out string valText)) @@ -684,7 +684,7 @@ bool MatchStringBuilderAppendConstant(out string text) } } - private bool MatchStringBuilderAppend(ILInstruction inst, ILVariable sb, out ILInstruction val) + private bool MatchStringBuilderAppend(ILInstruction inst, ILVariable sb, out ILInstruction? val) { val = null; if (!(inst is CallVirt { Method: { Name: "Append", DeclaringType: { Namespace: "System.Text", Name: "StringBuilder" } } } call)) @@ -912,7 +912,7 @@ void Visit(ILInstruction inst) } } - private bool MatchGetEqualityContract(ILInstruction inst, out ILInstruction target) + private bool MatchGetEqualityContract(ILInstruction inst, out ILInstruction? target) { target = null; if (!(inst is CallInstruction { Method: { Name: "get_EqualityContract" } } call)) @@ -1099,7 +1099,7 @@ bool IsGeneratedDeconstruct(IMethod method) return returnInst != null && returnInst.MatchReturn(out var retVal) && retVal.MatchNop(); } - bool MatchMemberAccess(ILInstruction inst, out ILInstruction target, out IMember member) + bool MatchMemberAccess(ILInstruction inst, out ILInstruction? target, out IMember? member) { target = null; member = null; diff --git a/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs b/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs index d304ad3fe6..d964179ba2 100644 --- a/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs +++ b/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs @@ -56,7 +56,7 @@ public static void CollectNamespaces(IEntity entity, MetadataModule module, Hash collector.CollectNamespaces(entity, module); } - void CollectNamespaces(IEntity entity, MetadataModule module, CodeMappingInfo mappingInfo = null) + void CollectNamespaces(IEntity entity, MetadataModule module, CodeMappingInfo? mappingInfo = null) { if (entity == null || entity.MetadataToken.IsNil || module.MetadataFile is not MetadataFile corFile) return; @@ -334,7 +334,7 @@ void CollectNamespacesFromMethodBody(MethodBodyBlock method, MetadataModule modu case HandleKind.MethodDefinition: case HandleKind.MethodSpecification: case HandleKind.MemberReference: - IMember member; + IMember? member; try { member = module.ResolveEntity(handle, genericContext) as IMember; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs index 51ea711448..c45e273df9 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs @@ -523,10 +523,10 @@ bool ImplicitReferenceConversion(IType fromType, IType toType, int subtypeCheckN if (!(fromType.IsReferenceType == true && toType.IsReferenceType != false)) return false; - ArrayType fromArray = fromType as ArrayType; + ArrayType? fromArray = fromType as ArrayType; if (fromArray != null) { - ArrayType toArray = toType as ArrayType; + ArrayType? toArray = toType as ArrayType; if (toArray != null) { // array covariance (the broken kind) @@ -556,7 +556,7 @@ bool ImplicitReferenceConversion(IType fromType, IType toType, int subtypeCheckN /// IType UnpackGenericArrayInterface(IType interfaceType) { - ParameterizedType pt = interfaceType as ParameterizedType; + ParameterizedType? pt = interfaceType as ParameterizedType; if (pt != null) { switch (pt.GetDefinition()?.KnownTypeCode) @@ -605,8 +605,8 @@ bool IdentityOrVarianceConversion(IType s, IType t, int subtypeCheckNestingDepth { if (!def.Equals(t.GetDefinition())) return false; - ParameterizedType ps = s as ParameterizedType; - ParameterizedType pt = t as ParameterizedType; + ParameterizedType? ps = s as ParameterizedType; + ParameterizedType? pt = t as ParameterizedType; if (ps != null && pt != null) { // C# 4.0 spec: §13.1.3.2 Variance Conversion @@ -700,8 +700,8 @@ bool ExplicitReferenceConversion(IType fromType, IType toType) ITypeDefinition def = fromType.GetDefinition(); if (def == null || !def.Equals(toType.GetDefinition())) return false; - ParameterizedType ps = fromType as ParameterizedType; - ParameterizedType pt = toType as ParameterizedType; + ParameterizedType? ps = fromType as ParameterizedType; + ParameterizedType? pt = toType as ParameterizedType; if (ps == null || pt == null) { // non-generic delegate - return true for the identity conversion @@ -940,7 +940,7 @@ bool IsEncompassingOrEncompassedBy(IType a, IType b) IType FindMostEncompassedType(IEnumerable candidates) { - IType best = null; + IType? best = null; foreach (var current in candidates) { if (best == null || IsEncompassedBy(current, best)) @@ -953,7 +953,7 @@ IType FindMostEncompassedType(IEnumerable candidates) IType FindMostEncompassingType(IEnumerable candidates) { - IType best = null; + IType? best = null; foreach (var current in candidates) { if (best == null || IsEncompassedBy(best, current)) @@ -1179,7 +1179,7 @@ List GetApplicableConversionOperators(ResolveResult fromResult, IT Conversion AnonymousFunctionConversion(ResolveResult resolveResult, IType toType) { // C# 5.0 spec §6.5 Anonymous function conversions - LambdaResolveResult f = resolveResult as LambdaResolveResult; + LambdaResolveResult? f = resolveResult as LambdaResolveResult; if (f == null) return Conversion.None; if (!f.IsAnonymousMethod) @@ -1245,7 +1245,7 @@ Conversion AnonymousFunctionConversion(ResolveResult resolveResult, IType toType static IType UnpackExpressionTreeType(IType type) { - ParameterizedType pt = type as ParameterizedType; + ParameterizedType? pt = type as ParameterizedType; if (pt != null && pt.TypeParameterCount == 1 && pt.Name == "Expression" && pt.Namespace == "System.Linq.Expressions") { return pt.GetTypeArgument(0); @@ -1261,7 +1261,7 @@ static IType UnpackExpressionTreeType(IType type) Conversion MethodGroupConversion(ResolveResult resolveResult, IType toType) { // C# 4.0 spec §6.6 Method group conversions - MethodGroupResolveResult rr = resolveResult as MethodGroupResolveResult; + MethodGroupResolveResult? rr = resolveResult as MethodGroupResolveResult; if (rr == null) return Conversion.None; IMethod invoke = toType.GetDelegateInvokeMethod(); @@ -1430,7 +1430,7 @@ Conversion TupleConversion(IType fromType, IType toType, bool isExplicit) /// 0 = neither is better; 1 = t1 is better; 2 = t2 is better public int BetterConversion(ResolveResult resolveResult, IType t1, IType t2) { - LambdaResolveResult lambda = resolveResult as LambdaResolveResult; + LambdaResolveResult? lambda = resolveResult as LambdaResolveResult; if (lambda != null) { if (!lambda.IsAnonymousMethod) @@ -1484,7 +1484,7 @@ public int BetterConversion(ResolveResult resolveResult, IType t1, IType t2) /// static IType UnpackTask(IType type) { - ParameterizedType pt = type as ParameterizedType; + ParameterizedType? pt = type as ParameterizedType; if (pt != null && pt.TypeParameterCount == 1 && pt.Name == "Task" && pt.Namespace == "System.Threading.Tasks") { return pt.GetTypeArgument(0); diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpInvocationResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpInvocationResolveResult.cs index b6fa7c0e34..b6771041e9 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpInvocationResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpInvocationResolveResult.cs @@ -57,9 +57,9 @@ public CSharpInvocationResolveResult( bool isExtensionMethodInvocation = false, bool isExpandedForm = false, bool isDelegateInvocation = false, - IReadOnlyList argumentToParameterMap = null, - IList initializerStatements = null, - IType returnTypeOverride = null + IReadOnlyList? argumentToParameterMap = null, + IList? initializerStatements = null, + IType? returnTypeOverride = null ) : base(targetResult, member, arguments, initializerStatements, returnTypeOverride) { @@ -88,7 +88,7 @@ public IReadOnlyList GetArgumentToParameterMap() public override IList GetArgumentsForCall() { ResolveResult[] results = new ResolveResult[Member.Parameters.Count]; - List paramsArguments = IsExpandedForm ? new List() : null; + List? paramsArguments = IsExpandedForm ? new List() : null; // map arguments to parameters: for (int i = 0; i < Arguments.Count; i++) { diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs index 14ab787ba0..239e3af973 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs @@ -193,7 +193,7 @@ public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition typeDefinition) if (this.CurrentTypeDefinition == typeDefinition) return this; - TypeDefinitionCache newTypeDefinitionCache; + TypeDefinitionCache? newTypeDefinitionCache; if (typeDefinition != null) newTypeDefinitionCache = new TypeDefinitionCache(typeDefinition); else @@ -344,7 +344,7 @@ public ResolveResult ResolveUnaryOperator(UnaryOperatorType op, ResolveResult ex switch (op) { case UnaryOperatorType.Dereference: - PointerType p = expression.Type as PointerType; + PointerType? p = expression.Type as PointerType; if (p != null) return UnaryOperatorResolveResult(p.ElementType, op, expression); else @@ -357,7 +357,7 @@ public ResolveResult ResolveUnaryOperator(UnaryOperatorType op, ResolveResult ex ResolveResult getAwaiterInvocation = ResolveInvocation(getAwaiterMethodGroup, Empty.Array, argumentNames: null, allowOptionalParameters: false); var lookup = CreateMemberLookup(); - IMethod getResultMethod; + IMethod? getResultMethod; IType awaitResultType; var getResultMethodGroup = lookup.Lookup(getAwaiterInvocation, "GetResult", EmptyList.Instance, true) as MethodGroupResolveResult; if (getResultMethodGroup != null) @@ -1490,7 +1490,7 @@ public ResolveResult LookupSimpleNameOrTypeName(string identifier, IReadOnlyList } } // Look in parameters of current method - IParameterizedMember parameterizedMember = this.CurrentMember as IParameterizedMember; + IParameterizedMember? parameterizedMember = this.CurrentMember as IParameterizedMember; if (parameterizedMember != null) { foreach (IParameter p in parameterizedMember.Parameters) @@ -1504,7 +1504,7 @@ public ResolveResult LookupSimpleNameOrTypeName(string identifier, IReadOnlyList } // look in type parameters of current method - IMethod m = this.CurrentMember as IMethod; + IMethod? m = this.CurrentMember as IMethod; if (m != null) { foreach (ITypeParameter tp in m.TypeParameters) @@ -1517,10 +1517,10 @@ public ResolveResult LookupSimpleNameOrTypeName(string identifier, IReadOnlyList bool parameterizeResultType = !(typeArguments.Count != 0 && typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument)); - ResolveResult r = null; + ResolveResult? r = null; if (currentTypeDefinitionCache != null) { - Dictionary cache = null; + Dictionary? cache = null; bool foundInCache = false; if (k == 0) { @@ -1597,7 +1597,7 @@ public ResolveResult LookupSimpleNameOrTypeName(string identifier, IReadOnlyList } } - public bool IsVariableReferenceWithSameType(ResolveResult rr, string identifier, out TypeResolveResult trr) + public bool IsVariableReferenceWithSameType(ResolveResult rr, string identifier, out TypeResolveResult? trr) { if (!(rr is MemberResolveResult || rr is LocalResolveResult)) { @@ -1680,7 +1680,7 @@ ResolveResult LookInCurrentUsingScope(string identifier, IReadOnlyList ty // finally, look in the imported namespaces: if (!(isInUsingDeclaration && u == currentUsingScope)) { - IType firstResult = null; + IType? firstResult = null; foreach (var importedNamespace in u.Usings) { ITypeDefinition def = importedNamespace.GetTypeDefinition(identifier, typeArguments.Count); @@ -1794,7 +1794,7 @@ public ResolveResult ResolveMemberAccess(ResolveResult target, string identifier // C# 4.0 spec: §7.6.4 bool parameterizeResultType = !(typeArguments.Count != 0 && typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument)); - NamespaceResolveResult nrr = target as NamespaceResolveResult; + NamespaceResolveResult? nrr = target as NamespaceResolveResult; if (nrr != null) { return ResolveMemberAccessOnNamespace(nrr, identifier, typeArguments, parameterizeResultType); @@ -1838,7 +1838,7 @@ public ResolveResult ResolveMemberAccess(ResolveResult target, string identifier } else { - MethodGroupResolveResult mgrr = result as MethodGroupResolveResult; + MethodGroupResolveResult? mgrr = result as MethodGroupResolveResult; if (mgrr != null) { Debug.Assert(mgrr.extensionMethods == null); @@ -1914,7 +1914,7 @@ public ForEachResolveResult ResolveForeach(ResolveResult expression) IType collectionType, enumeratorType, elementType; ResolveResult getEnumeratorInvocation; - ResolveResult currentRR = null; + ResolveResult? currentRR = null; // C# 4.0 spec: §8.8.4 The foreach statement if (expression.Type.Kind == TypeKind.Array || expression.Type.Kind == TypeKind.Dynamic) { @@ -1958,7 +1958,7 @@ public ForEachResolveResult ResolveForeach(ResolveResult expression) CheckForEnumerableInterface(expression, out collectionType, out enumeratorType, out elementType, out getEnumeratorInvocation); } } - IMethod moveNextMethod = null; + IMethod? moveNextMethod = null; var moveNextMethodGroup = memberLookup.Lookup(new ResolveResult(enumeratorType), "MoveNext", EmptyList.Instance, false) as MethodGroupResolveResult; if (moveNextMethodGroup != null) { @@ -1970,7 +1970,7 @@ public ForEachResolveResult ResolveForeach(ResolveResult expression) if (currentRR == null) currentRR = memberLookup.Lookup(new ResolveResult(enumeratorType), "Current", EmptyList.Instance, false); - IProperty currentProperty = null; + IProperty? currentProperty = null; if (currentRR is MemberResolveResult) currentProperty = ((MemberResolveResult)currentRR).Member as IProperty; @@ -2030,7 +2030,7 @@ void CheckForEnumerableInterface(ResolveResult expression, out IType collectionT /// new List { all extensions from SomeExtensions } /// } /// - public List> GetExtensionMethods(string name = null, IReadOnlyList typeArguments = null) + public List> GetExtensionMethods(string? name = null, IReadOnlyList? typeArguments = null) { return GetExtensionMethods(null, name, typeArguments); } @@ -2059,7 +2059,7 @@ public List> GetExtensionMethods(string name = null, IReadOnlyList /// new List { all extensions from SomeExtensions } /// } /// - public List> GetExtensionMethods(IType targetType, string name = null, IReadOnlyList typeArguments = null, bool substituteInferredTypes = false) + public List> GetExtensionMethods(IType targetType, string? name = null, IReadOnlyList? typeArguments = null, bool substituteInferredTypes = false) { var lookup = CreateMemberLookup(); List> extensionMethodGroups = new List>(); @@ -2127,7 +2127,7 @@ public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, b return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes); } - static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes) + static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType targetType, IMethod method, bool useTypeInference, out IType[]? outInferredTypes) { outInferredTypes = null; if (targetType == null) @@ -2248,7 +2248,7 @@ private ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] ar } bool isDynamic = arguments.Any(a => a.Type.Kind == TypeKind.Dynamic); - MethodGroupResolveResult mgrr = target as MethodGroupResolveResult; + MethodGroupResolveResult? mgrr = target as MethodGroupResolveResult; if (mgrr != null) { if (isDynamic) @@ -2292,12 +2292,12 @@ private ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] ar mgrr.TargetType, mgrr.MethodName, mgrr.TypeArguments, CreateParameters(arguments, argumentNames)); } } - UnknownMemberResolveResult umrr = target as UnknownMemberResolveResult; + UnknownMemberResolveResult? umrr = target as UnknownMemberResolveResult; if (umrr != null) { return new UnknownMethodResolveResult(umrr.TargetType, umrr.MemberName, umrr.TypeArguments, CreateParameters(arguments, argumentNames)); } - UnknownIdentifierResolveResult uirr = target as UnknownIdentifierResolveResult; + UnknownIdentifierResolveResult? uirr = target as UnknownIdentifierResolveResult; if (uirr != null && CurrentTypeDefinition != null) { return new UnknownMethodResolveResult(CurrentTypeDefinition, uirr.Identifier, EmptyList.Instance, CreateParameters(arguments, argumentNames)); @@ -2330,7 +2330,7 @@ private ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] ar /// The argument names. Pass the null string for positional arguments. /// /// InvocationResolveResult or UnknownMethodResolveResult - public ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[] argumentNames = null) + public ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[]? argumentNames = null) { return ResolveInvocation(target, arguments, argumentNames, allowOptionalParameters: true); } @@ -2370,7 +2370,7 @@ List CreateParameters(ResolveResult[] arguments, string[] argumentNa } // create the parameter: - ByReferenceResolveResult brrr = arguments[i] as ByReferenceResolveResult; + ByReferenceResolveResult? brrr = arguments[i] as ByReferenceResolveResult; if (brrr != null) { list.Add(new DefaultParameter(arguments[i].Type, argumentNames[i], referenceKind: brrr.ReferenceKind)); @@ -2394,19 +2394,19 @@ List CreateParameters(ResolveResult[] arguments, string[] argumentNa static string GuessParameterName(ResolveResult rr) { - MemberResolveResult mrr = rr as MemberResolveResult; + MemberResolveResult? mrr = rr as MemberResolveResult; if (mrr != null) return mrr.Member.Name; - UnknownMemberResolveResult umrr = rr as UnknownMemberResolveResult; + UnknownMemberResolveResult? umrr = rr as UnknownMemberResolveResult; if (umrr != null) return umrr.MemberName; - MethodGroupResolveResult mgrr = rr as MethodGroupResolveResult; + MethodGroupResolveResult? mgrr = rr as MethodGroupResolveResult; if (mgrr != null) return mgrr.MethodName; - LocalResolveResult vrr = rr as LocalResolveResult; + LocalResolveResult? vrr = rr as LocalResolveResult; if (vrr != null) return MakeParameterName(vrr.Variable.Name); @@ -2429,7 +2429,7 @@ static string MakeParameterName(string variableName) return char.ToLower(variableName[0]) + variableName.Substring(1); } - OverloadResolution CreateOverloadResolution(ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null) + OverloadResolution CreateOverloadResolution(ResolveResult[] arguments, string[]? argumentNames = null, IType[]? typeArguments = null) { var or = new OverloadResolution(compilation, arguments, argumentNames, typeArguments, conversions); or.CheckForOverflow = checkForOverflow; @@ -2450,7 +2450,7 @@ OverloadResolution CreateOverloadResolution(ResolveResult[] arguments, string[] /// The argument names. Pass the null string for positional arguments. /// /// ArrayAccessResolveResult, InvocationResolveResult, or ErrorResolveResult - public ResolveResult ResolveIndexer(ResolveResult target, ResolveResult[] arguments, string[] argumentNames = null) + public ResolveResult ResolveIndexer(ResolveResult target, ResolveResult[] arguments, string[]? argumentNames = null) { switch (target.Type.Kind) { @@ -2533,7 +2533,7 @@ void AdjustArrayAccessArguments(ResolveResult[] arguments) /// /// /// InvocationResolveResult or ErrorResolveResult - public ResolveResult ResolveObjectCreation(IType type, ResolveResult[] arguments, string[] argumentNames = null, bool allowProtectedAccess = false, IList initializerStatements = null) + public ResolveResult ResolveObjectCreation(IType type, ResolveResult[] arguments, string[]? argumentNames = null, bool allowProtectedAccess = false, IList? initializerStatements = null) { if (type.Kind == TypeKind.Delegate && arguments.Length == 1) { @@ -2875,7 +2875,7 @@ public static object GetDefaultValue(IType type) /// The initializer elements. May be null if no array initializer was specified. /// The resolver may mutate this array to wrap elements in s! /// - public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, int[] sizeArguments, ResolveResult[] initializerElements = null) + public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, int[] sizeArguments, ResolveResult[]? initializerElements = null) { ResolveResult[] sizeArgResults = new ResolveResult[sizeArguments.Length]; for (int i = 0; i < sizeArguments.Length; i++) @@ -2904,7 +2904,7 @@ public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, int[] si /// The initializer elements. May be null if no array initializer was specified. /// The resolver may mutate this array to wrap elements in s! /// - public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, ResolveResult[] sizeArguments, ResolveResult[] initializerElements = null) + public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, ResolveResult[] sizeArguments, ResolveResult[]? initializerElements = null) { int dimensions = sizeArguments.Length; if (dimensions == 0) @@ -2944,7 +2944,7 @@ public ResolveResult ResolveAssignment(AssignmentOperatorType op, ResolveResult return new OperatorResolveResult(lhs.Type, linqOp, lhs, this.Convert(rhs, lhs.Type)); } ResolveResult bopResult = ResolveBinaryOperator(bop.Value, lhs, rhs); - OperatorResolveResult opResult = bopResult as OperatorResolveResult; + OperatorResolveResult? opResult = bopResult as OperatorResolveResult; if (opResult == null || opResult.Operands.Count != 2) return bopResult; return new OperatorResolveResult(lhs.Type, linqOp, opResult.UserDefinedOperatorMethod, opResult.IsLiftedOperator, diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/DynamicInvocationResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/DynamicInvocationResolveResult.cs index caf46c8ff9..0b8d2d0859 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/DynamicInvocationResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/DynamicInvocationResolveResult.cs @@ -72,7 +72,7 @@ public class DynamicInvocationResolveResult : ResolveResult /// public readonly IList InitializerStatements; - public DynamicInvocationResolveResult(ResolveResult target, DynamicInvocationType invocationType, IList arguments, IList initializerStatements = null) : base(SpecialType.Dynamic) + public DynamicInvocationResolveResult(ResolveResult target, DynamicInvocationType invocationType, IList arguments, IList? initializerStatements = null) : base(SpecialType.Dynamic) { this.Target = target; this.InvocationType = invocationType; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs index 65a276942f..994aba2bf7 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs @@ -199,11 +199,11 @@ public IEnumerable GetAccessibleMembers(ResolveResult targetResolveResu if (!lookupGroupDict.TryGetValue(entityGroup.Key, out lookupGroups)) lookupGroupDict.Add(entityGroup.Key, lookupGroups = new List()); - List newNestedTypes = null; - List newMethods = null; - IMember newNonMethod = null; + List? newNestedTypes = null; + List? newMethods = null; + IMember? newNonMethod = null; - IEnumerable typeBaseTypes = null; + IEnumerable? typeBaseTypes = null; if (!targetIsTypeParameter) { @@ -310,8 +310,8 @@ public ResolveResult LookupType(IType declaringType, string name, IReadOnlyList< { foreach (IType type in declaringType.GetNonInterfaceBaseTypes()) { - List newNestedTypes = null; - IEnumerable typeBaseTypes = null; + List? newNestedTypes = null; + IEnumerable? typeBaseTypes = null; IEnumerable nestedTypes; if (parameterizeResultType) @@ -389,11 +389,11 @@ public ResolveResult Lookup(ResolveResult targetResolveResult, string name, IRea foreach (IType type in targetResolveResult.Type.GetNonInterfaceBaseTypes()) { - List newNestedTypes = null; - List newMethods = null; - IMember newNonMethod = null; + List? newNestedTypes = null; + List? newMethods = null; + IMember? newNonMethod = null; - IEnumerable typeBaseTypes = null; + IEnumerable? typeBaseTypes = null; if (!isInvocation && !targetIsTypeParameter) { @@ -452,10 +452,10 @@ public IReadOnlyList LookupIndexers(ResolveResult t List lookupGroups = new List(); foreach (IType type in targetType.GetNonInterfaceBaseTypes()) { - List newMethods = null; - IMember newNonMethod = null; + List? newMethods = null; + IMember? newNonMethod = null; - IEnumerable typeBaseTypes = null; + IEnumerable? typeBaseTypes = null; var members = type.GetProperties(filter, GetMemberOptions.IgnoreInheritedMembers); AddMembers(type, members, allowProtectedAccess, lookupGroups, true, ref typeBaseTypes, ref newMethods, ref newNonMethod); @@ -551,7 +551,7 @@ void AddMembers(IType type, IEnumerable members, if (!IsAccessible(member, allowProtectedAccess)) continue; - IParameterizedMember method; + IParameterizedMember? method; if (treatAllParameterizedMembersAsMethods) method = member as IParameterizedMember; else @@ -753,7 +753,7 @@ ResolveResult CreateResult(ResolveResult targetResolveResult, List { if (isInEnumMemberInitializer) { - IField field = resultGroup.NonMethod as IField; + IField? field = resultGroup.NonMethod as IField; if (field != null && field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Kind == TypeKind.Enum) { return new MemberResolveResult( diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs index d08108c228..3dbb5bf7a4 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs @@ -229,12 +229,12 @@ public override string ToString() return string.Format("[{0} with {1} method(s)]", GetType().Name, this.Methods.Count()); } - public OverloadResolution PerformOverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, + public OverloadResolution PerformOverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[]? argumentNames = null, bool allowExtensionMethods = true, bool allowExpandingParams = true, bool allowOptionalParameters = true, bool allowImplicitIn = true, - bool checkForOverflow = false, CSharpConversions conversions = null) + bool checkForOverflow = false, CSharpConversions? conversions = null) { Log.WriteLine("Performing overload resolution for " + this); Log.WriteCollection(" Arguments: ", arguments); @@ -260,7 +260,7 @@ public OverloadResolution PerformOverloadResolution(ICompilation compilation, Re ResolveResult[] extArguments = new ResolveResult[arguments.Length + 1]; extArguments[0] = new ResolveResult(this.TargetType); arguments.CopyTo(extArguments, 1); - string[] extArgumentNames = null; + string[]? extArgumentNames = null; if (argumentNames != null) { extArgumentNames = new string[argumentNames.Length + 1]; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs index bfeb1bbd25..3eaf041bee 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs @@ -78,7 +78,7 @@ sealed class Candidate public bool IsGenericMethod { get { - IMethod method = Member as IMethod; + IMethod? method = Member as IMethod; return method != null && method.TypeParameters.Count > 0; } } @@ -108,7 +108,7 @@ public Candidate(IParameterizedMember member, bool isExpanded) // (without any type parameter substitution, not even class type parameters) // We'll re-substitute them as part of RunTypeInference(). this.Parameters = memberDefinition.Parameters; - IMethod methodDefinition = memberDefinition as IMethod; + IMethod? methodDefinition = memberDefinition as IMethod; if (methodDefinition != null && methodDefinition.TypeParameters.Count > 0) { this.TypeParameters = methodDefinition.TypeParameters; @@ -136,7 +136,7 @@ public void AddError(OverloadResolutionErrors newError) OverloadResolutionErrors bestCandidateValidationResult; #region Constructor - public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null) + public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[]? argumentNames = null, IType[]? typeArguments = null, CSharpConversions? conversions = null) { if (compilation == null) throw new ArgumentNullException(nameof(compilation)); @@ -286,7 +286,7 @@ bool ResolveParameterTypes(Candidate candidate, bool useSpecializedParameters) } if (candidate.IsExpandedForm && i == candidate.Parameters.Count - 1) { - ArrayType arrayType = type as ArrayType; + ArrayType? arrayType = type as ArrayType; if (arrayType != null && arrayType.Dimensions == 1) type = arrayType.ElementType; else @@ -311,7 +311,7 @@ public void AddMethodLists(IReadOnlyList methodList if (methodLists == null) throw new ArgumentNullException(nameof(methodLists)); // Base types come first, so go through the list backwards (derived types first) - bool[] isHiddenByDerivedType; + bool[]? isHiddenByDerivedType; if (methodLists.Count > 1) isHiddenByDerivedType = new bool[methodLists.Count]; else @@ -436,8 +436,8 @@ void RunTypeInference(Candidate candidate) ResolveParameterTypes(candidate, true); return; } - ParameterizedType parameterizedDeclaringType = candidate.Member.DeclaringType as ParameterizedType; - IReadOnlyList classTypeArguments; + ParameterizedType? parameterizedDeclaringType = candidate.Member.DeclaringType as ParameterizedType; + IReadOnlyList? classTypeArguments; if (parameterizedDeclaringType != null) { classTypeArguments = parameterizedDeclaringType.TypeArguments; @@ -504,7 +504,7 @@ public override IType VisitParameterizedType(ParameterizedType type) if (newType != type && ConstraintsValid) { // something was changed, so we need to validate the constraints - ParameterizedType newParameterizedType = newType as ParameterizedType; + ParameterizedType? newParameterizedType = newType as ParameterizedType; if (newParameterizedType != null) { // C# 4.0 spec: §4.4.4 Satisfying constraints @@ -552,7 +552,7 @@ OverloadResolutionErrors ValidateMethodConstraints(Candidate candidate) /// The substitution is used to check constraints that depend on other type parameters (or recursively on the same type parameter). /// May be null if no substitution should be used. /// True if the constraints are satisfied; false otherwise. - public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution = null) + public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor? substitution = null) { if (typeParameter == null) throw new ArgumentNullException(nameof(typeParameter)); @@ -791,8 +791,8 @@ int BetterFunctionMember(Candidate c1, Candidate c2) return r; // prefer non-lifted operators - ILiftedOperator lift1 = c1.Member as ILiftedOperator; - ILiftedOperator lift2 = c2.Member as ILiftedOperator; + ILiftedOperator? lift1 = c1.Member as ILiftedOperator; + ILiftedOperator? lift2 = c2.Member as ILiftedOperator; if (lift1 == null && lift2 != null) return 1; if (lift1 != null && lift2 == null) @@ -843,16 +843,16 @@ static int MoreSpecificFormalParameter(IType t1, IType t2) if ((t2 is ITypeParameter) && !(t1 is ITypeParameter)) return 1; - ParameterizedType p1 = t1 as ParameterizedType; - ParameterizedType p2 = t2 as ParameterizedType; + ParameterizedType? p1 = t1 as ParameterizedType; + ParameterizedType? p2 = t2 as ParameterizedType; if (p1 != null && p2 != null && p1.TypeParameterCount == p2.TypeParameterCount) { int r = MoreSpecificFormalParameters(p1.TypeArguments, p2.TypeArguments); if (r > 0) return r; } - TypeWithElementType tew1 = t1 as TypeWithElementType; - TypeWithElementType tew2 = t2 as TypeWithElementType; + TypeWithElementType? tew1 = t1 as TypeWithElementType; + TypeWithElementType? tew2 = t2 as TypeWithElementType; if (tew1 != null && tew2 != null) { return MoreSpecificFormalParameter(tew1.ElementType, tew2.ElementType); @@ -1041,7 +1041,7 @@ public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments() { if (bestCandidate == null) return null; - IMethod method = bestCandidate.Member as IMethod; + IMethod? method = bestCandidate.Member as IMethod; if (method != null && method.TypeParameters.Count > 0) { return ((IMethod)method.MemberDefinition).Specialize(GetSubstitution(bestCandidate)); @@ -1072,7 +1072,7 @@ TypeParameterSubstitution GetSubstitution(Candidate candidate) /// /// If not null, use this instead of the ReturnType of the member as the type of the created resolve result. /// - public CSharpInvocationResolveResult CreateResolveResult(ResolveResult targetResolveResult, IList initializerStatements = null, IType returnTypeOverride = null) + public CSharpInvocationResolveResult CreateResolveResult(ResolveResult targetResolveResult, IList? initializerStatements = null, IType? returnTypeOverride = null) { IParameterizedMember member = GetBestCandidateWithSubstitutedTypeArguments(); if (member == null) diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs index 1c02d9da62..846922884d 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs @@ -113,7 +113,7 @@ TypeInference CreateNestedInstance() /// when inferring a method group or lambda. /// /// The inferred type arguments. - public IType[] InferTypeArguments(IReadOnlyList typeParameters, IReadOnlyList arguments, IReadOnlyList parameterTypes, out bool success, IReadOnlyList classTypeArguments = null) + public IType[] InferTypeArguments(IReadOnlyList typeParameters, IReadOnlyList arguments, IReadOnlyList parameterTypes, out bool success, IReadOnlyList? classTypeArguments = null) { if (typeParameters == null) throw new ArgumentNullException(nameof(typeParameters)); @@ -283,7 +283,7 @@ void PhaseOne() ResolveResult Ei = arguments[i]; IType Ti = parameterTypes[i]; - LambdaResolveResult lrr = Ei as LambdaResolveResult; + LambdaResolveResult? lrr = Ei as LambdaResolveResult; if (lrr != null) { MakeExplicitParameterTypeInference(lrr, Ti); @@ -397,7 +397,7 @@ bool PhaseTwo() IType[] InputTypes(ResolveResult e, IType t) { // C# 4.0 spec: §7.5.2.3 Input types - LambdaResolveResult lrr = e as LambdaResolveResult; + LambdaResolveResult? lrr = e as LambdaResolveResult; if (lrr != null && lrr.IsImplicitlyTyped || e is MethodGroupResolveResult) { IMethod m = GetDelegateOrExpressionTreeSignature(t); @@ -417,7 +417,7 @@ IType[] InputTypes(ResolveResult e, IType t) IType[] OutputTypes(ResolveResult e, IType t) { // C# 4.0 spec: §7.5.2.4 Output types - LambdaResolveResult lrr = e as LambdaResolveResult; + LambdaResolveResult? lrr = e as LambdaResolveResult; if (lrr != null || e is MethodGroupResolveResult) { IMethod m = GetDelegateOrExpressionTreeSignature(t); @@ -524,7 +524,7 @@ void MakeOutputTypeInference(ResolveResult e, IType t) Log.WriteLine(" MakeOutputTypeInference from " + e + " to " + t); // If E is an anonymous function with inferred return type U (§7.5.2.12) and T is a delegate type or expression // tree type with return type Tb, then a lower-bound inference (§7.5.2.9) is made from U to Tb. - LambdaResolveResult lrr = e as LambdaResolveResult; + LambdaResolveResult? lrr = e as LambdaResolveResult; if (lrr != null) { IMethod m = GetDelegateOrExpressionTreeSignature(t); @@ -556,7 +556,7 @@ void MakeOutputTypeInference(ResolveResult e, IType t) // with parameter types T1…Tk and return type Tb, and overload resolution // of E with the types T1…Tk yields a single method with return type U, then a lower­-bound // inference is made from U to Tb. - MethodGroupResolveResult mgrr = e as MethodGroupResolveResult; + MethodGroupResolveResult? mgrr = e as MethodGroupResolveResult; if (mgrr != null) { IMethod m = GetDelegateOrExpressionTreeSignature(t); @@ -651,24 +651,24 @@ void MakeExactInference(IType U, IType V) return; } // Handle by reference types: - ByReferenceType brU = U as ByReferenceType; - ByReferenceType brV = V as ByReferenceType; + ByReferenceType? brU = U as ByReferenceType; + ByReferenceType? brV = V as ByReferenceType; if (brU != null && brV != null) { MakeExactInference(brU.ElementType, brV.ElementType); return; } // Handle array types: - ArrayType arrU = U as ArrayType; - ArrayType arrV = V as ArrayType; + ArrayType? arrU = U as ArrayType; + ArrayType? arrV = V as ArrayType; if (arrU != null && arrV != null && arrU.Dimensions == arrV.Dimensions) { MakeExactInference(arrU.ElementType, arrV.ElementType); return; } // Handle parameterized type: - ParameterizedType pU = U.TupleUnderlyingTypeOrSelf() as ParameterizedType; - ParameterizedType pV = V.TupleUnderlyingTypeOrSelf() as ParameterizedType; + ParameterizedType? pU = U.TupleUnderlyingTypeOrSelf() as ParameterizedType; + ParameterizedType? pV = V.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (pU != null && pV != null && object.Equals(pU.GenericType, pV.GenericType) && pU.TypeParameterCount == pV.TypeParameterCount) @@ -743,17 +743,17 @@ void MakeLowerBoundInference(IType U, IType V) return; } // Handle by reference types: - ByReferenceType brU = U as ByReferenceType; - ByReferenceType brV = V as ByReferenceType; + ByReferenceType? brU = U as ByReferenceType; + ByReferenceType? brV = V as ByReferenceType; if (brU != null && brV != null) { MakeExactInference(brU.ElementType, brV.ElementType); return; } // Handle array types: - ArrayType arrU = U as ArrayType; - ArrayType arrV = V as ArrayType; - ParameterizedType pV = V.TupleUnderlyingTypeOrSelf() as ParameterizedType; + ArrayType? arrU = U as ArrayType; + ArrayType? arrV = V as ArrayType; + ParameterizedType? pV = V.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (arrU != null && arrV != null && arrU.Dimensions == arrV.Dimensions) { MakeLowerBoundInference(arrU.ElementType, arrV.ElementType); @@ -767,10 +767,10 @@ void MakeLowerBoundInference(IType U, IType V) // Handle parameterized types: if (pV != null) { - ParameterizedType uniqueBaseType = null; + ParameterizedType? uniqueBaseType = null; foreach (IType baseU in U.GetAllBaseTypes()) { - ParameterizedType pU = baseU.TupleUnderlyingTypeOrSelf() as ParameterizedType; + ParameterizedType? pU = baseU.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (pU != null && object.Equals(pU.GenericType, pV.GenericType) && pU.TypeParameterCount == pV.TypeParameterCount) { if (uniqueBaseType == null) @@ -872,9 +872,9 @@ void MakeUpperBoundInference(IType U, IType V) } // Handle array types: - ArrayType arrU = U as ArrayType; - ArrayType arrV = V as ArrayType; - ParameterizedType pU = U.TupleUnderlyingTypeOrSelf() as ParameterizedType; + ArrayType? arrU = U as ArrayType; + ArrayType? arrV = V as ArrayType; + ParameterizedType? pU = U.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (arrV != null && arrU != null && arrU.Dimensions == arrV.Dimensions) { MakeUpperBoundInference(arrU.ElementType, arrV.ElementType); @@ -888,10 +888,10 @@ void MakeUpperBoundInference(IType U, IType V) // Handle parameterized types: if (pU != null) { - ParameterizedType uniqueBaseType = null; + ParameterizedType? uniqueBaseType = null; foreach (IType baseV in V.GetAllBaseTypes()) { - ParameterizedType pV = baseV.TupleUnderlyingTypeOrSelf() as ParameterizedType; + ParameterizedType? pV = baseV.TupleUnderlyingTypeOrSelf() as ParameterizedType; if (pV != null && object.Equals(pU.GenericType, pV.GenericType) && pU.TypeParameterCount == pV.TypeParameterCount) { if (uniqueBaseType == null) diff --git a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs index 4dfc5f6583..5d1df3fc20 100644 --- a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs @@ -151,7 +151,7 @@ protected internal override TranslatedStatement VisitIfInstruction(IfInstruction return new IfElseStatement(condition, trueStatement, falseStatement).WithILInstruction(inst); } - internal IEnumerable CreateTypedCaseLabel(long i, IType type, List<(string Key, int Value)> map = null) + internal IEnumerable CreateTypedCaseLabel(long i, IType type, List<(string Key, int Value)>? map = null) { object value; // unpack nullable type, if necessary: @@ -243,7 +243,7 @@ SwitchStatement TranslateSwitch(BlockContainer switchContainer, SwitchInstructio foreach (var section in inst.Sections) { // This is used in the block-label mapping. - ConstantResolveResult firstValueResolveResult; + ConstantResolveResult? firstValueResolveResult; var astSection = new Syntax.SwitchSection(); // Create case labels: if (section == defaultSection) @@ -346,7 +346,7 @@ private void ConvertSwitchSectionBody(Syntax.SwitchSection astSection, ILInstruc if (!bodyInst.HasFlag(InstructionFlags.EndPointUnreachable)) { // we need to insert 'break;' - BlockStatement block = body as BlockStatement; + BlockStatement? block = body as BlockStatement; if (block != null) { block.Add(new BreakStatement()); @@ -731,7 +731,7 @@ Statement TransformToForeach(UsingInstruction inst, Expression resource) break; } - VariableDesignation designation = null; + VariableDesignation? designation = null; // Handle the required foreach-variable transformation: switch (transformation) @@ -875,7 +875,7 @@ static bool EqualErasedType(IType a, IType b) return NormalizeTypeVisitor.TypeErasure.EquivalentTypes(a, b); } - private bool IsDynamicCastToIEnumerable(Expression expr, out Expression dynamicExpr) + private bool IsDynamicCastToIEnumerable(Expression expr, out Expression? dynamicExpr) { if (!(expr is CastExpression cast)) { @@ -898,7 +898,7 @@ private bool IsDynamicCastToIEnumerable(Expression expr, out Expression dynamicE /// Otherwise returns the unmodified container. /// /// If the leave is a return/break and has no side-effects, we can move the return out of the using-block and put it after the loop, otherwise returns null. - BlockContainer UnwrapNestedContainerIfPossible(BlockContainer container, out Leave optionalLeaveInst) + BlockContainer UnwrapNestedContainerIfPossible(BlockContainer container, out Leave? optionalLeaveInst) { optionalLeaveInst = null; // Check block structure: @@ -978,7 +978,7 @@ enum RequiredGetCurrentTransformation /// Returns the call instruction invoking Current's getter. /// Returns the the foreach variable, if a suitable was found. This variable is only assigned once and its assignment is the first statement in . /// for details. - RequiredGetCurrentTransformation DetectGetCurrentTransformation(BlockContainer usingContainer, Block loopBody, BlockContainer loopContainer, ILVariable enumerator, ILInstruction moveNextUsage, out CallInstruction singleGetter, out ILVariable foreachVariable) + RequiredGetCurrentTransformation DetectGetCurrentTransformation(BlockContainer usingContainer, Block loopBody, BlockContainer loopContainer, ILVariable enumerator, ILInstruction moveNextUsage, out CallInstruction? singleGetter, out ILVariable? foreachVariable) { singleGetter = null; foreachVariable = null; @@ -1425,7 +1425,7 @@ LocalFunctionDeclarationStatement TranslateFunction(ILFunction function) method.Body = nestedBuilder.ConvertAsBlock(function.Body); - Comment prev = null; + Comment? prev = null; foreach (string warning in function.Warnings) { method.Body.InsertChildAfter(prev, prev = new Comment(warning), Roles.Comment); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs index e61079c71b..b3bd0edccb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs @@ -149,7 +149,7 @@ public IEnumerable Detach() /// Returns the first element for which the predicate returns true, /// or the null node (AstNode with IsNull=true) if no such object is found. /// - public T FirstOrNullObject(Func predicate = null) + public T FirstOrNullObject(Func? predicate = null) { foreach (T item in this) if (predicate == null || predicate(item)) @@ -161,7 +161,7 @@ public T FirstOrNullObject(Func predicate = null) /// Returns the last element for which the predicate returns true, /// or the null node (AstNode with IsNull=true) if no such object is found. /// - public T LastOrNullObject(Func predicate = null) + public T LastOrNullObject(Func? predicate = null) { T result = role.NullObject; foreach (T item in this) @@ -202,7 +202,7 @@ public override int GetHashCode() public override bool Equals(object obj) { - AstNodeCollection other = obj as AstNodeCollection; + AstNodeCollection? other = obj as AstNodeCollection; if (other == null) return false; return this.node == other.node && this.role == other.role; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs index a8b8da53ad..779103c1f2 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs @@ -133,7 +133,7 @@ public override NodeType NodeType { /// public bool IsVar() { - SimpleType st = this as SimpleType; + SimpleType? st = this as SimpleType; return st != null && st.Identifier == "var" && st.TypeArguments.Count == 0; } @@ -148,7 +148,7 @@ public bool IsVar() /// For resolving simple names, the current namespace and usings from the CurrentUsingScope /// (on CSharpTypeResolveContext only) is used. /// - public ITypeReference ToTypeReference(InterningProvider interningProvider = null) + public ITypeReference ToTypeReference(InterningProvider? interningProvider = null) { return ToTypeReference(GetNameLookupMode(), interningProvider); } @@ -163,7 +163,7 @@ public ITypeReference ToTypeReference(InterningProvider interningProvider = null /// For resolving simple names, the current namespace and usings from the CurrentUsingScope /// (on CSharpTypeResolveContext only) is used. /// - public abstract ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null); + public abstract ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null); /// /// Gets the name lookup mode from the context (looking at the ancestors of this ). diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs index fbe31464dc..6e69f95bbf 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs @@ -56,7 +56,7 @@ public override string ToString(CSharpFormattingOptions formattingOptions) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CSharpModifierToken o = other as CSharpModifierToken; + CSharpModifierToken? o = other as CSharpModifierToken; return o != null && this.modifier == o.modifier; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs index 6bbf8a5468..b954b7ea92 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs @@ -134,7 +134,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CSharpTokenNode o = other as CSharpTokenNode; + CSharpTokenNode? o = other as CSharpTokenNode; return o != null && !o.IsNull && !(o is CSharpModifierToken); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs index c042a2ca9e..518e4876f8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs @@ -146,7 +146,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ComposedType o = other as ComposedType; + ComposedType? o = other as ComposedType; return o != null && this.HasNullableSpecifier == o.HasNullableSpecifier && this.PointerRank == o.PointerRank @@ -201,7 +201,7 @@ public override AstType MakeRefType() return this; } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null) { if (interningProvider == null) interningProvider = InterningProvider.Dummy; @@ -289,7 +289,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ArraySpecifier o = other as ArraySpecifier; + ArraySpecifier? o = other as ArraySpecifier; return o != null && this.Dimensions == o.Dimensions; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs b/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs index 893f015fcc..f42da43c4e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs @@ -111,7 +111,7 @@ public AstNodeCollection Parameters { protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - DocumentationReference o = other as DocumentationReference; + DocumentationReference? o = other as DocumentationReference; if (!(o != null && this.SymbolKind == o.SymbolKind && this.HasParameterList == o.HasParameterList)) return false; if (this.SymbolKind == SymbolKind.Operator) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs index 633073b36e..9685f9e084 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs @@ -77,7 +77,7 @@ public AnonymousMethodExpression() { } - public AnonymousMethodExpression(BlockStatement body, IEnumerable parameters = null) + public AnonymousMethodExpression(BlockStatement body, IEnumerable? parameters = null) { if (parameters != null) { @@ -111,7 +111,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - AnonymousMethodExpression o = other as AnonymousMethodExpression; + AnonymousMethodExpression? o = other as AnonymousMethodExpression; return o != null && this.IsAsync == o.IsAsync && this.HasParameterList == o.HasParameterList && this.Parameters.DoMatch(o.Parameters, match) && this.Body.DoMatch(o.Body, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs index e4314f001f..5f20870e1c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs @@ -71,7 +71,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ArrayCreateExpression o = other as ArrayCreateExpression; + ArrayCreateExpression? o = other as ArrayCreateExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match) && this.AdditionalArraySpecifiers.DoMatch(o.AdditionalArraySpecifiers, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs index f9ce091523..d7841c25a3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs @@ -121,7 +121,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ArrayInitializerExpression o = other as ArrayInitializerExpression; + ArrayInitializerExpression? o = other as ArrayInitializerExpression; return o != null && this.Elements.DoMatch(o.Elements, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs index b01fd4f86a..0348795602 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - AsExpression o = other as AsExpression; + AsExpression? o = other as AsExpression; return o != null && this.Expression.DoMatch(o.Expression, match) && this.Type.DoMatch(o.Type, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs index 378b33bfa5..cee70016ad 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs @@ -105,7 +105,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - AssignmentExpression o = other as AssignmentExpression; + AssignmentExpression? o = other as AssignmentExpression; return o != null && (this.Operator == AssignmentOperatorType.Any || this.Operator == o.Operator) && this.Left.DoMatch(o.Left, match) && this.Right.DoMatch(o.Right, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs index 5084d0e044..46f9160693 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs @@ -65,7 +65,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - BaseReferenceExpression o = other as BaseReferenceExpression; + BaseReferenceExpression? o = other as BaseReferenceExpression; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs index 1386e1029c..e7d7f8f0a4 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs @@ -107,7 +107,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - BinaryOperatorExpression o = other as BinaryOperatorExpression; + BinaryOperatorExpression? o = other as BinaryOperatorExpression; return o != null && (this.Operator == BinaryOperatorType.Any || this.Operator == o.Operator) && this.Left.DoMatch(o.Left, match) && this.Right.DoMatch(o.Right, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs index f3bd22ec2c..bb24ba1dc6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CastExpression o = other as CastExpression; + CastExpression? o = other as CastExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs index baff6c51a3..76cfa5ffae 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CheckedExpression o = other as CheckedExpression; + CheckedExpression? o = other as CheckedExpression; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs index a1576e5cc3..18d2dcd8ba 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs @@ -89,7 +89,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ConditionalExpression o = other as ConditionalExpression; + ConditionalExpression? o = other as ConditionalExpression; return o != null && this.Condition.DoMatch(o.Condition, match) && this.TrueExpression.DoMatch(o.TrueExpression, match) && this.FalseExpression.DoMatch(o.FalseExpression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs index 372325a405..21ee02d882 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - DefaultValueExpression o = other as DefaultValueExpression; + DefaultValueExpression? o = other as DefaultValueExpression; return o != null && this.Type.DoMatch(o.Type, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs index e92115530b..e8e00f5301 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs @@ -95,7 +95,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - DirectionExpression o = other as DirectionExpression; + DirectionExpression? o = other as DirectionExpression; return o != null && this.FieldDirection == o.FieldDirection && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs index 76fc8c2a5c..d1849ac1cc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs @@ -81,7 +81,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - IdentifierExpression o = other as IdentifierExpression; + IdentifierExpression? o = other as IdentifierExpression; return o != null && MatchString(this.Identifier, o.Identifier) && this.TypeArguments.DoMatch(o.TypeArguments, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs index e688b2a74f..43c5311d8a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs @@ -54,7 +54,7 @@ public IndexerExpression() { } - public IndexerExpression(Expression target, IEnumerable arguments) + public IndexerExpression(Expression target, IEnumerable? arguments) { AddChild(target, Roles.TargetExpression); if (arguments != null) @@ -66,7 +66,7 @@ public IndexerExpression(Expression target, IEnumerable arguments) } } - public IndexerExpression(Expression target, params Expression[] arguments) : this(target, (IEnumerable)arguments) + public IndexerExpression(Expression target, params Expression[]? arguments) : this(target, (IEnumerable?)arguments) { } @@ -85,9 +85,9 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitIndexerExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { - IndexerExpression o = other as IndexerExpression; + IndexerExpression? o = other as IndexerExpression; return o != null && this.Target.DoMatch(o.Target, match) && this.Arguments.DoMatch(o.Arguments, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs index 562755a0af..6d3f2b5cc1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs @@ -42,7 +42,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, Match match) { - InterpolatedStringExpression o = other as InterpolatedStringExpression; + InterpolatedStringExpression? o = other as InterpolatedStringExpression; return o != null && !o.IsNull && this.Content.DoMatch(o.Content, match); } } @@ -117,7 +117,7 @@ public Interpolation() } - public Interpolation(Expression expression, int alignment = 0, string suffix = null) + public Interpolation(Expression expression, int alignment = 0, string? suffix = null) { Expression = expression; Alignment = alignment; @@ -141,7 +141,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, Match match) { - Interpolation o = other as Interpolation; + Interpolation? o = other as Interpolation; return o != null && this.Expression.DoMatch(o.Expression, match); } } @@ -177,7 +177,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, Match match) { - InterpolatedStringText o = other as InterpolatedStringText; + InterpolatedStringText? o = other as InterpolatedStringText; return o != null && o.Text == this.Text; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs index 3ed91cefc8..2d5a9c86e6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs @@ -87,7 +87,7 @@ public InvocationExpression(Expression target, params Expression[] arguments) : protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - InvocationExpression o = other as InvocationExpression; + InvocationExpression? o = other as InvocationExpression; return o != null && this.Target.DoMatch(o.Target, match) && this.Arguments.DoMatch(o.Arguments, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs index fa1bea0bc9..1801b42d9e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs @@ -76,7 +76,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - IsExpression o = other as IsExpression; + IsExpression? o = other as IsExpression; return o != null && this.Expression.DoMatch(o.Expression, match) && this.Type.DoMatch(o.Type, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs index 8782aa1d8e..e09e157099 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs @@ -84,7 +84,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - LambdaExpression o = other as LambdaExpression; + LambdaExpression? o = other as LambdaExpression; return o != null && this.IsAsync == o.IsAsync && this.Parameters.DoMatch(o.Parameters, match) && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs index fcda03b545..ad8754bb12 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs @@ -80,7 +80,7 @@ public MemberReferenceExpression() { } - public MemberReferenceExpression(Expression target, string memberName, IEnumerable arguments = null) + public MemberReferenceExpression(Expression target, string memberName, IEnumerable? arguments = null) { AddChild(target, Roles.TargetExpression); MemberName = memberName; @@ -114,7 +114,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - MemberReferenceExpression o = other as MemberReferenceExpression; + MemberReferenceExpression? o = other as MemberReferenceExpression; return o != null && this.Target.DoMatch(o.Target, match) && MatchString(this.MemberName, o.MemberName) && this.TypeArguments.DoMatch(o.TypeArguments, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs index 5f3fb3627d..d2b66aa9a9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs @@ -79,7 +79,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - NamedArgumentExpression o = other as NamedArgumentExpression; + NamedArgumentExpression? o = other as NamedArgumentExpression; return o != null && MatchString(this.Name, o.Name) && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs index ee67fb20f4..df13519687 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - NullReferenceExpression o = other as NullReferenceExpression; + NullReferenceExpression? o = other as NullReferenceExpression; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs index f559f6a89a..64b89508f4 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs @@ -66,7 +66,7 @@ public ObjectCreateExpression() { } - public ObjectCreateExpression(AstType type, IEnumerable arguments = null) + public ObjectCreateExpression(AstType type, IEnumerable? arguments = null) { AddChild(type, Roles.Type); if (arguments != null) @@ -99,7 +99,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ObjectCreateExpression o = other as ObjectCreateExpression; + ObjectCreateExpression? o = other as ObjectCreateExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match) && this.Initializer.DoMatch(o.Initializer, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs index b662ab3d41..0758f0f3c2 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs @@ -71,7 +71,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ParenthesizedExpression o = other as ParenthesizedExpression; + ParenthesizedExpression? o = other as ParenthesizedExpression; return o != null && this.Expression.DoMatch(o.Expression, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs index d678cdaf80..724decd854 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs @@ -82,7 +82,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - PointerReferenceExpression o = other as PointerReferenceExpression; + PointerReferenceExpression? o = other as PointerReferenceExpression; return o != null && MatchString(this.MemberName, o.MemberName) && this.TypeArguments.DoMatch(o.TypeArguments, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs index a1e8fcc3b8..3e0d356d73 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs @@ -145,7 +145,7 @@ unsafe static TextLocation AdvanceLocation(TextLocation startLocation, string st protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - PrimitiveExpression o = other as PrimitiveExpression; + PrimitiveExpression? o = other as PrimitiveExpression; return o != null && (this.Value == AnyValue || object.Equals(this.Value, o.Value)); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs index 87315b01f5..f5139d97fe 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs @@ -76,7 +76,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryExpression o = other as QueryExpression; + QueryExpression? o = other as QueryExpression; return o != null && !o.IsNull && this.Clauses.DoMatch(o.Clauses, match); } } @@ -150,7 +150,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryContinuationClause o = other as QueryContinuationClause; + QueryContinuationClause? o = other as QueryContinuationClause; return o != null && MatchString(this.Identifier, o.Identifier) && this.PrecedingQuery.DoMatch(o.PrecedingQuery, match); } } @@ -208,7 +208,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryFromClause o = other as QueryFromClause; + QueryFromClause? o = other as QueryFromClause; return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.Identifier, o.Identifier) && this.Expression.DoMatch(o.Expression, match); } @@ -261,7 +261,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryLetClause o = other as QueryLetClause; + QueryLetClause? o = other as QueryLetClause; return o != null && MatchString(this.Identifier, o.Identifier) && this.Expression.DoMatch(o.Expression, match); } } @@ -297,7 +297,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryWhereClause o = other as QueryWhereClause; + QueryWhereClause? o = other as QueryWhereClause; return o != null && this.Condition.DoMatch(o.Condition, match); } } @@ -406,7 +406,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryJoinClause o = other as QueryJoinClause; + QueryJoinClause? o = other as QueryJoinClause; return o != null && this.IsGroupJoin == o.IsGroupJoin && this.Type.DoMatch(o.Type, match) && MatchString(this.JoinIdentifier, o.JoinIdentifier) && this.InExpression.DoMatch(o.InExpression, match) && this.OnExpression.DoMatch(o.OnExpression, match) @@ -445,7 +445,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryOrderClause o = other as QueryOrderClause; + QueryOrderClause? o = other as QueryOrderClause; return o != null && this.Orderings.DoMatch(o.Orderings, match); } } @@ -490,7 +490,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryOrdering o = other as QueryOrdering; + QueryOrdering? o = other as QueryOrdering; return o != null && this.Direction == o.Direction && this.Expression.DoMatch(o.Expression, match); } } @@ -532,7 +532,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QuerySelectClause o = other as QuerySelectClause; + QuerySelectClause? o = other as QuerySelectClause; return o != null && this.Expression.DoMatch(o.Expression, match); } } @@ -579,7 +579,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - QueryGroupClause o = other as QueryGroupClause; + QueryGroupClause? o = other as QueryGroupClause; return o != null && this.Projection.DoMatch(o.Projection, match) && this.Key.DoMatch(o.Key, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs index b5daa0a9f6..30e63b8e40 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - SizeOfExpression o = other as SizeOfExpression; + SizeOfExpression? o = other as SizeOfExpression; return o != null && this.Type.DoMatch(o.Type, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs index f3c1c9b859..8633037f29 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs @@ -79,7 +79,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - StackAllocExpression o = other as StackAllocExpression; + StackAllocExpression? o = other as StackAllocExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.CountExpression.DoMatch(o.CountExpression, match) && this.Initializer.DoMatch(o.Initializer, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs index ca66a07961..d39e63048e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs @@ -65,7 +65,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - SwitchExpression o = other as SwitchExpression; + SwitchExpression? o = other as SwitchExpression; return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match); } } @@ -111,7 +111,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - SwitchExpressionSection o = other as SwitchExpressionSection; + SwitchExpressionSection? o = other as SwitchExpressionSection; return o != null && this.Pattern.DoMatch(o.Pattern, match) && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs index db61e2dade..0c42549ac7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs @@ -65,7 +65,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ThisReferenceExpression o = other as ThisReferenceExpression; + ThisReferenceExpression? o = other as ThisReferenceExpression; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs index 736d2da6d5..3aedc28e20 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs @@ -60,7 +60,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ThrowExpression o = other as ThrowExpression; + ThrowExpression? o = other as ThrowExpression; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs index b6605ab63d..b81517eb46 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs @@ -78,7 +78,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - TypeOfExpression o = other as TypeOfExpression; + TypeOfExpression? o = other as TypeOfExpression; return o != null && this.Type.DoMatch(o.Type, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs index 57c8ea9fa8..39f1b819c5 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs @@ -56,7 +56,7 @@ public TypeReferenceExpression(AstType type) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - TypeReferenceExpression o = other as TypeReferenceExpression; + TypeReferenceExpression? o = other as TypeReferenceExpression; return o != null && this.Type.DoMatch(o.Type, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs index 460f9a4217..7e80862684 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs @@ -89,7 +89,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UnaryOperatorExpression o = other as UnaryOperatorExpression; + UnaryOperatorExpression? o = other as UnaryOperatorExpression; return o != null && (this.Operator == UnaryOperatorType.Any || this.Operator == o.Operator) && this.Expression.DoMatch(o.Expression, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs index aa81601273..e21235b4cb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UncheckedExpression o = other as UncheckedExpression; + UncheckedExpression? o = other as UncheckedExpression; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs index 7de290d8d6..aa7e5af7bc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs @@ -97,7 +97,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UndocumentedExpression o = other as UndocumentedExpression; + UndocumentedExpression? o = other as UndocumentedExpression; return o != null && this.UndocumentedExpressionType == o.UndocumentedExpressionType && this.Arguments.DoMatch(o.Arguments, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs index 96aee3ee9a..4259d3d7d3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs @@ -74,7 +74,7 @@ protected internal override bool DoMatch(AstNode other, PatternMatching.Match ma && this.ReturnType.DoMatch(o.ReturnType, match); } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null) { throw new NotImplementedException(); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs index b07bca2b2c..901cbf7c96 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs @@ -79,7 +79,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - Attribute o = other as Attribute; + Attribute? o = other as Attribute; return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs index cf8658fe04..338e15a2c4 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs @@ -131,7 +131,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - AttributeSection o = other as AttributeSection; + AttributeSection? o = other as AttributeSection; return o != null && MatchString(this.AttributeTarget, o.AttributeTarget) && this.Attributes.DoMatch(o.Attributes, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs index b2a84f0ff4..b79956329f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs @@ -145,7 +145,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - Comment o = other as Comment; + Comment? o = other as Comment; return o != null && this.CommentType == o.CommentType && MatchString(this.Content, o.Content); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs index 4b0c18618c..aac00ed522 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - Constraint o = other as Constraint; + Constraint? o = other as Constraint; return o != null && this.TypeParameter.DoMatch(o.TypeParameter, match) && this.BaseTypes.DoMatch(o.BaseTypes, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs index 0d85f5a598..59803f5ca8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs @@ -82,7 +82,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - DelegateDeclaration o = other as DelegateDeclaration; + DelegateDeclaration? o = other as DelegateDeclaration; return o != null && MatchString(this.Name, o.Name) && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.TypeParameters.DoMatch(o.TypeParameters, match) && this.Parameters.DoMatch(o.Parameters, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs index b41e9f8823..72fbc1c287 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs @@ -77,7 +77,7 @@ static AstType ConstructType(string[] arr, int i) /// public string FullName { get { - NamespaceDeclaration parentNamespace = Parent as NamespaceDeclaration; + NamespaceDeclaration? parentNamespace = Parent as NamespaceDeclaration; if (parentNamespace != null) return BuildQualifiedName(parentNamespace.FullName, Name); return Name; @@ -152,7 +152,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - NamespaceDeclaration o = other as NamespaceDeclaration; + NamespaceDeclaration? o = other as NamespaceDeclaration; return o != null && MatchString(this.Name, o.Name) && this.Members.DoMatch(o.Members, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs index a1b175d1c0..767dbe1d23 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs @@ -62,7 +62,7 @@ public LinePreprocessorDirective(TextLocation startLocation, TextLocation endLoc { } - public LinePreprocessorDirective(string argument = null) : base(PreProcessorDirectiveType.Line, argument) + public LinePreprocessorDirective(string? argument = null) : base(PreProcessorDirectiveType.Line, argument) { } } @@ -115,7 +115,7 @@ public PragmaWarningPreprocessorDirective(TextLocation startLocation, TextLocati { } - public PragmaWarningPreprocessorDirective(string argument = null) : base(PreProcessorDirectiveType.Pragma, argument) + public PragmaWarningPreprocessorDirective(string? argument = null) : base(PreProcessorDirectiveType.Pragma, argument) { } @@ -172,7 +172,7 @@ public PreProcessorDirective(PreProcessorDirectiveType type, TextLocation startL this.endLocation = endLocation; } - public PreProcessorDirective(PreProcessorDirectiveType type, string argument = null) + public PreProcessorDirective(PreProcessorDirectiveType type, string? argument = null) { this.Type = type; this.Argument = argument; @@ -195,7 +195,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - PreProcessorDirective o = other as PreProcessorDirective; + PreProcessorDirective? o = other as PreProcessorDirective; return o != null && Type == o.Type && MatchString(Argument, o.Argument); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs index a60d12843a..19e0074d21 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs @@ -149,7 +149,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - TypeDeclaration o = other as TypeDeclaration; + TypeDeclaration? o = other as TypeDeclaration; return o != null && this.ClassType == o.ClassType && MatchString(this.Name, o.Name) && this.MatchAttributesAndModifiers(o, match) && this.TypeParameters.DoMatch(o.TypeParameters, match) && this.BaseTypes.DoMatch(o.BaseTypes, match) && this.Constraints.DoMatch(o.Constraints, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs index db5c622cfe..20cc0bd6eb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs @@ -106,7 +106,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - TypeParameterDeclaration o = other as TypeParameterDeclaration; + TypeParameterDeclaration? o = other as TypeParameterDeclaration; return o != null && this.Variance == o.Variance && MatchString(this.Name, o.Name) && this.Attributes.DoMatch(o.Attributes, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs index 1b3ab140fd..c0fc1c2b23 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs @@ -101,7 +101,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UsingAliasDeclaration o = other as UsingAliasDeclaration; + UsingAliasDeclaration? o = other as UsingAliasDeclaration; return o != null && MatchString(this.Alias, o.Alias) && this.Import.DoMatch(o.Import, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs index d7246003c5..a828b92399 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs @@ -117,7 +117,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UsingDeclaration o = other as UsingDeclaration; + UsingDeclaration? o = other as UsingDeclaration; return o != null && this.Import.DoMatch(o.Import, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs b/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs index a82a9d54f7..8256661a57 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs @@ -101,7 +101,7 @@ public abstract class AbstractAnnotatable : IAnnotatable /// protected void CloneAnnotations() { - ICloneable cloneable = annotations as ICloneable; + ICloneable? cloneable = annotations as ICloneable; if (cloneable != null) annotations = cloneable.Clone(); } @@ -123,7 +123,7 @@ public object Clone() for (int i = 0; i < this.Count; i++) { object obj = this[i]; - ICloneable c = obj as ICloneable; + ICloneable? c = obj as ICloneable; copy.Add(c != null ? c.Clone() : obj); } return copy; @@ -141,7 +141,7 @@ public virtual void AddAnnotation(object annotation) { return; // we successfully added a single annotation } - AnnotationList list = oldAnnotation as AnnotationList; + AnnotationList? list = oldAnnotation as AnnotationList; if (list == null) { // we need to transform the old annotation into a list @@ -168,7 +168,7 @@ public virtual void RemoveAnnotations() where T : class { retry: // Retry until successful object oldAnnotations = this.annotations; - AnnotationList list = oldAnnotations as AnnotationList; + AnnotationList? list = oldAnnotations as AnnotationList; if (list != null) { lock (list) @@ -190,7 +190,7 @@ public virtual void RemoveAnnotations(Type type) throw new ArgumentNullException(nameof(type)); retry: // Retry until successful object oldAnnotations = this.annotations; - AnnotationList list = oldAnnotations as AnnotationList; + AnnotationList? list = oldAnnotations as AnnotationList; if (list != null) { lock (list) @@ -209,14 +209,14 @@ public virtual void RemoveAnnotations(Type type) public T Annotation() where T : class { object annotations = this.annotations; - AnnotationList list = annotations as AnnotationList; + AnnotationList? list = annotations as AnnotationList; if (list != null) { lock (list) { foreach (object obj in list) { - T t = obj as T; + T? t = obj as T; if (t != null) return t; } @@ -234,7 +234,7 @@ public object Annotation(Type type) if (type == null) throw new ArgumentNullException(nameof(type)); object annotations = this.annotations; - AnnotationList list = annotations as AnnotationList; + AnnotationList? list = annotations as AnnotationList; if (list != null) { lock (list) @@ -260,7 +260,7 @@ public object Annotation(Type type) public IEnumerable Annotations { get { object annotations = this.annotations; - AnnotationList list = annotations as AnnotationList; + AnnotationList? list = annotations as AnnotationList; if (list != null) { lock (list) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs index 726c939fbd..64c1a008bb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs @@ -166,7 +166,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - Identifier o = other as Identifier; + Identifier? o = other as Identifier; return o != null && !o.IsNull && MatchString(this.Name, o.Name); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs b/ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs index 78ee9359de..2783e354b2 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs @@ -41,7 +41,7 @@ public IdentifierExpressionBackreference(string referencedGroupName) public override bool DoMatch(PatternMatching.INode other, PatternMatching.Match match) { - IdentifierExpression ident = other as IdentifierExpression; + IdentifierExpression? ident = other as IdentifierExpression; if (ident == null || ident.TypeArguments.Any()) return false; AstNode referenced = (AstNode)match.Get(referencedGroupName).Last(); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs index 5dddbfb562..99e529ba53 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs @@ -62,7 +62,7 @@ protected internal override bool DoMatch(AstNode other, Match match) && this.Arguments.DoMatch(o.Arguments, match); } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null) { throw new NotImplementedException(); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs index 00abace78c..74f02f5f3c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs @@ -114,21 +114,21 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - MemberType o = other as MemberType; + MemberType? o = other as MemberType; return o != null && this.IsDoubleColon == o.IsDoubleColon && MatchString(this.MemberName, o.MemberName) && this.Target.DoMatch(o.Target, match) && this.TypeArguments.DoMatch(o.TypeArguments, match); } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null) { if (interningProvider == null) interningProvider = InterningProvider.Dummy; - TypeOrNamespaceReference t; + TypeOrNamespaceReference? t; if (this.IsDoubleColon) { - SimpleType st = this.Target as SimpleType; + SimpleType? st = this.Target as SimpleType; if (st != null) { t = interningProvider.Intern(new AliasNamespaceReference(interningProvider.Intern(st.Identifier))); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNode.cs index 00b2107e21..7afa2a669f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNode.cs @@ -31,7 +31,7 @@ public string GroupName { get { return groupName; } } - public AnyNode(string groupName = null) + public AnyNode(string? groupName = null) { this.groupName = groupName; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNodeOrNull.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNodeOrNull.cs index 7ce94c72eb..7090a68ef8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNodeOrNull.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNodeOrNull.cs @@ -39,7 +39,7 @@ public string GroupName { get { return groupName; } } - public AnyNodeOrNull(string groupName = null) + public AnyNodeOrNull(string? groupName = null) { this.groupName = groupName; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs index a6f1125429..8fa3cf9437 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs @@ -102,7 +102,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - PrimitiveType o = other as PrimitiveType; + PrimitiveType? o = other as PrimitiveType; return o != null && MatchString(this.Keyword, o.Keyword); } @@ -111,7 +111,7 @@ public override string ToString(CSharpFormattingOptions formattingOptions) return Keyword; } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null) { KnownTypeCode typeCode = GetTypeCodeForPrimitiveType(this.Keyword); if (typeCode == KnownTypeCode.None) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs index 17a19e345b..df9808c930 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs @@ -143,11 +143,11 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - SimpleType o = other as SimpleType; + SimpleType? o = other as SimpleType; return o != null && MatchString(this.Identifier, o.Identifier) && this.TypeArguments.DoMatch(o.TypeArguments, match); } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null) { if (interningProvider == null) interningProvider = InterningProvider.Dummy; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs index 9965c7af98..1e2e9e8735 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs @@ -142,7 +142,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - BlockStatement o = other as BlockStatement; + BlockStatement? o = other as BlockStatement; return o != null && !o.IsNull && this.Statements.DoMatch(o.Statements, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs index df8732e818..cf3a735cd1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs @@ -59,7 +59,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - BreakStatement o = other as BreakStatement; + BreakStatement? o = other as BreakStatement; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs index c701dcfc51..728a73abfa 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs @@ -69,7 +69,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CheckedStatement o = other as CheckedStatement; + CheckedStatement? o = other as CheckedStatement; return o != null && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs index a4b8abacf4..23d674ce0c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs @@ -59,7 +59,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ContinueStatement o = other as ContinueStatement; + ContinueStatement? o = other as ContinueStatement; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs index ce05ff6b67..17aa604cb6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs @@ -82,7 +82,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - DoWhileStatement o = other as DoWhileStatement; + DoWhileStatement? o = other as DoWhileStatement; return o != null && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match) && this.Condition.DoMatch(o.Condition, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs index c76016963b..c0fd1919c1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs @@ -66,7 +66,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - EmptyStatement o = other as EmptyStatement; + EmptyStatement? o = other as EmptyStatement; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs index 5a4f2a413b..890a9fcd72 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs @@ -67,7 +67,7 @@ public ExpressionStatement(Expression expression) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ExpressionStatement o = other as ExpressionStatement; + ExpressionStatement? o = other as ExpressionStatement; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs index 3b34ea2fb9..1f62f6f4e6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - FixedStatement o = other as FixedStatement; + FixedStatement? o = other as FixedStatement; return o != null && this.Type.DoMatch(o.Type, match) && this.Variables.DoMatch(o.Variables, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs index 91784f0d49..6e63c87670 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs @@ -88,7 +88,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ForStatement o = other as ForStatement; + ForStatement? o = other as ForStatement; return o != null && this.Initializers.DoMatch(o.Initializers, match) && this.Condition.DoMatch(o.Condition, match) && this.Iterators.DoMatch(o.Iterators, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs index a01bc05de7..f46b6e2b02 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs @@ -98,7 +98,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ForeachStatement o = other as ForeachStatement; + ForeachStatement? o = other as ForeachStatement; return o != null && this.VariableType.DoMatch(o.VariableType, match) && this.VariableDesignation.DoMatch(o.VariableDesignation, match) && this.InExpression.DoMatch(o.InExpression, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs index b1b064c017..8f431d7d19 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs @@ -80,7 +80,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - GotoStatement o = other as GotoStatement; + GotoStatement? o = other as GotoStatement; return o != null && MatchString(this.Label, o.Label); } } @@ -130,7 +130,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - GotoCaseStatement o = other as GotoCaseStatement; + GotoCaseStatement? o = other as GotoCaseStatement; return o != null && this.LabelExpression.DoMatch(o.LabelExpression, match); } } @@ -172,7 +172,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - GotoDefaultStatement o = other as GotoDefaultStatement; + GotoDefaultStatement? o = other as GotoDefaultStatement; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs index fece09f10e..67e04b7cf5 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs @@ -86,7 +86,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - IfElseStatement o = other as IfElseStatement; + IfElseStatement? o = other as IfElseStatement; return o != null && this.Condition.DoMatch(o.Condition, match) && this.TrueStatement.DoMatch(o.TrueStatement, match) && this.FalseStatement.DoMatch(o.FalseStatement, match); } @@ -94,7 +94,7 @@ public IfElseStatement() { } - public IfElseStatement(Expression condition, Statement trueStatement, Statement falseStatement = null) + public IfElseStatement(Expression condition, Statement trueStatement, Statement? falseStatement = null) { this.Condition = condition; this.TrueStatement = trueStatement; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs index ca56ec4789..2c2302fc88 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs @@ -67,7 +67,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - LabelStatement o = other as LabelStatement; + LabelStatement? o = other as LabelStatement; return o != null && MatchString(this.Label, o.Label); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs index a8f25c579b..fb66fabab3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs @@ -73,7 +73,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - LockStatement o = other as LockStatement; + LockStatement? o = other as LockStatement; return o != null && this.Expression.DoMatch(o.Expression, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs index 75b96f4fe7..23da927ec9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs @@ -73,7 +73,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ReturnStatement o = other as ReturnStatement; + ReturnStatement? o = other as ReturnStatement; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs index a3412d1c85..d714c1a725 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs @@ -81,7 +81,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - SwitchStatement o = other as SwitchStatement; + SwitchStatement? o = other as SwitchStatement; return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match); } } @@ -167,7 +167,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - SwitchSection o = other as SwitchSection; + SwitchSection? o = other as SwitchSection; return o != null && this.CaseLabels.DoMatch(o.CaseLabels, match) && this.Statements.DoMatch(o.Statements, match); } } @@ -221,7 +221,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CaseLabel o = other as CaseLabel; + CaseLabel? o = other as CaseLabel; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs index a16d67a34d..14cd2f5f72 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs @@ -73,7 +73,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ThrowStatement o = other as ThrowStatement; + ThrowStatement? o = other as ThrowStatement; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs index f3ad325bcc..e61537b377 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - TryCatchStatement o = other as TryCatchStatement; + TryCatchStatement? o = other as TryCatchStatement; return o != null && this.TryBlock.DoMatch(o.TryBlock, match) && this.CatchClauses.DoMatch(o.CatchClauses, match) && this.FinallyBlock.DoMatch(o.FinallyBlock, match); } } @@ -253,7 +253,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CatchClause o = other as CatchClause; + CatchClause? o = other as CatchClause; return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.VariableName, o.VariableName) && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs index f24f7213ec..a74c3cb10e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs @@ -69,7 +69,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UncheckedStatement o = other as UncheckedStatement; + UncheckedStatement? o = other as UncheckedStatement; return o != null && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs index 1a977d5b9d..0c066b04bc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs @@ -60,7 +60,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UnsafeStatement o = other as UnsafeStatement; + UnsafeStatement? o = other as UnsafeStatement; return o != null && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs index 33bf9d8397..b4a910da34 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs @@ -89,7 +89,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - UsingStatement o = other as UsingStatement; + UsingStatement? o = other as UsingStatement; return o != null && this.IsAsync == o.IsAsync && this.ResourceAcquisition.DoMatch(o.ResourceAcquisition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs index 1a6066f176..3ac821ee78 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs @@ -35,7 +35,7 @@ public VariableDeclarationStatement() { } - public VariableDeclarationStatement(AstType type, string name, Expression initializer = null) + public VariableDeclarationStatement(AstType type, string name, Expression? initializer = null) { this.Type = type; this.Variables.Add(new VariableInitializer(name, initializer)); @@ -81,7 +81,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - VariableDeclarationStatement o = other as VariableDeclarationStatement; + VariableDeclarationStatement? o = other as VariableDeclarationStatement; return o != null && this.Modifiers == o.Modifiers && this.Type.DoMatch(o.Type, match) && this.Variables.DoMatch(o.Variables, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs index 3e852e35d9..1d198abe44 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs @@ -73,7 +73,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - WhileStatement o = other as WhileStatement; + WhileStatement? o = other as WhileStatement; return o != null && this.Condition.DoMatch(o.Condition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs index 4a777afa9b..9dcc362f37 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs @@ -64,7 +64,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - YieldBreakStatement o = other as YieldBreakStatement; + YieldBreakStatement? o = other as YieldBreakStatement; return o != null; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs index 235201ab26..a9c66d7560 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs @@ -69,7 +69,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - YieldReturnStatement o = other as YieldReturnStatement; + YieldReturnStatement? o = other as YieldReturnStatement; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs index 92e3bb63dc..35d9e2a84e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs @@ -58,7 +58,7 @@ public AstNodeCollection Members { get { return GetChildrenByRole(MemberRole); } } - IList conditionalSymbols = null; + IList? conditionalSymbols = null; /// /// Gets the conditional symbols used to parse the source file. Note that this list contains @@ -119,7 +119,7 @@ public IEnumerable GetTypes(bool includeInnerTypes = false) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - SyntaxTree o = other as SyntaxTree; + SyntaxTree? o = other as SyntaxTree; return o != null && this.Members.DoMatch(o.Members, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs index 16f5cd4aac..69b6c7fc2a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs @@ -49,7 +49,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitTupleType(this, data); } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider = null) { return new TupleTypeReference( this.Elements.Select(e => e.Type.ToTypeReference(lookupMode, interningProvider)).ToImmutableArray(), diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs index def135ba95..c5f628442f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs @@ -111,7 +111,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - Accessor o = other as Accessor; + Accessor? o = other as Accessor; return o != null && !o.IsNull && this.MatchAttributesAndModifiers(o, match) && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs index 890b770881..631027602d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs @@ -79,7 +79,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ConstructorDeclaration o = other as ConstructorDeclaration; + ConstructorDeclaration? o = other as ConstructorDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.Parameters.DoMatch(o.Parameters, match) && this.Initializer.DoMatch(o.Initializer, match) && this.Body.DoMatch(o.Body, match); } @@ -182,7 +182,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - ConstructorInitializer o = other as ConstructorInitializer; + ConstructorInitializer? o = other as ConstructorInitializer; return o != null && !o.IsNull && (this.ConstructorInitializerType == ConstructorInitializerType.Any || this.ConstructorInitializerType == o.ConstructorInitializerType) && this.Arguments.DoMatch(o.Arguments, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs index 5039831ee2..648874d600 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs @@ -69,7 +69,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - DestructorDeclaration o = other as DestructorDeclaration; + DestructorDeclaration? o = other as DestructorDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.Body.DoMatch(o.Body, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs index cbf983454c..f6392f9ed4 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs @@ -62,7 +62,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - EnumMemberDeclaration o = other as EnumMemberDeclaration; + EnumMemberDeclaration? o = other as EnumMemberDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs index 1abb7c739f..85c773affa 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs @@ -78,7 +78,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - EventDeclaration o = other as EventDeclaration; + EventDeclaration? o = other as EventDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.Variables.DoMatch(o.Variables, match); } @@ -141,7 +141,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - CustomEventDeclaration o = other as CustomEventDeclaration; + CustomEventDeclaration? o = other as CustomEventDeclaration; return o != null && MatchString(this.Name, o.Name) && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs index 548b0333e3..6bcf686262 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs @@ -72,7 +72,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - FieldDeclaration o = other as FieldDeclaration; + FieldDeclaration? o = other as FieldDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.Variables.DoMatch(o.Variables, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs index 56c6023009..97e61cea58 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs @@ -42,7 +42,7 @@ public FixedVariableInitializer() { } - public FixedVariableInitializer(string name, Expression initializer = null) + public FixedVariableInitializer(string name, Expression? initializer = null) { this.Name = name; this.CountExpression = initializer; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs index bad5ce81bd..fcbfb87133 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs @@ -118,7 +118,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - IndexerDeclaration o = other as IndexerDeclaration; + IndexerDeclaration? o = other as IndexerDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs index d01822868f..07217b17eb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs @@ -92,7 +92,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - MethodDeclaration o = other as MethodDeclaration; + MethodDeclaration? o = other as MethodDeclaration; return o != null && MatchString(this.Name, o.Name) && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs index 9ffc9058bf..3f9f96b92f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs @@ -355,7 +355,7 @@ public override Identifier NameToken { protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - OperatorDeclaration o = other as OperatorDeclaration; + OperatorDeclaration? o = other as OperatorDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match) && this.OperatorType == o.OperatorType diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs index f7fd874340..879fae19ec 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs @@ -99,7 +99,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - PropertyDeclaration o = other as PropertyDeclaration; + PropertyDeclaration? o = other as PropertyDeclaration; return o != null && MatchString(this.Name, o.Name) && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs index d5b74faa87..77eea3886f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs @@ -118,7 +118,7 @@ public VariableInitializer() { } - public VariableInitializer(string name, Expression initializer = null) + public VariableInitializer(string name, Expression? initializer = null) { this.Name = name; this.Initializer = initializer; @@ -168,7 +168,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { - VariableInitializer o = other as VariableInitializer; + VariableInitializer? o = other as VariableInitializer; return o != null && MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs index c269983037..97c0e72292 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs @@ -509,7 +509,7 @@ AstType ConvertTypeHelper(IType genericType, IReadOnlyList typeArguments) localTypeArguments = Empty.Array; } ResolveResult rr = resolver.LookupSimpleNameOrTypeName(typeDef.Name, localTypeArguments, NameLookupMode); - TypeResolveResult trr = rr as TypeResolveResult; + TypeResolveResult? trr = rr as TypeResolveResult; if (trr != null || (localTypeArguments.Length == 0 && resolver.IsVariableReferenceWithSameType(rr, typeDef.Name, out trr))) { if (!trr.IsError && TypeMatches(trr.Type, typeDef, typeArguments)) @@ -567,7 +567,7 @@ bool TypeMatches(IType type, ITypeDefinition typeDef, IReadOnlyList typeA { if (!TypeDefMatches(typeDef, type.GetDefinition())) return false; - ParameterizedType pt = type as ParameterizedType; + ParameterizedType? pt = type as ParameterizedType; if (pt == null) { return typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument); @@ -623,7 +623,7 @@ public AstType ConvertNamespace(string namespaceName, out NamespaceResolveResult return ConvertNamespace(namespaceName, out nrr, requiresGlobalPrefix: false); } - AstType ConvertNamespace(string namespaceName, out NamespaceResolveResult nrr, bool requiresGlobalPrefix) + AstType ConvertNamespace(string namespaceName, out NamespaceResolveResult? nrr, bool requiresGlobalPrefix) { if (resolver != null) { @@ -707,7 +707,7 @@ AstType ConvertNamespace(string namespaceName, out NamespaceResolveResult nrr, b } } - bool IsValidNamespace(string firstNamespacePart, out NamespaceResolveResult nrr) + bool IsValidNamespace(string firstNamespacePart, out NamespaceResolveResult? nrr) { nrr = null; if (resolver == null) @@ -813,7 +813,7 @@ public AstType ConvertAttributeType(IType type) throw new ArgumentNullException(nameof(type)); AstType astType = ConvertTypeHelper(type); - string shortName = null; + string? shortName = null; if (type.Name.Length > 9 && type.Name.EndsWith("Attribute", StringComparison.Ordinal)) { shortName = type.Name.Remove(type.Name.Length - 9); @@ -844,7 +844,7 @@ private void ApplyShortAttributeNameIfPossible(IType type, AstType astType, stri switch (astType) { case SimpleType st: - ResolveResult shortRR = null; + ResolveResult? shortRR = null; ResolveResult withExtraAttrSuffix = resolver.LookupSimpleNameOrTypeName(type.Name + "Attribute", EmptyList.Instance, NameLookupMode.Type); if (shortName != null) { @@ -1081,7 +1081,7 @@ public Expression ConvertConstantValue(IType expectedType, IType type, object co } } - bool IsSpecialConstant(IType expectedType, object constant, out Expression expression) + bool IsSpecialConstant(IType expectedType, object constant, out Expression? expression) { expression = null; if (!specialConstants.TryGetValue(constant, out var info)) @@ -1231,7 +1231,7 @@ Expression ConvertEnumValue(IType type, long val) if (IsFlagsEnum(enumDefinition)) { long enumValue = val; - Expression expr = null; + Expression? expr = null; long negatedEnumValue = ~val; // limit negatedEnumValue to the appropriate range switch (enumBaseTypeCode) @@ -1249,7 +1249,7 @@ Expression ConvertEnumValue(IType type, long val) negatedEnumValue &= uint.MaxValue; break; } - Expression negatedExpr = null; + Expression? negatedExpr = null; foreach (var (fieldValue, field) in fields.OrderByDescending(f => CalculateHammingWeight(unchecked((ulong)f.value)))) { if (fieldValue == 0) @@ -1363,7 +1363,7 @@ Expression ConvertFloatingPointLiteral(IType type, object constantValue) constantValue = CSharpPrimitiveCast.Cast(type.GetTypeCode(), constantValue, false); bool isDouble = type.IsKnownType(KnownTypeCode.Double); ICompilation compilation = type.GetDefinition().Compilation; - Expression expr = null; + Expression? expr = null; string str; if (isDouble) @@ -1698,7 +1698,7 @@ public AstNode ConvertSymbol(ISymbol symbol) case SymbolKind.TypeParameter: return ConvertTypeParameter((ITypeParameter)symbol); default: - IEntity entity = symbol as IEntity; + IEntity? entity = symbol as IEntity; if (entity != null) return ConvertEntity(entity); throw new ArgumentException("Invalid value for SymbolKind: " + symbol.SymbolKind); @@ -1970,7 +1970,7 @@ FieldDeclaration ConvertField(IField field) { ct.HasReadOnlySpecifier = true; } - Expression initializer = null; + Expression? initializer = null; if (field.IsConst && this.ShowConstantValues) { try @@ -2470,7 +2470,7 @@ public VariableDeclarationStatement ConvertVariable(IVariable v) VariableDeclarationStatement decl = new VariableDeclarationStatement(); decl.Modifiers = v.IsConst ? Modifiers.Const : Modifiers.None; decl.Type = ConvertType(v.Type); - Expression initializer = null; + Expression? initializer = null; if (v.IsConst) { try diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs b/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs index 7ffaf24e49..8cf6280758 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs @@ -241,7 +241,7 @@ class Result public void Run(AstNode node, TransformContext context) { - BlockStatement block = node as BlockStatement; + BlockStatement? block = node as BlockStatement; if (block == null) { for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) @@ -262,18 +262,18 @@ Result GetResultFromBlock(BlockStatement block) // For a block, we are tracking 4 possibilities: // a) context is checked, no unchecked block open Cost costCheckedContext = new Cost(0, 0); - InsertedNode nodesCheckedContext = null; + InsertedNode? nodesCheckedContext = null; // b) context is checked, an unchecked block is open Cost costCheckedContextUncheckedBlockOpen = Cost.Infinite; - InsertedNode nodesCheckedContextUncheckedBlockOpen = null; - Statement uncheckedBlockStart = null; + InsertedNode? nodesCheckedContextUncheckedBlockOpen = null; + Statement? uncheckedBlockStart = null; // c) context is unchecked, no checked block open Cost costUncheckedContext = new Cost(0, 0); - InsertedNode nodesUncheckedContext = null; + InsertedNode? nodesUncheckedContext = null; // d) context is unchecked, a checked block is open Cost costUncheckedContextCheckedBlockOpen = Cost.Infinite; - InsertedNode nodesUncheckedContextCheckedBlockOpen = null; - Statement checkedBlockStart = null; + InsertedNode? nodesUncheckedContextCheckedBlockOpen = null; + Statement? checkedBlockStart = null; Statement statement = block.Statements.FirstOrDefault(); while (true) @@ -348,7 +348,7 @@ Result GetResult(AstNode node) result.CostInUncheckedContext += childResult.CostInUncheckedContext; result.NodesToInsertInUncheckedContext += childResult.NodesToInsertInUncheckedContext; } - Expression expr = node as Expression; + Expression? expr = node as Expression; if (expr != null) { CheckedUncheckedAnnotation annotation = expr.Annotation(); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs index ad92d1a276..1d9002811c 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs @@ -54,11 +54,11 @@ void CombineQueries(AstNode node, Dictionary fromOrLetIdentifier next = child.NextSibling; CombineQueries(child, fromOrLetIdentifiers); } - QueryExpression query = node as QueryExpression; + QueryExpression? query = node as QueryExpression; if (query != null) { QueryFromClause fromClause = (QueryFromClause)query.Clauses.First(); - QueryExpression innerQuery = fromClause.Expression as QueryExpression; + QueryExpression? innerQuery = fromClause.Expression as QueryExpression; if (innerQuery != null) { if (TryRemoveTransparentIdentifier(query, fromClause, innerQuery, fromOrLetIdentifiers)) @@ -107,7 +107,7 @@ bool TryRemoveTransparentIdentifier(QueryExpression query, QueryFromClause fromC { if (!CSharpDecompiler.IsTransparentIdentifier(fromClause.Identifier)) return false; - QuerySelectClause selectClause = innerQuery.Clauses.Last() as QuerySelectClause; + QuerySelectClause? selectClause = innerQuery.Clauses.Last() as QuerySelectClause; Match match = selectTransparentIdentifierPattern.Match(selectClause); if (!match.Success) return false; @@ -118,7 +118,7 @@ bool TryRemoveTransparentIdentifier(QueryExpression query, QueryFromClause fromC fromClause.Remove(); selectClause.Remove(); // Move clauses from innerQuery to query - QueryClause insertionPos = null; + QueryClause? insertionPos = null; foreach (var clause in innerQuery.Clauses) { query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach()); @@ -165,10 +165,10 @@ void RemoveTransparentIdentifierReferences(AstNode node, Dictionary() != null && ie.Arguments.Count == 1) { return childNode.DoMatch(ie.Arguments.Single(), match); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs index c84d9e81a5..787b97d996 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs @@ -284,7 +284,7 @@ private static bool IsValidInStatementExpression(Expression expr) /// void FindInsertionPoints(AstNode node, int nodeLevel) { - BlockContainer scope = node.Annotation(); + BlockContainer? scope = node.Annotation(); if (scope != null && IsRelevantScope(scope)) { // track loops and function bodies as scopes, for comparison with CaptureScope. @@ -657,7 +657,7 @@ void InsertVariableDeclarations(TransformContext context) else { // Insert a separate declaration statement. - Expression initializer = null; + Expression? initializer = null; AstType type = context.TypeSystemAstBuilder.ConvertType(v.Type); if (v.DefaultInitialization == VariableInitKind.NeedsDefaultValue) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceExtensionMethods.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceExtensionMethods.cs index 7540446667..976262ef3e 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceExtensionMethods.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceExtensionMethods.cs @@ -147,9 +147,9 @@ public override void VisitInvocationExpression(InvocationExpression invocationEx } static bool CanTransformToExtensionMethodCall(CSharpResolver resolver, - InvocationExpression invocationExpression, out MemberReferenceExpression memberRefExpr, - out ResolveResult target, - out Expression firstArgument) + InvocationExpression invocationExpression, out MemberReferenceExpression? memberRefExpr, + out ResolveResult? target, + out Expression? firstArgument) { var method = invocationExpression.GetSymbol() as IMethod; memberRefExpr = null; @@ -186,7 +186,7 @@ static bool CanTransformToExtensionMethodCall(CSharpResolver resolver, } Debug.Assert(target != null); ResolveResult[] args = new ResolveResult[invocationExpression.Arguments.Count - 1]; - string[] argNames = null; + string[]? argNames = null; int pos = 0; foreach (var arg in invocationExpression.Arguments.Skip(1)) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs index 8e5e55368b..04455f5f3c 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs @@ -50,7 +50,7 @@ public void Run(AstNode rootNode, TransformContext context) } // See if the data source of this query is a degenerate query, // and combine the queries if possible. - QueryExpression innerQuery = fromClause.Expression as QueryExpression; + QueryExpression? innerQuery = fromClause.Expression as QueryExpression; while (IsDegenerateQuery(innerQuery)) { QueryFromClause innerFromClause = (QueryFromClause)innerQuery.Clauses.First(); @@ -58,7 +58,7 @@ public void Run(AstNode rootNode, TransformContext context) break; // Replace the fromClause with all clauses from the inner query fromClause.Remove(); - QueryClause insertionPos = null; + QueryClause? insertionPos = null; foreach (var clause in innerQuery.Clauses) { query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach()); @@ -106,7 +106,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) { if (invocation == null) return null; - MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression; + MemberReferenceExpression? mre = invocation.Target as MemberReferenceExpression; if (mre == null || IsNullConditional(mre.Target)) return null; switch (mre.MemberName) @@ -170,7 +170,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) return null; if (IsNullConditional(collectionSelector)) return null; - LambdaExpression lambda = invocation.Arguments.ElementAt(1) as LambdaExpression; + LambdaExpression? lambda = invocation.Arguments.ElementAt(1) as LambdaExpression; if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) { ParameterDeclaration p1 = lambda.Parameters.ElementAt(0); @@ -261,7 +261,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) Expression innerLambda = invocation.Arguments.ElementAt(2); if (!MatchSimpleLambda(innerLambda, out ParameterDeclaration element2, out Expression key2)) return null; - LambdaExpression lambda = invocation.Arguments.ElementAt(3) as LambdaExpression; + LambdaExpression? lambda = invocation.Arguments.ElementAt(3) as LambdaExpression; if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) { ParameterDeclaration p1 = lambda.Parameters.ElementAt(0); @@ -370,7 +370,7 @@ bool ValidateThenByChain(InvocationExpression invocation, string expectedParamet } /// Matches simple lambdas of the form "a => b" - bool MatchSimpleLambda(Expression expr, out ParameterDeclaration parameter, out Expression body) + bool MatchSimpleLambda(Expression expr, out ParameterDeclaration? parameter, out Expression? body) { if (expr is LambdaExpression lambda && lambda.Parameters.Count == 1 && lambda.Body is Expression) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs index 40ba71aca3..0688e9c49a 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs @@ -116,7 +116,7 @@ public override bool VisitUnaryOperatorExpression(UnaryOperatorExpression unaryO public override bool VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression) { bool result = base.VisitMemberReferenceExpression(memberReferenceExpression); - UnaryOperatorExpression uoe = memberReferenceExpression.Target as UnaryOperatorExpression; + UnaryOperatorExpression? uoe = memberReferenceExpression.Target as UnaryOperatorExpression; if (uoe != null && uoe.Operator == UnaryOperatorType.Dereference) { PointerReferenceExpression pre = new PointerReferenceExpression(); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUsingDeclarations.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUsingDeclarations.cs index 1b4523399b..6c2c4ed45f 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUsingDeclarations.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUsingDeclarations.cs @@ -205,7 +205,7 @@ public FullyQualifyAmbiguousTypeNamesVisitor(TransformContext context, UsingScop this.astBuilder = CreateAstBuilder(currentContext); } - TypeSystemAstBuilder CreateAstBuilder(CSharpTypeResolveContext context, IL.ILFunction function = null) + TypeSystemAstBuilder CreateAstBuilder(CSharpTypeResolveContext context, IL.ILFunction? function = null) { CSharpResolver resolver = new CSharpResolver(context); if (function != null) diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs index 3605d968d7..2d1d28376a 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs @@ -431,7 +431,7 @@ Statement TransformForeachOnArray(ForStatement forStatement) ) ))); - bool MatchLowerBound(int indexNum, out IL.ILVariable index, IL.ILVariable collection, Statement statement) + bool MatchLowerBound(int indexNum, out IL.ILVariable? index, IL.ILVariable collection, Statement statement) { index = null; var m = variableAssignLowerBoundPattern.Match(statement); @@ -443,7 +443,7 @@ bool MatchLowerBound(int indexNum, out IL.ILVariable index, IL.ILVariable collec return m.Get("collection").Single().GetILVariable() == collection; } - bool MatchForeachOnMultiDimArray(IL.ILVariable[] upperBounds, IL.ILVariable collection, Statement firstInitializerStatement, out IdentifierExpression foreachVariable, out IList statements, out IL.ILVariable[] lowerBounds) + bool MatchForeachOnMultiDimArray(IL.ILVariable[] upperBounds, IL.ILVariable collection, Statement firstInitializerStatement, out IdentifierExpression? foreachVariable, out IList? statements, out IL.ILVariable[] lowerBounds) { int i = 0; foreachVariable = null; @@ -482,8 +482,8 @@ Statement TransformForeachOnMultiDimArray(ExpressionStatement expressionStatemen return null; Match m; Statement stmt = expressionStatement; - IL.ILVariable collection = null; - IL.ILVariable[] upperBounds = null; + IL.ILVariable? collection = null; + IL.ILVariable[]? upperBounds = null; List statementsToDelete = new List(); int i = 0; // first we look for all the upper bound initializations @@ -610,10 +610,10 @@ bool CanTransformToAutomaticProperty(IProperty property, bool accessorsMustBeCom PropertyDeclaration TransformAutomaticProperty(PropertyDeclaration propertyDeclaration) { - IProperty property = propertyDeclaration.GetSymbol() as IProperty; + IProperty? property = propertyDeclaration.GetSymbol() as IProperty; if (!CanTransformToAutomaticProperty(property, !property.DeclaringTypeDefinition.Fields.Any(f => f.Name == "_" + property.Name && f.IsCompilerGenerated()))) return null; - IField field = null; + IField? field = null; Match m = automaticPropertyPattern.Match(propertyDeclaration); if (m.Success) { @@ -702,7 +702,7 @@ public override AstNode VisitIdentifier(Identifier identifier) return base.VisitIdentifier(identifier); } - internal static bool IsBackingFieldOfAutomaticProperty(IField field, out IProperty property) + internal static bool IsBackingFieldOfAutomaticProperty(IField field, out IProperty? property) { property = null; if (!NameCouldBeBackingFieldOfAutomaticProperty(field.Name, out string propertyName)) @@ -725,7 +725,7 @@ internal static bool IsBackingFieldOfAutomaticProperty(IField field, out IProper static readonly System.Text.RegularExpressions.Regex automaticPropertyBackingFieldNameRegex = new System.Text.RegularExpressions.Regex(@"^(<(?.+)>k__BackingField|_(?.+))$"); - static bool NameCouldBeBackingFieldOfAutomaticProperty(string name, out string propertyName) + static bool NameCouldBeBackingFieldOfAutomaticProperty(string name, out string? propertyName) { propertyName = null; var m = automaticPropertyBackingFieldNameRegex.Match(name); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs index ae490e1d78..ff1ed9e3ee 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs @@ -48,7 +48,7 @@ public override void VisitAssignmentExpression(AssignmentExpression assignment) // Also supports "x = (T)(x op y)" -> "x op= y", if x.GetType() == T // and y is implicitly convertible to T. Expression rhs = assignment.Right; - IType expectedType = null; + IType? expectedType = null; if (assignment.Right is CastExpression { Type: var astType } cast) { rhs = cast.Expression; @@ -132,13 +132,13 @@ public static AssignmentOperatorType GetAssignmentOperatorForBinaryOperator(Bina static bool CanConvertToCompoundAssignment(Expression left) { - MemberReferenceExpression mre = left as MemberReferenceExpression; + MemberReferenceExpression? mre = left as MemberReferenceExpression; if (mre != null) return IsWithoutSideEffects(mre.Target); - IndexerExpression ie = left as IndexerExpression; + IndexerExpression? ie = left as IndexerExpression; if (ie != null) return IsWithoutSideEffects(ie.Target) && ie.Arguments.All(IsWithoutSideEffects); - UnaryOperatorExpression uoe = left as UnaryOperatorExpression; + UnaryOperatorExpression? uoe = left as UnaryOperatorExpression; if (uoe != null && uoe.Operator == UnaryOperatorType.Dereference) return IsWithoutSideEffects(uoe.Expression); return IsWithoutSideEffects(left); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs b/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs index 36624535b5..c1181a5621 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs @@ -495,7 +495,7 @@ public override void VisitCastExpression(CastExpression castExpression) Match m = getMethodOrConstructorFromHandlePattern.Match(castExpression); if (m.Success) { - IMethod method = m.Get("method").Single().GetSymbol() as IMethod; + IMethod? method = m.Get("method").Single().GetSymbol() as IMethod; if (m.Has("declaringType") && method != null) { Expression newNode = new MemberReferenceExpression(new TypeReferenceExpression(m.Get("declaringType").Single().Detach()), method.Name); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs index 8bcf924fa8..219f671ca2 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs @@ -66,7 +66,7 @@ public void Run(AstNode node, TransformContext context) public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) { var currentCtor = (IMethod)constructorDeclaration.GetSymbol(); - ConstructorInitializer ci = null; + ConstructorInitializer? ci = null; if (constructorDeclaration.Body.Statements.FirstOrDefault() is ExpressionStatement stmt) { switch (stmt.Expression) @@ -330,7 +330,7 @@ void HandleStaticFieldInitializers(IEnumerable members) if (staticCtor != null) { bool ctorIsUnsafe = staticCtor.HasModifier(Modifiers.Unsafe); - IMethod ctorMethod = staticCtor.GetSymbol() as IMethod; + IMethod? ctorMethod = staticCtor.GetSymbol() as IMethod; if (!ctorMethod.MetadataToken.IsNil) { var metadata = context.TypeSystem.MainModule.MetadataFile.Metadata; @@ -340,10 +340,10 @@ void HandleStaticFieldInitializers(IEnumerable members) int pos = 0; while (pos < staticCtor.Body.Statements.Count) { - ExpressionStatement es = staticCtor.Body.Statements.ElementAtOrDefault(pos) as ExpressionStatement; + ExpressionStatement? es = staticCtor.Body.Statements.ElementAtOrDefault(pos) as ExpressionStatement; if (es == null) break; - AssignmentExpression assignment = es.Expression as AssignmentExpression; + AssignmentExpression? assignment = es.Expression as AssignmentExpression; if (assignment == null || assignment.Operator != AssignmentOperatorType.Assign) break; IMember fieldOrProperty = (assignment.Left.GetSymbol() as IMember)?.MemberDefinition; diff --git a/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs b/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs index ad864b5acd..680dbd88c2 100644 --- a/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs @@ -664,7 +664,7 @@ TranslatedExpression LdcI4(ICompilation compilation, int val) /// In conditional contexts, remove the bool-cast emitted when converting /// an "implicit operator bool" invocation. /// - public TranslatedExpression UnwrapImplicitBoolConversion(Func typeFilter = null) + public TranslatedExpression UnwrapImplicitBoolConversion(Func? typeFilter = null) { if (!this.Type.IsKnownType(KnownTypeCode.Boolean)) return this; diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs index 1bb991deef..ab3d55d794 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs @@ -70,7 +70,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - AliasNamespaceReference anr = other as AliasNamespaceReference; + AliasNamespaceReference? anr = other as AliasNamespaceReference; return anr != null && this.identifier == anr.identifier; } } diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs index 986ee10207..9f8d94406c 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs @@ -30,7 +30,7 @@ public sealed class CSharpTypeResolveContext : ITypeResolveContext readonly IMember currentMember; readonly string[] methodTypeParameterNames; - public CSharpTypeResolveContext(IModule module, ResolvedUsingScope usingScope = null, ITypeDefinition typeDefinition = null, IMember member = null) + public CSharpTypeResolveContext(IModule module, ResolvedUsingScope? usingScope = null, ITypeDefinition? typeDefinition = null, IMember? member = null) { if (module == null) throw new ArgumentNullException(nameof(module)); diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs index 4418f9cd34..c1e4acd840 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs @@ -86,7 +86,7 @@ public override ResolveResult Resolve(CSharpResolver resolver) public override IType ResolveType(CSharpResolver resolver) { - TypeResolveResult trr = Resolve(resolver) as TypeResolveResult; + TypeResolveResult? trr = Resolve(resolver) as TypeResolveResult; return trr != null ? trr.Type : new UnknownType(null, identifier, typeArguments.Count); } @@ -113,7 +113,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - MemberTypeOrNamespaceReference o = other as MemberTypeOrNamespaceReference; + MemberTypeOrNamespaceReference? o = other as MemberTypeOrNamespaceReference; return o != null && this.target == o.target && this.identifier == o.identifier && this.typeArguments == o.typeArguments && this.lookupMode == o.lookupMode; diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs index ded6bccbc0..0367c6c2db 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs @@ -75,7 +75,7 @@ public override ResolveResult Resolve(CSharpResolver resolver) public override IType ResolveType(CSharpResolver resolver) { - TypeResolveResult trr = Resolve(resolver) as TypeResolveResult; + TypeResolveResult? trr = Resolve(resolver) as TypeResolveResult; return trr != null ? trr.Type : new UnknownType(null, identifier, typeArguments.Count); } @@ -101,7 +101,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - SimpleTypeOrNamespaceReference o = other as SimpleTypeOrNamespaceReference; + SimpleTypeOrNamespaceReference? o = other as SimpleTypeOrNamespaceReference; return o != null && this.identifier == o.identifier && this.typeArguments == o.typeArguments && this.lookupMode == o.lookupMode; } diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs index c9ed00c328..aa69222f3f 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs @@ -45,7 +45,7 @@ public abstract class TypeOrNamespaceReference : ITypeReference /// public INamespace ResolveNamespace(CSharpResolver resolver) { - NamespaceResolveResult nrr = Resolve(resolver) as NamespaceResolveResult; + NamespaceResolveResult? nrr = Resolve(resolver) as NamespaceResolveResult; return nrr != null ? nrr.Namespace : null; } diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs index 05ef4e6eb1..684d155735 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs @@ -155,7 +155,7 @@ public bool HasAlias(string identifier) public ResolvedUsingScope Resolve(ICompilation compilation) { CacheManager cache = compilation.CacheManager; - ResolvedUsingScope resolved = cache.GetShared(this) as ResolvedUsingScope; + ResolvedUsingScope? resolved = cache.GetShared(this) as ResolvedUsingScope; if (resolved == null) { var csContext = new CSharpTypeResolveContext(compilation.MainModule, parent != null ? parent.Resolve(compilation) : null); diff --git a/ICSharpCode.Decompiler/DebugInfo/PortablePdbWriter.cs b/ICSharpCode.Decompiler/DebugInfo/PortablePdbWriter.cs index 3779ace159..dcc20f6322 100644 --- a/ICSharpCode.Decompiler/DebugInfo/PortablePdbWriter.cs +++ b/ICSharpCode.Decompiler/DebugInfo/PortablePdbWriter.cs @@ -72,7 +72,7 @@ public static void WritePdb( Stream targetStream, bool noLogo = false, BlobContentId? pdbId = null, - IProgress progress = null) + IProgress? progress = null) { MetadataBuilder metadata = new MetadataBuilder(); MetadataReader reader = file.Metadata; @@ -249,7 +249,7 @@ void ProcessMethod(MethodDefinitionHandle method, DocumentHandle document, { var methodDef = reader.GetMethodDefinition(method); int localSignatureRowId; - MethodBodyBlock methodBody; + MethodBodyBlock? methodBody; if (methodDef.RelativeVirtualAddress != 0) { methodBody = file.Reader.GetMethodBody(methodDef.RelativeVirtualAddress); diff --git a/ICSharpCode.Decompiler/DecompilerException.cs b/ICSharpCode.Decompiler/DecompilerException.cs index b32563526d..d536148b4f 100644 --- a/ICSharpCode.Decompiler/DecompilerException.cs +++ b/ICSharpCode.Decompiler/DecompilerException.cs @@ -45,7 +45,7 @@ public class DecompilerException : Exception, ISerializable public MetadataFile File { get; } public DecompilerException(MetadataModule module, IEntity decompiledEntity, - Exception innerException, string message = null) + Exception innerException, string? message = null) : base(message ?? GetDefaultMessage(decompiledEntity), innerException) { this.File = module.MetadataFile; @@ -170,7 +170,7 @@ static string GetStackTrace(Exception exception) // source location if (frame.GetILOffset() >= 0) { - string filename = null; + string? filename = null; try { string fullpath = frame.GetFileName(); diff --git a/ICSharpCode.Decompiler/DecompilerSettings.cs b/ICSharpCode.Decompiler/DecompilerSettings.cs index 773128bc82..97e87da107 100644 --- a/ICSharpCode.Decompiler/DecompilerSettings.cs +++ b/ICSharpCode.Decompiler/DecompilerSettings.cs @@ -2175,7 +2175,7 @@ public CSharpFormattingOptions CSharpFormattingOptions { public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) { if (PropertyChanged != null) { diff --git a/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs b/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs index a1d4cc7436..3f3aea4e5a 100644 --- a/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs +++ b/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs @@ -96,7 +96,7 @@ public static void WriteTo(this ExceptionRegion exceptionHandler, MetadataFile m static string ToInvariantCultureString(object value) { - IConvertible convertible = value as IConvertible; + IConvertible? convertible = value as IConvertible; return (null != convertible) ? convertible.ToString(System.Globalization.CultureInfo.InvariantCulture) : value.ToString(); @@ -189,7 +189,7 @@ public static void WriteOperand(ITextOutput writer, object operand) if (operand == null) throw new ArgumentNullException(nameof(operand)); - string s = operand as string; + string? s = operand as string; if (s != null) { WriteOperand(writer, s); diff --git a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs index fbd386d4f0..fbbd5e6dd2 100644 --- a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs @@ -440,7 +440,7 @@ protected virtual void WriteInstruction(ITextOutput output, MetadataFile metadat metadataToken = blob.ReadInt32(); output.Write(' '); UserStringHandle? userString; - string text; + string? text; try { userString = MetadataTokens.UserStringHandle(metadataToken); diff --git a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs index 11c8bdb9a0..9815de4d60 100644 --- a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs @@ -322,7 +322,7 @@ internal static void WriteMetadataToken(ITextOutput output, MetadataFile module, output.Write(' '); } output.Write("/* "); - string format = base10 ? null : "X8"; + string? format = base10 ? null : "X8"; if (handle == null || !handle.Value.IsEntityHandle()) { output.Write(metadataToken.ToString(format)); @@ -539,7 +539,7 @@ public bool IsSystemType((PrimitiveTypeCode, string) type) { string[] nameParts = typeName.Split(new[] { ", " }, 2, StringSplitOptions.None); string[] typeNameParts = nameParts[0].Split('.'); - MetadataFile containingModule = null; + MetadataFile? containingModule = null; TypeDefinitionHandle typeDefHandle = default; // if we deal with an assembly-qualified name, resolve the assembly if (nameParts.Length == 2) @@ -620,7 +620,7 @@ PrimitiveTypeCode ResolveEnumUnderlyingType(string typeName, PEFile module) MetadataFile mscorlib; - bool TryResolveMscorlib(out MetadataFile mscorlib) + bool TryResolveMscorlib(out MetadataFile? mscorlib) { mscorlib = null; if (this.mscorlib != null) @@ -642,8 +642,8 @@ void TryDecodeSecurityDeclaration(TextOutputWithRollback output, BlobReader blob output.WriteLine(" = {"); output.Indent(); - string currentAssemblyName = null; - string currentFullAssemblyName = null; + string? currentAssemblyName = null; + string? currentFullAssemblyName = null; if (module.Metadata.IsAssembly) { try @@ -1862,7 +1862,7 @@ void OpenBlock(bool defaultCollapsed) output.Indent(); } - void CloseBlock(string comment = null) + void CloseBlock(string? comment = null) { output.Unindent(); output.Write("}"); diff --git a/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs b/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs index 75470a24d4..64c3ec881f 100644 --- a/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs +++ b/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs @@ -71,13 +71,13 @@ public static string GetIdString(this IEntity entity) b.Append('#'); } b.Append(member.Name.Replace('.', '#').Replace('<', '{').Replace('>', '}')); - IMethod method = member as IMethod; + IMethod? method = member as IMethod; if (method != null && method.TypeParameters.Count > 0) { b.Append("``"); b.Append(method.TypeParameters.Count); } - IParameterizedMember parameterizedMember = member as IParameterizedMember; + IParameterizedMember? parameterizedMember = member as IParameterizedMember; if (parameterizedMember != null && parameterizedMember.Parameters.Count > 0) { b.Append('('); @@ -180,7 +180,7 @@ static void AppendTypeParameters(StringBuilder b, IType type, int outerTypeParam int tpc = type.TypeParameterCount - outerTypeParameterCount; if (tpc > 0) { - ParameterizedType pt = type as ParameterizedType; + ParameterizedType? pt = type as ParameterizedType; if (pt != null) { b.Append('{'); diff --git a/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs b/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs index cae69da095..f2b4b2ad99 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs @@ -67,7 +67,7 @@ public XmlDocumentationCache(int size = 50) this.entries = new KeyValuePair[size]; } - internal bool TryGet(string key, out string value) + internal bool TryGet(string key, out string? value) { foreach (var pair in entries) { diff --git a/ICSharpCode.Decompiler/FlowAnalysis/Dominance.cs b/ICSharpCode.Decompiler/FlowAnalysis/Dominance.cs index 815b92046c..7285bdc646 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/Dominance.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/Dominance.cs @@ -69,7 +69,7 @@ public static class Dominance { ControlFlowNode b = nodes[i]; // Compute new immediate dominator: - ControlFlowNode newIdom = null; + ControlFlowNode? newIdom = null; foreach (var p in b.Predecessors) { // Ignore predecessors that were not processed yet diff --git a/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj b/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj index 583adedebe..1f9500aa8e 100644 --- a/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj +++ b/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj @@ -41,6 +41,7 @@ true ICSharpCode.Decompiler.ruleset true + enable diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs index 259367b2d4..7a02039b22 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs @@ -482,7 +482,7 @@ bool MatchVisualBasicStateMachineFieldAssignements(IList body, IL /// /// Matches a (potentially virtual) instance method call. /// - static bool MatchCall(ILInstruction inst, string name, out InstructionCollection args) + static bool MatchCall(ILInstruction inst, string name, out InstructionCollection? args) { if (inst is CallInstruction call && (call.OpCode == OpCode.Call || call.OpCode == OpCode.CallVirt) && call.Method.Name == name && !call.Method.IsStatic) @@ -609,7 +609,7 @@ private bool MatchAsyncEnumeratorCreationPattern(ILFunction function) } static bool MatchEnumeratorCreationNewObj(ILInstruction inst, ILTransformContext context, - out int initialState, out ITypeDefinition stateMachineType) + out int initialState, out ITypeDefinition? stateMachineType) { initialState = default; stateMachineType = default; @@ -644,7 +644,7 @@ public static bool IsCompilerGeneratorAsyncEnumerator(TypeDefinitionHandle type, return false; } - static void AnalyzeEnumeratorCtor(IMethod ctor, ILTransformContext context, out IField builderField, out IType builderType, out IField stateField) + static void AnalyzeEnumeratorCtor(IMethod ctor, ILTransformContext context, out IField? builderField, out IType builderType, out IField? stateField) { builderField = null; stateField = null; @@ -824,7 +824,7 @@ private Block CheckSetResultReturnBlock(BlockContainer blockContainer, int setRe pos++; } // [vb-only] stloc S_11(ldc.i4 -2) - ILVariable finalStateSlot = null; + ILVariable? finalStateSlot = null; int? finalStateSlotValue = null; if (block.Instructions[pos] is StLoc stlocFinalState && stlocFinalState.Value is LdcI4 ldcI4 && stlocFinalState.Variable.Kind == VariableKind.StackSlot) @@ -869,7 +869,7 @@ private Block CheckSetResultReturnBlock(BlockContainer blockContainer, int setRe return blockContainer.Blocks[setResultReturnBlockIndex]; } - private bool MatchDisposeCombinedTokens(BlockContainer blockContainer, ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst, bool[] blocksAnalyzed, out Block setResultAndExitBlock) + private bool MatchDisposeCombinedTokens(BlockContainer blockContainer, ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst, bool[] blocksAnalyzed, out Block? setResultAndExitBlock) { setResultAndExitBlock = null; // ... @@ -1423,7 +1423,7 @@ bool MatchLdDisposeMode(ILInstruction inst) } } - bool AnalyzeAwaitBlock(Block block, out ILVariable awaiter, out IField awaiterField, out int state, out int yieldOffset) + bool AnalyzeAwaitBlock(Block block, out ILVariable? awaiter, out IField? awaiterField, out int state, out int yieldOffset) { awaiter = null; awaiterField = null; @@ -1538,7 +1538,7 @@ static ILInstruction StackSlotValue(ILInstruction inst) return inst; } - private bool AnalyzeYieldReturn(Block block, out ILInstruction yieldValue, out int newState) + private bool AnalyzeYieldReturn(Block block, out ILInstruction? yieldValue, out int newState) { yieldValue = default; newState = default; @@ -1701,7 +1701,7 @@ static ILInstruction UnwrapConvUnknown(ILInstruction inst) return inst; } - bool CheckAwaitBlock(Block block, out Block resumeBlock, out IField stackField) + bool CheckAwaitBlock(Block block, out Block? resumeBlock, out IField? stackField) { // awaitBlock: // (pre-roslyn: save stack) @@ -1819,7 +1819,7 @@ bool MatchStateFieldAssignement(Block block, ref int pos) // stloc S_28(ldc.i4 -1) // stloc cachedStateVar(ldloc S_28) // stfld <>1__state(ldloc this, ldloc S_28) - ILVariable m1Var = null; + ILVariable? m1Var = null; if (block.Instructions[pos] is StLoc stlocM1 && stlocM1.Value.MatchLdcI4(initialState) && stlocM1.Variable.Kind == VariableKind.StackSlot) { m1Var = stlocM1.Variable; diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs index 5ac50c1c12..88fe3c6973 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs @@ -66,7 +66,7 @@ public static void Run(ILFunction function, ILTransformContext context) var cfg = new ControlFlowGraph(container, context.CancellationToken); if (transformableCatchBlocks.Count > 0) changedContainers.Add(container); - SwitchInstruction switchInstructionOpt = null; + SwitchInstruction? switchInstructionOpt = null; foreach (var result in transformableCatchBlocks) { removedBlocks.Clear(); @@ -198,7 +198,7 @@ public static void Run(ILFunction function, ILTransformContext context) private static void TransformAsyncThrowToThrow(ILTransformContext context, HashSet removedBlocks, Block block) { - ILVariable v = null; + ILVariable? v = null; if (MatchExceptionCaptureBlock(context, block, ref v, out StLoc typedExceptionVariableStore, out Block captureBlock, out Block throwBlock)) @@ -222,7 +222,7 @@ static void MoveBlock(Block block, BlockContainer target) /// /// Analyzes all catch handlers and returns every handler that follows the await catch handler pattern. /// - static bool AnalyzeHandlers(InstructionCollection handlers, out ILVariable catchHandlerIdentifier, + static bool AnalyzeHandlers(InstructionCollection handlers, out ILVariable? catchHandlerIdentifier, out List transformableCatchBlocks) { transformableCatchBlocks = new List(); @@ -254,9 +254,9 @@ static bool AnalyzeHandlers(InstructionCollection handlers, out /// stloc V_5(ldc.i4 2) - store id of catch block in 'identifierVariable' /// br IL_0075 - jump out of catch block to the head of the catch-handler jump table /// - static bool MatchAwaitCatchHandler(TryCatchHandler handler, out int id, out ILVariable identifierVariable, - out Block realEntryPoint, out ILInstruction nextBlockOrExitContainer, - out ILInstruction jumpTableEntry, out ILVariable objectVariable) + static bool MatchAwaitCatchHandler(TryCatchHandler handler, out int id, out ILVariable? identifierVariable, + out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, + out ILInstruction? jumpTableEntry, out ILVariable? objectVariable) { id = 0; identifierVariable = null; @@ -326,7 +326,7 @@ static bool MatchAwaitCatchHandler(TryCatchHandler handler, out int id, out ILVa return false; } - bool ParseSwitchJumpTable(int id, SwitchInstruction jumpTable, ILVariable identifierVariable, out Block realEntryPoint, out ILInstruction nextBlockOrExitContainer, out ILInstruction jumpTableEntry) + bool ParseSwitchJumpTable(int id, SwitchInstruction jumpTable, ILVariable identifierVariable, out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, out ILInstruction? jumpTableEntry) { realEntryPoint = null; nextBlockOrExitContainer = null; @@ -354,7 +354,7 @@ bool ParseSwitchJumpTable(int id, SwitchInstruction jumpTable, ILVariable identi return false; } - bool ParseIfJumpTable(int id, Block jumpTableEntryBlock, ILVariable identifierVariable, out Block realEntryPoint, out ILInstruction nextBlockOrExitContainer, out ILInstruction jumpTableEntry) + bool ParseIfJumpTable(int id, Block jumpTableEntryBlock, ILVariable identifierVariable, out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, out ILInstruction? jumpTableEntry) { realEntryPoint = null; nextBlockOrExitContainer = null; @@ -419,7 +419,7 @@ bool ParseIfJumpTable(int id, Block jumpTableEntryBlock, ILVariable identifierVa // => // throw(ldloc result.Handler.Variable) internal static bool MatchExceptionCaptureBlock(ILTransformContext context, Block block, - ref ILVariable objectVariable, out StLoc typedExceptionVariableStore, out Block captureBlock, out Block throwBlock) + ref ILVariable objectVariable, out StLoc? typedExceptionVariableStore, out Block? captureBlock, out Block? throwBlock) { bool DerivesFromException(IType t) => t.GetAllBaseTypes().Any(ty => ty.IsKnownType(KnownTypeCode.Exception)); diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs index bc6e103444..03a22b151a 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs @@ -200,7 +200,7 @@ private void MergeCommonBranches(Block block, IfInstruction ifInst) var commonExits = elseExits.Where(e1 => thenExits.Any(e2 => DetectExitPoints.CompatibleExitInstruction(e1, e2))); // find the common exit with the highest block exit priority - ILInstruction commonExit = null; + ILInstruction? commonExit = null; foreach (var exit in commonExits) { if (commonExit == null || CompareBlockExitPriority(exit, commonExit) > 0) @@ -610,7 +610,7 @@ private bool IsKeywordExit(ILInstruction exitInst, out Keyword keyword) /// Determine if the specified instruction necessarily exits (EndPointUnreachable) /// and if so return last (or single) exit instruction /// - private static bool TryGetExit(ILInstruction inst, out ILInstruction exitInst) + private static bool TryGetExit(ILInstruction inst, out ILInstruction? exitInst) { if (inst is Block block && block.Instructions.Count > 0) inst = block.Instructions.Last(); diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs b/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs index af864827e5..9dd4aa74fd 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs @@ -247,7 +247,7 @@ static bool CombineBlockWithNextBlock(BlockContainer container, Block block, ILT // Ensure the block will stay a basic block -- we don't want extended basic blocks prior to LoopDetection. if (block.Instructions.Count > 1 && block.Instructions[block.Instructions.Count - 2].HasFlag(InstructionFlags.MayBranch)) return false; - Branch br = block.Instructions.Last() as Branch; + Branch? br = block.Instructions.Last() as Branch; // Check whether we can combine the target block with this block if (br == null || br.TargetBlock.Parent != container || br.TargetBlock.IncomingEdgeCount != 1) return false; diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs index 3475d4d610..d67b9ad7cd 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs @@ -241,8 +241,8 @@ void DetectNullSafeArrayToPointerOrCustomRefPin(BlockContainer container) // stloc V_1(get.pinnable.reference(ldloc mem)) // stloc ptr(conv ref->u (ldloc V_1)) // br targetBlock - private bool IsCustomRefPinPattern(Block block, out ILInstruction ldlocMem, out CallInstruction callGPR, - out ILVariable v, out StLoc ptrAssign, out Block targetBlock, out Block nullBlock, out Block notNullBlock) + private bool IsCustomRefPinPattern(Block block, out ILInstruction? ldlocMem, out CallInstruction? callGPR, + out ILVariable? v, out StLoc? ptrAssign, out Block? targetBlock, out Block? nullBlock, out Block? notNullBlock) { ldlocMem = null; callGPR = null; @@ -356,7 +356,7 @@ private bool IsCustomRefPinPattern(Block block, out ILInstruction ldlocMem, out // ... // stloc P(array.to.pointer(V)) // br B_target - bool IsNullSafeArrayToPointerPattern(Block block, out ILVariable v, out ILVariable p, out Block targetBlock) + bool IsNullSafeArrayToPointerPattern(Block block, out ILVariable? v, out ILVariable? p, out Block? targetBlock) { v = null; p = null; @@ -495,7 +495,7 @@ bool IsNullSafeArrayToPointerNotNullAndNotEmptyBlock(Block block, ILVariable v, return block.Instructions[1].MatchBranch(targetBlock); } - bool IsNullSafeArrayToPointerNullOrEmptyBlock(Block block, out ILVariable p, out Block targetBlock) + bool IsNullSafeArrayToPointerNullOrEmptyBlock(Block block, out ILVariable? p, out Block? targetBlock) { p = null; targetBlock = null; @@ -602,7 +602,7 @@ bool CreatePinnedRegion(Block block, StLoc stLoc) context.Step("CreatePinnedRegion", block); BlockContainer body = new BlockContainer(); - Block[] clonedBlocks = cloneBlocks ? new Block[sourceContainer.Blocks.Count] : null; + Block[]? clonedBlocks = cloneBlocks ? new Block[sourceContainer.Blocks.Count] : null; for (int i = 0; i < sourceContainer.Blocks.Count; i++) { if (reachedEdgesPerBlock[i] > 0) @@ -704,7 +704,7 @@ static void HandleBranchLeavingPinnedRegion(ILInstruction potentialBranch, int[] { // branch that leaves body. // The target block should have an instruction that resets the pin; delete that instruction: - StLoc unpin = branch.TargetBlock.Instructions.First() as StLoc; + StLoc? unpin = branch.TargetBlock.Instructions.First() as StLoc; if (unpin != null && unpin.Variable == pinnedRegionVar && IsNullOrZero(unpin.Value)) { branch.TargetBlock.Instructions.RemoveAt(0); @@ -790,7 +790,7 @@ private void MoveArrayToPointerToPinnedRegionInit(PinnedRegion pinnedRegion) // and then uses array.to.pointer immediately within the region. Debug.Assert(pinnedRegion.Variable.Type.Kind == TypeKind.Array); // Find the single load of the variable within the pinnedRegion: - LdLoc ldloc = null; + LdLoc? ldloc = null; foreach (var inst in pinnedRegion.Descendants.OfType()) { if (inst.Variable == pinnedRegion.Variable && inst != pinnedRegion) @@ -863,7 +863,7 @@ private bool IsSlotAcceptingBothManagedAndUnmanagedPointers(SlotInfo slotInfo) return slotInfo == Block.InstructionSlot || slotInfo == LdObj.TargetSlot || slotInfo == StObj.TargetSlot; } - bool IsBranchOnNull(ILInstruction condBranch, ILVariable nativeVar, out Block targetBlock) + bool IsBranchOnNull(ILInstruction condBranch, ILVariable nativeVar, out Block? targetBlock) { targetBlock = null; // if (comp(ldloc nativeVar == conv i4->i (ldc.i4 0))) br targetBlock @@ -903,7 +903,7 @@ void HandleStringToPointer(PinnedRegion pinnedRegion) return; Block targetBlock; - Block adjustOffsetToStringData = null; + Block? adjustOffsetToStringData = null; if (body.EntryPoint.Instructions.Count == 2) { if (!initInst.MatchBinaryNumericInstruction(BinaryNumericOperator.Add, out ILInstruction left, out ILInstruction right)) @@ -1014,7 +1014,7 @@ bool IsOffsetToStringDataBlock(Block block, ILVariable nativeVar, Block targetBl bool IsOffsetToStringDataCall(ILInstruction inst) { - Call call = inst.UnwrapConv(ConversionKind.SignExtend) as Call; + Call? call = inst.UnwrapConv(ConversionKind.SignExtend) as Call; return call != null && call.Method.FullName == "System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData"; } diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs index d8f2be9bea..ec6697ca21 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs @@ -78,7 +78,7 @@ public void Run(Block block, BlockTransformContext context) Debug.Assert(h.UserData == block); Debug.Assert(!TreeTraversal.PreOrder(h, n => n.DominatorTreeChildren).Any(n => n.Visited)); - List loop = null; + List? loop = null; foreach (var t in h.Predecessors) { if (h.Dominates(t)) @@ -332,7 +332,7 @@ internal ControlFlowNode FindExitPoint(ControlFlowNode loopHead, IReadOnlyList /// Determines if the analysed switch can be constructed without any gotos /// - private bool SwitchUsesGoto(List flowNodes, List caseNodes, out Block breakBlock) + private bool SwitchUsesGoto(List flowNodes, List caseNodes, out Block? breakBlock) { // cases with predecessors that aren't part of the switch logic // must either require "goto case" statements, or consist of a single "break;" diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs index dbea7d4cfe..ecfc976b6d 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs @@ -1130,7 +1130,7 @@ internal static void TranslateFieldsToLocalAccess(ILFunction function, ILInstruc var fieldDef = (IField)ldflda.Field.MemberDefinition; if (!fieldToVariableMap.TryGetValue(fieldDef, out var v)) { - string name = null; + string? name = null; if (!string.IsNullOrEmpty(fieldDef.Name) && fieldDef.Name[0] == '<') { int pos = fieldDef.Name.IndexOf('>'); @@ -1334,7 +1334,7 @@ void CreateTryBlock(Block block, int state) IMethod FindFinallyMethod(int state) { - IMethod foundMethod = null; + IMethod? foundMethod = null; foreach (var (method, stateRange) in finallyMethodToStateRange) { if (stateRange.Contains(state)) @@ -1426,7 +1426,7 @@ private void CleanSkipFinallyBodies(ILFunction function) } context.StepEndGroup(keepIfEmpty: true); - bool IsCallToMonoFinallyMethod(Call call, out IMethod finallyMethod) + bool IsCallToMonoFinallyMethod(Call call, out IMethod? finallyMethod) { finallyMethod = default; if (call == null) diff --git a/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs b/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs index d49a684deb..bcaea6c769 100644 --- a/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs +++ b/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs @@ -190,7 +190,7 @@ public override void WriteTo(ITextOutput output, ILAstWritingOptions options) output.MarkFoldEnd(); } - internal static bool IsConversionStLoc(ILInstruction inst, out ILVariable variable, out ILVariable inputVariable) + internal static bool IsConversionStLoc(ILInstruction inst, out ILVariable variable, out ILVariable? inputVariable) { inputVariable = null; if (!inst.MatchStLoc(out variable, out var value)) @@ -210,7 +210,7 @@ internal static bool IsConversionStLoc(ILInstruction inst, out ILVariable variab return input.MatchLdLoc(out inputVariable) || input.MatchLdLoca(out inputVariable); } - internal static bool IsAssignment(ILInstruction inst, ICompilation typeSystem, out IType expectedType, out ILInstruction value) + internal static bool IsAssignment(ILInstruction inst, ICompilation typeSystem, out IType? expectedType, out ILInstruction? value) { expectedType = null; value = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs b/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs index c43f30eb1f..b54ecfc8f8 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs @@ -371,7 +371,7 @@ HashSet CollectLoopCounters(ILFunction function) string GenerateNameForVariable(ILVariable variable) { - string proposedName = null; + string? proposedName = null; if (variable.Type.IsKnownType(KnownTypeCode.Int32)) { // test whether the variable might be a loop counter @@ -701,7 +701,7 @@ static Dictionary CollectReservedVariableNames(ILFunction function, } internal static string GenerateForeachVariableName(ILFunction function, ILInstruction valueContext, - ILVariable existingVariable = null, bool mustResolveConflicts = false) + ILVariable? existingVariable = null, bool mustResolveConflicts = false) { if (function == null) throw new ArgumentNullException(nameof(function)); @@ -760,7 +760,7 @@ internal static string GenerateForeachVariableName(ILFunction function, ILInstru } internal static string GenerateVariableName(ILFunction function, IType type, - ILInstruction valueContext = null, ILVariable existingVariable = null, + ILInstruction? valueContext = null, ILVariable? existingVariable = null, bool mustResolveConflicts = false) { if (function == null) diff --git a/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs b/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs index 4bfa3a9963..5f4171de96 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs @@ -84,7 +84,7 @@ public void Run(Block block, BlockTransformContext context) bool CachedDelegateInitializationWithField(IfInstruction inst) { - Block trueInst = inst.TrueInst as Block; + Block? trueInst = inst.TrueInst as Block; if (trueInst == null || trueInst.Instructions.Count != 1 || !inst.FalseInst.MatchNop()) return false; var storeInst = trueInst.Instructions[0]; @@ -114,7 +114,7 @@ bool CachedDelegateInitializationWithField(IfInstruction inst) /// bool CachedDelegateInitializationWithLocal(IfInstruction inst) { - Block trueInst = inst.TrueInst as Block; + Block? trueInst = inst.TrueInst as Block; if (trueInst == null || (trueInst.Instructions.Count != 1) || !inst.FalseInst.MatchNop()) return false; if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdLoc(out ILVariable v) || !right.MatchLdNull()) @@ -154,7 +154,7 @@ bool CachedDelegateInitializationWithLocal(IfInstruction inst) /// bool CachedDelegateInitializationRoslynInStaticWithLocal(IfInstruction inst) { - Block trueInst = inst.TrueInst as Block; + Block? trueInst = inst.TrueInst as Block; if (trueInst == null || (trueInst.Instructions.Count != 1) || !inst.FalseInst.MatchNop()) return false; if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdLoc(out ILVariable s) || !right.MatchLdNull()) @@ -186,7 +186,7 @@ bool CachedDelegateInitializationRoslynInStaticWithLocal(IfInstruction inst) /// bool CachedDelegateInitializationRoslynWithLocal(IfInstruction inst) { - Block trueInst = inst.TrueInst as Block; + Block? trueInst = inst.TrueInst as Block; if (trueInst == null || (trueInst.Instructions.Count != 1) || !inst.FalseInst.MatchNop()) return false; if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdLoc(out ILVariable s) || !right.MatchLdNull()) diff --git a/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs b/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs index 1f3251fd2a..be27d32973 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs @@ -61,7 +61,7 @@ public void Run(ILFunction function, ILTransformContext context) } } - static void RunOnBlock(Block block, ILTransformContext context, HashSet splitVariables = null) + static void RunOnBlock(Block block, ILTransformContext context, HashSet? splitVariables = null) { for (int i = 0; i < block.Instructions.Count; i++) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs index 8a765b7e3c..c2b5cde12e 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs @@ -103,7 +103,7 @@ struct ConversionInfo /// Get index of deconstruction result or tuple element /// Returns -1 on failure. /// - int FindIndex(ILInstruction inst, out Action delayedActions) + int FindIndex(ILInstruction inst, out Action? delayedActions) { delayedActions = null; if (inst.MatchLdLoc(out var v)) @@ -189,7 +189,7 @@ bool InlineDeconstructionInitializer(Block block, int pos) bool TransformDeconstruction(Block block, int pos) { int startPos = pos; - Action delayedActions = null; + Action? delayedActions = null; if (MatchDeconstruction(block.Instructions[pos], out IMethod deconstructMethod, out ILInstruction rootTestedOperand)) { @@ -262,8 +262,8 @@ bool TransformDeconstruction(Block block, int pos) return true; } - bool MatchDeconstruction(ILInstruction inst, out IMethod deconstructMethod, - out ILInstruction testedOperand) + bool MatchDeconstruction(ILInstruction inst, out IMethod? deconstructMethod, + out ILInstruction? testedOperand) { testedOperand = null; deconstructMethod = null; @@ -328,7 +328,7 @@ bool MatchConversions(Block block, ref int pos, return true; } - bool MatchConversion(ILInstruction inst, out ILInstruction inputInstruction, + bool MatchConversion(ILInstruction inst, out ILInstruction? inputInstruction, out ILVariable outputVariable, out ConversionInfo info) { info = default; @@ -433,7 +433,7 @@ void AddMissingAssignmentsForConversions(int index, ref Action addAssignment) + bool MatchAssignment(ILInstruction inst, out IType? targetType, out ILInstruction? valueInst, out Action? addAssignment) { targetType = null; valueInst = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs b/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs index bf87343576..4b606fa02a 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs @@ -79,8 +79,8 @@ void IILTransform.Run(ILFunction function, ILTransformContext context) } } - internal static bool MatchDelegateConstruction(ILInstruction inst, out IMethod targetMethod, - out ILInstruction target, out IType delegateType, bool allowTransformed = false) + internal static bool MatchDelegateConstruction(ILInstruction inst, out IMethod? targetMethod, + out ILInstruction? target, out IType? delegateType, bool allowTransformed = false) { targetMethod = null; target = null; @@ -285,7 +285,7 @@ protected internal override void VisitILFunction(ILFunction function) { if (function == thisVariable?.Function) { - ILVariable v = null; + ILVariable? v = null; switch (target) { case LdLoc l: diff --git a/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs b/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs index f68c6d076e..4d4e410202 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs @@ -162,7 +162,7 @@ void PropagateExceptionInstance(StLoc store) /// br falseBlock /// } /// - bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, Block entryPoint, out IType exceptionType, out ILInstruction exceptionSlot, out Block whenConditionBlock) + bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, Block entryPoint, out IType? exceptionType, out ILInstruction? exceptionSlot, out Block? whenConditionBlock) { exceptionType = null; exceptionSlot = null; @@ -218,7 +218,7 @@ bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, /// br exitBlock /// } /// - bool MatchFalseBlock(BlockContainer container, Block falseBlock, out ILVariable returnVar, out Block exitBlock) + bool MatchFalseBlock(BlockContainer container, Block falseBlock, out ILVariable? returnVar, out Block? exitBlock) { returnVar = null; exitBlock = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs index 2c78d42f90..6a2e686b9c 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs @@ -272,7 +272,7 @@ ILInstruction MakeDynamicInstruction(CallSiteInfo callsite, CallVirt targetInvok } } - bool ScanCallSiteInitBlock(Block callSiteInitBlock, IField callSiteCacheField, IType callSiteDelegateType, out CallSiteInfo callSiteInfo, out Block blockAfterInit) + bool ScanCallSiteInitBlock(Block callSiteInitBlock, IField callSiteCacheField, IType callSiteDelegateType, out CallSiteInfo callSiteInfo, out Block? blockAfterInit) { callSiteInfo = default(CallSiteInfo); blockAfterInit = null; @@ -560,7 +560,7 @@ bool ExtractArgumentInfo(ILInstruction value, ref CallSiteInfo callSiteInfo, int return true; } - bool MatchCallSiteCacheNullCheck(ILInstruction condition, out IField callSiteCacheField, out IType callSiteDelegate, out bool invertBranches) + bool MatchCallSiteCacheNullCheck(ILInstruction condition, out IField? callSiteCacheField, out IType? callSiteDelegate, out bool invertBranches) { callSiteCacheField = null; callSiteDelegate = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs index 9afcb2706c..050da61467 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs @@ -79,7 +79,7 @@ public void Run(Block block, int pos, StatementTransformContext context) /// } /// static bool MatchIsEventAssignmentIfInstruction(ILInstruction ifInst, DynamicIsEventInstruction isEvent, ILVariable flagVar, ILVariable getMemberVar, - out DynamicSetMemberInstruction setMemberInst, out ILInstruction getMemberVarUse, out ILInstruction isEventConditionUse) + out DynamicSetMemberInstruction? setMemberInst, out ILInstruction? getMemberVarUse, out ILInstruction? isEventConditionUse) { setMemberInst = null; getMemberVarUse = null; @@ -121,7 +121,7 @@ static bool MatchIsEventAssignmentIfInstruction(ILInstruction ifInst, DynamicIsE /// stloc V_2(dynamic.getmember B(target)) /// } /// - static bool MatchLhsCacheIfInstruction(ILInstruction ifInst, ILVariable flagVar, out StLoc cacheStore) + static bool MatchLhsCacheIfInstruction(ILInstruction ifInst, ILVariable flagVar, out StLoc? cacheStore) { cacheStore = null; if (!ifInst.MatchIfInstruction(out var condition, out var trueInst)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs b/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs index 3d99d04009..17944d8f3d 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs @@ -185,7 +185,7 @@ protected internal override void VisitNewObj(NewObj inst) base.VisitNewObj(inst); } - bool TransformDecimalCtorToConstant(NewObj inst, out LdcDecimal result) + bool TransformDecimalCtorToConstant(NewObj inst, out LdcDecimal? result) { IType t = inst.Method.DeclaringType; result = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs b/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs index ed086d68f2..277df2cb45 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs @@ -301,7 +301,7 @@ protected internal override void VisitCallVirt(CallVirt inst) protected internal override void VisitNewObj(NewObj inst) { - Block block; + Block? block; if (TransformSpanTCtorContainingStackAlloc(inst, out ILInstruction locallocSpan)) { context.Step("new Span(stackalloc) -> stackalloc Span", inst); @@ -342,7 +342,7 @@ protected internal override void VisitNewObj(NewObj inst) /// => /// ldvirtdelegate System.Delegate TargetMethod(target) /// - bool TransformDelegateCtorLdVirtFtnToLdVirtDelegate(NewObj inst, out LdVirtDelegate ldVirtDelegate) + bool TransformDelegateCtorLdVirtFtnToLdVirtDelegate(NewObj inst, out LdVirtDelegate? ldVirtDelegate) { ldVirtDelegate = null; if (inst.Method.DeclaringType.Kind != TypeKind.Delegate) @@ -379,7 +379,7 @@ bool TransformDelegateCtorLdVirtFtnToLdVirtDelegate(NewObj inst, out LdVirtDeleg /// final: ldloc I_0 /// } /// - bool TransformSpanTCtorContainingStackAlloc(NewObj newObj, out ILInstruction locallocSpan) + bool TransformSpanTCtorContainingStackAlloc(NewObj newObj, out ILInstruction? locallocSpan) { locallocSpan = null; IType type = newObj.Method.DeclaringType; @@ -428,7 +428,7 @@ bool MatchesElementCount(ILInstruction sizeInBytesInstr, IType elementType, ILIn return true; } - bool TransformDecimalFieldToConstant(LdObj inst, out LdcDecimal result) + bool TransformDecimalFieldToConstant(LdObj inst, out LdcDecimal? result) { if (inst.MatchLdsFld(out var field) && field.DeclaringType.IsKnownType(KnownTypeCode.Decimal)) { @@ -542,10 +542,10 @@ protected internal override void VisitIfInstruction(IfInstruction inst) IfInstruction HandleConditionalOperator(IfInstruction inst) { // if (cond) stloc A(V1) else stloc A(V2) --> stloc A(if (cond) V1 else V2) - Block trueInst = inst.TrueInst as Block; + Block? trueInst = inst.TrueInst as Block; if (trueInst == null || trueInst.Instructions.Count != 1) return inst; - Block falseInst = inst.FalseInst as Block; + Block? falseInst = inst.FalseInst as Block; if (falseInst == null || falseInst.Instructions.Count != 1) return inst; ILVariable v; @@ -570,8 +570,8 @@ private void HandleSwitchExpression(BlockContainer container, SwitchInstruction Debug.Assert(container.ResultType == StackType.Void); var defaultSection = switchInst.GetDefaultSection(); StackType resultType = StackType.Void; - BlockContainer leaveTarget = null; - ILVariable resultVariable = null; + BlockContainer? leaveTarget = null; + ILVariable? resultVariable = null; foreach (var section in switchInst.Sections) { if (section != defaultSection) diff --git a/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs index d912ae2478..047940188f 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs @@ -53,7 +53,7 @@ public void Run(ILFunction function, ILTransformContext context) } } - bool MatchWhileLoop(BlockContainer loop, out IfInstruction condition, out Block loopBody) + bool MatchWhileLoop(BlockContainer loop, out IfInstruction? condition, out Block loopBody) { // ConditionDetection favours leave inside if and branch at end of block // while-loop: @@ -199,7 +199,7 @@ bool MatchDoWhileLoop(BlockContainer loop) loop.Blocks.MoveElementToEnd(originalBlock); } // combine all conditions and the exit instruction into one IfInstruction: - IfInstruction condition = null; + IfInstruction? condition = null; conditionBlock.AddILRange(exit); foreach (var inst in conditions) { @@ -356,7 +356,7 @@ static bool MatchDoWhileConditionBlock(BlockContainer loop, Block block, out boo } // early match before block containers have been constructed - internal static bool MatchDoWhileConditionBlock(Block block, out Block target1, out Block target2) + internal static bool MatchDoWhileConditionBlock(Block block, out Block target1, out Block? target2) { target1 = target2 = null; if (block.Instructions.Count < 2) @@ -419,7 +419,7 @@ bool MatchForLoop(BlockContainer loop, IfInstruction whileCondition, Block while // split conditions: var conditions = new List(); SplitConditions(whileCondition.Condition, conditions); - IfInstruction forCondition = null; + IfInstruction? forCondition = null; int numberOfConditions = 0; foreach (var condition in conditions) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs b/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs index 7b38b2e907..b94826d999 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs @@ -170,7 +170,7 @@ public static bool InlineIfPossible(Block block, int pos, ILTransformContext con public static bool InlineOneIfPossible(Block block, int pos, InliningOptions options, ILTransformContext context) { context.CancellationToken.ThrowIfCancellationRequested(); - StLoc stloc = block.Instructions[pos] as StLoc; + StLoc? stloc = block.Instructions[pos] as StLoc; if (stloc == null || stloc.Variable.Kind == VariableKind.PinnedLocal) return false; ILVariable v = stloc.Variable; @@ -370,7 +370,7 @@ static bool IsGeneratedTemporaryForAddressOf(LdLoca loadInst, ILVariable v, ILIn } } - internal static bool MethodRequiresCopyForReadonlyLValue(IMethod method, IType constrainedTo = null) + internal static bool MethodRequiresCopyForReadonlyLValue(IMethod method, IType? constrainedTo = null) { if (method == null) return true; @@ -387,7 +387,7 @@ internal static bool IsUsedAsThisPointerInCall(LdLoca ldloca) return IsUsedAsThisPointerInCall(ldloca, out _, out _); } - static bool IsUsedAsThisPointerInCall(LdLoca ldloca, out IMethod method, out IType constrainedType) + static bool IsUsedAsThisPointerInCall(LdLoca ldloca, out IMethod? method, out IType? constrainedType) { method = null; constrainedType = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs index f21c7fb0af..f23b750005 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs @@ -150,7 +150,7 @@ void IStatementTransform.Run(Block block, int pos, StatementTransformContext con if (!context.Settings.Ranges) return; int startPos = pos; - ILVariable containerVar = null; + ILVariable? containerVar = null; // The container length access may be a separate instruction, or it may be inline with the variable's use if (MatchContainerLengthStore(block.Instructions[pos], out ILVariable containerLengthVar, ref containerVar)) { @@ -410,7 +410,7 @@ void ExtendSlicing() } Debug.Assert(containerLengthVar.IsSingleDefinition); Debug.Assert(containerLengthVar.LoadCount == 1 || containerLengthVar.LoadCount == 2); - NewObj rangeCtorCall = null; + NewObj? rangeCtorCall = null; foreach (var inst in containerLengthVar.LoadInstructions[0].Ancestors) { if (inst is NewObj newobj && IndexMethods.IsRangeCtor(newobj.Method)) @@ -465,7 +465,7 @@ void ExtendSlicing() } } - private bool MatchIndexImplicitConv(ILInstruction inst, out ILInstruction offsetInst) + private bool MatchIndexImplicitConv(ILInstruction inst, out ILInstruction? offsetInst) { offsetInst = null; if (!(inst is CallInstruction call)) @@ -745,7 +745,7 @@ static IndexKind MatchGetOffset(ILInstruction inst, out ILInstruction indexLoad, /// Matches an instruction computing a slice length: /// binary.sub.i4(call GetOffset(endIndexLoad, ldloc length), ldloc startOffset)) /// - static bool MatchSliceLength(ILInstruction inst, out IndexKind endIndexKind, out ILInstruction endIndexLoad, ILVariable containerLengthVar, ref ILVariable containerVar, ILVariable startOffsetVar) + static bool MatchSliceLength(ILInstruction inst, out IndexKind endIndexKind, out ILInstruction? endIndexLoad, ILVariable containerLengthVar, ref ILVariable containerVar, ILVariable startOffsetVar) { endIndexKind = default; endIndexLoad = default; diff --git a/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs index ed26c0402d..864af3c279 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs @@ -104,7 +104,7 @@ private bool IsKnownCall(Block block, int pos, ILVariable v) return true; } - private bool FindToStringAndClear(Block block, int pos, int interpolationStart, int interpolationEnd, ILVariable v, out ILInstruction insertionPoint) + private bool FindToStringAndClear(Block block, int pos, int interpolationStart, int interpolationEnd, ILVariable v, out ILInstruction? insertionPoint) { insertionPoint = null; if (pos >= block.Instructions.Count) diff --git a/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs b/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs index f00fc48b0e..f2ab98f1a5 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs @@ -758,7 +758,7 @@ public static bool IsLocalFunctionMethod(IMethod method, ILTransformContext cont return IsLocalFunctionMethod(method.ParentModule.MetadataFile, (MethodDefinitionHandle)method.MetadataToken, context); } - public static bool IsLocalFunctionMethod(MetadataFile module, MethodDefinitionHandle methodHandle, ILTransformContext context = null) + public static bool IsLocalFunctionMethod(MetadataFile module, MethodDefinitionHandle methodHandle, ILTransformContext? context = null) { if (context != null && context.PEFile != module) return false; @@ -797,7 +797,7 @@ public static bool LocalFunctionNeedsAccessibilityChange(MetadataFile module, Me return false; } - public static bool IsLocalFunctionDisplayClass(MetadataFile module, TypeDefinitionHandle typeHandle, ILTransformContext context = null) + public static bool IsLocalFunctionDisplayClass(MetadataFile module, TypeDefinitionHandle typeHandle, ILTransformContext? context = null) { if (context != null && context.PEFile != module) return false; @@ -831,7 +831,7 @@ public static bool IsLocalFunctionDisplayClass(MetadataFile module, TypeDefiniti /// static readonly Regex functionNameRegex = new Regex(@"^<(.*)>g__([^\|]*)\|{0,1}\d+(_\d+)?$", RegexOptions.Compiled); - internal static bool ParseLocalFunctionName(string name, out string callerName, out string functionName) + internal static bool ParseLocalFunctionName(string name, out string? callerName, out string? functionName) { callerName = null; functionName = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs index 084c3bd797..116ca50d70 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs @@ -331,7 +331,7 @@ bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, ILVariable obj) return true; } - bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out StLoc obj) + bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out StLoc? obj) { obj = null; if (entryPoint.Instructions.Count == 0 || entryPoint.IncomingEdgeCount != 1) @@ -341,7 +341,7 @@ bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out StLoc obj) return true; } - bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out ILVariable exitVairable, out StLoc obj) + bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out ILVariable? exitVairable, out StLoc? obj) { // This pattern is commonly seen in yield return state machines emitted by the legacy C# compiler. obj = null; @@ -358,7 +358,7 @@ bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out ILVariable exitV return false; } - bool MatchCall(Call call, string methodName, ILVariable flag, out StLoc obj) + bool MatchCall(Call call, string methodName, ILVariable flag, out StLoc? obj) { obj = null; const string ThreadingMonitor = "System.Threading.Monitor"; diff --git a/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs index cb7d2161c6..5f35409c60 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs @@ -237,7 +237,7 @@ void TryNullPropForVoidCall(ILVariable testedVar, Mode mode, Block body, IfInstr ).WithILRange(ifInst)); } - bool IsValidAccessChain(ILVariable testedVar, Mode mode, ILInstruction inst, out ILInstruction finalLoad) + bool IsValidAccessChain(ILVariable testedVar, Mode mode, ILInstruction inst, out ILInstruction? finalLoad) { finalLoad = null; int chainLength = 0; @@ -445,7 +445,7 @@ private void IntroduceUnwrap(ILVariable testedVar, ILInstruction varLoad, Mode m // => // leave (nullable.rewrap(constrained[type].call_instruction(nullable.unwrap(targetInst), ...))) private bool TransformNullPropagationOnUnconstrainedGenericExpression(Block block, int pos, - out ILVariable target, out ILInstruction nonNullInst, out ILInstruction nullInst, out Block endBlock) + out ILVariable? target, out ILInstruction? nonNullInst, out ILInstruction? nullInst, out Block? endBlock) { target = null; nonNullInst = null; @@ -475,7 +475,7 @@ private bool TransformNullPropagationOnUnconstrainedGenericExpression(Block bloc // stloc resultTemporary(constrained[type].call_instruction(ldloc target, ...)) // br endBlock - private bool MatchStLocResultTemporary(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, out ILInstruction nonNullInst, out ILInstruction nullInst, out Block endBlock) + private bool MatchStLocResultTemporary(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, out ILInstruction? nonNullInst, out ILInstruction? nullInst, out Block? endBlock) { endBlock = null; nonNullInst = null; @@ -496,7 +496,7 @@ private bool MatchStLocResultTemporary(Block block, int pos, IType type, ILVaria return true; } - private bool MatchLeaveResult(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, out ILInstruction nonNullInst, out ILInstruction nullInst) + private bool MatchLeaveResult(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, out ILInstruction? nonNullInst, out ILInstruction? nullInst) { nonNullInst = null; nullInst = null; @@ -519,7 +519,7 @@ private bool MatchLeaveResult(Block block, int pos, IType type, ILVariable targe // br endBlock // } // } - private bool IsFallbackBlock(Block block, IType type, ILVariable target, ILVariable defaultTemporary, ILVariable resultTemporary, ILInstruction endBlockOrLeaveContainer, out ILInstruction nullInst) + private bool IsFallbackBlock(Block block, IType type, ILVariable target, ILVariable defaultTemporary, ILVariable resultTemporary, ILInstruction endBlockOrLeaveContainer, out ILInstruction? nullInst) { nullInst = null; if (!(block.Instructions.Count == 3)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs index 111cac3ce5..41d4aac38c 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs @@ -371,7 +371,7 @@ private bool IsGenericNewPattern(ILInstruction compLeft, ILInstruction compRight compRight.MatchLdNull(); } - private bool MatchThreeValuedLogicConditionPattern(ILInstruction condition, out ILVariable nullable1, out ILVariable nullable2) + private bool MatchThreeValuedLogicConditionPattern(ILInstruction condition, out ILVariable? nullable1, out ILVariable? nullable2) { // Try to match: nullable1.GetValueOrDefault() || (!nullable2.GetValueOrDefault() && !nullable1.HasValue) nullable1 = null; @@ -1018,7 +1018,7 @@ private ILInstruction NewNullable(ILInstruction inst, IType underlyingType) /// /// Matches 'call get_HasValue(arg)' /// - internal static bool MatchHasValueCall(ILInstruction inst, out ILInstruction arg) + internal static bool MatchHasValueCall(ILInstruction inst, out ILInstruction? arg) { arg = null; if (!(inst is Call call)) @@ -1036,7 +1036,7 @@ internal static bool MatchHasValueCall(ILInstruction inst, out ILInstruction arg /// /// Matches 'call get_HasValue(ldloca v)' /// - internal static bool MatchHasValueCall(ILInstruction inst, out ILVariable v) + internal static bool MatchHasValueCall(ILInstruction inst, out ILVariable? v) { if (MatchHasValueCall(inst, out ILInstruction arg)) { @@ -1065,7 +1065,7 @@ internal static bool MatchNegatedHasValueCall(ILInstruction inst, ILVariable v) /// /// Matches 'newobj Nullable{underlyingType}.ctor(arg)' /// - internal static bool MatchNullableCtor(ILInstruction inst, out IType underlyingType, out ILInstruction arg) + internal static bool MatchNullableCtor(ILInstruction inst, out IType? underlyingType, out ILInstruction? arg) { underlyingType = null; arg = null; @@ -1083,7 +1083,7 @@ internal static bool MatchNullableCtor(ILInstruction inst, out IType underlyingT /// /// Matches 'call Nullable{T}.GetValueOrDefault(arg)' /// - internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstruction arg) + internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstruction? arg) { arg = null; if (!(inst is Call call)) @@ -1099,7 +1099,7 @@ internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstructio /// /// Matches 'call nullableValue.GetValueOrDefault(fallback)' /// - internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstruction nullableValue, out ILInstruction fallback) + internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstruction? nullableValue, out ILInstruction? fallback) { nullableValue = null; fallback = null; @@ -1117,7 +1117,7 @@ internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstructio /// /// Matches 'call Nullable{T}.GetValueOrDefault(ldloca v)' /// - internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILVariable v) + internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILVariable? v) { v = null; return MatchGetValueOrDefault(inst, out ILInstruction arg) @@ -1132,7 +1132,7 @@ internal static bool MatchGetValueOrDefault(ILInstruction inst, ILVariable v) return MatchGetValueOrDefault(inst, out ILVariable v2) && v == v2; } - static bool MatchNull(ILInstruction inst, out IType underlyingType) + static bool MatchNull(ILInstruction inst, out IType? underlyingType) { underlyingType = null; if (inst.MatchDefaultValue(out IType type)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/ProxyCallReplacer.cs b/ICSharpCode.Decompiler/IL/Transforms/ProxyCallReplacer.cs index 164b806e23..f409c85b7a 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ProxyCallReplacer.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ProxyCallReplacer.cs @@ -63,7 +63,7 @@ void Run(CallInstruction inst, ILTransformContext context) if (blockContainer.Blocks.Count != 1) return; var block = blockContainer.Blocks[0]; - Call call; + Call? call; ILInstruction returnValue; switch (block.Instructions.Count) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs index 2876f141e7..5a92f5cb24 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs @@ -84,7 +84,7 @@ private void Visit(BlockContainer container, Block continueTarget) /// /// Marks the target block of continue statements. /// The instruction following the end point of the block. Can only be null if the end point is unreachable. - private void Visit(Block block, Block continueTarget, ILInstruction nextInstruction = null) + private void Visit(Block block, Block continueTarget, ILInstruction? nextInstruction = null) { Debug.Assert(block.HasFlag(InstructionFlags.EndPointUnreachable) || nextInstruction != null); diff --git a/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs b/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs index 7501338b32..bd4b6de126 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs @@ -85,7 +85,7 @@ public void Run(ILFunction function, ILTransformContext context) { if (v.Kind == VariableKind.StackSlot && v.StackType == StackType.Ref && v.AddressCount == 0) { - IType newType = null; + IType? newType = null; // Multiple store are possible in case of (c ? ref a : ref b) += 1, for example. foreach (var stloc in v.StoreInstructions.OfType()) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs index 7490a32060..827824abe8 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs @@ -77,7 +77,7 @@ public void Run(ILFunction function, ILTransformContext context) /// /// Matches legacy C# switch on nullable. /// - bool MatchSwitchOnNullable(InstructionCollection instructions, int i, out SwitchInstruction newSwitch) + bool MatchSwitchOnNullable(InstructionCollection instructions, int i, out SwitchInstruction? newSwitch) { newSwitch = null; // match first block: @@ -133,7 +133,7 @@ static SwitchInstruction BuildLiftedSwitch(Block nullCaseBlock, SwitchInstructio /// /// Matches Roslyn C# switch on nullable. /// - bool MatchRoslynSwitchOnNullable(InstructionCollection instructions, int i, out SwitchInstruction newSwitch) + bool MatchRoslynSwitchOnNullable(InstructionCollection instructions, int i, out SwitchInstruction? newSwitch) { newSwitch = null; // match first block: diff --git a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs index e254d243b6..eb21baff88 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs @@ -231,7 +231,7 @@ bool AddSwitchSection(string value, ILInstruction inst) return true; } - ILInstruction switchValue = null; + ILInstruction? switchValue = null; if (isVBCompareString && string.IsNullOrEmpty(firstBlockValue)) { if (!AddSwitchSection(null, firstBlock ?? firstBlockOrDefaultJump)) @@ -473,7 +473,7 @@ bool SimplifyCSharp1CascadingIfStatements(InstructionCollection i return true; } - bool IsIsInternedCall(Call call, out ILInstruction argument) + bool IsIsInternedCall(Call call, out ILInstruction? argument) { if (call != null && call.Method.DeclaringType.IsKnownType(KnownTypeCode.String) @@ -503,7 +503,7 @@ bool IsIsInternedCall(Call call, out ILInstruction argument) /// The is updated if the value gets copied to a different variable. /// See comments below for more info. /// - ILInstruction MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out string value, out bool emptyStringEqualsNull, out ILInstruction caseBlockOrLeave) + ILInstruction MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out string? value, out bool emptyStringEqualsNull, out ILInstruction? caseBlockOrLeave) { value = null; caseBlockOrLeave = null; @@ -569,7 +569,7 @@ bool MatchLegacySwitchOnStringWithDict(InstructionCollection inst return false; // If the switchValueVar is a stack slot and there is an assignment involving it right before the // switch-value null-check, we use the previously assigned variable as switchValueVar. - ILInstruction switchValue; + ILInstruction? switchValue; if (switchValueVar.Kind == VariableKind.StackSlot && instructions.ElementAtOrDefault(i - 1) is StLoc extraStore && extraStore.Value.MatchLdLoc(switchValueVar)) @@ -584,7 +584,7 @@ bool MatchLegacySwitchOnStringWithDict(InstructionCollection inst if (!switchValueVar.Type.IsKnownType(KnownTypeCode.String)) return false; // either br nullCase or leave container - BlockContainer leaveContainer = null; + BlockContainer? leaveContainer = null; if (!exitBlockJump.MatchBranch(out var nullValueCaseBlock) && !exitBlockJump.MatchLeave(out leaveContainer)) return false; var nextBlockJump = instructions.ElementAtOrDefault(i + 1) as Branch; @@ -760,7 +760,7 @@ bool AddNullSection(List sections, List<(string Value, int Index) /// /// Matches 'volatile.ldobj dictionaryType(ldsflda dictField)' /// - bool MatchDictionaryFieldLoad(ILInstruction inst, Func typeMatcher, out IField dictField, out IType dictionaryType) + bool MatchDictionaryFieldLoad(ILInstruction inst, Func typeMatcher, out IField? dictField, out IType? dictionaryType) { dictField = null; dictionaryType = null; @@ -773,7 +773,7 @@ bool MatchDictionaryFieldLoad(ILInstruction inst, Func typeMatcher, /// /// Matches and extracts values from Add-call sequences. /// - bool ExtractStringValuesFromInitBlock(Block block, out List<(string, int)> values, out Block blockAfterInit, IType dictionaryType, IField dictionaryField, bool isHashtablePattern) + bool ExtractStringValuesFromInitBlock(Block block, out List<(string, int)>? values, out Block? blockAfterInit, IType dictionaryType, IField dictionaryField, bool isHashtablePattern) { values = null; blockAfterInit = null; @@ -822,7 +822,7 @@ bool ExtractStringValuesFromInitBlock(Block block, out List<(string, int)> value /// -or- /// call Add(ldloc dictVar, ldstr value, box System.Int32(ldc.i4 index)) /// - bool MatchAddCall(IType dictionaryType, ILInstruction inst, ILVariable dictVar, out int index, out string value) + bool MatchAddCall(IType dictionaryType, ILInstruction inst, ILVariable dictVar, out int index, out string? value) { value = null; index = -1; @@ -941,7 +941,7 @@ bool MatchLegacySwitchOnStringWithHashtable(Block block, HashtableInitializer ha return true; } - bool FindHashtableInitBlock(Block entryPoint, out List<(string, int)> stringValues, out IField dictField, out Block blockAfterThisInitBlock, out ILInstruction thisSwitchInitJumpInst, out ILInstruction nextSwitchInitJumpInst) + bool FindHashtableInitBlock(Block entryPoint, out List<(string, int)>? stringValues, out IField? dictField, out Block? blockAfterThisInitBlock, out ILInstruction? thisSwitchInitJumpInst, out ILInstruction? nextSwitchInitJumpInst) { stringValues = null; dictField = null; @@ -996,8 +996,8 @@ bool MatchRoslynSwitchOnString(InstructionCollection instructions // br nextBlock InstructionCollection switchBlockInstructions = instructions; int switchBlockInstructionsOffset = i; - Block nullValueCaseBlock = null; - ILInstruction instForNullCheck = null; + Block? nullValueCaseBlock = null; + ILInstruction? instForNullCheck = null; if (instructions[i].MatchIfInstruction(out var condition, out var exitBlockJump) && condition.MatchCompEqualsNull(out instForNullCheck)) { @@ -1169,7 +1169,7 @@ private bool MatchRoslynSwitchOnStringUsingLengthAndChar(Block block, int i) // br nextBlock Block switchOnLengthBlock; int switchOnLengthBlockStartOffset; - Block nullCase = null; + Block? nullCase = null; if (instructions[i].MatchIfInstruction(out var condition, out var exitBlockJump) && condition.MatchCompEqualsNull(out var ldloc) && ldloc is LdLoc { Variable: var switchValueVar }) @@ -1202,7 +1202,7 @@ private bool MatchRoslynSwitchOnStringUsingLengthAndChar(Block block, int i) switchValueVar = null; // will be extracted in MatchSwitchOnLengthBlock switchOnLengthBlockStartOffset = i; } - Block defaultCase = null; + Block? defaultCase = null; if (!MatchSwitchOnLengthBlock(ref switchValueVar, switchOnLengthBlock, switchOnLengthBlockStartOffset, out var blocksByLength)) return false; List<(string, ILInstruction)> stringValues = new(); @@ -1310,12 +1310,12 @@ bool MatchGetChars(ILInstruction instruction, ILVariable switchValueVar, out int } } - bool MatchSwitchOnCharBlock(Block block, int length, ILVariable switchValueVar, out List<(string StringValue, ILInstruction BodyOrLeave)> results) + bool MatchSwitchOnCharBlock(Block block, int length, ILVariable switchValueVar, out List<(string StringValue, ILInstruction BodyOrLeave)>? results) { results = null; if (block.IncomingEdgeCount != 1) return false; - SwitchInstruction @switch; + SwitchInstruction? @switch; List> sections; int index; switch (block.Instructions.Count) @@ -1399,10 +1399,10 @@ bool MatchSwitchOnCharBlock(Block block, int length, ILVariable switchValueVar, return results?.Count > 0; } - bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengthBlock, int startOffset, out List<(LongSet Length, Block TargetBlock)> blocks) + bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengthBlock, int startOffset, out List<(LongSet Length, Block TargetBlock)>? blocks) { blocks = null; - SwitchInstruction @switch; + SwitchInstruction? @switch; ILInstruction getLengthCall; ILVariable lengthVar; switch (switchOnLengthBlock.Instructions.Count - startOffset) @@ -1506,7 +1506,7 @@ bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengt /// br newDefaultBlock /// } /// - private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable switchVar, out Block nullValueCaseBlock) + private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable switchVar, out Block? nullValueCaseBlock) { nullValueCaseBlock = null; if (exitOrDefaultBlock == null) @@ -1532,7 +1532,7 @@ private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable /// if (call op_Equality(ldloc switchValueVar, stringValue)) br body /// br exit /// - bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, out ILInstruction bodyOrLeave, out Block defaultOrExitBlock, out string stringValue, out bool emptyStringEqualsNull) + bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, out ILInstruction? bodyOrLeave, out Block? defaultOrExitBlock, out string? stringValue, out bool emptyStringEqualsNull) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1592,7 +1592,7 @@ bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, out ILIns /// br exit /// } /// - bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar, out ILInstruction bodyOrLeave, out Block defaultOrExitBlock) + bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar, out ILInstruction? bodyOrLeave, out Block? defaultOrExitBlock) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1660,7 +1660,7 @@ bool MatchStringLengthCall(ILInstruction inst, ILVariable switchValueVar) /// - or - /// 'stloc(targetVar, call ComputeReadOnlySpanHash(ldloc switchValue))' /// - internal static bool MatchComputeStringOrReadOnlySpanHashCall(ILInstruction inst, ILVariable targetVar, out LdLoc switchValue) + internal static bool MatchComputeStringOrReadOnlySpanHashCall(ILInstruction inst, ILVariable targetVar, out LdLoc? switchValue) { switchValue = null; if (!inst.MatchStLoc(targetVar, out var value)) @@ -1692,7 +1692,7 @@ bool MatchStringEqualityComparison(ILInstruction condition, ILVariable variable, /// or 'comp(ldloc(variable) == ldnull)' /// or 'call SequenceEqual(ldloc variable, call AsSpan(ldstr stringValue))' /// - bool MatchStringEqualityComparison(ILInstruction condition, out ILVariable variable, out string stringValue, out bool isVBCompareString) + bool MatchStringEqualityComparison(ILInstruction condition, out ILVariable? variable, out string? stringValue, out bool isVBCompareString) { stringValue = null; variable = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs index 7ddec2e564..9a78754686 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs @@ -114,7 +114,7 @@ bool DoTransform(ILFunction function, Block body, int pos) return false; } - internal static bool TransformSpanTArrayInitialization(NewObj inst, StatementTransformContext context, out ILInstruction replacement) + internal static bool TransformSpanTArrayInitialization(NewObj inst, StatementTransformContext context, out ILInstruction? replacement) { replacement = null; if (!context.Settings.ArrayInitializers) @@ -143,7 +143,7 @@ internal static bool TransformSpanTArrayInitialization(NewObj inst, StatementTra return false; } - private static unsafe bool DecodeUTF8String(BlobReader blob, int size, out string text) + private static unsafe bool DecodeUTF8String(BlobReader blob, int size, out string? text) { if (size > blob.RemainingBytes) { @@ -166,7 +166,7 @@ private static unsafe bool DecodeUTF8String(BlobReader blob, int size, out strin return MemoryExtensions.SequenceEqual(bytes, new ReadOnlySpan(blob.CurrentPointer, size)); } - static bool MatchSpanTCtorWithPointerAndSize(NewObj newObj, StatementTransformContext context, out IType elementType, out FieldDefinition field, out int size) + static bool MatchSpanTCtorWithPointerAndSize(NewObj newObj, StatementTransformContext context, out IType? elementType, out FieldDefinition field, out int size) { field = default; size = default; @@ -288,7 +288,7 @@ private ILInstruction ReadElement(ref BlobReader blob, IType elementType) } } - bool HandleCpblkInitializer(Block block, int pos, ILVariable v, long length, out BlobReader blob, out IType elementType) + bool HandleCpblkInitializer(Block block, int pos, ILVariable v, long length, out BlobReader blob, out IType? elementType) { blob = default; elementType = null; @@ -359,7 +359,7 @@ bool MatchGetStaticFieldAddress(ILInstruction input, out IField field) static bool IsRuntimeHelpers(IType type) => type is { Name: "RuntimeHelpers", Namespace: "System.Runtime.CompilerServices" }; - unsafe bool HandleSequentialLocAllocInitializer(Block block, int pos, ILVariable store, ILInstruction locAllocInstruction, out IType elementType, out StObj[] values, out int instructionsToRemove) + unsafe bool HandleSequentialLocAllocInitializer(Block block, int pos, ILVariable store, ILInstruction locAllocInstruction, out IType? elementType, out StObj[]? values, out int instructionsToRemove) { int elementCount = 0; long minExpectedOffset = 0; @@ -498,7 +498,7 @@ StObj StElemPtr(ILVariable target, int offset, ILInstruction value, IType type) /// /// Handle simple case where RuntimeHelpers.InitializeArray is not used. /// - internal static bool HandleSimpleArrayInitializer(ILFunction function, Block block, int pos, ILVariable store, int[] arrayLength, out (ILInstruction[] Indices, ILInstruction Value)[] values, out int instructionsToRemove) + internal static bool HandleSimpleArrayInitializer(ILFunction function, Block block, int pos, ILVariable store, int[] arrayLength, out (ILInstruction[] Indices, ILInstruction Value)[]? values, out int instructionsToRemove) { instructionsToRemove = 0; int elementCount = 0; @@ -656,7 +656,7 @@ ILInstruction[] CalculateNextIndices(InstructionCollection indice return true; } - bool HandleJaggedArrayInitializer(Block block, int pos, ILVariable store, IType elementType, int length, out ILVariable finalStore, out ILInstruction[] values, out int instructionsToRemove) + bool HandleJaggedArrayInitializer(Block block, int pos, ILVariable store, IType elementType, int length, out ILVariable? finalStore, out ILInstruction[]? values, out int instructionsToRemove) { instructionsToRemove = 0; finalStore = null; @@ -703,7 +703,7 @@ bool HandleJaggedArrayInitializer(Block block, int pos, ILVariable store, IType return true; } - bool MatchJaggedArrayStore(Block block, int pos, ILVariable store, int index, out ILInstruction initializer, out IType type) + bool MatchJaggedArrayStore(Block block, int pos, ILVariable store, int index, out ILInstruction? initializer, out IType? type) { initializer = null; type = null; @@ -751,7 +751,7 @@ static Block BlockFromInitializer(ILVariable v, IType elementType, int[] arrayLe return block; } - static bool MatchNewArr(ILInstruction instruction, out IType arrayType, out int[] length) + static bool MatchNewArr(ILInstruction instruction, out IType? arrayType, out int[]? length) { length = null; arrayType = null; @@ -769,7 +769,7 @@ static bool MatchNewArr(ILInstruction instruction, out IType arrayType, out int[ return true; } - bool MatchInitializeArrayCall(ILInstruction instruction, out ILInstruction array, out FieldDefinition field) + bool MatchInitializeArrayCall(ILInstruction instruction, out ILInstruction? array, out FieldDefinition field) { array = null; field = default; @@ -789,7 +789,7 @@ bool MatchInitializeArrayCall(ILInstruction instruction, out ILInstruction array return true; } - bool HandleRuntimeHelpersInitializeArray(Block body, int pos, ILVariable array, IType arrayType, int[] arrayLength, out ILInstruction[] values, out int foundPos) + bool HandleRuntimeHelpersInitializeArray(Block body, int pos, ILVariable array, IType arrayType, int[] arrayLength, out ILInstruction[]? values, out int foundPos) { if (MatchInitializeArrayCall(body.Instructions[pos], out var arrayInst, out var field) && arrayInst.MatchLdLoc(array)) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs index b5530fb70d..d084b09f76 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs @@ -176,7 +176,7 @@ bool TransformInlineAssignmentStObjOrCall(Block block, int pos) return false; if (call.ResultType != StackType.Void || call.Arguments.Count == 0) return false; - IProperty property = call.Method.AccessorOwner as IProperty; + IProperty? property = call.Method.AccessorOwner as IProperty; if (property == null) return false; if (!call.Method.Equals(property.Setter)) @@ -264,7 +264,7 @@ static bool ValidateCompoundAssign(BinaryNumericInstruction binary, Conv conv, I return true; } - static bool MatchingGetterAndSetterCalls(CallInstruction getterCall, CallInstruction setterCall, out Action finalizeMatch) + static bool MatchingGetterAndSetterCalls(CallInstruction getterCall, CallInstruction setterCall, out Action? finalizeMatch) { finalizeMatch = null; if (getterCall == null || setterCall == null || !IsSameMember(getterCall.Method.AccessorOwner, setterCall.Method.AccessorOwner)) @@ -677,8 +677,8 @@ private static ImplicitTruncationResult CommonImplicitTruncation(ImplicitTruncat /// /// Every IsCompoundStore() call should be followed by an IsMatchingCompoundLoad() call. /// - static bool IsCompoundStore(ILInstruction inst, out IType storeType, - out ILInstruction value, ICompilation compilation) + static bool IsCompoundStore(ILInstruction inst, out IType? storeType, + out ILInstruction? value, ICompilation compilation) { value = null; storeType = null; @@ -766,10 +766,10 @@ static bool IsCompoundStore(ILInstruction inst, out IType storeType, /// Instruction preceding the load. /// static bool IsMatchingCompoundLoad(ILInstruction load, ILInstruction store, - out ILInstruction target, out CompoundTargetKind targetKind, - out Action finalizeMatch, - ILVariable forbiddenVariable = null, - ILInstruction previousInstruction = null) + out ILInstruction? target, out CompoundTargetKind targetKind, + out Action? finalizeMatch, + ILVariable? forbiddenVariable = null, + ILInstruction? previousInstruction = null) { target = null; targetKind = 0; @@ -870,7 +870,7 @@ bool TransformPostIncDecOperatorWithInlineStore(Block block, int pos) { return false; } - StLoc stloc; + StLoc? stloc; var binary = UnwrapSmallIntegerConv(value, out var conv) as BinaryNumericInstruction; if (binary != null && (binary.Right.MatchLdcI(1) || binary.Right.MatchLdcF4(1) || binary.Right.MatchLdcF8(1))) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs index c433c3b810..0d6edf78dc 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs @@ -60,7 +60,7 @@ class VariableToDeclare public HashSet Initializers { get; } = new HashSet(); - public VariableToDeclare(DisplayClass container, IField field, ILVariable declaredVariable = null) + public VariableToDeclare(DisplayClass container, IField field, ILVariable? declaredVariable = null) { this.container = container; this.field = field; @@ -266,7 +266,7 @@ private DisplayClass AnalyzeVariable(ILVariable v) DisplayClass DetectDisplayClass(ILVariable v) { - ITypeDefinition definition; + ITypeDefinition? definition; if (v.Kind != VariableKind.StackSlot) { definition = v.Type.GetDefinition(); @@ -363,7 +363,7 @@ ILInstruction Visit(ILInstruction inst) ILInstruction VisitChildren(ILInstruction inst) { // Visit all children of the instruction - ILInstruction result = null; + ILInstruction? result = null; foreach (var child in inst.Children) { var newResult = Visit(child); @@ -519,7 +519,7 @@ VariableToDeclare AddVariable(DisplayClass result, StObj statement, IField field /// If a value does not match either LdLoc or a LdObj LdLdFlda* LdLoc chain, null is returned. /// The if any of the variables/fields in the chain cannot be propagated, null is returned. /// - ILVariable ResolveVariableToPropagate(ILInstruction value, IType expectedType = null) + ILVariable ResolveVariableToPropagate(ILInstruction value, IType? expectedType = null) { ILVariable v; switch (value) @@ -553,7 +553,7 @@ ILVariable ResolveVariableToPropagate(ILInstruction value, IType expectedType = return null; return v; case LdObj ldfld: - DisplayClass currentDisplayClass = null; + DisplayClass? currentDisplayClass = null; foreach (var item in ldfld.Target.Descendants) { if (IsDisplayClassLoad(item, out v)) @@ -588,7 +588,7 @@ private void Transform(ILFunction function) } } - internal static bool IsClosure(ILTransformContext context, ILVariable variable, out ITypeDefinition closureType, out ILInstruction initializer) + internal static bool IsClosure(ILTransformContext context, ILVariable variable, out ITypeDefinition? closureType, out ILInstruction? initializer) { closureType = null; initializer = null; @@ -610,7 +610,7 @@ internal static bool IsClosure(ILTransformContext context, ILVariable variable, return false; } - static bool IsClosureInit(ILTransformContext context, StLoc inst, out ITypeDefinition closureType) + static bool IsClosureInit(ILTransformContext context, StLoc inst, out ITypeDefinition? closureType) { if (inst.Value is NewObj newObj) { @@ -673,7 +673,7 @@ DisplayClass HandleMonoStateMachine(ILFunction function, ILVariable thisVariable } return displayClass; - bool FindThisField(out IField foundField) + bool FindThisField(out IField? foundField) { foundField = null; foreach (var field in closureType.GetFields(f2 => !f2.IsStatic && !displayClass.VariablesToDeclare.ContainsKey(f2) && f2.Type.GetDefinition() == decompilationContext.CurrentTypeDefinition)) @@ -851,7 +851,7 @@ private bool IsDisplayClassLoad(ILInstruction target, out ILVariable variable) } private bool IsDisplayClassFieldAccess(ILInstruction inst, - out ILVariable displayClassVar, out DisplayClass displayClass, out IField field) + out ILVariable? displayClassVar, out DisplayClass? displayClass, out IField? field) { displayClass = null; displayClassVar = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs index 81632f6a5b..fad9630480 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs @@ -63,7 +63,7 @@ static bool IsEmptyParameterList(ILInstruction inst) return false; } - bool MatchParameterVariableAssignment(ILInstruction expr, out ILVariable parameterReferenceVar, out IType type, out string name) + bool MatchParameterVariableAssignment(ILInstruction expr, out ILVariable parameterReferenceVar, out IType? type, out string? name) { // stloc(v, call(Expression::Parameter, call(Type::GetTypeFromHandle, ldtoken(...)), ldstr(...))) type = null; @@ -80,7 +80,7 @@ bool MatchParameterVariableAssignment(ILInstruction expr, out ILVariable paramet return false; if (!(initCall.Method.FullNameIs("System.Linq.Expressions.Expression", "Parameter"))) return false; - CallInstruction typeArg = initCall.Arguments[0] as CallInstruction; + CallInstruction? typeArg = initCall.Arguments[0] as CallInstruction; if (typeArg == null || typeArg.Arguments.Count != 1) return false; if (!typeArg.Method.FullNameIs("System.Type", "GetTypeFromHandle")) @@ -266,7 +266,7 @@ bool ReadParameters(ILInstruction initializer, IList parameters, ILi } } - (Func, IType) ConvertInstruction(ILInstruction instruction, IType typeHint = null) + (Func, IType) ConvertInstruction(ILInstruction instruction, IType? typeHint = null) { var (inst, type) = Convert(); @@ -578,9 +578,9 @@ ILInstruction Convert() { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); - IList arguments = null; - Func targetConverter = null; - IType targetType = null; + IList? arguments = null; + Func? targetConverter = null; + IType? targetType = null; if (MatchGetMethodFromHandle(invocation.Arguments[0], out var member)) { // static method @@ -853,7 +853,7 @@ ILInstruction BuildCall() { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); - Func targetConverter = null; + Func? targetConverter = null; if (!invocation.Arguments[0].MatchLdNull()) { targetConverter = ConvertInstruction(invocation.Arguments[0]).Item1; @@ -1124,7 +1124,7 @@ ILInstruction BuildInitializer() return (BuildInitializer, arrayType); } - bool MatchNew(CallInstruction invocation, out IMethod ctor) + bool MatchNew(CallInstruction invocation, out IMethod? ctor) { ctor = null; if (invocation.Method.Name != "New") @@ -1233,8 +1233,8 @@ ILInstruction BuildNewObj(IMethod method, Func[] args) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); - Func targetConverter = null; - IType targetType = null; + Func? targetConverter = null; + IType? targetType = null; if (!invocation.Arguments[0].MatchLdNull()) { (targetConverter, targetType) = ConvertInstruction(invocation.Arguments[0]); @@ -1413,7 +1413,7 @@ bool IsExpressionTreeParameter(ILVariable variable) return variable.Type.FullName == "System.Linq.Expressions.ParameterExpression"; } - bool MatchConstantCall(ILInstruction inst, out ILInstruction value, out IType type) + bool MatchConstantCall(ILInstruction inst, out ILInstruction? value, out IType? type) { value = null; type = null; @@ -1436,7 +1436,7 @@ bool MatchConstantCall(ILInstruction inst, out ILInstruction value, out IType ty return false; } - internal static bool MatchGetTypeFromHandle(ILInstruction inst, out IType type) + internal static bool MatchGetTypeFromHandle(ILInstruction inst, out IType? type) { type = null; return inst is CallInstruction getTypeCall @@ -1445,7 +1445,7 @@ internal static bool MatchGetTypeFromHandle(ILInstruction inst, out IType type) && getTypeCall.Arguments[0].MatchLdTypeToken(out type); } - bool MatchGetMethodFromHandle(ILInstruction inst, out IMember member) + bool MatchGetMethodFromHandle(ILInstruction inst, out IMember? member) { member = null; //castclass System.Reflection.MethodInfo(call GetMethodFromHandle(ldmembertoken op_Addition)) @@ -1458,7 +1458,7 @@ bool MatchGetMethodFromHandle(ILInstruction inst, out IMember member) return MatchFromHandleParameterList(call, out member); } - bool MatchGetConstructorFromHandle(ILInstruction inst, out IMember member) + bool MatchGetConstructorFromHandle(ILInstruction inst, out IMember? member) { member = null; //castclass System.Reflection.ConstructorInfo(call GetMethodFromHandle(ldmembertoken op_Addition)) @@ -1471,7 +1471,7 @@ bool MatchGetConstructorFromHandle(ILInstruction inst, out IMember member) return MatchFromHandleParameterList(call, out member); } - bool MatchGetFieldFromHandle(ILInstruction inst, out IMember member) + bool MatchGetFieldFromHandle(ILInstruction inst, out IMember? member) { member = null; if (!(inst is CallInstruction call && call.Method.FullName == "System.Reflection.FieldInfo.GetFieldFromHandle")) @@ -1479,7 +1479,7 @@ bool MatchGetFieldFromHandle(ILInstruction inst, out IMember member) return MatchFromHandleParameterList(call, out member); } - static bool MatchFromHandleParameterList(CallInstruction call, out IMember member) + static bool MatchFromHandleParameterList(CallInstruction call, out IMember? member) { member = null; switch (call.Arguments.Count) @@ -1500,7 +1500,7 @@ static bool MatchFromHandleParameterList(CallInstruction call, out IMember membe return true; } - bool MatchArgumentList(ILInstruction inst, out IList arguments) + bool MatchArgumentList(ILInstruction inst, out IList? arguments) { arguments = null; if (!(inst is Block block && block.Kind == BlockKind.ArrayInitializer)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs index 7b6f5cdbee..304678625f 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs @@ -59,7 +59,7 @@ public static bool MatchTupleFieldAccess(LdFlda inst, out IType tupleType, out I /// Matches 'newobj TupleType(...)'. /// Takes care of flattening long tuples. /// - public static bool MatchTupleConstruction(NewObj newobj, out ILInstruction[] arguments) + public static bool MatchTupleConstruction(NewObj? newobj, out ILInstruction[]? arguments) { arguments = null; if (newobj == null) diff --git a/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs index 9f1221385c..974943d299 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs @@ -116,7 +116,7 @@ bool LegacyPattern(Block block, int pos, StatementTransformContext context) return false; } - static bool MatchCondition(ILInstruction condition, out ILVariable v, out string name) + static bool MatchCondition(ILInstruction condition, out ILVariable? v, out string? name) { v = null; name = null; @@ -232,7 +232,7 @@ public static ILInstruction TransformDynamic(ILInstruction condition, ILInstruct } // Check trueInst: - DynamicUnaryOperatorInstruction rhsUnary; + DynamicUnaryOperatorInstruction? rhsUnary; if (trueInst.MatchLdLoc(lhsVar)) { // OK, typical pattern where the expression evaluates to 'dynamic' diff --git a/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs index 96fe3d13d6..b78e39189a 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs @@ -245,7 +245,7 @@ bool MatchDisposeCheck(ILVariable objVar, ILInstruction checkInst, bool isRefere { numObjVarLoadsInCheck = 2; ILInstruction disposeInvocation; - CallInstruction disposeCall; + CallInstruction? disposeCall; if (objVar.Type.IsKnownType(KnownTypeCode.NullableOfT)) { if (checkInst.MatchIfInstruction(out var condition, out var disposeInst)) @@ -488,7 +488,7 @@ private bool TransformAsyncUsing(Block block, int i) return true; } - bool CheckAsyncResourceType(IType type, out string disposeMethodFullName) + bool CheckAsyncResourceType(IType type, out string? disposeMethodFullName) { disposeMethodFullName = null; IType t = NullableType.GetUnderlyingType(type); diff --git a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs index 00a208674f..9007bde8c6 100644 --- a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs +++ b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs @@ -95,7 +95,7 @@ public DotNetCorePathFinder(TargetFrameworkIdentifier targetFramework, Version t } public DotNetCorePathFinder(string parentAssemblyFileName, string targetFrameworkIdString, string preferredRuntimePack, - TargetFrameworkIdentifier targetFramework, Version targetFrameworkVersion, ReferenceLoadInfo loadInfo = null) + TargetFrameworkIdentifier targetFramework, Version targetFrameworkVersion, ReferenceLoadInfo? loadInfo = null) : this(targetFramework, targetFrameworkVersion, preferredRuntimePack) { string assemblyName = Path.GetFileNameWithoutExtension(parentAssemblyFileName); @@ -211,7 +211,7 @@ static IEnumerable LoadPackageInfos(string depsJsonFileNa } } - public string TryResolveDotNetCoreShared(IAssemblyReference name, out string runtimePack) + public string TryResolveDotNetCoreShared(IAssemblyReference name, out string? runtimePack) { if (dotnetBasePath == null) { diff --git a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs index 692515ca9f..91e80b102c 100644 --- a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs +++ b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs @@ -44,7 +44,7 @@ public static string DetectTargetFrameworkId(this MetadataFile assembly) return DetectTargetFrameworkId(assembly.Metadata, assembly.FileName); } - public static string DetectTargetFrameworkId(this MetadataReader metadata, string assemblyPath = null) + public static string DetectTargetFrameworkId(this MetadataReader metadata, string? assemblyPath = null) { if (metadata == null) throw new ArgumentNullException(nameof(metadata)); diff --git a/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs b/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs index 90f44096a8..a7522a0f6f 100644 --- a/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs +++ b/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs @@ -73,7 +73,7 @@ public static string GetFullAssemblyName(this MetadataReader reader) $"PublicKeyToken={publicKey}"; } - public static bool TryGetFullAssemblyName(this MetadataReader reader, out string assemblyName) + public static bool TryGetFullAssemblyName(this MetadataReader reader, out string? assemblyName) { try { @@ -124,7 +124,7 @@ public static string GetFullAssemblyName(this SRM.AssemblyReference reference, M return builder.ToString(); } - public static bool TryGetFullAssemblyName(this SRM.AssemblyReference reference, MetadataReader reader, out string assemblyName) + public static bool TryGetFullAssemblyName(this SRM.AssemblyReference reference, MetadataReader reader, out string? assemblyName) { try { diff --git a/ICSharpCode.Decompiler/SRMExtensions.cs b/ICSharpCode.Decompiler/SRMExtensions.cs index 750f49f42a..1b4a82aa63 100644 --- a/ICSharpCode.Decompiler/SRMExtensions.cs +++ b/ICSharpCode.Decompiler/SRMExtensions.cs @@ -650,7 +650,7 @@ sealed class FieldValueSizeDecoder : ISignatureTypeProvider readonly MetadataModule module; readonly int pointerSize; - public FieldValueSizeDecoder(ICompilation typeSystem = null) + public FieldValueSizeDecoder(ICompilation? typeSystem = null) { this.module = (MetadataModule)typeSystem?.MainModule; if (module?.MetadataFile is not PEFile pefile) diff --git a/ICSharpCode.Decompiler/Semantics/Conversion.cs b/ICSharpCode.Decompiler/Semantics/Conversion.cs index a92735b4f3..792b49bb00 100644 --- a/ICSharpCode.Decompiler/Semantics/Conversion.cs +++ b/ICSharpCode.Decompiler/Semantics/Conversion.cs @@ -170,7 +170,7 @@ public override string ToString() public override bool Equals(Conversion other) { - NumericOrEnumerationConversion o = other as NumericOrEnumerationConversion; + NumericOrEnumerationConversion? o = other as NumericOrEnumerationConversion; return o != null && isImplicit == o.isImplicit && isLifted == o.isLifted && isEnumeration == o.isEnumeration; } @@ -247,7 +247,7 @@ public override bool IsThrowExpressionConversion { public override string ToString() { - string name = null; + string? name = null; switch (type) { case 0: @@ -337,7 +337,7 @@ public override IMethod Method { public override bool Equals(Conversion other) { - UserDefinedConv o = other as UserDefinedConv; + UserDefinedConv? o = other as UserDefinedConv; return o != null && isLifted == o.isLifted && isImplicit == o.isImplicit && isValid == o.isValid && method.Equals(o.method); } @@ -396,7 +396,7 @@ public override IMethod Method { public override bool Equals(Conversion other) { - MethodGroupConv o = other as MethodGroupConv; + MethodGroupConv? o = other as MethodGroupConv; return o != null && method.Equals(o.method); } diff --git a/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs b/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs index 1b07b653f2..551f92605e 100644 --- a/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs @@ -43,9 +43,9 @@ public class InvocationResolveResult : MemberResolveResult public readonly IList InitializerStatements; public InvocationResolveResult(ResolveResult targetResult, IParameterizedMember member, - IList arguments = null, - IList initializerStatements = null, - IType returnTypeOverride = null) + IList? arguments = null, + IList? initializerStatements = null, + IType? returnTypeOverride = null) : base(targetResult, member, returnTypeOverride) { this.Arguments = arguments ?? EmptyList.Instance; diff --git a/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs b/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs index ac8be79892..4c7922b1f7 100644 --- a/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs @@ -43,7 +43,7 @@ static IType UnpackTypeIfByRefParameter(IVariable variable) IType type = variable.Type; if (type.Kind == TypeKind.ByReference) { - IParameter p = variable as IParameter; + IParameter? p = variable as IParameter; if (p != null && p.ReferenceKind != ReferenceKind.None) return ((ByReferenceType)type).ElementType; } diff --git a/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs b/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs index 358a843860..bfd1729cd8 100644 --- a/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs @@ -33,11 +33,11 @@ public class MemberResolveResult : ResolveResult { readonly IMember member; readonly bool isConstant; - readonly object constantValue; - readonly ResolveResult targetResult; + readonly object? constantValue; + readonly ResolveResult? targetResult; readonly bool isVirtualCall; - public MemberResolveResult(ResolveResult targetResult, IMember member, IType returnTypeOverride = null) + public MemberResolveResult(ResolveResult? targetResult, IMember member, IType? returnTypeOverride = null) : base(returnTypeOverride ?? ComputeType(member)) { this.targetResult = targetResult; @@ -45,7 +45,7 @@ public MemberResolveResult(ResolveResult targetResult, IMember member, IType ret var thisRR = targetResult as ThisResolveResult; this.isVirtualCall = member.IsOverridable && !(thisRR != null && thisRR.CausesNonVirtualInvocation); - IField field = member as IField; + IField? field = member as IField; if (field != null) { isConstant = field.IsConst; @@ -54,13 +54,13 @@ public MemberResolveResult(ResolveResult targetResult, IMember member, IType ret } } - public MemberResolveResult(ResolveResult targetResult, IMember member, bool isVirtualCall, IType returnTypeOverride = null) + public MemberResolveResult(ResolveResult? targetResult, IMember member, bool isVirtualCall, IType? returnTypeOverride = null) : base(returnTypeOverride ?? ComputeType(member)) { this.targetResult = targetResult; this.member = member; this.isVirtualCall = isVirtualCall; - IField field = member as IField; + IField? field = member as IField; if (field != null) { isConstant = field.IsConst; @@ -104,7 +104,7 @@ public MemberResolveResult(ResolveResult targetResult, IMember member, IType ret this.isVirtualCall = isVirtualCall; } - public ResolveResult TargetResult { + public ResolveResult? TargetResult { get { return targetResult; } } @@ -127,7 +127,7 @@ public override bool IsCompileTimeConstant { get { return isConstant; } } - public override object ConstantValue { + public override object? ConstantValue { get { return constantValue; } } diff --git a/ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs b/ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs index 10f6d488f3..02c7bdd762 100644 --- a/ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs @@ -50,7 +50,7 @@ public class NamedArgumentResolveResult : ResolveResult /// public readonly ResolveResult Argument; - public NamedArgumentResolveResult(IParameter parameter, ResolveResult argument, IParameterizedMember member = null) + public NamedArgumentResolveResult(IParameter parameter, ResolveResult argument, IParameterizedMember? member = null) : base(argument.Type) { if (parameter == null) diff --git a/ICSharpCode.Decompiler/Semantics/ResolveResult.cs b/ICSharpCode.Decompiler/Semantics/ResolveResult.cs index 6ca0a177a0..6abb83e967 100644 --- a/ICSharpCode.Decompiler/Semantics/ResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/ResolveResult.cs @@ -48,7 +48,7 @@ public virtual bool IsCompileTimeConstant { get { return false; } } - public virtual object ConstantValue { + public virtual object? ConstantValue { get { return null; } } diff --git a/ICSharpCode.Decompiler/Semantics/TupleResolveResult.cs b/ICSharpCode.Decompiler/Semantics/TupleResolveResult.cs index 59923dff42..67f3e8f06a 100644 --- a/ICSharpCode.Decompiler/Semantics/TupleResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/TupleResolveResult.cs @@ -37,7 +37,7 @@ public class TupleResolveResult : ResolveResult public TupleResolveResult(ICompilation compilation, ImmutableArray elements, ImmutableArray elementNames = default(ImmutableArray), - IModule valueTupleAssembly = null) + IModule? valueTupleAssembly = null) : base(GetTupleType(compilation, elements, elementNames, valueTupleAssembly)) { this.Elements = elements; diff --git a/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs b/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs index 76418f3b25..0ebba87ef6 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs @@ -45,12 +45,12 @@ public static IType ApplyAttributesToType( SRM.CustomAttributeHandleCollection? additionalAttributes = null) { bool hasDynamicAttribute = false; - bool[] dynamicAttributeData = null; + bool[]? dynamicAttributeData = null; bool hasNativeIntegersAttribute = (options & TypeSystemOptions.NativeIntegersWithoutAttribute) != 0; - bool[] nativeIntegersAttributeData = null; - string[] tupleElementNames = null; + bool[]? nativeIntegersAttributeData = null; + string[]? tupleElementNames = null; Nullability nullability; - Nullability[] nullableAttributeData = null; + Nullability[]? nullableAttributeData = null; if ((options & TypeSystemOptions.NullabilityAnnotations) != 0) { nullability = nullableContext; @@ -253,7 +253,7 @@ public override IType VisitByReferenceType(ByReferenceType type) return base.VisitByReferenceType(type); } - public override IType VisitParameterizedType(ParameterizedType type) + public override IType VisitParameterizedType(ParameterizedType? type) { bool useTupleTypes = (options & TypeSystemOptions.Tuple) != 0; if (useTupleTypes && TupleType.IsTupleCompatible(type, out int tupleCardinality)) diff --git a/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs b/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs index f10da4531a..f0d942d314 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs @@ -43,7 +43,7 @@ public ArrayType(ICompilation compilation, IType elementType, int dimensions = 1 this.dimensions = dimensions; this.nullability = nullability; - ICompilationProvider p = elementType as ICompilationProvider; + ICompilationProvider? p = elementType as ICompilationProvider; if (p != null && p.Compilation != compilation) throw new InvalidOperationException("Cannot create an array type using a different compilation from the element type."); } @@ -87,7 +87,7 @@ public override int GetHashCode() public override bool Equals(IType other) { - ArrayType a = other as ArrayType; + ArrayType? a = other as ArrayType; return a != null && elementType.Equals(a.elementType) && a.dimensions == dimensions && a.nullability == nullability; } @@ -113,7 +113,7 @@ public override IEnumerable DirectBaseTypes { if (dimensions == 1 && elementType.Kind != TypeKind.Pointer) { // single-dimensional arrays implement IList - ITypeDefinition def = compilation.FindType(KnownTypeCode.IListOfT) as ITypeDefinition; + ITypeDefinition? def = compilation.FindType(KnownTypeCode.IListOfT) as ITypeDefinition; if (def != null) baseTypes.Add(new ParameterizedType(def, new[] { elementType })); // And in .NET 4.5 they also implement IReadOnlyList @@ -125,7 +125,7 @@ public override IEnumerable DirectBaseTypes { } } - public override IEnumerable GetMethods(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetMethods(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -133,7 +133,7 @@ public override IEnumerable GetMethods(Predicate filter = null return compilation.FindType(KnownTypeCode.Array).GetMethods(filter, options); } - public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -141,7 +141,7 @@ public override IEnumerable GetMethods(IReadOnlyList typeArgumen return compilation.FindType(KnownTypeCode.Array).GetMethods(typeArguments, filter, options); } - public override IEnumerable GetAccessors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetAccessors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -149,7 +149,7 @@ public override IEnumerable GetAccessors(Predicate filter = nu return compilation.FindType(KnownTypeCode.Array).GetAccessors(filter, options); } - public override IEnumerable GetProperties(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetProperties(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -216,7 +216,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - ArrayTypeReference o = other as ArrayTypeReference; + ArrayTypeReference? o = other as ArrayTypeReference; return o != null && elementType == o.elementType && dimensions == o.dimensions; } } diff --git a/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs b/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs index 1b686012e1..c4d6796c14 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs @@ -51,7 +51,7 @@ public override int GetHashCode() public override bool Equals(IType other) { - ByReferenceType a = other as ByReferenceType; + ByReferenceType? a = other as ByReferenceType; return a != null && elementType.Equals(a.elementType); } @@ -103,7 +103,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - ByReferenceTypeReference brt = other as ByReferenceTypeReference; + ByReferenceTypeReference? brt = other as ByReferenceTypeReference; return brt != null && this.elementType == brt.elementType; } } diff --git a/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs b/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs index 5d71478fdd..6832fa9c22 100644 --- a/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs @@ -151,7 +151,7 @@ public override IType VisitChildren(TypeVisitor visitor) { IType r = ReturnType.AcceptVisitor(visitor); // Keep ta == null as long as no elements changed, allocate the array only if necessary. - IType[] pt = (r != ReturnType) ? new IType[ParameterTypes.Length] : null; + IType[]? pt = (r != ReturnType) ? new IType[ParameterTypes.Length] : null; for (int i = 0; i < ParameterTypes.Length; i++) { IType p = ParameterTypes[i].AcceptVisitor(visitor); diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs index aca56d7e33..4c6fa71cee 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs @@ -61,7 +61,7 @@ public static IList FreezeList(IList list) public static void Freeze(object item) { - IFreezable f = item as IFreezable; + IFreezable? f = item as IFreezable; if (f != null) f.Freeze(); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs index b6b3bef3ad..c69467999f 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs @@ -101,47 +101,47 @@ public virtual IEnumerable DirectBaseTypes { get { return EmptyList.Instance; } } - public virtual IEnumerable GetNestedTypes(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetNestedTypes(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } - public virtual IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } - public virtual IEnumerable GetMethods(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetMethods(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } - public virtual IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } - public virtual IEnumerable GetConstructors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) + public virtual IEnumerable GetConstructors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) { return EmptyList.Instance; } - public virtual IEnumerable GetProperties(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetProperties(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } - public virtual IEnumerable GetFields(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetFields(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } - public virtual IEnumerable GetEvents(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetEvents(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } - public virtual IEnumerable GetMembers(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetMembers(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { IEnumerable members = GetMethods(filter, options); return members @@ -150,7 +150,7 @@ public virtual IEnumerable GetMembers(Predicate filter = null, .Concat(GetEvents(filter, options)); } - public virtual IEnumerable GetAccessors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public virtual IEnumerable GetAccessors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return EmptyList.Instance; } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs index 289fc35e76..2104a5edb3 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs @@ -29,12 +29,12 @@ public abstract class AbstractTypeParameter : ITypeParameter, ICompilationProvid { readonly ICompilation compilation; readonly SymbolKind ownerType; - readonly IEntity owner; + readonly IEntity? owner; readonly int index; readonly string name; readonly VarianceModifier variance; - protected AbstractTypeParameter(IEntity owner, int index, string name, VarianceModifier variance) + protected AbstractTypeParameter(IEntity owner, int index, string? name, VarianceModifier variance) { if (owner == null) throw new ArgumentNullException(nameof(owner)); @@ -46,7 +46,7 @@ protected AbstractTypeParameter(IEntity owner, int index, string name, VarianceM this.variance = variance; } - protected AbstractTypeParameter(ICompilation compilation, SymbolKind ownerType, int index, string name, VarianceModifier variance) + protected AbstractTypeParameter(ICompilation compilation, SymbolKind ownerType, int index, string? name, VarianceModifier variance) { if (compilation == null) throw new ArgumentNullException(nameof(compilation)); @@ -65,7 +65,7 @@ public SymbolKind OwnerType { get { return ownerType; } } - public IEntity Owner { + public IEntity? Owner { get { return owner; } } @@ -83,7 +83,7 @@ public ICompilation Compilation { get { return compilation; } } - volatile IType effectiveBaseClass; + volatile IType? effectiveBaseClass; public IType EffectiveBaseClass { get { @@ -132,7 +132,7 @@ IType CalculateEffectiveBaseClass() return result; } - IReadOnlyCollection effectiveInterfaceSet; + IReadOnlyCollection? effectiveInterfaceSet; public IReadOnlyCollection EffectiveInterfaceSet { get { @@ -193,7 +193,7 @@ public bool? IsReferenceType { IType effectiveBaseClass = this.EffectiveBaseClass; if (effectiveBaseClass.Kind == TypeKind.Class || effectiveBaseClass.Kind == TypeKind.Delegate) { - ITypeDefinition effectiveBaseClassDef = effectiveBaseClass.GetDefinition(); + ITypeDefinition? effectiveBaseClassDef = EffectiveBaseClass.GetDefinition(); if (effectiveBaseClassDef != null) { switch (effectiveBaseClassDef.KnownTypeCode) @@ -225,7 +225,7 @@ public IType ChangeNullability(Nullability nullability) return new NullabilityAnnotatedTypeParameter(this, nullability); } - IType IType.DeclaringType { + IType? IType.DeclaringType { get { return null; } } @@ -265,12 +265,12 @@ public string ReflectionName { } } - ITypeDefinition IType.GetDefinition() + ITypeDefinition? IType.GetDefinition() { return null; } - ITypeDefinitionOrUnknown IType.GetDefinitionOrUnknown() + ITypeDefinitionOrUnknown? IType.GetDefinitionOrUnknown() { return null; } @@ -285,17 +285,17 @@ public IType VisitChildren(TypeVisitor visitor) return this; } - IEnumerable IType.GetNestedTypes(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetNestedTypes(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetNestedTypes(IReadOnlyList typeArguments, Predicate filter, GetMemberOptions options) + IEnumerable IType.GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - public IEnumerable GetConstructors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) + public IEnumerable GetConstructors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { @@ -315,7 +315,7 @@ public IEnumerable GetConstructors(Predicate filter = null, Ge } } - public IEnumerable GetMethods(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMethods(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -323,7 +323,7 @@ public IEnumerable GetMethods(Predicate filter = null, GetMemb return GetMembersHelper.GetMethods(this, FilterNonStatic(filter), options); } - public IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -331,7 +331,7 @@ public IEnumerable GetMethods(IReadOnlyList typeArguments, Predi return GetMembersHelper.GetMethods(this, typeArguments, FilterNonStatic(filter), options); } - public IEnumerable GetProperties(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetProperties(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -339,7 +339,7 @@ public IEnumerable GetProperties(Predicate filter = null, return GetMembersHelper.GetProperties(this, FilterNonStatic(filter), options); } - public IEnumerable GetFields(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetFields(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -347,7 +347,7 @@ public IEnumerable GetFields(Predicate filter = null, GetMemberO return GetMembersHelper.GetFields(this, FilterNonStatic(filter), options); } - public IEnumerable GetEvents(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetEvents(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -355,7 +355,7 @@ public IEnumerable GetEvents(Predicate filter = null, GetMemberO return GetMembersHelper.GetEvents(this, FilterNonStatic(filter), options); } - public IEnumerable GetMembers(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMembers(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -363,7 +363,7 @@ public IEnumerable GetMembers(Predicate filter = null, GetMemb return GetMembersHelper.GetMembers(this, FilterNonStatic(filter), options); } - public IEnumerable GetAccessors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetAccessors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) return EmptyList.Instance; @@ -376,13 +376,13 @@ TypeParameterSubstitution IType.GetSubstitution() return TypeParameterSubstitution.Identity; } - static Predicate FilterNonStatic(Predicate filter) where T : class, IMember + static Predicate FilterNonStatic(Predicate? filter) where T : class, IMember { return member => (!member.IsStatic || member.SymbolKind == SymbolKind.Operator || member.IsVirtual) && (filter == null || filter(member)); } - public sealed override bool Equals(object obj) + public sealed override bool Equals(object? obj) { return Equals(obj as IType); } @@ -392,7 +392,7 @@ public override int GetHashCode() return base.GetHashCode(); } - public virtual bool Equals(IType other) + public virtual bool Equals(IType? other) { return this == other; // use reference equality for type parameters } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs index 6c1b4519c3..aa89607bfb 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs @@ -67,7 +67,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - DefaultAssemblyReference o = other as DefaultAssemblyReference; + DefaultAssemblyReference? o = other as DefaultAssemblyReference; return o != null && shortName == o.shortName; } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs index 4fa30a8180..a5e7f43954 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs @@ -48,8 +48,8 @@ public DefaultParameter(IType type, string name) this.attributes = EmptyList.Instance; } - public DefaultParameter(IType type, string name, IParameterizedMember owner = null, IReadOnlyList attributes = null, - ReferenceKind referenceKind = ReferenceKind.None, bool isParams = false, bool isOptional = false, object defaultValue = null) + public DefaultParameter(IType type, string name, IParameterizedMember? owner = null, IReadOnlyList? attributes = null, + ReferenceKind referenceKind = ReferenceKind.None, bool isParams = false, bool isOptional = false, object? defaultValue = null) { if (type == null) throw new ArgumentNullException(nameof(type)); diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultTypeParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultTypeParameter.cs index 3e4398ec33..05df03ba30 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultTypeParameter.cs @@ -33,11 +33,11 @@ public class DefaultTypeParameter : AbstractTypeParameter public DefaultTypeParameter( IEntity owner, - int index, string name = null, + int index, string? name = null, VarianceModifier variance = VarianceModifier.Invariant, - IReadOnlyList attributes = null, + IReadOnlyList? attributes = null, bool hasValueTypeConstraint = false, bool hasReferenceTypeConstraint = false, bool hasDefaultConstructorConstraint = false, - IReadOnlyList constraints = null, Nullability nullabilityConstraint = Nullability.Oblivious) + IReadOnlyList? constraints = null, Nullability nullabilityConstraint = Nullability.Oblivious) : base(owner, index, name, variance) { this.hasValueTypeConstraint = hasValueTypeConstraint; @@ -50,11 +50,11 @@ public DefaultTypeParameter( public DefaultTypeParameter( ICompilation compilation, SymbolKind ownerType, - int index, string name = null, + int index, string? name = null, VarianceModifier variance = VarianceModifier.Invariant, - IReadOnlyList attributes = null, + IReadOnlyList? attributes = null, bool hasValueTypeConstraint = false, bool hasReferenceTypeConstraint = false, bool hasDefaultConstructorConstraint = false, - IReadOnlyList constraints = null, Nullability nullabilityConstraint = Nullability.Oblivious) + IReadOnlyList? constraints = null, Nullability nullabilityConstraint = Nullability.Oblivious) : base(compilation, ownerType, index, name, variance) { this.hasValueTypeConstraint = hasValueTypeConstraint; @@ -75,7 +75,7 @@ public DefaultTypeParameter( public override IReadOnlyList TypeConstraints { get; } - IReadOnlyList MakeConstraints(IReadOnlyList constraints) + IReadOnlyList MakeConstraints(IReadOnlyList? constraints) { var result = new List(); bool hasNonInterfaceConstraint = false; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs index c81b8d85dd..56c86518a1 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs @@ -41,7 +41,7 @@ public DefaultVariable(IType type, string name) } public DefaultVariable(IType type, string name, - bool isConst = false, object constantValue = null) + bool isConst = false, object? constantValue = null) : this(type, name) { this.isConst = isConst; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs index 0c161ca5c2..ac27c97ec3 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs @@ -38,7 +38,7 @@ public sealed class GetClassTypeReference : ITypeReference, ISupportsInterning /// If this parameter is null, the GetClassTypeReference will search in all /// assemblies belonging to the compilation. /// - public GetClassTypeReference(FullTypeName fullTypeName, IModuleReference module = null, bool? isReferenceType = null) + public GetClassTypeReference(FullTypeName fullTypeName, IModuleReference? module = null, bool? isReferenceType = null) { this.fullTypeName = fullTypeName; this.module = module; @@ -100,7 +100,7 @@ public IType Resolve(ITypeResolveContext context) if (context == null) throw new ArgumentNullException(nameof(context)); - IType type = null; + IType? type = null; if (module == null) { // No assembly specified: look in all assemblies, but prefer the current assembly @@ -147,7 +147,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - GetClassTypeReference o = other as GetClassTypeReference; + GetClassTypeReference? o = other as GetClassTypeReference; return o != null && module == o.module && fullTypeName == o.fullTypeName && isReferenceType == o.isReferenceType; } } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs index a160a44994..2ce8d45df3 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs @@ -60,7 +60,7 @@ static IEnumerable GetNestedTypesImpl(IType outerType, IReadOnlyList FilterTypeParameterCount(int expectedTypeParameterCoun const GetMemberOptions declaredMembers = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions; - static IEnumerable GetMethodsImpl(IType baseType, IReadOnlyList methodTypeArguments, Predicate filter, GetMemberOptions options) + static IEnumerable GetMethodsImpl(IType baseType, IReadOnlyList? methodTypeArguments, Predicate filter, GetMemberOptions options) { IEnumerable declaredMethods = baseType.GetMethods(filter, options | declaredMembers); - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if ((options & GetMemberOptions.ReturnMemberDefinitions) == 0 && (pt != null || (methodTypeArguments != null && methodTypeArguments.Count > 0))) { - TypeParameterSubstitution substitution = null; + TypeParameterSubstitution? substitution = null; foreach (IMethod m in declaredMethods) { if (methodTypeArguments != null && methodTypeArguments.Count > 0) @@ -183,7 +183,7 @@ static IEnumerable GetAccessorsImpl(IType baseType, Predicate #endregion #region GetConstructors - public static IEnumerable GetConstructors(IType type, Predicate filter, GetMemberOptions options) + public static IEnumerable GetConstructors(IType type, Predicate? filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { @@ -195,7 +195,7 @@ public static IEnumerable GetConstructors(IType type, Predicate GetConstructorsImpl(IType baseType, Predicate filter, GetMemberOptions options) + static IEnumerable GetConstructorsImpl(IType baseType, Predicate? filter, GetMemberOptions options) { return GetConstructorsOrAccessorsImpl(baseType, baseType.GetConstructors(filter, options | declaredMembers), options); } @@ -207,7 +207,7 @@ static IEnumerable GetConstructorsOrAccessorsImpl(IType baseType, IEnum return declaredMembers; } - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); @@ -241,7 +241,7 @@ static IEnumerable GetPropertiesImpl(IType baseType, Predicate GetFields(IType type, Predicate filter } } - static IEnumerable GetFieldsImpl(IType baseType, Predicate filter, GetMemberOptions options) + static IEnumerable GetFieldsImpl(IType baseType, Predicate? filter, GetMemberOptions options) { IEnumerable declaredFields = baseType.GetFields(filter, options | declaredMembers); if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) @@ -275,7 +275,7 @@ static IEnumerable GetFieldsImpl(IType baseType, Predicate filte return declaredFields; } - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); @@ -309,7 +309,7 @@ static IEnumerable GetEventsImpl(IType baseType, Predicate filte return declaredEvents; } - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs index 31a332ad73..5d2f71bd16 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs @@ -42,7 +42,7 @@ public sealed class MergedNamespace : INamespace /// The main compilation. /// The individual namespaces being merged. /// The extern alias for this namespace. - public MergedNamespace(ICompilation compilation, INamespace[] namespaces, string externAlias = null) + public MergedNamespace(ICompilation compilation, INamespace[] namespaces, string? externAlias = null) { if (compilation == null) throw new ArgumentNullException(nameof(compilation)); @@ -137,7 +137,7 @@ Dictionary GetChildNamespaces() public ITypeDefinition GetTypeDefinition(string name, int typeParameterCount) { - ITypeDefinition anyTypeDef = null; + ITypeDefinition? anyTypeDef = null; foreach (var ns in namespaces) { ITypeDefinition typeDef = ns.GetTypeDefinition(name, typeParameterCount); diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs index 83946c9fa0..a409025103 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs @@ -186,7 +186,7 @@ private void DecodeSignature() var genericContext = new GenericContext(DeclaringType.TypeParameters, this.TypeParameters); IType returnType; IParameter[] parameters; - ModifiedType mod; + ModifiedType? mod; try { var nullableContext = methodDef.GetCustomAttributes().GetNullableContext(module.metadata) ?? DeclaringTypeDefinition.NullableContext; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs index 632a3e4cc7..9d3b2fdc44 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs @@ -324,7 +324,7 @@ public IEnumerable DirectBaseTypes { var context = new GenericContext(TypeParameters); var interfaceImplCollection = td.GetInterfaceImplementations(); baseTypes = new List(1 + interfaceImplCollection.Count); - IType baseType = null; + IType? baseType = null; try { EntityHandle baseTypeHandle = td.BaseType; @@ -569,7 +569,7 @@ bool IEquatable.Equals(IType other) } #region GetNestedTypes - public IEnumerable GetNestedTypes(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetNestedTypes(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { const GetMemberOptions opt = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions; if ((options & opt) == opt) @@ -582,7 +582,7 @@ public IEnumerable GetNestedTypes(Predicate filter = nul } } - public IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return GetMembersHelper.GetNestedTypes(this, typeArguments, filter, options); } @@ -606,7 +606,7 @@ IEnumerable ApplyFilter(IEnumerable input, Predicate filter) where T } } - public IEnumerable GetMethods(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMethods(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if (Kind == TypeKind.Void) return EmptyList.Instance; @@ -620,14 +620,14 @@ public IEnumerable GetMethods(Predicate filter = null, GetMemb } } - public IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if (Kind == TypeKind.Void) return EmptyList.Instance; return GetMembersHelper.GetMethods(this, typeArguments, filter, options); } - public IEnumerable GetConstructors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) + public IEnumerable GetConstructors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) { if (Kind == TypeKind.Void) return EmptyList.Instance; @@ -654,7 +654,7 @@ public IEnumerable GetConstructors(Predicate filter = null, Ge } } - public IEnumerable GetProperties(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetProperties(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if (Kind == TypeKind.Void) return EmptyList.Instance; @@ -668,7 +668,7 @@ public IEnumerable GetProperties(Predicate filter = null, } } - public IEnumerable GetFields(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetFields(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if (Kind == TypeKind.Void) return EmptyList.Instance; @@ -682,7 +682,7 @@ public IEnumerable GetFields(Predicate filter = null, GetMemberO } } - public IEnumerable GetEvents(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetEvents(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if (Kind == TypeKind.Void) return EmptyList.Instance; @@ -696,7 +696,7 @@ public IEnumerable GetEvents(Predicate filter = null, GetMemberO } } - public IEnumerable GetMembers(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMembers(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if (Kind == TypeKind.Void) return EmptyList.Instance; @@ -710,7 +710,7 @@ public IEnumerable GetMembers(Predicate filter = null, GetMemb } } - public IEnumerable GetAccessors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetAccessors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if (Kind == TypeKind.Void) return EmptyList.Instance; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs index 2380c7730b..6e6bc3ceeb 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs @@ -67,7 +67,7 @@ public int AdditionalTypeParameterCount { public IType Resolve(ITypeResolveContext context) { - ITypeDefinition declaringType = declaringTypeRef.Resolve(context) as ITypeDefinition; + ITypeDefinition? declaringType = declaringTypeRef.Resolve(context) as ITypeDefinition; if (declaringType != null) { int tpc = declaringType.TypeParameterCount; @@ -95,7 +95,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - NestedTypeReference o = other as NestedTypeReference; + NestedTypeReference? o = other as NestedTypeReference; return o != null && declaringTypeRef == o.declaringTypeRef && name == o.name && additionalTypeParameterCount == o.additionalTypeParameterCount && isReferenceType == o.isReferenceType; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs index 42954b151c..ba4e5dfbff 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs @@ -89,7 +89,7 @@ public IType DeclaringType { if (result != null) return result; IType definitionDeclaringType = baseMember.DeclaringType; - ITypeDefinition definitionDeclaringTypeDef = definitionDeclaringType as ITypeDefinition; + ITypeDefinition? definitionDeclaringTypeDef = definitionDeclaringType as ITypeDefinition; if (definitionDeclaringTypeDef != null && definitionDeclaringType.TypeParameterCount > 0) { if (substitution.ClassTypeArguments != null && substitution.ClassTypeArguments.Count == definitionDeclaringType.TypeParameterCount) @@ -225,7 +225,7 @@ public virtual IMember Specialize(TypeParameterSubstitution newSubstitution) public virtual bool Equals(IMember obj, TypeVisitor typeNormalization) { - SpecializedMember other = obj as SpecializedMember; + SpecializedMember? other = obj as SpecializedMember; if (other == null) return false; return this.baseMember.Equals(other.baseMember, typeNormalization) @@ -234,7 +234,7 @@ public virtual bool Equals(IMember obj, TypeVisitor typeNormalization) public override bool Equals(object obj) { - SpecializedMember other = obj as SpecializedMember; + SpecializedMember? other = obj as SpecializedMember; if (other == null) return false; return this.baseMember.Equals(other.baseMember) && this.substitution.Equals(other.substitution); diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs index e72d6eeb74..623b59a08c 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs @@ -175,7 +175,7 @@ internal set { public override bool Equals(IMember obj, TypeVisitor typeNormalization) { - SpecializedMethod other = obj as SpecializedMethod; + SpecializedMethod? other = obj as SpecializedMethod; if (other == null) return false; return this.baseMember.Equals(other.baseMember, typeNormalization) @@ -184,7 +184,7 @@ public override bool Equals(IMember obj, TypeVisitor typeNormalization) public override bool Equals(object obj) { - SpecializedMethod other = obj as SpecializedMethod; + SpecializedMethod? other = obj as SpecializedMethod; if (other == null) return false; return this.baseMember.Equals(other.baseMember) && this.substitutionWithoutSpecializedTypeParameters.Equals(other.substitutionWithoutSpecializedTypeParameters); @@ -270,7 +270,7 @@ public override int GetHashCode() public override bool Equals(IType other) { // Compare the owner, not the substitution, because the substitution may contain this specialized type parameter recursively - SpecializedTypeParameter o = other as SpecializedTypeParameter; + SpecializedTypeParameter? o = other as SpecializedTypeParameter; return o != null && baseTp.Equals(o.baseTp) && this.Owner.Equals(o.Owner); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/TypeParameterReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/TypeParameterReference.cs index c8d943477d..21c26ae2e4 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/TypeParameterReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/TypeParameterReference.cs @@ -70,7 +70,7 @@ public IType Resolve(ITypeResolveContext context) { if (ownerType == SymbolKind.Method) { - IMethod method = context.CurrentMember as IMethod; + IMethod? method = context.CurrentMember as IMethod; if (method != null && index < method.TypeParameters.Count) { return method.TypeParameters[index]; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs index 9489194bf4..756bfb258a 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs @@ -124,7 +124,7 @@ public override int GetHashCode() public override bool Equals(IType other) { - UnknownType o = other as UnknownType; + UnknownType? o = other as UnknownType; if (o == null) return false; return this.namespaceKnown == o.namespaceKnown && this.fullTypeName == o.fullTypeName && this.isReferenceType == o.isReferenceType; diff --git a/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs b/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs index f9b976fe17..154f063756 100644 --- a/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs @@ -121,7 +121,7 @@ public static IMember GetDerivedMember(IMember baseMember, ITypeDefinition deriv baseMember = baseMember.MemberDefinition; bool includeInterfaces = baseMember.DeclaringTypeDefinition.Kind == TypeKind.Interface; - IMethod method = baseMember as IMethod; + IMethod? method = baseMember as IMethod; if (method != null) { foreach (IMethod derivedMethod in derivedType.Methods) @@ -137,7 +137,7 @@ public static IMember GetDerivedMember(IMember baseMember, ITypeDefinition deriv } } } - IProperty property = baseMember as IProperty; + IProperty? property = baseMember as IProperty; if (property != null) { foreach (IProperty derivedProperty in derivedType.Properties) diff --git a/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs b/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs index 3db10f748c..c8a28fe11e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs @@ -118,7 +118,7 @@ public override int GetHashCode() public override bool Equals(IType other) { - IntersectionType o = other as IntersectionType; + IntersectionType? o = other as IntersectionType; if (o != null && types.Count == o.types.Count) { for (int i = 0; i < types.Count; i++) diff --git a/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs b/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs index bc7ff1bb43..a7c2881fa9 100644 --- a/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs +++ b/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs @@ -471,7 +471,7 @@ IMethod ResolveMethodSpecification(MethodSpecificationHandle methodSpecHandle, G /// Class type arguments are provided by the declaring type stored in the memberRef. /// Method type arguments are provided by the caller. /// - IMethod ResolveMethodReference(MemberReferenceHandle memberRefHandle, GenericContext context, IReadOnlyList methodTypeArguments = null, bool expandVarArgs = true) + IMethod ResolveMethodReference(MemberReferenceHandle memberRefHandle, GenericContext context, IReadOnlyList? methodTypeArguments = null, bool expandVarArgs = true) { var memberRef = metadata.GetMemberReference(memberRefHandle); if (memberRef.GetKind() != MemberReferenceKind.Method) @@ -479,8 +479,8 @@ IMethod ResolveMethodReference(MemberReferenceHandle memberRefHandle, GenericCon throw new BadImageFormatException($"Member reference must be method, but was: {memberRef.GetKind()}"); } MethodSignature signature; - IReadOnlyList classTypeArguments = null; - IMethod method; + IReadOnlyList? classTypeArguments = null; + IMethod? method; if (memberRef.Parent.Kind == HandleKind.MethodDefinition) { method = ResolveMethodDefinition((MethodDefinitionHandle)memberRef.Parent, expandVarArgs: false); @@ -600,7 +600,7 @@ IMethod CreateFakeMethod(IType declaringType, string name, MethodSignature 0) { var typeParameters = new List(); diff --git a/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs b/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs index d87668c353..5959cded99 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs @@ -63,52 +63,52 @@ public override ITypeDefinitionOrUnknown GetDefinitionOrUnknown() return elementType.GetDefinitionOrUnknown(); } - public override IEnumerable GetAccessors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetAccessors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetAccessors(filter, options); } - public override IEnumerable GetConstructors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) + public override IEnumerable GetConstructors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) { return elementType.GetConstructors(filter, options); } - public override IEnumerable GetEvents(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetEvents(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetEvents(filter, options); } - public override IEnumerable GetFields(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetFields(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetFields(filter, options); } - public override IEnumerable GetMembers(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetMembers(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetMembers(filter, options); } - public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetMethods(typeArguments, filter, options); } - public override IEnumerable GetMethods(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetMethods(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetMethods(filter, options); } - public override IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetNestedTypes(typeArguments, filter, options); } - public override IEnumerable GetNestedTypes(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetNestedTypes(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetNestedTypes(filter, options); } - public override IEnumerable GetProperties(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetProperties(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return elementType.GetProperties(filter, options); } diff --git a/ICSharpCode.Decompiler/TypeSystem/NullableType.cs b/ICSharpCode.Decompiler/TypeSystem/NullableType.cs index 0fa4618900..81580cd86d 100644 --- a/ICSharpCode.Decompiler/TypeSystem/NullableType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/NullableType.cs @@ -32,7 +32,7 @@ public static bool IsNullable(IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); - ParameterizedType pt = type.SkipModifiers() as ParameterizedType; + ParameterizedType? pt = type.SkipModifiers() as ParameterizedType; return pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT); } @@ -49,7 +49,7 @@ public static IType GetUnderlyingType(IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); - ParameterizedType pt = type.SkipModifiers() as ParameterizedType; + ParameterizedType? pt = type.SkipModifiers() as ParameterizedType; if (pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT)) return pt.GetTypeArgument(0); else diff --git a/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs b/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs index af823370ce..dc91fd6bb8 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs @@ -131,12 +131,12 @@ public bool Equals(IMember x, IMember y) return true; if (x == null || y == null || x.SymbolKind != y.SymbolKind || !nameComparer.Equals(x.Name, y.Name)) return false; - IParameterizedMember px = x as IParameterizedMember; - IParameterizedMember py = y as IParameterizedMember; + IParameterizedMember? px = x as IParameterizedMember; + IParameterizedMember? py = y as IParameterizedMember; if (px != null && py != null) { - IMethod mx = x as IMethod; - IMethod my = y as IMethod; + IMethod? mx = x as IMethod; + IMethod? my = y as IMethod; if (mx != null && my != null && mx.TypeParameters.Count != my.TypeParameters.Count) return false; return ParameterListComparer.Instance.Equals(px.Parameters, py.Parameters); @@ -152,12 +152,12 @@ public int GetHashCode(IMember obj) unchecked { int hash = (int)obj.SymbolKind * 33 + nameComparer.GetHashCode(obj.Name); - IParameterizedMember pm = obj as IParameterizedMember; + IParameterizedMember? pm = obj as IParameterizedMember; if (pm != null) { hash *= 27; hash += ParameterListComparer.Instance.GetHashCode(pm.Parameters); - IMethod m = pm as IMethod; + IMethod? m = pm as IMethod; if (m != null) hash += m.TypeParameters.Count; } diff --git a/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs b/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs index 3acc578604..693c1bf2b8 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs @@ -53,12 +53,12 @@ public ParameterizedType(IType genericType, IEnumerable typeArguments) throw new ArgumentException("Cannot use ParameterizedType with 0 type arguments."); if (genericType.TypeParameterCount != this.typeArguments.Length) throw new ArgumentException("Number of type arguments must match the type definition's number of type parameters"); - ICompilationProvider gp = genericType as ICompilationProvider; + ICompilationProvider? gp = genericType as ICompilationProvider; for (int i = 0; i < this.typeArguments.Length; i++) { if (this.typeArguments[i] == null) throw new ArgumentNullException("typeArguments[" + i + "]"); - ICompilationProvider p = this.typeArguments[i] as ICompilationProvider; + ICompilationProvider? p = this.typeArguments[i] as ICompilationProvider; if (p != null && gp != null && p.Compilation != gp.Compilation) throw new InvalidOperationException("Cannot parameterize a type with type arguments from a different compilation."); } @@ -199,7 +199,7 @@ public TypeParameterSubstitution GetSubstitution() /// of this parameterized type, /// and also substitutes method type parameters with the specified method type arguments. /// - public TypeParameterSubstitution GetSubstitution(IReadOnlyList methodTypeArguments) + public TypeParameterSubstitution GetSubstitution(IReadOnlyList? methodTypeArguments) { return new TypeParameterSubstitution(typeArguments, methodTypeArguments); } @@ -211,7 +211,7 @@ public IEnumerable DirectBaseTypes { } } - public IEnumerable GetNestedTypes(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetNestedTypes(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetNestedTypes(filter, options); @@ -219,7 +219,7 @@ public IEnumerable GetNestedTypes(Predicate filter = nul return GetMembersHelper.GetNestedTypes(this, filter, options); } - public IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetNestedTypes(typeArguments, filter, options); @@ -227,7 +227,7 @@ public IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Pre return GetMembersHelper.GetNestedTypes(this, typeArguments, filter, options); } - public IEnumerable GetConstructors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) + public IEnumerable GetConstructors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetConstructors(filter, options); @@ -235,7 +235,7 @@ public IEnumerable GetConstructors(Predicate filter = null, Ge return GetMembersHelper.GetConstructors(this, filter, options); } - public IEnumerable GetMethods(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMethods(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetMethods(filter, options); @@ -243,7 +243,7 @@ public IEnumerable GetMethods(Predicate filter = null, GetMemb return GetMembersHelper.GetMethods(this, filter, options); } - public IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetMethods(typeArguments, filter, options); @@ -251,7 +251,7 @@ public IEnumerable GetMethods(IReadOnlyList typeArguments, Predi return GetMembersHelper.GetMethods(this, typeArguments, filter, options); } - public IEnumerable GetProperties(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetProperties(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetProperties(filter, options); @@ -259,7 +259,7 @@ public IEnumerable GetProperties(Predicate filter = null, return GetMembersHelper.GetProperties(this, filter, options); } - public IEnumerable GetFields(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetFields(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetFields(filter, options); @@ -267,7 +267,7 @@ public IEnumerable GetFields(Predicate filter = null, GetMemberO return GetMembersHelper.GetFields(this, filter, options); } - public IEnumerable GetEvents(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetEvents(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetEvents(filter, options); @@ -275,7 +275,7 @@ public IEnumerable GetEvents(Predicate filter = null, GetMemberO return GetMembersHelper.GetEvents(this, filter, options); } - public IEnumerable GetMembers(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetMembers(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetMembers(filter, options); @@ -283,7 +283,7 @@ public IEnumerable GetMembers(Predicate filter = null, GetMemb return GetMembersHelper.GetMembers(this, filter, options); } - public IEnumerable GetAccessors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public IEnumerable GetAccessors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) return genericType.GetAccessors(filter, options); @@ -300,7 +300,7 @@ public bool Equals(IType other) { if (this == other) return true; - ParameterizedType c = other as ParameterizedType; + ParameterizedType? c = other as ParameterizedType; if (c == null || !genericType.Equals(c.genericType) || typeArguments.Length != c.typeArguments.Length) return false; for (int i = 0; i < typeArguments.Length; i++) @@ -334,7 +334,7 @@ public IType VisitChildren(TypeVisitor visitor) { IType g = genericType.AcceptVisitor(visitor); // Keep ta == null as long as no elements changed, allocate the array only if necessary. - IType[] ta = (g != genericType) ? new IType[typeArguments.Length] : null; + IType[]? ta = (g != genericType) ? new IType[typeArguments.Length] : null; for (int i = 0; i < typeArguments.Length; i++) { IType r = typeArguments[i].AcceptVisitor(visitor); @@ -443,7 +443,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - ParameterizedTypeReference o = other as ParameterizedTypeReference; + ParameterizedTypeReference? o = other as ParameterizedTypeReference; if (o != null && genericType == o.genericType && typeArguments.Length == o.typeArguments.Length) { for (int i = 0; i < typeArguments.Length; i++) diff --git a/ICSharpCode.Decompiler/TypeSystem/PointerType.cs b/ICSharpCode.Decompiler/TypeSystem/PointerType.cs index 3de6cd4b78..c5038e04fa 100644 --- a/ICSharpCode.Decompiler/TypeSystem/PointerType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/PointerType.cs @@ -49,7 +49,7 @@ public override int GetHashCode() public override bool Equals(IType other) { - PointerType a = other as PointerType; + PointerType? a = other as PointerType; return a != null && elementType.Equals(a.elementType); } @@ -101,7 +101,7 @@ int ISupportsInterning.GetHashCodeForInterning() bool ISupportsInterning.EqualsForInterning(ISupportsInterning other) { - PointerTypeReference o = other as PointerTypeReference; + PointerTypeReference? o = other as PointerTypeReference; return o != null && this.elementType == o.elementType; } } diff --git a/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs b/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs index df8e396f12..8a55aa119e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs @@ -229,7 +229,7 @@ public static ITypeReference ToTypeReference(this TypeCode typeCode) /// public static TypeCode GetTypeCode(this IType type) { - ITypeDefinition def = type as ITypeDefinition; + ITypeDefinition? def = type as ITypeDefinition; if (def != null) { KnownTypeCode typeCode = def.KnownTypeCode; @@ -321,7 +321,7 @@ static ITypeReference ParseReflectionName(string reflectionTypeName, ref int pos { // not a type parameter reference: read the actual type name string typeName = ReadTypeName(reflectionTypeName, ref pos, out int tpc); - string assemblyName = local ? null : SkipAheadAndReadAssemblyName(reflectionTypeName, pos); + string? assemblyName = local ? null : SkipAheadAndReadAssemblyName(reflectionTypeName, pos); reference = CreateGetClassTypeReference(assemblyName, typeName, tpc); } // read type suffixes @@ -426,7 +426,7 @@ static ITypeReference ParseReflectionName(string reflectionTypeName, ref int pos static ITypeReference CreateGetClassTypeReference(string assemblyName, string typeName, int tpc) { - IModuleReference assemblyReference; + IModuleReference? assemblyReference; if (assemblyName != null) { assemblyReference = new DefaultAssemblyReference(assemblyName); diff --git a/ICSharpCode.Decompiler/TypeSystem/TaskType.cs b/ICSharpCode.Decompiler/TypeSystem/TaskType.cs index 5289b75b07..ee87d33bcd 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TaskType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TaskType.cs @@ -59,7 +59,7 @@ public static bool IsTask(IType type) /// /// Gets whether the specified type is a Task-like type. /// - public static bool IsCustomTask(IType type, out IType builderType) + public static bool IsCustomTask(IType type, out IType? builderType) { builderType = null; ITypeDefinition def = type.GetDefinition(); diff --git a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs index d77387f4f3..8bf805decd 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs @@ -57,7 +57,7 @@ public sealed class TupleType : AbstractType, ICompilationProvider public TupleType(ICompilation compilation, ImmutableArray elementTypes, ImmutableArray elementNames = default(ImmutableArray), - IModule valueTupleAssembly = null) + IModule? valueTupleAssembly = null) { this.Compilation = compilation; this.UnderlyingType = CreateUnderlyingType(compilation, elementTypes, valueTupleAssembly); @@ -166,7 +166,7 @@ public static TupleType FromUnderlyingType(ICompilation compilation, IType type) /// public static ImmutableArray GetTupleElementTypes(IType tupleType) { - List output = null; + List? output = null; if (Collect(tupleType)) { return output.ToImmutableArray(); @@ -271,7 +271,7 @@ public override IType AcceptVisitor(TypeVisitor visitor) public override IType VisitChildren(TypeVisitor visitor) { - IType[] newElementTypes = null; + IType[]? newElementTypes = null; for (int i = 0; i < ElementTypes.Length; i++) { IType type = ElementTypes[i]; @@ -296,12 +296,12 @@ public override IType VisitChildren(TypeVisitor visitor) } } - public override IEnumerable GetAccessors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetAccessors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return UnderlyingType.GetAccessors(filter, options); } - public override IEnumerable GetConstructors(Predicate filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) + public override IEnumerable GetConstructors(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers) { // CS8181 'new' cannot be used with tuple type. Use a tuple literal expression instead. return EmptyList.Instance; @@ -317,12 +317,12 @@ public override ITypeDefinitionOrUnknown GetDefinitionOrUnknown() return UnderlyingType.GetDefinitionOrUnknown(); } - public override IEnumerable GetEvents(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetEvents(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return UnderlyingType.GetEvents(filter, options); } - public override IEnumerable GetFields(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetFields(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { // The fields from the underlying type (Item1..Item7 and Rest) foreach (var field in UnderlyingType.GetFields(filter, options)) @@ -349,27 +349,27 @@ public override IEnumerable GetFields(Predicate filter = null, G return new TupleElementField(f, Compilation.TypeResolveContext); }*/ - public override IEnumerable GetMethods(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetMethods(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return UnderlyingType.GetMethods(filter, options); } - public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return UnderlyingType.GetMethods(typeArguments, filter, options); } - public override IEnumerable GetNestedTypes(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetNestedTypes(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return UnderlyingType.GetNestedTypes(filter, options); } - public override IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return UnderlyingType.GetNestedTypes(typeArguments, filter, options); } - public override IEnumerable GetProperties(Predicate filter = null, GetMemberOptions options = GetMemberOptions.None) + public override IEnumerable GetProperties(Predicate? filter = null, GetMemberOptions options = GetMemberOptions.None) { return UnderlyingType.GetProperties(filter, options); } @@ -396,7 +396,7 @@ public TupleTypeReference(ImmutableArray elementTypes) public TupleTypeReference(ImmutableArray elementTypes, ImmutableArray elementNames = default(ImmutableArray), - IModuleReference valueTupleAssembly = null) + IModuleReference? valueTupleAssembly = null) { this.ValueTupleAssembly = valueTupleAssembly; this.ElementTypes = elementTypes; diff --git a/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs b/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs index 0202f72fa1..6150688e48 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs @@ -33,8 +33,8 @@ public class TypeParameterSubstitution : TypeVisitor /// public static readonly TypeParameterSubstitution Identity = new TypeParameterSubstitution(null, null); - readonly IReadOnlyList classTypeArguments; - readonly IReadOnlyList methodTypeArguments; + readonly IReadOnlyList? classTypeArguments; + readonly IReadOnlyList? methodTypeArguments; /// /// Creates a new type parameter substitution. @@ -47,7 +47,7 @@ public class TypeParameterSubstitution : TypeVisitor /// The type arguments to substitute for method type parameters. /// Pass null to keep method type parameters unmodified. /// - public TypeParameterSubstitution(IReadOnlyList classTypeArguments, IReadOnlyList methodTypeArguments) + public TypeParameterSubstitution(IReadOnlyList? classTypeArguments, IReadOnlyList? methodTypeArguments) { this.classTypeArguments = classTypeArguments; this.methodTypeArguments = methodTypeArguments; @@ -57,7 +57,7 @@ public TypeParameterSubstitution(IReadOnlyList classTypeArguments, IReadO /// Gets the list of class type arguments. /// Returns null if this substitution keeps class type parameters unmodified. /// - public IReadOnlyList ClassTypeArguments { + public IReadOnlyList? ClassTypeArguments { get { return classTypeArguments; } } @@ -65,7 +65,7 @@ public IReadOnlyList ClassTypeArguments { /// Gets the list of method type arguments. /// Returns null if this substitution keeps method type parameters unmodified. /// - public IReadOnlyList MethodTypeArguments { + public IReadOnlyList? MethodTypeArguments { get { return methodTypeArguments; } } @@ -109,9 +109,9 @@ public bool Equals(TypeParameterSubstitution other, TypeVisitor normalization) && TypeListEquals(methodTypeArguments, other.methodTypeArguments, normalization); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - TypeParameterSubstitution other = obj as TypeParameterSubstitution; + TypeParameterSubstitution? other = obj as TypeParameterSubstitution; if (other == null) return false; return TypeListEquals(classTypeArguments, other.classTypeArguments) @@ -126,7 +126,7 @@ public override int GetHashCode() } } - static bool TypeListEquals(IReadOnlyList a, IReadOnlyList b) + static bool TypeListEquals(IReadOnlyList? a, IReadOnlyList? b) { if (a == b) return true; @@ -142,7 +142,7 @@ static bool TypeListEquals(IReadOnlyList a, IReadOnlyList b) return true; } - static bool TypeListEquals(IReadOnlyList a, IReadOnlyList b, TypeVisitor normalization) + static bool TypeListEquals(IReadOnlyList? a, IReadOnlyList? b, TypeVisitor normalization) { if (a == b) return true; @@ -160,7 +160,7 @@ static bool TypeListEquals(IReadOnlyList a, IReadOnlyList b, TypeV return true; } - static int TypeListHashCode(IReadOnlyList obj) + static int TypeListHashCode(IReadOnlyList? obj) { if (obj == null) return 0; diff --git a/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs b/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs index e26781cfbf..ca75ab3a7e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs @@ -89,7 +89,7 @@ public static IEnumerable GetAllBaseTypeDefinitions(this IType /// /// Gets whether this type definition is derived from the base type definition. /// - public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType) + public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition? baseType) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -234,7 +234,7 @@ public static bool IsUnbound(this IType type) /// public static bool IsUnmanagedType(this IType type, bool allowGenerics) { - HashSet types = null; + HashSet? types = null; return IsUnmanagedTypeInternal(type); bool IsUnmanagedTypeInternal(IType type) @@ -660,7 +660,7 @@ public static IType GetElementTypeFromIEnumerable(this IType collectionType, ICo KnownTypeCode typeCode = baseTypeDef.KnownTypeCode; if (typeCode == KnownTypeCode.IEnumerableOfT || (allowIEnumerator && typeCode == KnownTypeCode.IEnumeratorOfT)) { - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { isGeneric = true; diff --git a/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs b/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs index 07175fc03f..e48653d42e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs @@ -60,7 +60,7 @@ public IReadOnlyList Parameters { public override bool Equals(object obj) { - VarArgInstanceMethod other = obj as VarArgInstanceMethod; + VarArgInstanceMethod? other = obj as VarArgInstanceMethod; return other != null && baseMethod.Equals(other.baseMethod); } @@ -71,7 +71,7 @@ public override int GetHashCode() public bool Equals(IMember obj, TypeVisitor typeNormalization) { - VarArgInstanceMethod other = obj as VarArgInstanceMethod; + VarArgInstanceMethod? other = obj as VarArgInstanceMethod; return other != null && baseMethod.Equals(other.baseMethod, typeNormalization); } diff --git a/ILSpy/ILSpy.csproj b/ILSpy/ILSpy.csproj index 36a8e7b443..7bed5bc81d 100644 --- a/ILSpy/ILSpy.csproj +++ b/ILSpy/ILSpy.csproj @@ -9,6 +9,7 @@ false false true + enable ICSharpCode.ILSpy True diff --git a/ILSpy/TreeNodes/DerivedTypesTreeNode.cs b/ILSpy/TreeNodes/DerivedTypesTreeNode.cs index d3fd992683..36fdcd7298 100644 --- a/ILSpy/TreeNodes/DerivedTypesTreeNode.cs +++ b/ILSpy/TreeNodes/DerivedTypesTreeNode.cs @@ -73,7 +73,8 @@ internal static IEnumerable FindDerivedTypes(AssemblyList continue; var metadata = module.Metadata; var assembly = module.GetTypeSystemOrNull()?.MainModule as MetadataModule; - if (assembly != null) + + if (assembly == null) continue; foreach (var h in metadata.TypeDefinitions) { From c51ee93a85a8cd757df9eeb05f0d6b0ebd33027e Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Fri, 20 Sep 2024 14:21:48 -0400 Subject: [PATCH 02/15] focus on CS8769 --- .../CSharp/Resolver/CSharpResolver.cs | 6 +-- .../TypeSystem/CSharpTypeResolveContext.cs | 26 ++++----- .../IL/Transforms/TransformExpressionTrees.cs | 54 +++++++++---------- .../TypeSystem/GenericContext.cs | 6 +-- .../Implementation/DecoratedType.cs | 20 +++---- .../TypeSystem/Implementation/FakeMember.cs | 19 +++---- .../Implementation/MetadataEvent.cs | 4 +- .../Implementation/MetadataField.cs | 6 +-- .../Implementation/MetadataMethod.cs | 8 +-- .../Implementation/MetadataProperty.cs | 4 +- .../Implementation/MetadataTypeDefinition.cs | 4 +- .../Implementation/MinimalCorlib.cs | 44 +++++++-------- .../NullabilityAnnotatedType.cs | 2 +- .../Implementation/SyntheticRangeIndexer.cs | 4 +- ICSharpCode.Decompiler/Util/LazyInit.cs | 2 +- 15 files changed, 106 insertions(+), 103 deletions(-) diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs index 239e3af973..bfe1860004 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs @@ -154,7 +154,7 @@ public CSharpResolver WithCurrentMember(IMember member) return WithContext(context.WithCurrentMember(member)); } - ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember member) + ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember? member) { return WithCurrentMember(member); } @@ -188,7 +188,7 @@ public ITypeDefinition CurrentTypeDefinition { /// /// Sets the current type definition. /// - public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition typeDefinition) + public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition? typeDefinition) { if (this.CurrentTypeDefinition == typeDefinition) return this; @@ -203,7 +203,7 @@ public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition typeDefinition) checkForOverflow, isWithinLambdaExpression, newTypeDefinitionCache, localVariableStack, objectInitializerStack); } - ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition typeDefinition) + ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition? typeDefinition) { return WithCurrentTypeDefinition(typeDefinition); } diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs index 9f8d94406c..8a0374f2ce 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/CSharpTypeResolveContext.cs @@ -17,6 +17,7 @@ // DEALINGS IN THE SOFTWARE. using System; +using System.Diagnostics.CodeAnalysis; using ICSharpCode.Decompiler.TypeSystem; @@ -25,10 +26,10 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem public sealed class CSharpTypeResolveContext : ITypeResolveContext { readonly IModule module; - readonly ResolvedUsingScope currentUsingScope; - readonly ITypeDefinition currentTypeDefinition; - readonly IMember currentMember; - readonly string[] methodTypeParameterNames; + readonly ResolvedUsingScope? currentUsingScope; + readonly ITypeDefinition? currentTypeDefinition; + readonly IMember? currentMember; + readonly string[]? methodTypeParameterNames; public CSharpTypeResolveContext(IModule module, ResolvedUsingScope? usingScope = null, ITypeDefinition? typeDefinition = null, IMember? member = null) { @@ -40,7 +41,7 @@ public CSharpTypeResolveContext(IModule module, ResolvedUsingScope? usingScope = this.currentMember = member; } - private CSharpTypeResolveContext(IModule module, ResolvedUsingScope usingScope, ITypeDefinition typeDefinition, IMember member, string[] methodTypeParameterNames) + private CSharpTypeResolveContext(IModule module, ResolvedUsingScope? usingScope, ITypeDefinition? typeDefinition, IMember? member, string[]? methodTypeParameterNames) { this.module = module; this.currentUsingScope = usingScope; @@ -49,7 +50,7 @@ private CSharpTypeResolveContext(IModule module, ResolvedUsingScope usingScope, this.methodTypeParameterNames = methodTypeParameterNames; } - public ResolvedUsingScope CurrentUsingScope { + public ResolvedUsingScope? CurrentUsingScope { get { return currentUsingScope; } } @@ -61,30 +62,31 @@ public IModule CurrentModule { get { return module; } } - public ITypeDefinition CurrentTypeDefinition { + public ITypeDefinition? CurrentTypeDefinition { get { return currentTypeDefinition; } } - public IMember CurrentMember { + public IMember? CurrentMember { get { return currentMember; } } - public CSharpTypeResolveContext WithCurrentTypeDefinition(ITypeDefinition typeDefinition) + + public CSharpTypeResolveContext WithCurrentTypeDefinition(ITypeDefinition? typeDefinition) { return new CSharpTypeResolveContext(module, currentUsingScope, typeDefinition, currentMember, methodTypeParameterNames); } - ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition typeDefinition) + ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition? typeDefinition) { return WithCurrentTypeDefinition(typeDefinition); } - public CSharpTypeResolveContext WithCurrentMember(IMember member) + public CSharpTypeResolveContext WithCurrentMember(IMember? member) { return new CSharpTypeResolveContext(module, currentUsingScope, currentTypeDefinition, member, methodTypeParameterNames); } - ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember member) + ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember? member) { return WithCurrentMember(member); } diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs index fad9630480..690a001504 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs @@ -153,7 +153,7 @@ bool TryConvertExpressionTree(ILInstruction instruction, ILInstruction statement /// Converts a Expression.Lambda call into an ILFunction. /// If the conversion fails, null is returned. /// - (Func, IType) ConvertLambda(CallInstruction instruction) + (Func?, IType) ConvertLambda(CallInstruction instruction) { if (instruction.Method.Name != "Lambda" || instruction.Arguments.Count != 2 || instruction.Method.ReturnType.FullName != "System.Linq.Expressions.Expression" || instruction.Method.ReturnType.TypeArguments.Count != 1) return (null, SpecialType.UnknownType); @@ -198,7 +198,7 @@ ILFunction BuildFunction() } } - (Func, IType) ConvertQuote(CallInstruction invocation) + (Func?, IType) ConvertQuote(CallInstruction invocation) { if (invocation.Arguments.Count != 1) return (null, SpecialType.UnknownType); @@ -266,7 +266,7 @@ bool ReadParameters(ILInstruction initializer, IList parameters, ILi } } - (Func, IType) ConvertInstruction(ILInstruction instruction, IType? typeHint = null) + (Func?, IType) ConvertInstruction(ILInstruction instruction, IType? typeHint = null) { var (inst, type) = Convert(); @@ -289,7 +289,7 @@ ILInstruction DoConvert() } return (DoConvert, typeHint ?? type); - (Func, IType) Convert() + (Func?, IType) Convert() { switch (instruction) { @@ -446,7 +446,7 @@ IType UnwrapExpressionTree(IType delegateType) return delegateType; } - (Func, IType) ConvertArrayIndex(CallInstruction invocation) + (Func?, IType) ConvertArrayIndex(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -473,7 +473,7 @@ ILInstruction Convert() return (Convert, type.ElementType); } - (Func, IType) ConvertArrayLength(CallInstruction invocation) + (Func?, IType) ConvertArrayLength(CallInstruction invocation) { if (invocation.Arguments.Count != 1) return (null, SpecialType.UnknownType); @@ -483,7 +483,7 @@ ILInstruction Convert() return (() => new LdLen(StackType.I4, converted()), context.TypeSystem.FindType(KnownTypeCode.Int32)); } - (Func, IType) ConvertBinaryNumericOperator(CallInstruction invocation, BinaryNumericOperator op, bool? isChecked = null) + (Func?, IType) ConvertBinaryNumericOperator(CallInstruction invocation, BinaryNumericOperator op, bool? isChecked = null) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); @@ -574,7 +574,7 @@ ILInstruction Convert() return (null, SpecialType.UnknownType); } - (Func, IType) ConvertCall(CallInstruction invocation) + (Func?, IType) ConvertCall(CallInstruction invocation) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); @@ -697,7 +697,7 @@ Func[] ConvertCallArguments(IList arguments, IMeth return converted; } - (Func, IType) ConvertCast(CallInstruction invocation, bool isChecked) + (Func?, IType) ConvertCast(CallInstruction invocation, bool isChecked) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); @@ -711,7 +711,7 @@ Func[] ConvertCallArguments(IList arguments, IMeth return (() => new ExpressionTreeCast(targetType, expr(), isChecked), targetType); } - (Func, IType) ConvertCoalesce(CallInstruction invocation) + (Func?, IType) ConvertCoalesce(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -742,7 +742,7 @@ Func[] ConvertCallArguments(IList arguments, IMeth }, targetType); } - (Func, IType) ConvertComparison(CallInstruction invocation, ComparisonKind kind) + (Func?, IType) ConvertComparison(CallInstruction invocation, ComparisonKind kind) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); @@ -790,7 +790,7 @@ Func[] ConvertCallArguments(IList arguments, IMeth return (() => new Comp(kind, lifting, utype.GetStackType(), utype.GetSign(), left(), right()), resultType); } - (Func, IType) ConvertCondition(CallInstruction invocation) + (Func?, IType) ConvertCondition(CallInstruction invocation) { if (invocation.Arguments.Count != 3) return (null, SpecialType.UnknownType); @@ -808,7 +808,7 @@ Func[] ConvertCallArguments(IList arguments, IMeth return (() => new IfInstruction(condition(), trueInst(), falseInst()), trueInstType); } - (Func, IType) ConvertConstant(CallInstruction invocation) + (Func?, IType) ConvertConstant(CallInstruction invocation) { if (!MatchConstantCall(invocation, out var value, out var type)) return (null, SpecialType.UnknownType); @@ -821,7 +821,7 @@ Func[] ConvertCallArguments(IList arguments, IMeth return (() => ConvertValue(value, invocation), type); } - (Func, IType) ConvertElementInit(CallInstruction invocation) + (Func?, IType) ConvertElementInit(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -849,7 +849,7 @@ ILInstruction BuildCall() return (BuildCall, member.ReturnType); } - (Func, IType) ConvertField(CallInstruction invocation, IType typeHint) + (Func?, IType) ConvertField(CallInstruction invocation, IType typeHint) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -896,7 +896,7 @@ ILInstruction BuildField() } } - (Func, IType) ConvertInvoke(CallInstruction invocation) + (Func?, IType) ConvertInvoke(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -922,7 +922,7 @@ ILInstruction BuildCall() return (BuildCall, invokeMethod.ReturnType); } - (Func, IType) ConvertListInit(CallInstruction invocation) + (Func?, IType) ConvertListInit(CallInstruction invocation) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); @@ -978,7 +978,7 @@ Block BuildBlock() return (BuildBlock, ctor.DeclaringType); } - (Func, IType) ConvertLogicOperator(CallInstruction invocation, bool and) + (Func?, IType) ConvertLogicOperator(CallInstruction invocation, bool and) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); @@ -1016,7 +1016,7 @@ Block BuildBlock() } } - (Func, IType) ConvertMemberInit(CallInstruction invocation) + (Func?, IType) ConvertMemberInit(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -1064,7 +1064,7 @@ ILInstruction BuildBlock() return (BuildBlock, ctor.DeclaringType); } - (Func, IType) ConvertNewArrayBounds(CallInstruction invocation) + (Func?, IType) ConvertNewArrayBounds(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -1085,7 +1085,7 @@ ILInstruction BuildBlock() return (() => new NewArr(type, indices.SelectArray(f => f())), new ArrayType(context.TypeSystem, type, arguments.Count)); } - (Func, IType) ConvertNewArrayInit(CallInstruction invocation) + (Func?, IType) ConvertNewArrayInit(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -1154,7 +1154,7 @@ bool MatchNew(CallInstruction invocation, out IMethod? ctor) } } - (Func, IType) ConvertNewObject(CallInstruction invocation) + (Func?, IType) ConvertNewObject(CallInstruction invocation) { switch (invocation.Arguments.Count) { @@ -1203,7 +1203,7 @@ ILInstruction BuildNewObj(IMethod method, Func[] args) return (null, SpecialType.UnknownType); } - (Func, IType) ConvertNotOperator(CallInstruction invocation) + (Func?, IType) ConvertNotOperator(CallInstruction invocation) { if (invocation.Arguments.Count < 1) return (null, SpecialType.UnknownType); @@ -1229,7 +1229,7 @@ ILInstruction BuildNewObj(IMethod method, Func[] args) } } - (Func, IType) ConvertProperty(CallInstruction invocation) + (Func?, IType) ConvertProperty(CallInstruction invocation) { if (invocation.Arguments.Count < 2) return (null, SpecialType.UnknownType); @@ -1272,7 +1272,7 @@ ILInstruction BuildProperty() return (BuildProperty, member.ReturnType); } - (Func, IType) ConvertTypeAs(CallInstruction invocation) + (Func?, IType) ConvertTypeAs(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -1293,7 +1293,7 @@ ILInstruction BuildTypeAs() return (BuildTypeAs, type); } - (Func, IType) ConvertTypeIs(CallInstruction invocation) + (Func?, IType) ConvertTypeIs(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -1306,7 +1306,7 @@ ILInstruction BuildTypeAs() return (null, SpecialType.UnknownType); } - (Func, IType) ConvertUnaryNumericOperator(CallInstruction invocation, BinaryNumericOperator op, bool? isChecked = null) + (Func?, IType) ConvertUnaryNumericOperator(CallInstruction invocation, BinaryNumericOperator op, bool? isChecked = null) { if (invocation.Arguments.Count < 1) return (null, SpecialType.UnknownType); diff --git a/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs b/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs index ddb41c94e1..1521753999 100644 --- a/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs +++ b/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs @@ -25,10 +25,10 @@ namespace ICSharpCode.Decompiler.TypeSystem { public readonly struct GenericContext { - public readonly IReadOnlyList ClassTypeParameters; - public readonly IReadOnlyList MethodTypeParameters; + public readonly IReadOnlyList? ClassTypeParameters; + public readonly IReadOnlyList? MethodTypeParameters; - public GenericContext(IReadOnlyList classTypeParameters) + public GenericContext(IReadOnlyList? classTypeParameters) { this.ClassTypeParameters = classTypeParameters; this.MethodTypeParameters = null; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs index 5107044f2a..5e9f1a5870 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs @@ -44,12 +44,12 @@ protected DecoratedType(IType baseType) public abstract bool Equals(IType other); - IEnumerable IType.GetAccessors(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetAccessors(Predicate? filter, GetMemberOptions options) { return baseType.GetAccessors(filter, options); } - IEnumerable IType.GetConstructors(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetConstructors(Predicate? filter, GetMemberOptions options) { return baseType.GetConstructors(filter, options); } @@ -64,42 +64,42 @@ ITypeDefinitionOrUnknown IType.GetDefinitionOrUnknown() return baseType.GetDefinitionOrUnknown(); } - IEnumerable IType.GetEvents(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetEvents(Predicate? filter, GetMemberOptions options) { return baseType.GetEvents(filter, options); } - IEnumerable IType.GetFields(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetFields(Predicate? filter, GetMemberOptions options) { return baseType.GetFields(filter, options); } - IEnumerable IType.GetMembers(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetMembers(Predicate? filter, GetMemberOptions options) { return baseType.GetMembers(filter, options); } - IEnumerable IType.GetMethods(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetMethods(Predicate? filter, GetMemberOptions options) { return baseType.GetMethods(filter, options); } - IEnumerable IType.GetMethods(IReadOnlyList typeArguments, Predicate filter, GetMemberOptions options) + IEnumerable IType.GetMethods(IReadOnlyList typeArguments, Predicate? filter, GetMemberOptions options) { return baseType.GetMethods(typeArguments, filter, options); } - IEnumerable IType.GetNestedTypes(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetNestedTypes(Predicate? filter, GetMemberOptions options) { return baseType.GetNestedTypes(filter, options); } - IEnumerable IType.GetNestedTypes(IReadOnlyList typeArguments, Predicate filter, GetMemberOptions options) + IEnumerable IType.GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter, GetMemberOptions options) { return baseType.GetNestedTypes(typeArguments, filter, options); } - IEnumerable IType.GetProperties(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetProperties(Predicate? filter, GetMemberOptions options) { return baseType.GetProperties(filter, options); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs index ca9b556d7d..13426414aa 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Reflection; using System.Reflection.Metadata; @@ -94,7 +95,7 @@ string INamedElement.ReflectionName { string INamedElement.Namespace => DeclaringType?.Namespace; - bool IMember.Equals(IMember obj, TypeVisitor typeNormalization) + bool IMember.Equals(IMember? obj, TypeVisitor typeNormalization) { return Equals(obj); } @@ -152,10 +153,10 @@ public FakeMethod(ICompilation compilation, SymbolKind symbolKind) : base(compil bool IMethod.HasBody => false; public bool IsAccessor => AccessorOwner is not null; - public IMember AccessorOwner { get; set; } + public IMember? AccessorOwner { get; set; } public MethodSemanticsAttributes AccessorKind { get; set; } - IMethod IMethod.ReducedFrom => null; + IMethod? IMethod.ReducedFrom => null; public IReadOnlyList Parameters { get; set; } = EmptyList.Instance; @@ -195,11 +196,11 @@ public override IMember Specialize(TypeParameterSubstitution substitution) public bool CanGet => Getter is not null; public bool CanSet => Setter is not null; - public IMethod Getter { get; set; } - public IMethod Setter { get; set; } + public IMethod? Getter { get; set; } + public IMethod? Setter { get; set; } public bool IsIndexer { get; set; } public bool ReturnTypeIsRefReadOnly => false; - public IReadOnlyList Parameters { get; set; } + public IReadOnlyList Parameters { get; set; } = ImmutableArray.Empty; public override string ToString() => "FakeProperty " + ReturnType + " " + DeclaringType.Name + "." + Name + @@ -226,8 +227,8 @@ public override IMember Specialize(TypeParameterSubstitution substitution) public bool CanAdd => AddAccessor is not null; public bool CanRemove => RemoveAccessor is not null; public bool CanInvoke => InvokeAccessor is not null; - public IMethod AddAccessor { get; set; } - public IMethod RemoveAccessor { get; set; } - public IMethod InvokeAccessor { get; set; } + public IMethod? AddAccessor { get; set; } + public IMethod? RemoveAccessor { get; set; } + public IMethod? InvokeAccessor { get; set; } } } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs index 0232760718..d7f1be94b6 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs @@ -164,7 +164,7 @@ public IAttribute GetAttribute(KnownAttribute attribute) public string ReflectionName => $"{DeclaringType?.ReflectionName}.{Name}"; public string Namespace => DeclaringType?.Namespace ?? string.Empty; - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is MetadataEvent ev) { @@ -178,7 +178,7 @@ public override int GetHashCode() return 0x7937039a ^ module.MetadataFile.GetHashCode() ^ handle.GetHashCode(); } - bool IMember.Equals(IMember obj, TypeVisitor typeNormalization) + bool IMember.Equals(IMember? obj, TypeVisitor typeNormalization) { return Equals(obj); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataField.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataField.cs index 4486c90f54..3970ea97c8 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataField.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataField.cs @@ -258,7 +258,7 @@ bool IsDecimalConstant { } } - public object GetConstantValue(bool throwOnInvalidMetadata) + public object? GetConstantValue(bool throwOnInvalidMetadata) { object val = LazyInit.VolatileRead(ref this.constantValue); if (val != null) @@ -295,7 +295,7 @@ public object GetConstantValue(bool throwOnInvalidMetadata) } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is MetadataField f) { @@ -309,7 +309,7 @@ public override int GetHashCode() return 0x11dda32b ^ module.MetadataFile.GetHashCode() ^ handle.GetHashCode(); } - bool IMember.Equals(IMember obj, TypeVisitor typeNormalization) + bool IMember.Equals(IMember? obj, TypeVisitor typeNormalization) { return Equals(obj); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs index a409025103..d81e86d3da 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs @@ -130,7 +130,7 @@ public string Name { public bool HasBody => module.metadata.GetMethodDefinition(handle).HasBody(); - public IMember AccessorOwner { + public IMember? AccessorOwner { get { if (accessorOwner.IsNil) return null; @@ -294,7 +294,7 @@ public IEnumerable ExplicitlyImplementedInterfaceMembers { } IMember IMember.MemberDefinition => this; - IMethod IMethod.ReducedFrom => null; + IMethod? IMethod.ReducedFrom => null; TypeParameterSubstitution IMember.Substitution => TypeParameterSubstitution.Identity; public ITypeDefinition DeclaringTypeDefinition { @@ -602,7 +602,7 @@ public bool IsOverridable public string ReflectionName => $"{DeclaringType?.ReflectionName}.{Name}"; public string Namespace => DeclaringType?.Namespace ?? string.Empty; - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is MetadataMethod m) { @@ -616,7 +616,7 @@ public override int GetHashCode() return 0x5a00d671 ^ module.MetadataFile.GetHashCode() ^ handle.GetHashCode(); } - bool IMember.Equals(IMember obj, TypeVisitor typeNormalization) + bool IMember.Equals(IMember? obj, TypeVisitor typeNormalization) { return Equals(obj); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs index da2d8a4cf6..70e24e7356 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs @@ -298,7 +298,7 @@ Accessibility ComputeAccessibility() public string ReflectionName => $"{DeclaringType?.ReflectionName}.{Name}"; public string Namespace => DeclaringType?.Namespace ?? string.Empty; - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is MetadataProperty p) { @@ -312,7 +312,7 @@ public override int GetHashCode() return 0x32b6a76c ^ module.MetadataFile.GetHashCode() ^ handle.GetHashCode(); } - bool IMember.Equals(IMember obj, TypeVisitor typeNormalization) + bool IMember.Equals(IMember? obj, TypeVisitor typeNormalization) { return Equals(obj); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs index 9d3b2fdc44..a020f991ba 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs @@ -549,7 +549,7 @@ IType IType.VisitChildren(TypeVisitor visitor) return this; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is MetadataTypeDefinition td) { @@ -563,7 +563,7 @@ public override int GetHashCode() return 0x2e0520f2 ^ module.MetadataFile.GetHashCode() ^ handle.GetHashCode(); } - bool IEquatable.Equals(IType other) + bool IEquatable.Equals(IType? other) { return Equals(other); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs index 4f1b9cc8af..11740ab7d3 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs @@ -62,13 +62,13 @@ private MinimalCorlib(ICompilation compilation, IEnumerable string ISymbol.Name => "corlib"; SymbolKind ISymbol.SymbolKind => SymbolKind.Module; - Metadata.MetadataFile IModule.MetadataFile => null; + Metadata.MetadataFile? IModule.MetadataFile => null; INamespace IModule.RootNamespace => rootNamespace; public IEnumerable TopLevelTypeDefinitions => typeDefinitions.Where(td => td != null); public IEnumerable TypeDefinitions => TopLevelTypeDefinitions; - public ITypeDefinition GetTypeDefinition(TopLevelTypeName topLevelTypeName) + public ITypeDefinition? GetTypeDefinition(TopLevelTypeName topLevelTypeName) { foreach (var typeDef in typeDefinitions) { @@ -105,11 +105,11 @@ sealed class CorlibNamespace : INamespace { readonly MinimalCorlib corlib; internal List childNamespaces = new List(); - public INamespace ParentNamespace { get; } + public INamespace? ParentNamespace { get; } public string FullName { get; } public string Name { get; } - public CorlibNamespace(MinimalCorlib corlib, INamespace parentNamespace, string fullName, string name) + public CorlibNamespace(MinimalCorlib corlib, INamespace? parentNamespace, string fullName, string name) { this.corlib = corlib; this.ParentNamespace = parentNamespace; @@ -127,7 +127,7 @@ public CorlibNamespace(MinimalCorlib corlib, INamespace parentNamespace, string SymbolKind ISymbol.SymbolKind => SymbolKind.Namespace; ICompilation ICompilationProvider.Compilation => corlib.Compilation; - INamespace INamespace.GetChildNamespace(string name) + INamespace? INamespace.GetChildNamespace(string name) { return childNamespaces.FirstOrDefault(ns => ns.Name == name); } @@ -148,7 +148,7 @@ public CorlibTypeDefinition(MinimalCorlib corlib, KnownTypeCode typeCode) { this.corlib = corlib; this.typeCode = typeCode; - KnownTypeReference ktr = KnownTypeReference.Get(typeCode); + KnownTypeReference? ktr = KnownTypeReference.Get(typeCode); this.typeKind = ktr.typeKind; this.MetadataName = ktr.Name + (ktr.TypeParameterCount > 0 ? "`" + ktr.TypeParameterCount : ""); } @@ -168,10 +168,10 @@ public CorlibTypeDefinition(MinimalCorlib corlib, KnownTypeCode typeCode) public string MetadataName { get; } - ITypeDefinition IEntity.DeclaringTypeDefinition => null; - IType ITypeDefinition.DeclaringType => null; - IType IType.DeclaringType => null; - IType IEntity.DeclaringType => null; + ITypeDefinition? IEntity.DeclaringTypeDefinition => null; + IType? ITypeDefinition.DeclaringType => null; + IType? IType.DeclaringType => null; + IType? IEntity.DeclaringType => null; bool ITypeDefinition.HasExtensionMethods => false; bool ITypeDefinition.IsReadOnly => false; @@ -248,61 +248,61 @@ string INamedElement.FullName { string INamedElement.Namespace => KnownTypeReference.Get(typeCode).Namespace; - bool IEquatable.Equals(IType other) + bool IEquatable.Equals(IType? other) { return this == other; } - IEnumerable IType.GetAccessors(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetAccessors(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } IEnumerable IEntity.GetAttributes() => EmptyList.Instance; bool IEntity.HasAttribute(KnownAttribute attribute) => false; - IAttribute IEntity.GetAttribute(KnownAttribute attribute) => null; + IAttribute? IEntity.GetAttribute(KnownAttribute attribute) => null; - IEnumerable IType.GetConstructors(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetConstructors(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetEvents(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetEvents(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetFields(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetFields(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetMembers(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetMembers(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetMethods(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetMethods(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetMethods(IReadOnlyList typeArguments, Predicate filter, GetMemberOptions options) + IEnumerable IType.GetMethods(IReadOnlyList typeArguments, Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetNestedTypes(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetNestedTypes(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetNestedTypes(IReadOnlyList typeArguments, Predicate filter, GetMemberOptions options) + IEnumerable IType.GetNestedTypes(IReadOnlyList typeArguments, Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } - IEnumerable IType.GetProperties(Predicate filter, GetMemberOptions options) + IEnumerable IType.GetProperties(Predicate? filter, GetMemberOptions options) { return EmptyList.Instance; } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/NullabilityAnnotatedType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/NullabilityAnnotatedType.cs index abfd5b184b..63b9d50852 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/NullabilityAnnotatedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/NullabilityAnnotatedType.cs @@ -34,7 +34,7 @@ public override IType AcceptVisitor(TypeVisitor visitor) return visitor.VisitNullabilityAnnotatedType(this); } - public override bool Equals(IType other) + public override bool Equals(IType? other) { return other is NullabilityAnnotatedType nat && nat.nullability == nullability diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SyntheticRangeIndexer.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SyntheticRangeIndexer.cs index 2bc60031ec..8c0072e2d5 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SyntheticRangeIndexer.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SyntheticRangeIndexer.cs @@ -105,7 +105,7 @@ public SyntheticRangeIndexAccessor(IMethod underlyingMethod, IType indexOrRangeT string INamedElement.ReflectionName => underlyingMethod.ReflectionName; string INamedElement.Namespace => underlyingMethod.Namespace; - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is SyntheticRangeIndexAccessor g && this.underlyingMethod.Equals(g.underlyingMethod) @@ -118,7 +118,7 @@ public override int GetHashCode() return underlyingMethod.GetHashCode() ^ indexOrRangeType.GetHashCode(); } - bool IMember.Equals(IMember obj, TypeVisitor typeNormalization) + bool IMember.Equals(IMember? obj, TypeVisitor typeNormalization) { return obj is SyntheticRangeIndexAccessor g && this.underlyingMethod.Equals(g.underlyingMethod, typeNormalization) diff --git a/ICSharpCode.Decompiler/Util/LazyInit.cs b/ICSharpCode.Decompiler/Util/LazyInit.cs index d19344cd4e..77589b46f7 100644 --- a/ICSharpCode.Decompiler/Util/LazyInit.cs +++ b/ICSharpCode.Decompiler/Util/LazyInit.cs @@ -35,7 +35,7 @@ public static T VolatileRead(ref T location) where T : class? /// - If target is not null: returns target. /// [return: NotNullIfNotNull("newValue")] - public static T? GetOrSet(ref T? target, T? newValue) where T : class + public static T? GetOrSet([NotNullIfNotNull(nameof(newValue))] ref T? target, T? newValue) where T : class { T? oldValue = Interlocked.CompareExchange(ref target, newValue, null); return oldValue ?? newValue; From 049bb33577361d2ab5a7de776caf0c54678807e4 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Fri, 20 Sep 2024 14:35:07 -0400 Subject: [PATCH 03/15] focus on CS8768 and CS8767 --- .../CSharp/Syntax/PatternMatching/INode.cs | 4 ++-- .../Documentation/XmlDocumentationProvider.cs | 2 +- ICSharpCode.Decompiler/Semantics/Conversion.cs | 18 +++++++++--------- .../TypeSystem/Implementation/AbstractType.cs | 10 +++++----- .../TypeSystem/Implementation/DecoratedType.cs | 8 ++++---- .../Implementation/GetMembersHelper.cs | 12 ++++++------ .../Implementation/LocalFunctionMethod.cs | 12 ++++++------ .../Implementation/MetadataMethod.cs | 2 +- .../Implementation/SimpleCompilation.cs | 2 +- .../Implementation/SpecializedField.cs | 2 +- .../Implementation/SpecializedMember.cs | 8 ++++---- .../Implementation/SpecializedMethod.cs | 14 +++++++------- .../TypeSystem/Implementation/UnknownType.cs | 2 +- .../TypeSystem/ModifiedType.cs | 2 +- .../TypeSystem/ParameterListComparer.cs | 4 ++-- .../TypeSystem/ParameterizedType.cs | 4 ++-- .../TypeSystem/SimpleTypeResolveContext.cs | 4 ++-- .../TypeSystem/VarArgInstanceMethod.cs | 6 +++--- 18 files changed, 58 insertions(+), 58 deletions(-) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs index d1e3fc6e73..327204e3eb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs @@ -26,8 +26,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching public interface INode { Role Role { get; } - INode FirstChild { get; } - INode NextSibling { get; } + INode? FirstChild { get; } + INode? NextSibling { get; } bool IsNull { get; } bool DoMatch(INode other, Match match); diff --git a/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs b/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs index f2b4b2ad99..af9bf21f79 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs @@ -437,7 +437,7 @@ string LoadDocumentation(string key, int positionInFile) } #endregion - public virtual void OnDeserialization(object sender) + public virtual void OnDeserialization(object? sender) { cache = new XmlDocumentationCache(); } diff --git a/ICSharpCode.Decompiler/Semantics/Conversion.cs b/ICSharpCode.Decompiler/Semantics/Conversion.cs index 792b49bb00..1d5248527f 100644 --- a/ICSharpCode.Decompiler/Semantics/Conversion.cs +++ b/ICSharpCode.Decompiler/Semantics/Conversion.cs @@ -168,7 +168,7 @@ public override string ToString() + " conversion"; } - public override bool Equals(Conversion other) + public override bool Equals(Conversion? other) { NumericOrEnumerationConversion? o = other as NumericOrEnumerationConversion; return o != null && isImplicit == o.isImplicit && isLifted == o.isLifted && isEnumeration == o.isEnumeration; @@ -335,7 +335,7 @@ public override IMethod Method { get { return method; } } - public override bool Equals(Conversion other) + public override bool Equals(Conversion? other) { UserDefinedConv? o = other as UserDefinedConv; return o != null && isLifted == o.isLifted && isImplicit == o.isImplicit && isValid == o.isValid && method.Equals(o.method); @@ -394,7 +394,7 @@ public override IMethod Method { get { return method; } } - public override bool Equals(Conversion other) + public override bool Equals(Conversion? other) { MethodGroupConv? o = other as MethodGroupConv; return o != null && method.Equals(o.method); @@ -419,7 +419,7 @@ public TupleConv(ImmutableArray elementConversions) this.IsImplicit = elementConversions.All(c => c.IsImplicit); } - public override bool Equals(Conversion other) + public override bool Equals(Conversion? other) { return other is TupleConv o && ElementConversions.SequenceEqual(o.ElementConversions); @@ -534,14 +534,14 @@ public virtual bool IsUserDefined { /// /// The conversion that is applied to the input before the user-defined conversion operator is invoked. /// - public virtual Conversion ConversionBeforeUserDefinedOperator { + public virtual Conversion? ConversionBeforeUserDefinedOperator { get { return null; } } /// /// The conversion that is applied to the result of the user-defined conversion operator. /// - public virtual Conversion ConversionAfterUserDefinedOperator { + public virtual Conversion? ConversionAfterUserDefinedOperator { get { return null; } } @@ -602,7 +602,7 @@ public virtual bool IsAnonymousFunctionConversion { /// For user-defined conversions, this is the method being called. /// For method-group conversions, this is the method that was chosen from the group. /// - public virtual IMethod Method { + public virtual IMethod? Method { get { return null; } } @@ -621,7 +621,7 @@ public virtual IMethod Method { /// public virtual ImmutableArray ElementConversions => default(ImmutableArray); - public override sealed bool Equals(object obj) + public override sealed bool Equals(object? obj) { return Equals(obj as Conversion); } @@ -631,7 +631,7 @@ public override int GetHashCode() return base.GetHashCode(); } - public virtual bool Equals(Conversion other) + public virtual bool Equals(Conversion? other) { return this == other; } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs index c69467999f..fd9e25ace8 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs @@ -83,16 +83,16 @@ public virtual IReadOnlyList TypeArguments { get { return EmptyList.Instance; } } - public virtual IType DeclaringType { + public virtual IType? DeclaringType { get { return null; } } - public virtual ITypeDefinition GetDefinition() + public virtual ITypeDefinition? GetDefinition() { return null; } - public virtual ITypeDefinitionOrUnknown GetDefinitionOrUnknown() + public virtual ITypeDefinitionOrUnknown? GetDefinitionOrUnknown() { return null; } @@ -165,7 +165,7 @@ public TypeParameterSubstitution GetSubstitution(IReadOnlyList methodType return TypeParameterSubstitution.Identity; } - public override sealed bool Equals(object obj) + public override sealed bool Equals(object? obj) { return Equals(obj as IType); } @@ -175,7 +175,7 @@ public override int GetHashCode() return base.GetHashCode(); } - public virtual bool Equals(IType other) + public virtual bool Equals(IType? other) { return this == other; // use reference equality by default } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs index 5e9f1a5870..a3d25f8225 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs @@ -22,7 +22,7 @@ protected DecoratedType(IType baseType) Nullability IType.Nullability => baseType.Nullability; public abstract IType ChangeNullability(Nullability nullability); - IType IType.DeclaringType => baseType.DeclaringType; + IType? IType.DeclaringType => baseType.DeclaringType; int IType.TypeParameterCount => baseType.TypeParameterCount; @@ -42,7 +42,7 @@ protected DecoratedType(IType baseType) public abstract IType AcceptVisitor(TypeVisitor visitor); - public abstract bool Equals(IType other); + public abstract bool Equals(IType? other); IEnumerable IType.GetAccessors(Predicate? filter, GetMemberOptions options) { @@ -54,12 +54,12 @@ IEnumerable IType.GetConstructors(Predicate? filter, GetMember return baseType.GetConstructors(filter, options); } - ITypeDefinition IType.GetDefinition() + ITypeDefinition? IType.GetDefinition() { return baseType.GetDefinition(); } - ITypeDefinitionOrUnknown IType.GetDefinitionOrUnknown() + ITypeDefinitionOrUnknown? IType.GetDefinitionOrUnknown() { return baseType.GetDefinitionOrUnknown(); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs index 2ce8d45df3..285403b712 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs @@ -98,12 +98,12 @@ static IEnumerable GetNestedTypesImpl(IType outerType, IReadOnlyList GetMethods(IType type, Predicate filter, GetMemberOptions options) + public static IEnumerable GetMethods(IType type, Predicate? filter, GetMemberOptions options) { return GetMethods(type, null, filter, options); } - public static IEnumerable GetMethods(IType type, IReadOnlyList typeArguments, Predicate filter, GetMemberOptions options) + public static IEnumerable GetMethods(IType type, IReadOnlyList? typeArguments, Predicate? filter, GetMemberOptions options) { if (typeArguments != null && typeArguments.Count > 0) { @@ -127,7 +127,7 @@ static Predicate FilterTypeParameterCount(int expectedTypeParameterCoun const GetMemberOptions declaredMembers = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions; - static IEnumerable GetMethodsImpl(IType baseType, IReadOnlyList? methodTypeArguments, Predicate filter, GetMemberOptions options) + static IEnumerable GetMethodsImpl(IType baseType, IReadOnlyList? methodTypeArguments, Predicate? filter, GetMemberOptions options) { IEnumerable declaredMethods = baseType.GetMethods(filter, options | declaredMembers); @@ -164,7 +164,7 @@ static IEnumerable GetMethodsImpl(IType baseType, IReadOnlyList? #endregion #region GetAccessors - public static IEnumerable GetAccessors(IType type, Predicate filter, GetMemberOptions options) + public static IEnumerable GetAccessors(IType type, Predicate? filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { @@ -323,7 +323,7 @@ static IEnumerable GetEventsImpl(IType baseType, Predicate filte #endregion #region GetMembers - public static IEnumerable GetMembers(IType type, Predicate filter, GetMemberOptions options) + public static IEnumerable GetMembers(IType type, Predicate? filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { @@ -335,7 +335,7 @@ public static IEnumerable GetMembers(IType type, Predicate fil } } - static IEnumerable GetMembersImpl(IType baseType, Predicate filter, GetMemberOptions options) + static IEnumerable GetMembersImpl(IType baseType, Predicate? filter, GetMemberOptions options) { foreach (var m in GetMethodsImpl(baseType, null, filter, options)) yield return m; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs index 30d7aa60bc..b63f220b59 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs @@ -43,7 +43,7 @@ public LocalFunctionMethod(IMethod baseMethod, string name, bool isStaticLocalFu this.NumberOfCompilerGeneratedTypeParameters = numberOfCompilerGeneratedTypeParameters; } - public bool Equals(IMember obj, TypeVisitor typeNormalization) + public bool Equals(IMember? obj, TypeVisitor typeNormalization) { if (!(obj is LocalFunctionMethod other)) return false; @@ -53,7 +53,7 @@ public bool Equals(IMember obj, TypeVisitor typeNormalization) && IsStaticLocalFunction == other.IsStaticLocalFunction; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is LocalFunctionMethod other)) return false; @@ -108,7 +108,7 @@ IMember IMember.Specialize(TypeParameterSubstitution substitution) public bool IsOperator => baseMethod.IsOperator; public bool HasBody => baseMethod.HasBody; public bool IsAccessor => baseMethod.IsAccessor; - public IMember AccessorOwner => baseMethod.AccessorOwner; + public IMember? AccessorOwner => baseMethod.AccessorOwner; public MethodSemanticsAttributes AccessorKind => baseMethod.AccessorKind; public IMethod ReducedFrom => baseMethod; @@ -141,12 +141,12 @@ public IReadOnlyList Parameters { public System.Reflection.Metadata.EntityHandle MetadataToken => baseMethod.MetadataToken; public SymbolKind SymbolKind => baseMethod.SymbolKind; - public ITypeDefinition DeclaringTypeDefinition => baseMethod.DeclaringTypeDefinition; + public ITypeDefinition? DeclaringTypeDefinition => baseMethod.DeclaringTypeDefinition; public IType DeclaringType => baseMethod.DeclaringType; - public IModule ParentModule => baseMethod.ParentModule; + public IModule? ParentModule => baseMethod.ParentModule; IEnumerable IEntity.GetAttributes() => baseMethod.GetAttributes(); bool IEntity.HasAttribute(KnownAttribute attribute) => baseMethod.HasAttribute(attribute); - IAttribute IEntity.GetAttribute(KnownAttribute attribute) => baseMethod.GetAttribute(attribute); + IAttribute? IEntity.GetAttribute(KnownAttribute attribute) => baseMethod.GetAttribute(attribute); IEnumerable IMethod.GetReturnTypeAttributes() => baseMethod.GetReturnTypeAttributes(); bool IMethod.ReturnTypeIsRefReadOnly => baseMethod.ReturnTypeIsRefReadOnly; bool IMethod.ThisIsRefReadOnly => baseMethod.ThisIsRefReadOnly; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs index d81e86d3da..8bdb5c2651 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs @@ -476,7 +476,7 @@ public bool HasAttribute(KnownAttribute attribute) return b.HasAttribute(metadata, def.GetCustomAttributes(), attribute, symbolKind); } - public IAttribute GetAttribute(KnownAttribute attribute) + public IAttribute? GetAttribute(KnownAttribute attribute) { if (!attribute.IsCustomAttribute()) { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs index ade71cf714..1257c0b661 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs @@ -140,7 +140,7 @@ public CacheManager CacheManager { get { return cacheManager; } } - public virtual INamespace GetNamespaceForExternAlias(string alias) + public virtual INamespace? GetNamespaceForExternAlias(string? alias) { if (string.IsNullOrEmpty(alias)) return this.RootNamespace; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs index fe4dc9ccc9..1636603137 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs @@ -57,7 +57,7 @@ public bool IsConst { get { return fieldDefinition.IsConst; } } - public object GetConstantValue(bool throwOnInvalidMetadata) + public object? GetConstantValue(bool throwOnInvalidMetadata) { return fieldDefinition.GetConstantValue(throwOnInvalidMetadata); } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs index ba4e5dfbff..0f8f557341 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs @@ -157,7 +157,7 @@ public SymbolKind SymbolKind { get { return baseMember.SymbolKind; } } - public ITypeDefinition DeclaringTypeDefinition { + public ITypeDefinition? DeclaringTypeDefinition { get { return baseMember.DeclaringTypeDefinition; } } @@ -214,7 +214,7 @@ public ICompilation Compilation { get { return baseMember.Compilation; } } - public IModule ParentModule { + public IModule? ParentModule { get { return baseMember.ParentModule; } } @@ -223,7 +223,7 @@ public virtual IMember Specialize(TypeParameterSubstitution newSubstitution) return baseMember.Specialize(TypeParameterSubstitution.Compose(newSubstitution, this.substitution)); } - public virtual bool Equals(IMember obj, TypeVisitor typeNormalization) + public virtual bool Equals(IMember? obj, TypeVisitor typeNormalization) { SpecializedMember? other = obj as SpecializedMember; if (other == null) @@ -232,7 +232,7 @@ public virtual bool Equals(IMember obj, TypeVisitor typeNormalization) && this.substitution.Equals(other.substitution, typeNormalization); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { SpecializedMember? other = obj as SpecializedMember; if (other == null) diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs index 623b59a08c..774efea03f 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs @@ -146,13 +146,13 @@ public bool IsAccessor { public MethodSemanticsAttributes AccessorKind => methodDefinition.AccessorKind; - public IMethod ReducedFrom { + public IMethod? ReducedFrom { get { return null; } } - IMember accessorOwner; + IMember? accessorOwner; - public IMember AccessorOwner { + public IMember? AccessorOwner { get { var result = LazyInit.VolatileRead(ref accessorOwner); if (result != null) @@ -173,7 +173,7 @@ internal set { } } - public override bool Equals(IMember obj, TypeVisitor typeNormalization) + public override bool Equals(IMember? obj, TypeVisitor typeNormalization) { SpecializedMethod? other = obj as SpecializedMethod; if (other == null) @@ -182,7 +182,7 @@ public override bool Equals(IMember obj, TypeVisitor typeNormalization) && this.substitutionWithoutSpecializedTypeParameters.Equals(other.substitutionWithoutSpecializedTypeParameters, typeNormalization); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { SpecializedMethod? other = obj as SpecializedMethod; if (other == null) @@ -267,11 +267,11 @@ public override int GetHashCode() return baseTp.GetHashCode() ^ this.Owner.GetHashCode(); } - public override bool Equals(IType other) + public override bool Equals(IType? other) { // Compare the owner, not the substitution, because the substitution may contain this specialized type parameter recursively SpecializedTypeParameter? o = other as SpecializedTypeParameter; - return o != null && baseTp.Equals(o.baseTp) && this.Owner.Equals(o.Owner); + return o != null && baseTp.Equals(o.baseTp) && this.Owner?.Equals(o.Owner) == true; } public override bool HasValueTypeConstraint => baseTp.HasValueTypeConstraint; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs index 756bfb258a..88e0b57a6b 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs @@ -122,7 +122,7 @@ public override int GetHashCode() return (namespaceKnown ? 812571 : 12651) ^ fullTypeName.GetHashCode(); } - public override bool Equals(IType other) + public override bool Equals(IType? other) { UnknownType? o = other as UnknownType; if (o == null) diff --git a/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs b/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs index 5959cded99..cbe73db36a 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs @@ -132,7 +132,7 @@ public override IType AcceptVisitor(TypeVisitor visitor) return visitor.VisitModOpt(this); } - public override bool Equals(IType other) + public override bool Equals(IType? other) { return other is ModifiedType o && kind == o.kind && modifier.Equals(o.modifier) && elementType.Equals(o.elementType); } diff --git a/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs b/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs index dc91fd6bb8..684631440b 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs @@ -52,7 +52,7 @@ public static ParameterListComparer WithOptions(bool includeModifiers = false) }; } - public bool Equals(IReadOnlyList x, IReadOnlyList y) + public bool Equals(IReadOnlyList? x, IReadOnlyList? y) { if (x == y) return true; @@ -125,7 +125,7 @@ public SignatureComparer(StringComparer nameComparer) /// public static readonly SignatureComparer Ordinal = new SignatureComparer(StringComparer.Ordinal); - public bool Equals(IMember x, IMember y) + public bool Equals(IMember? x, IMember? y) { if (x == y) return true; diff --git a/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs b/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs index 693c1bf2b8..537440a1be 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs @@ -291,12 +291,12 @@ public IEnumerable GetAccessors(Predicate? filter = null, GetM return GetMembersHelper.GetAccessors(this, filter, options); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as IType); } - public bool Equals(IType other) + public bool Equals(IType? other) { if (this == other) return true; diff --git a/ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs b/ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs index 782de8da1e..5356f8d1d5 100644 --- a/ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs +++ b/ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs @@ -79,12 +79,12 @@ public IMember CurrentMember { get { return currentMember; } } - public ITypeResolveContext WithCurrentTypeDefinition(ITypeDefinition typeDefinition) + public ITypeResolveContext WithCurrentTypeDefinition(ITypeDefinition? typeDefinition) { return new SimpleTypeResolveContext(compilation, currentModule, typeDefinition, currentMember); } - public ITypeResolveContext WithCurrentMember(IMember member) + public ITypeResolveContext WithCurrentMember(IMember? member) { return new SimpleTypeResolveContext(compilation, currentModule, currentTypeDefinition, member); } diff --git a/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs b/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs index e48653d42e..efeb561911 100644 --- a/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs @@ -58,7 +58,7 @@ public IReadOnlyList Parameters { get { return parameters; } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { VarArgInstanceMethod? other = obj as VarArgInstanceMethod; return other != null && baseMethod.Equals(other.baseMethod); @@ -69,7 +69,7 @@ public override int GetHashCode() return baseMethod.GetHashCode(); } - public bool Equals(IMember obj, TypeVisitor typeNormalization) + public bool Equals(IMember? obj, TypeVisitor typeNormalization) { VarArgInstanceMethod? other = obj as VarArgInstanceMethod; return other != null && baseMethod.Equals(other.baseMethod, typeNormalization); @@ -119,7 +119,7 @@ public IMethod Specialize(TypeParameterSubstitution substitution) IEnumerable IEntity.GetAttributes() => baseMethod.GetAttributes(); bool IEntity.HasAttribute(KnownAttribute attribute) => baseMethod.HasAttribute(attribute); - IAttribute IEntity.GetAttribute(KnownAttribute attribute) => baseMethod.GetAttribute(attribute); + IAttribute? IEntity.GetAttribute(KnownAttribute attribute) => baseMethod.GetAttribute(attribute); IEnumerable IMethod.GetReturnTypeAttributes() => baseMethod.GetReturnTypeAttributes(); bool IMethod.ReturnTypeIsRefReadOnly => baseMethod.ReturnTypeIsRefReadOnly; From 6e4a0255ae8afd08c6769ffc40d9cfdaa10f4674 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Fri, 20 Sep 2024 14:56:56 -0400 Subject: [PATCH 04/15] focus on CS8765 --- .editorconfig | 9 +++++++- .../CSharp/Resolver/CSharpConversions.cs | 2 +- .../CSharp/Syntax/AstNodeCollection.cs | 2 +- .../CSharp/Syntax/AstType.cs | 8 +++---- .../CSharp/Syntax/CSharpModifierToken.cs | 4 ++-- .../CSharp/Syntax/CSharpTokenNode.cs | 6 ++--- .../CSharp/Syntax/ComposedType.cs | 8 +++---- .../CSharp/Syntax/DocumentationReference.cs | 2 +- .../Expressions/AnonymousMethodExpression.cs | 2 +- .../AnonymousTypeCreateExpression.cs | 2 +- .../Expressions/ArrayCreateExpression.cs | 2 +- .../Expressions/ArrayInitializerExpression.cs | 6 ++--- .../CSharp/Syntax/Expressions/AsExpression.cs | 2 +- .../Expressions/AssignmentExpression.cs | 2 +- .../Expressions/BaseReferenceExpression.cs | 2 +- .../Expressions/BinaryOperatorExpression.cs | 2 +- .../Syntax/Expressions/CastExpression.cs | 2 +- .../Syntax/Expressions/CheckedExpression.cs | 2 +- .../Expressions/ConditionalExpression.cs | 2 +- .../Expressions/DeclarationExpression.cs | 2 +- .../Expressions/DefaultValueExpression.cs | 2 +- .../Syntax/Expressions/DirectionExpression.cs | 2 +- .../Syntax/Expressions/ErrorExpression.cs | 2 +- .../CSharp/Syntax/Expressions/Expression.cs | 4 ++-- .../Expressions/IdentifierExpression.cs | 2 +- .../InterpolatedStringExpression.cs | 8 +++---- .../Expressions/InvocationExpression.cs | 2 +- .../CSharp/Syntax/Expressions/IsExpression.cs | 2 +- .../Syntax/Expressions/LambdaExpression.cs | 2 +- .../Expressions/MemberReferenceExpression.cs | 2 +- .../Expressions/NamedArgumentExpression.cs | 2 +- .../Syntax/Expressions/NamedExpression.cs | 2 +- .../Expressions/NullReferenceExpression.cs | 2 +- .../Expressions/ObjectCreateExpression.cs | 2 +- .../OutVarDeclarationExpression.cs | 2 +- .../Expressions/ParenthesizedExpression.cs | 2 +- .../Expressions/PointerReferenceExpression.cs | 2 +- .../Syntax/Expressions/PrimitiveExpression.cs | 2 +- .../Syntax/Expressions/QueryExpression.cs | 22 +++++++++---------- .../Expressions/RecursivePatternExpression.cs | 2 +- .../Syntax/Expressions/SizeOfExpression.cs | 2 +- .../Expressions/StackAllocExpression.cs | 2 +- .../Syntax/Expressions/SwitchExpression.cs | 4 ++-- .../Expressions/ThisReferenceExpression.cs | 2 +- .../Syntax/Expressions/ThrowExpression.cs | 2 +- .../Syntax/Expressions/TupleExpression.cs | 2 +- .../Syntax/Expressions/TypeOfExpression.cs | 2 +- .../Expressions/TypeReferenceExpression.cs | 2 +- .../Expressions/UnaryOperatorExpression.cs | 2 +- .../Syntax/Expressions/UncheckedExpression.cs | 2 +- .../Expressions/UndocumentedExpression.cs | 2 +- .../Expressions/WithInitializerExpression.cs | 2 +- .../CSharp/Syntax/FunctionPointerAstType.cs | 2 +- .../CSharp/Syntax/GeneralScope/Attribute.cs | 4 ++-- .../Syntax/GeneralScope/AttributeSection.cs | 4 ++-- .../CSharp/Syntax/GeneralScope/Comment.cs | 2 +- .../CSharp/Syntax/GeneralScope/Constraint.cs | 2 +- .../GeneralScope/DelegateDeclaration.cs | 2 +- .../GeneralScope/ExternAliasDeclaration.cs | 2 +- .../GeneralScope/NamespaceDeclaration.cs | 2 +- .../GeneralScope/PreProcessorDirective.cs | 2 +- .../Syntax/GeneralScope/TypeDeclaration.cs | 2 +- .../GeneralScope/TypeParameterDeclaration.cs | 2 +- .../GeneralScope/UsingAliasDeclaration.cs | 2 +- .../Syntax/GeneralScope/UsingDeclaration.cs | 2 +- .../CSharp/Syntax/Identifier.cs | 4 ++-- .../CSharp/Syntax/InvocationAstType.cs | 2 +- .../CSharp/Syntax/MemberType.cs | 2 +- .../CSharp/Syntax/PatternMatching/Pattern.cs | 2 +- .../CSharp/Syntax/PrimitiveType.cs | 4 ++-- .../CSharp/Syntax/SimpleType.cs | 6 ++--- .../Syntax/Statements/BlockStatement.cs | 6 ++--- .../Syntax/Statements/BreakStatement.cs | 2 +- .../Syntax/Statements/CheckedStatement.cs | 2 +- .../Syntax/Statements/ContinueStatement.cs | 2 +- .../Syntax/Statements/DoWhileStatement.cs | 2 +- .../Syntax/Statements/EmptyStatement.cs | 2 +- .../Syntax/Statements/ExpressionStatement.cs | 2 +- .../Syntax/Statements/FixedStatement.cs | 2 +- .../CSharp/Syntax/Statements/ForStatement.cs | 2 +- .../Syntax/Statements/ForeachStatement.cs | 2 +- .../CSharp/Syntax/Statements/GotoStatement.cs | 6 ++--- .../Syntax/Statements/IfElseStatement.cs | 2 +- .../Syntax/Statements/LabelStatement.cs | 2 +- .../LocalFunctionDeclarationStatement.cs | 2 +- .../CSharp/Syntax/Statements/LockStatement.cs | 2 +- .../Syntax/Statements/ReturnStatement.cs | 2 +- .../CSharp/Syntax/Statements/Statement.cs | 4 ++-- .../Syntax/Statements/SwitchStatement.cs | 8 +++---- .../Syntax/Statements/ThrowStatement.cs | 2 +- .../Syntax/Statements/TryCatchStatement.cs | 8 +++---- .../Syntax/Statements/UncheckedStatement.cs | 2 +- .../Syntax/Statements/UnsafeStatement.cs | 2 +- .../Syntax/Statements/UsingStatement.cs | 2 +- .../VariableDeclarationStatement.cs | 2 +- .../Syntax/Statements/WhileStatement.cs | 2 +- .../Syntax/Statements/YieldBreakStatement.cs | 2 +- .../Syntax/Statements/YieldReturnStatement.cs | 2 +- .../CSharp/Syntax/SyntaxTree.cs | 2 +- .../CSharp/Syntax/TextLocation.cs | 10 ++++----- .../CSharp/Syntax/TupleAstType.cs | 6 ++--- .../CSharp/Syntax/TypeMembers/Accessor.cs | 4 ++-- .../TypeMembers/ConstructorDeclaration.cs | 6 ++--- .../TypeMembers/DestructorDeclaration.cs | 2 +- .../TypeMembers/EnumMemberDeclaration.cs | 2 +- .../Syntax/TypeMembers/EventDeclaration.cs | 4 ++-- .../Syntax/TypeMembers/FieldDeclaration.cs | 2 +- .../TypeMembers/FixedFieldDeclaration.cs | 2 +- .../TypeMembers/FixedVariableInitializer.cs | 2 +- .../Syntax/TypeMembers/IndexerDeclaration.cs | 2 +- .../Syntax/TypeMembers/MethodDeclaration.cs | 2 +- .../Syntax/TypeMembers/OperatorDeclaration.cs | 2 +- .../Syntax/TypeMembers/PropertyDeclaration.cs | 2 +- .../Syntax/TypeMembers/VariableInitializer.cs | 6 ++--- .../CSharp/Syntax/VariableDesignation.cs | 6 ++--- .../Disassembler/OpCodeInfo.cs | 2 +- .../Metadata/LightJson/JsonValue.cs | 2 +- .../Output/TextOutputWriter.cs | 2 +- .../TypeSystem/ArrayType.cs | 2 +- .../TypeSystem/AssemblyQualifiedTypeName.cs | 2 +- .../TypeSystem/ByReferenceType.cs | 2 +- .../TypeSystem/FullTypeName.cs | 2 +- .../TypeSystem/FunctionPointerType.cs | 2 +- .../Implementation/MetadataTypeParameter.cs | 2 +- .../TypeSystem/IntersectionType.cs | 18 +++++++-------- .../TypeSystem/PointerType.cs | 2 +- .../TypeSystem/SpecialType.cs | 2 +- .../TypeSystem/TopLevelTypeName.cs | 2 +- .../TypeSystem/TupleType.cs | 2 +- ILSpy/AboutPage.cs | 2 +- ILSpy/Analyzers/AnalyzeCommand.cs | 4 ++-- ILSpy/Commands/CheckForUpdatesCommand.cs | 4 ++-- ILSpy/Commands/CommandWrapper.cs | 4 ++-- ILSpy/Commands/DecompileAllCommand.cs | 6 ++--- ILSpy/Commands/DelegateCommand.cs | 8 +++---- ILSpy/Commands/DisassembleAllCommand.cs | 4 ++-- ILSpy/Commands/ExitCommand.cs | 2 +- ILSpy/Commands/GeneratePdbContextMenuEntry.cs | 4 ++-- ILSpy/Commands/ManageAssemblyListsCommand.cs | 2 +- ILSpy/Commands/OpenFromGacCommand.cs | 4 ++-- ILSpy/Commands/Pdb2XmlCommand.cs | 4 ++-- .../RemoveAssembliesWithLoadErrors.cs | 8 +++---- ILSpy/Commands/SetThemeCommand.cs | 2 +- ILSpy/Commands/ShowPane.cs | 4 ++-- ILSpy/Commands/SimpleCommand.cs | 10 ++++----- ILSpy/Commands/SortAssemblyListCommand.cs | 6 ++--- ILSpy/Docking/CloseAllDocumentsCommand.cs | 4 ++-- ILSpy/Docking/TabPageGuardConverter.cs | 4 ++-- ILSpy/ILSpyTraceListener.cs | 4 ++-- ILSpy/Metadata/FlagsFilterControl.xaml.cs | 2 +- ILSpy/Metadata/HexFilterControl.xaml.cs | 2 +- ILSpy/Metadata/MetaDataGrid.cs | 6 ++--- ILSpy/NavigationState.cs | 2 +- ILSpy/Options/OptionsDialog.xaml.cs | 2 +- ILSpy/ViewModels/PaneModel.cs | 4 ++-- ILSpy/ViewModels/TabPageModel.cs | 2 +- 156 files changed, 256 insertions(+), 249 deletions(-) diff --git a/.editorconfig b/.editorconfig index 3de3e13f37..9516bd4f26 100644 --- a/.editorconfig +++ b/.editorconfig @@ -149,4 +149,11 @@ dotnet_naming_rule.private_fields_rule.symbols = private_fields_symbols dotnet_diagnostic.MEF006.severity = silent -dotnet_diagnostic.IDE2003.severity = silent \ No newline at end of file +dotnet_diagnostic.IDE2003.severity = silent + +#cleared null error types +dotnet_diagnostic.CS8765.severity = error +dotnet_diagnostic.CS8766.severity = error +dotnet_diagnostic.CS8767.severity = error +dotnet_diagnostic.CS8768.severity = error +dotnet_diagnostic.CS8769.severity = error diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs index c45e273df9..1d96a9bab7 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs @@ -77,7 +77,7 @@ public TypePair(IType fromType, IType toType) this.ToType = toType; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return (obj is TypePair) && Equals((TypePair)obj); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs index b3bd0edccb..d63e778847 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs @@ -200,7 +200,7 @@ public override int GetHashCode() return node.GetHashCode() ^ role.GetHashCode(); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { AstNodeCollection? other = obj as AstNodeCollection; if (other == null) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs index 779103c1f2..74c0434e9d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs @@ -56,12 +56,12 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider) { return SpecialType.UnknownType; } @@ -102,12 +102,12 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider) { throw new NotSupportedException(); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs index 6e69f95bbf..b3a45155b2 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs @@ -49,12 +49,12 @@ public override TextLocation EndLocation { } } - public override string ToString(CSharpFormattingOptions formattingOptions) + public override string ToString(CSharpFormattingOptions? formattingOptions) { return GetModifierName(Modifier); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CSharpModifierToken? o = other as CSharpModifierToken; return o != null && this.modifier == o.modifier; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs index b954b7ea92..114ae9cb0c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs @@ -64,7 +64,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -107,7 +107,7 @@ public CSharpTokenNode(TextLocation location, TokenRole role) this.flags |= role.Index << AstNodeFlagsUsedBits; } - public override string ToString(CSharpFormattingOptions formattingOptions) + public override string ToString(CSharpFormattingOptions? formattingOptions) { uint tokenRoleIndex = (this.flags >> AstNodeFlagsUsedBits); if (Role.GetByIndex(tokenRoleIndex) is TokenRole r) @@ -132,7 +132,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitCSharpTokenNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CSharpTokenNode? o = other as CSharpTokenNode; return o != null && !o.IsNull && !(o is CSharpModifierToken); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs index 518e4876f8..8914430f94 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs @@ -144,7 +144,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitComposedType(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ComposedType? o = other as ComposedType; return o != null @@ -156,7 +156,7 @@ protected internal override bool DoMatch(AstNode other, PatternMatching.Match ma && this.ArraySpecifiers.DoMatch(o.ArraySpecifiers, match); } - public override string ToString(CSharpFormattingOptions formattingOptions) + public override string ToString(CSharpFormattingOptions? formattingOptions) { StringBuilder b = new StringBuilder(); if (this.HasRefSpecifier) @@ -287,13 +287,13 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitArraySpecifier(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ArraySpecifier? o = other as ArraySpecifier; return o != null && this.Dimensions == o.Dimensions; } - public override string ToString(CSharpFormattingOptions formattingOptions) + public override string ToString(CSharpFormattingOptions? formattingOptions) { return "[" + new string(',', this.Dimensions - 1) + "]"; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs b/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs index f42da43c4e..2293f8c70b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs @@ -109,7 +109,7 @@ public AstNodeCollection Parameters { get { return GetChildrenByRole(Roles.Parameter); } } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { DocumentationReference? o = other as DocumentationReference; if (!(o != null && this.SymbolKind == o.SymbolKind && this.HasParameterList == o.HasParameterList)) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs index 9685f9e084..03ea04f441 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs @@ -109,7 +109,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitAnonymousMethodExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { AnonymousMethodExpression? o = other as AnonymousMethodExpression; return o != null && this.IsAsync == o.IsAsync && this.HasParameterList == o.HasParameterList diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousTypeCreateExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousTypeCreateExpression.cs index e74e2e1afc..3812760314 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousTypeCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousTypeCreateExpression.cs @@ -81,7 +81,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitAnonymousTypeCreateExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { var o = other as AnonymousTypeCreateExpression; return o != null && this.Initializers.DoMatch(o.Initializers, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs index 5f20870e1c..03559b43a8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs @@ -69,7 +69,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitArrayCreateExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ArrayCreateExpression? o = other as ArrayCreateExpression; return o != null && this.Type.DoMatch(o.Type, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs index d7841c25a3..ea15c49bea 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs @@ -85,7 +85,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -119,7 +119,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitArrayInitializerExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ArrayInitializerExpression? o = other as ArrayInitializerExpression; return o != null && this.Elements.DoMatch(o.Elements, match); @@ -176,7 +176,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs index 0348795602..6303dac275 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs @@ -73,7 +73,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitAsExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { AsExpression? o = other as AsExpression; return o != null && this.Expression.DoMatch(o.Expression, match) && this.Type.DoMatch(o.Type, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs index cee70016ad..3fe7b3fa88 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs @@ -103,7 +103,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitAssignmentExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { AssignmentExpression? o = other as AssignmentExpression; return o != null && (this.Operator == AssignmentOperatorType.Any || this.Operator == o.Operator) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs index 46f9160693..9076b1cfd7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs @@ -63,7 +63,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitBaseReferenceExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { BaseReferenceExpression? o = other as BaseReferenceExpression; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs index e7d7f8f0a4..db0d470acd 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs @@ -105,7 +105,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitBinaryOperatorExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { BinaryOperatorExpression? o = other as BinaryOperatorExpression; return o != null && (this.Operator == BinaryOperatorType.Any || this.Operator == o.Operator) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs index bb24ba1dc6..20a78de71a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitCastExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CastExpression? o = other as CastExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs index 76cfa5ffae..313f18c7e6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitCheckedExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CheckedExpression? o = other as CheckedExpression; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs index 18d2dcd8ba..94b19addb9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs @@ -87,7 +87,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitConditionalExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ConditionalExpression? o = other as ConditionalExpression; return o != null && this.Condition.DoMatch(o.Condition, match) && this.TrueExpression.DoMatch(o.TrueExpression, match) && this.FalseExpression.DoMatch(o.FalseExpression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DeclarationExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DeclarationExpression.cs index 5584565249..37f4f21568 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DeclarationExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DeclarationExpression.cs @@ -50,7 +50,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitDeclarationExpression(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is DeclarationExpression o && Type.DoMatch(o.Type, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs index 21ee02d882..dd5eab75d3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitDefaultValueExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { DefaultValueExpression? o = other as DefaultValueExpression; return o != null && this.Type.DoMatch(o.Type, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs index e8e00f5301..e26062f1f3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs @@ -93,7 +93,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitDirectionExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { DirectionExpression? o = other as DirectionExpression; return o != null && this.FieldDirection == o.FieldDirection && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ErrorExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ErrorExpression.cs index 89f9fcfdd6..252ec224e0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ErrorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ErrorExpression.cs @@ -72,7 +72,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitErrorNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { var o = other as ErrorExpression; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs index c5d73352e2..fe121170e6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs @@ -56,7 +56,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -97,7 +97,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs index d1849ac1cc..6205080d6c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs @@ -79,7 +79,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitIdentifierExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { IdentifierExpression? o = other as IdentifierExpression; return o != null && MatchString(this.Identifier, o.Identifier) && this.TypeArguments.DoMatch(o.TypeArguments, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs index 6d3f2b5cc1..332dc6f3f8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs @@ -40,7 +40,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitInterpolatedStringExpression(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { InterpolatedStringExpression? o = other as InterpolatedStringExpression; return o != null && !o.IsNull && this.Content.DoMatch(o.Content, match); @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -139,7 +139,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitInterpolation(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { Interpolation? o = other as Interpolation; return o != null && this.Expression.DoMatch(o.Expression, match); @@ -175,7 +175,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitInterpolatedStringText(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { InterpolatedStringText? o = other as InterpolatedStringText; return o != null && o.Text == this.Text; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs index 2d5a9c86e6..3fbb984ffd 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs @@ -85,7 +85,7 @@ public InvocationExpression(Expression target, params Expression[] arguments) : { } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { InvocationExpression? o = other as InvocationExpression; return o != null && this.Target.DoMatch(o.Target, match) && this.Arguments.DoMatch(o.Arguments, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs index 1801b42d9e..c1c721571d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs @@ -74,7 +74,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitIsExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { IsExpression? o = other as IsExpression; return o != null && this.Expression.DoMatch(o.Expression, match) && this.Type.DoMatch(o.Type, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs index e09e157099..8320f99c67 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs @@ -82,7 +82,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitLambdaExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { LambdaExpression? o = other as LambdaExpression; return o != null && this.IsAsync == o.IsAsync && this.Parameters.DoMatch(o.Parameters, match) && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs index ad8754bb12..77afc0be0a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs @@ -112,7 +112,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitMemberReferenceExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { MemberReferenceExpression? o = other as MemberReferenceExpression; return o != null && this.Target.DoMatch(o.Target, match) && MatchString(this.MemberName, o.MemberName) && this.TypeArguments.DoMatch(o.TypeArguments, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs index d2b66aa9a9..eae728b507 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNamedArgumentExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { NamedArgumentExpression? o = other as NamedArgumentExpression; return o != null && MatchString(this.Name, o.Name) && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedExpression.cs index d8fe23df8a..768b6af429 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedExpression.cs @@ -86,7 +86,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNamedExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { var o = other as NamedExpression; return o != null && MatchString(this.Name, o.Name) && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs index df13519687..796e016f17 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullReferenceExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { NullReferenceExpression? o = other as NullReferenceExpression; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs index 64b89508f4..4a71917fc7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs @@ -97,7 +97,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitObjectCreateExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ObjectCreateExpression? o = other as ObjectCreateExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match) && this.Initializer.DoMatch(o.Initializer, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/OutVarDeclarationExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/OutVarDeclarationExpression.cs index 022987e805..4699a8f83b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/OutVarDeclarationExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/OutVarDeclarationExpression.cs @@ -64,7 +64,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitOutVarDeclarationExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { var o = other as OutVarDeclarationExpression; return o != null && this.Type.DoMatch(o.Type, match) && this.Variable.DoMatch(o.Variable, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs index 0758f0f3c2..1e33acee0a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs @@ -69,7 +69,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitParenthesizedExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ParenthesizedExpression? o = other as ParenthesizedExpression; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs index 724decd854..51987aec91 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs @@ -80,7 +80,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPointerReferenceExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { PointerReferenceExpression? o = other as PointerReferenceExpression; return o != null && MatchString(this.MemberName, o.MemberName) && this.TypeArguments.DoMatch(o.TypeArguments, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs index 3e0d356d73..0ba154a399 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs @@ -143,7 +143,7 @@ unsafe static TextLocation AdvanceLocation(TextLocation startLocation, string st return new TextLocation(line, col); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { PrimitiveExpression? o = other as PrimitiveExpression; return o != null && (this.Value == AnyValue || object.Equals(this.Value, o.Value)); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs index f5139d97fe..5093bc564d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs @@ -48,7 +48,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -74,7 +74,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryExpression? o = other as QueryExpression; return o != null && !o.IsNull && this.Clauses.DoMatch(o.Clauses, match); @@ -148,7 +148,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryContinuationClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryContinuationClause? o = other as QueryContinuationClause; return o != null && MatchString(this.Identifier, o.Identifier) && this.PrecedingQuery.DoMatch(o.PrecedingQuery, match); @@ -206,7 +206,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryFromClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryFromClause? o = other as QueryFromClause; return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.Identifier, o.Identifier) @@ -259,7 +259,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryLetClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryLetClause? o = other as QueryLetClause; return o != null && MatchString(this.Identifier, o.Identifier) && this.Expression.DoMatch(o.Expression, match); @@ -295,7 +295,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryWhereClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryWhereClause? o = other as QueryWhereClause; return o != null && this.Condition.DoMatch(o.Condition, match); @@ -404,7 +404,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryJoinClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryJoinClause? o = other as QueryJoinClause; return o != null && this.IsGroupJoin == o.IsGroupJoin @@ -443,7 +443,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryOrderClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryOrderClause? o = other as QueryOrderClause; return o != null && this.Orderings.DoMatch(o.Orderings, match); @@ -488,7 +488,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryOrdering(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryOrdering? o = other as QueryOrdering; return o != null && this.Direction == o.Direction && this.Expression.DoMatch(o.Expression, match); @@ -530,7 +530,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQuerySelectClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QuerySelectClause? o = other as QuerySelectClause; return o != null && this.Expression.DoMatch(o.Expression, match); @@ -577,7 +577,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitQueryGroupClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { QueryGroupClause? o = other as QueryGroupClause; return o != null && this.Projection.DoMatch(o.Projection, match) && this.Key.DoMatch(o.Key, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/RecursivePatternExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/RecursivePatternExpression.cs index 3a26d735ba..4c92a9341b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/RecursivePatternExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/RecursivePatternExpression.cs @@ -55,7 +55,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitRecursivePatternExpression(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is RecursivePatternExpression o && Type.DoMatch(o.Type, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs index 30e63b8e40..60e777361c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitSizeOfExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { SizeOfExpression? o = other as SizeOfExpression; return o != null && this.Type.DoMatch(o.Type, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs index 8633037f29..50d767324b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitStackAllocExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { StackAllocExpression? o = other as StackAllocExpression; return o != null && this.Type.DoMatch(o.Type, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs index d39e63048e..4382025921 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs @@ -63,7 +63,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitSwitchExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { SwitchExpression? o = other as SwitchExpression; return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match); @@ -109,7 +109,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitSwitchExpressionSection(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { SwitchExpressionSection? o = other as SwitchExpressionSection; return o != null && this.Pattern.DoMatch(o.Pattern, match) && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs index 0c42549ac7..e82a4f0e5c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs @@ -63,7 +63,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitThisReferenceExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ThisReferenceExpression? o = other as ThisReferenceExpression; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs index 3aedc28e20..895ec32a64 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs @@ -58,7 +58,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitThrowExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ThrowExpression? o = other as ThrowExpression; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TupleExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TupleExpression.cs index 143726af45..bd1ed58af1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TupleExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TupleExpression.cs @@ -43,7 +43,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitTupleExpression(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is TupleExpression tuple && Elements.DoMatch(tuple.Elements, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs index b81517eb46..4064708ebc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs @@ -76,7 +76,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitTypeOfExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { TypeOfExpression? o = other as TypeOfExpression; return o != null && this.Type.DoMatch(o.Type, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs index 39f1b819c5..eec5420707 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs @@ -54,7 +54,7 @@ public TypeReferenceExpression(AstType type) AddChild(type, Roles.Type); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { TypeReferenceExpression? o = other as TypeReferenceExpression; return o != null && this.Type.DoMatch(o.Type, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs index 7e80862684..3052e1bf78 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs @@ -87,7 +87,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUnaryOperatorExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UnaryOperatorExpression? o = other as UnaryOperatorExpression; return o != null && (this.Operator == UnaryOperatorType.Any || this.Operator == o.Operator) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs index e21235b4cb..f2ca9fd4e8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUncheckedExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UncheckedExpression? o = other as UncheckedExpression; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs index aa7e5af7bc..dbf6ea68c7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs @@ -95,7 +95,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUndocumentedExpression(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UndocumentedExpression? o = other as UndocumentedExpression; return o != null && this.UndocumentedExpressionType == o.UndocumentedExpressionType && this.Arguments.DoMatch(o.Arguments, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/WithInitializerExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/WithInitializerExpression.cs index 809dfb3670..3ff877de67 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/WithInitializerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/WithInitializerExpression.cs @@ -57,7 +57,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitWithInitializerExpression(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is WithInitializerExpression o && this.Expression.DoMatch(o.Expression, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs index 4259d3d7d3..d5eab341c7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs @@ -66,7 +66,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitFunctionPointerType(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other is FunctionPointerAstType o && this.CallingConventions.DoMatch(o.CallingConventions, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs index 901cbf7c96..3709476d64 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs @@ -77,13 +77,13 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitAttribute(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { Attribute? o = other as Attribute; return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match); } - public override string ToString(CSharpFormattingOptions formattingOptions) + public override string ToString(CSharpFormattingOptions? formattingOptions) { if (IsNull) return "Null"; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs index 338e15a2c4..fedcacd320 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs @@ -66,7 +66,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } @@ -129,7 +129,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitAttributeSection(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { AttributeSection? o = other as AttributeSection; return o != null && MatchString(this.AttributeTarget, o.AttributeTarget) && this.Attributes.DoMatch(o.Attributes, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs index b79956329f..fc7783a41b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs @@ -143,7 +143,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitComment(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { Comment? o = other as Comment; return o != null && this.CommentType == o.CommentType && MatchString(this.Content, o.Content); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs index aac00ed522..ba88d94431 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs @@ -73,7 +73,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitConstraint(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { Constraint? o = other as Constraint; return o != null && this.TypeParameter.DoMatch(o.TypeParameter, match) && this.BaseTypes.DoMatch(o.BaseTypes, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs index 59803f5ca8..f15538aa1a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs @@ -80,7 +80,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitDelegateDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { DelegateDeclaration? o = other as DelegateDeclaration; return o != null && MatchString(this.Name, o.Name) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs index 353e71f2c0..c2fe80d662 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs @@ -83,7 +83,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitExternAliasDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { var o = other as ExternAliasDeclaration; return o != null && MatchString(this.Name, o.Name); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs index 72fbc1c287..24ba4ab54e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs @@ -150,7 +150,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNamespaceDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { NamespaceDeclaration? o = other as NamespaceDeclaration; return o != null && MatchString(this.Name, o.Name) && this.Members.DoMatch(o.Members, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs index 767dbe1d23..cd5e9a1dc1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs @@ -193,7 +193,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPreProcessorDirective(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { PreProcessorDirective? o = other as PreProcessorDirective; return o != null && Type == o.Type && MatchString(Argument, o.Argument); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs index 19e0074d21..115fd5dcc4 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs @@ -147,7 +147,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitTypeDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { TypeDeclaration? o = other as TypeDeclaration; return o != null && this.ClassType == o.ClassType && MatchString(this.Name, o.Name) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs index 20cc0bd6eb..3bb3976078 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs @@ -104,7 +104,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitTypeParameterDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { TypeParameterDeclaration? o = other as TypeParameterDeclaration; return o != null && this.Variance == o.Variance && MatchString(this.Name, o.Name) && this.Attributes.DoMatch(o.Attributes, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs index c0fc1c2b23..d9172161d8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs @@ -99,7 +99,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUsingAliasDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UsingAliasDeclaration? o = other as UsingAliasDeclaration; return o != null && MatchString(this.Alias, o.Alias) && this.Import.DoMatch(o.Import, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs index a828b92399..966cae60c3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs @@ -115,7 +115,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUsingDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UsingDeclaration? o = other as UsingDeclaration; return o != null && this.Import.DoMatch(o.Import, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs index 64c1a008bb..1dc8c399f1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs @@ -54,7 +54,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -164,7 +164,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitIdentifier(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { Identifier? o = other as Identifier; return o != null && !o.IsNull && MatchString(this.Name, o.Name); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs index 99e529ba53..ad178e2757 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs @@ -55,7 +55,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitInvocationType(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is InvocationAstType o && this.BaseType.DoMatch(o.BaseType, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs index 74f02f5f3c..bad911c0be 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs @@ -112,7 +112,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitMemberType(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { MemberType? o = other as MemberType; return o != null && this.IsDoubleColon == o.IsDoubleColon diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs index f644813f5d..7e02f50631 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs @@ -31,7 +31,7 @@ public abstract class Pattern : INode /// public static readonly string AnyString = "$any$"; - public static bool MatchString(string pattern, string text) + public static bool MatchString(string? pattern, string? text) { return pattern == AnyString || pattern == text; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs index 8fa3cf9437..cec4ba1078 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs @@ -100,13 +100,13 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPrimitiveType(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { PrimitiveType? o = other as PrimitiveType; return o != null && MatchString(this.Keyword, o.Keyword); } - public override string ToString(CSharpFormattingOptions formattingOptions) + public override string ToString(CSharpFormattingOptions? formattingOptions) { return Keyword; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs index df9808c930..231ba13e81 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs @@ -60,12 +60,12 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } - public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider) + public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider? interningProvider) { return SpecialType.UnknownType; } @@ -141,7 +141,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitSimpleType(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { SimpleType? o = other as SimpleType; return o != null && MatchString(this.Identifier, o.Identifier) && this.TypeArguments.DoMatch(o.TypeArguments, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs index 1e2e9e8735..5ef3ae3740 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs @@ -60,7 +60,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -101,7 +101,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } @@ -140,7 +140,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitBlockStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { BlockStatement? o = other as BlockStatement; return o != null && !o.IsNull && this.Statements.DoMatch(o.Statements, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs index cf3a735cd1..81c0375f9a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs @@ -57,7 +57,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitBreakStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { BreakStatement? o = other as BreakStatement; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs index 728a73abfa..11e4872108 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs @@ -67,7 +67,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitCheckedStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CheckedStatement? o = other as CheckedStatement; return o != null && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs index 23d674ce0c..8fac0c894e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs @@ -57,7 +57,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitContinueStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ContinueStatement? o = other as ContinueStatement; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs index 17aa604cb6..79c8a6a650 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs @@ -80,7 +80,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitDoWhileStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { DoWhileStatement? o = other as DoWhileStatement; return o != null && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match) && this.Condition.DoMatch(o.Condition, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs index c0fd1919c1..d7ea9f661c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs @@ -64,7 +64,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitEmptyStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { EmptyStatement? o = other as EmptyStatement; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs index 890a9fcd72..4c5a9ac77c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs @@ -65,7 +65,7 @@ public ExpressionStatement(Expression expression) this.Expression = expression; } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ExpressionStatement? o = other as ExpressionStatement; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs index 1f62f6f4e6..bfbb173a9b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitFixedStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { FixedStatement? o = other as FixedStatement; return o != null && this.Type.DoMatch(o.Type, match) && this.Variables.DoMatch(o.Variables, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs index 6e63c87670..2a418afb19 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs @@ -86,7 +86,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitForStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ForStatement? o = other as ForStatement; return o != null && this.Initializers.DoMatch(o.Initializers, match) && this.Condition.DoMatch(o.Condition, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs index f46b6e2b02..a6e39f1aec 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs @@ -96,7 +96,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitForeachStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ForeachStatement? o = other as ForeachStatement; return o != null && this.VariableType.DoMatch(o.VariableType, match) && this.VariableDesignation.DoMatch(o.VariableDesignation, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs index 8f431d7d19..f5f28d40ef 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs @@ -78,7 +78,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitGotoStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { GotoStatement? o = other as GotoStatement; return o != null && MatchString(this.Label, o.Label); @@ -128,7 +128,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitGotoCaseStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { GotoCaseStatement? o = other as GotoCaseStatement; return o != null && this.LabelExpression.DoMatch(o.LabelExpression, match); @@ -170,7 +170,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitGotoDefaultStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { GotoDefaultStatement? o = other as GotoDefaultStatement; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs index 67e04b7cf5..f7a3ab46fd 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs @@ -84,7 +84,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitIfElseStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { IfElseStatement? o = other as IfElseStatement; return o != null && this.Condition.DoMatch(o.Condition, match) && this.TrueStatement.DoMatch(o.TrueStatement, match) && this.FalseStatement.DoMatch(o.FalseStatement, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs index 2c2302fc88..8218b0a345 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs @@ -65,7 +65,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitLabelStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { LabelStatement? o = other as LabelStatement; return o != null && MatchString(this.Label, o.Label); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LocalFunctionDeclarationStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LocalFunctionDeclarationStatement.cs index da2d1550f4..0a2f4ad26b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LocalFunctionDeclarationStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LocalFunctionDeclarationStatement.cs @@ -49,7 +49,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitLocalFunctionDeclarationStatement(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is LocalFunctionDeclarationStatement o && Declaration.DoMatch(o.Declaration, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs index fb66fabab3..c988127d74 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs @@ -71,7 +71,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitLockStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { LockStatement? o = other as LockStatement; return o != null && this.Expression.DoMatch(o.Expression, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs index 23da927ec9..74b9dae6d8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs @@ -71,7 +71,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitReturnStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ReturnStatement? o = other as ReturnStatement; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs index b278d1e3f9..959431ad5a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs @@ -55,7 +55,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -96,7 +96,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs index d714c1a725..364e6df947 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs @@ -79,7 +79,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitSwitchStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { SwitchStatement? o = other as SwitchStatement; return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match); @@ -122,7 +122,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } @@ -165,7 +165,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitSwitchSection(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { SwitchSection? o = other as SwitchSection; return o != null && this.CaseLabels.DoMatch(o.CaseLabels, match) && this.Statements.DoMatch(o.Statements, match); @@ -219,7 +219,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitCaseLabel(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CaseLabel? o = other as CaseLabel; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs index 14cd2f5f72..cb6fc857f8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs @@ -71,7 +71,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitThrowStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ThrowStatement? o = other as ThrowStatement; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs index e61537b377..a3352f0ff0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs @@ -75,7 +75,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitTryCatchStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { TryCatchStatement? o = other as TryCatchStatement; return o != null && this.TryBlock.DoMatch(o.TryBlock, match) && this.CatchClauses.DoMatch(o.CatchClauses, match) && this.FinallyBlock.DoMatch(o.FinallyBlock, match); @@ -119,7 +119,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -160,7 +160,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } @@ -251,7 +251,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitCatchClause(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CatchClause? o = other as CatchClause; return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.VariableName, o.VariableName) && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs index a74c3cb10e..4b91caec5a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs @@ -67,7 +67,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUncheckedStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UncheckedStatement? o = other as UncheckedStatement; return o != null && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs index 0c066b04bc..afa19a96de 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs @@ -58,7 +58,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUnsafeStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UnsafeStatement? o = other as UnsafeStatement; return o != null && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs index b4a910da34..2524726d37 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs @@ -87,7 +87,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitUsingStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { UsingStatement? o = other as UsingStatement; return o != null && this.IsAsync == o.IsAsync && this.ResourceAcquisition.DoMatch(o.ResourceAcquisition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs index 3ac821ee78..15b58fa8eb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs @@ -79,7 +79,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitVariableDeclarationStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { VariableDeclarationStatement? o = other as VariableDeclarationStatement; return o != null && this.Modifiers == o.Modifiers && this.Type.DoMatch(o.Type, match) && this.Variables.DoMatch(o.Variables, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs index 1d198abe44..5f9d8f80d7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs @@ -71,7 +71,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitWhileStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { WhileStatement? o = other as WhileStatement; return o != null && this.Condition.DoMatch(o.Condition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs index 9dcc362f37..cfcd651629 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs @@ -62,7 +62,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitYieldBreakStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { YieldBreakStatement? o = other as YieldBreakStatement; return o != null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs index a9c66d7560..f741a95193 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs @@ -67,7 +67,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitYieldReturnStatement(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { YieldReturnStatement? o = other as YieldReturnStatement; return o != null && this.Expression.DoMatch(o.Expression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs index 35d9e2a84e..d4a0fed7b2 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs @@ -117,7 +117,7 @@ public IEnumerable GetTypes(bool includeInnerTypes = false) } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { SyntaxTree? o = other as SyntaxTree; return o != null && this.Members.DoMatch(o.Members, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TextLocation.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TextLocation.cs index 487a9cc1ca..307b13b53c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TextLocation.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TextLocation.cs @@ -98,7 +98,7 @@ public override int GetHashCode() /// /// Equality test. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is TextLocation)) return false; @@ -187,17 +187,17 @@ public int CompareTo(TextLocation other) public class TextLocationConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) { return destinationType == typeof(TextLocation) || base.CanConvertTo(context, destinationType); } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is string) { @@ -210,7 +210,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c return base.ConvertFrom(context, culture, value); } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (value is TextLocation) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs index 69b6c7fc2a..c944f392ff 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs @@ -57,7 +57,7 @@ public override ITypeReference ToTypeReference(NameLookupMode lookupMode, Intern ); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is TupleAstType o && Elements.DoMatch(o.Elements, match); } @@ -91,7 +91,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -130,7 +130,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitTupleTypeElement(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is TupleTypeElement o && Type.DoMatch(o.Type, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs index c5f628442f..8b37f582c8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs @@ -57,7 +57,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -109,7 +109,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitAccessor(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { Accessor? o = other as Accessor; return o != null && !o.IsNull && this.MatchAttributesAndModifiers(o, match) && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs index 631027602d..12d1a13e94 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs @@ -77,7 +77,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitConstructorDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ConstructorDeclaration? o = other as ConstructorDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.Parameters.DoMatch(o.Parameters, match) @@ -127,7 +127,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -180,7 +180,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitConstructorInitializer(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { ConstructorInitializer? o = other as ConstructorInitializer; return o != null && !o.IsNull diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs index 648874d600..a11ddbce1c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs @@ -67,7 +67,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitDestructorDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { DestructorDeclaration? o = other as DestructorDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.Body.DoMatch(o.Body, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs index f6392f9ed4..b4f58e628e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs @@ -60,7 +60,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitEnumMemberDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { EnumMemberDeclaration? o = other as EnumMemberDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs index 85c773affa..ff5ab3e54f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs @@ -76,7 +76,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitEventDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { EventDeclaration? o = other as EventDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) @@ -139,7 +139,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitCustomEventDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { CustomEventDeclaration? o = other as CustomEventDeclaration; return o != null && MatchString(this.Name, o.Name) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs index 6bcf686262..933d7adc1f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs @@ -70,7 +70,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitFieldDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { FieldDeclaration? o = other as FieldDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedFieldDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedFieldDeclaration.cs index 2d31d86abf..f803db180d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedFieldDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedFieldDeclaration.cs @@ -59,7 +59,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitFixedFieldDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { var o = other as FixedFieldDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs index 97e61cea58..f6f71d346a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs @@ -94,7 +94,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitFixedVariableInitializer(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { var o = other as FixedVariableInitializer; return o != null && MatchString(this.Name, o.Name) && this.CountExpression.DoMatch(o.CountExpression, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs index fcbfb87133..b42b54a6e0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs @@ -116,7 +116,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitIndexerDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { IndexerDeclaration? o = other as IndexerDeclaration; return o != null diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs index 07217b17eb..bb86a18fd0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs @@ -90,7 +90,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitMethodDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { MethodDeclaration? o = other as MethodDeclaration; return o != null && MatchString(this.Name, o.Name) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs index 3f9f96b92f..70343f3ace 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs @@ -353,7 +353,7 @@ public override Identifier NameToken { set { throw new NotSupportedException(); } } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { OperatorDeclaration? o = other as OperatorDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs index 879fae19ec..657cad0df8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs @@ -97,7 +97,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPropertyDeclaration(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { PropertyDeclaration? o = other as PropertyDeclaration; return o != null && MatchString(this.Name, o.Name) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs index 77eea3886f..98768ede38 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs @@ -55,7 +55,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -96,7 +96,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitPatternPlaceholder(this, child, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return child.DoMatch(other, match); } @@ -166,7 +166,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitVariableInitializer(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { VariableInitializer? o = other as VariableInitializer; return o != null && MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs b/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs index 8d7991dec2..9712d1a185 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs @@ -50,7 +50,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitNullNode(this, data); } - protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) + protected internal override bool DoMatch(AstNode? other, PatternMatching.Match match) { return other == null || other.IsNull; } @@ -90,7 +90,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitSingleVariableDesignation(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is SingleVariableDesignation o && MatchString(this.Identifier, o.Identifier); } @@ -129,7 +129,7 @@ public override S AcceptVisitor(IAstVisitor visitor, T data) return visitor.VisitParenthesizedVariableDesignation(this, data); } - protected internal override bool DoMatch(AstNode other, Match match) + protected internal override bool DoMatch(AstNode? other, Match match) { return other is ParenthesizedVariableDesignation o && VariableDesignations.DoMatch(o.VariableDesignations, match); } diff --git a/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs b/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs index 931bc671de..a1748d7808 100644 --- a/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs +++ b/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs @@ -48,7 +48,7 @@ public bool Equals(OpCodeInfo other) public static bool operator ==(OpCodeInfo lhs, OpCodeInfo rhs) => lhs.Equals(rhs); public static bool operator !=(OpCodeInfo lhs, OpCodeInfo rhs) => !(lhs == rhs); - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is OpCodeInfo opCode) return Equals(opCode); diff --git a/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs index c79ac3459e..17f203f34e 100644 --- a/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs +++ b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs @@ -764,7 +764,7 @@ public static JsonValue Parse(string text) } /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) { diff --git a/ICSharpCode.Decompiler/Output/TextOutputWriter.cs b/ICSharpCode.Decompiler/Output/TextOutputWriter.cs index afd84cbbc4..c2774d404e 100644 --- a/ICSharpCode.Decompiler/Output/TextOutputWriter.cs +++ b/ICSharpCode.Decompiler/Output/TextOutputWriter.cs @@ -42,7 +42,7 @@ public override void Write(char value) output.Write(value); } - public override void Write(string value) + public override void Write(string? value) { output.Write(value); } diff --git a/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs b/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs index f0d942d314..8c7a98b180 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs @@ -85,7 +85,7 @@ public override int GetHashCode() return unchecked(elementType.GetHashCode() * 71681 + dimensions); } - public override bool Equals(IType other) + public override bool Equals(IType? other) { ArrayType? a = other as ArrayType; return a != null && elementType.Equals(a.elementType) && a.dimensions == dimensions && a.nullability == nullability; diff --git a/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs b/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs index 2643842f18..e819fd416c 100644 --- a/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs +++ b/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs @@ -45,7 +45,7 @@ public override string ToString() return TypeName.ToString() + ", " + AssemblyName; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return (obj is AssemblyQualifiedTypeName) && Equals((AssemblyQualifiedTypeName)obj); } diff --git a/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs b/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs index c4d6796c14..4eda51b970 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs @@ -49,7 +49,7 @@ public override int GetHashCode() return elementType.GetHashCode() ^ 91725813; } - public override bool Equals(IType other) + public override bool Equals(IType? other) { ByReferenceType? a = other as ByReferenceType; return a != null && elementType.Equals(a.elementType); diff --git a/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs b/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs index 36712ee645..74701a6ed9 100644 --- a/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs +++ b/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs @@ -262,7 +262,7 @@ public override string ToString() } #region Equals and GetHashCode implementation - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is FullTypeName && Equals((FullTypeName)obj); } diff --git a/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs b/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs index 6832fa9c22..babf67d830 100644 --- a/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs @@ -179,7 +179,7 @@ public override IType VisitChildren(TypeVisitor visitor) ParameterReferenceKinds); } - public override bool Equals(IType other) + public override bool Equals(IType? other) { return other is FunctionPointerType fpt && CallingConvention == fpt.CallingConvention diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs index 282e5c2bf9..36bf02a1f6 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs @@ -251,7 +251,7 @@ public override int GetHashCode() return 0x51fc5b83 ^ module.MetadataFile.GetHashCode() ^ handle.GetHashCode(); } - public override bool Equals(IType other) + public override bool Equals(IType? other) { return other is MetadataTypeParameter tp && handle == tp.handle && module.MetadataFile == tp.module.MetadataFile; } diff --git a/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs b/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs index c8a28fe11e..02e6e4fa8e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs @@ -116,7 +116,7 @@ public override int GetHashCode() return hashCode; } - public override bool Equals(IType other) + public override bool Equals(IType? other) { IntersectionType? o = other as IntersectionType; if (o != null && types.Count == o.types.Count) @@ -135,42 +135,42 @@ public override IEnumerable DirectBaseTypes { get { return types; } } - public override IEnumerable GetMethods(Predicate filter, GetMemberOptions options) + public override IEnumerable GetMethods(Predicate? filter, GetMemberOptions options) { return GetMembersHelper.GetMethods(this, FilterNonStatic(filter), options); } - public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate filter, GetMemberOptions options) + public override IEnumerable GetMethods(IReadOnlyList typeArguments, Predicate? filter, GetMemberOptions options) { return GetMembersHelper.GetMethods(this, typeArguments, filter, options); } - public override IEnumerable GetProperties(Predicate filter, GetMemberOptions options) + public override IEnumerable GetProperties(Predicate? filter, GetMemberOptions options) { return GetMembersHelper.GetProperties(this, FilterNonStatic(filter), options); } - public override IEnumerable GetFields(Predicate filter, GetMemberOptions options) + public override IEnumerable GetFields(Predicate? filter, GetMemberOptions options) { return GetMembersHelper.GetFields(this, FilterNonStatic(filter), options); } - public override IEnumerable GetEvents(Predicate filter, GetMemberOptions options) + public override IEnumerable GetEvents(Predicate? filter, GetMemberOptions options) { return GetMembersHelper.GetEvents(this, FilterNonStatic(filter), options); } - public override IEnumerable GetMembers(Predicate filter, GetMemberOptions options) + public override IEnumerable GetMembers(Predicate? filter, GetMemberOptions options) { return GetMembersHelper.GetMembers(this, FilterNonStatic(filter), options); } - public override IEnumerable GetAccessors(Predicate filter, GetMemberOptions options) + public override IEnumerable GetAccessors(Predicate? filter, GetMemberOptions options) { return GetMembersHelper.GetAccessors(this, FilterNonStatic(filter), options); } - static Predicate FilterNonStatic(Predicate filter) where T : class, IMember + static Predicate FilterNonStatic(Predicate? filter) where T : class, IMember { if (filter == null) return member => !member.IsStatic; diff --git a/ICSharpCode.Decompiler/TypeSystem/PointerType.cs b/ICSharpCode.Decompiler/TypeSystem/PointerType.cs index c5038e04fa..fba8536ecc 100644 --- a/ICSharpCode.Decompiler/TypeSystem/PointerType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/PointerType.cs @@ -47,7 +47,7 @@ public override int GetHashCode() return elementType.GetHashCode() ^ 91725811; } - public override bool Equals(IType other) + public override bool Equals(IType? other) { PointerType? a = other as PointerType; return a != null && elementType.Equals(a.elementType); diff --git a/ICSharpCode.Decompiler/TypeSystem/SpecialType.cs b/ICSharpCode.Decompiler/TypeSystem/SpecialType.cs index c7cf024284..489e0c97b3 100644 --- a/ICSharpCode.Decompiler/TypeSystem/SpecialType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/SpecialType.cs @@ -101,7 +101,7 @@ IType ITypeReference.Resolve(ITypeResolveContext context) #pragma warning disable 809 [Obsolete("Please compare special types using the kind property instead.")] - public override bool Equals(IType other) + public override bool Equals(IType? other) { // We consider a special types equal when they have equal types. // However, an unknown type with additional information is not considered to be equal to the SpecialType with TypeKind.Unknown. diff --git a/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs b/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs index d6039e150b..5a20650c67 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs @@ -95,7 +95,7 @@ public override string ToString() return this.ReflectionName; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return (obj is TopLevelTypeName) && Equals((TopLevelTypeName)obj); } diff --git a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs index 8bf805decd..4eab3d4306 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs @@ -220,7 +220,7 @@ bool Collect(IType type) public override string ReflectionName => UnderlyingType.ReflectionName; public override string Namespace => UnderlyingType.Namespace; - public override bool Equals(IType other) + public override bool Equals(IType? other) { var o = other as TupleType; if (o == null) diff --git a/ILSpy/AboutPage.cs b/ILSpy/AboutPage.cs index 43303bf889..0fbaa89ba1 100644 --- a/ILSpy/AboutPage.cs +++ b/ILSpy/AboutPage.cs @@ -40,7 +40,7 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class AboutPage : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { MainWindow.Instance.NavigateTo( new RequestNavigateEventArgs(new Uri("resource://aboutpage"), null), diff --git a/ILSpy/Analyzers/AnalyzeCommand.cs b/ILSpy/Analyzers/AnalyzeCommand.cs index 889e6afa0b..65e2f30959 100644 --- a/ILSpy/Analyzers/AnalyzeCommand.cs +++ b/ILSpy/Analyzers/AnalyzeCommand.cs @@ -76,12 +76,12 @@ internal sealed class AnalyzeCommand : SimpleCommand { private static readonly AnalyzerTreeViewModel AnalyzerTreeView = App.ExportProvider.GetExportedValue(); - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return MainWindow.Instance.SelectedNodes.All(n => n is IMemberTreeNode); } - public override void Execute(object parameter) + public override void Execute(object? parameter) { foreach (var node in MainWindow.Instance.SelectedNodes.OfType()) { diff --git a/ILSpy/Commands/CheckForUpdatesCommand.cs b/ILSpy/Commands/CheckForUpdatesCommand.cs index 58438c6043..c5d1ee0bde 100644 --- a/ILSpy/Commands/CheckForUpdatesCommand.cs +++ b/ILSpy/Commands/CheckForUpdatesCommand.cs @@ -28,12 +28,12 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class CheckForUpdatesCommand : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return base.CanExecute(parameter); } - public override async void Execute(object parameter) + public override async void Execute(object? parameter) { await MainWindow.Instance.ShowMessageIfUpdatesAvailableAsync(ILSpySettings.Load(), forceCheck: true); } diff --git a/ILSpy/Commands/CommandWrapper.cs b/ILSpy/Commands/CommandWrapper.cs index 42b34ee055..2cf061b708 100644 --- a/ILSpy/Commands/CommandWrapper.cs +++ b/ILSpy/Commands/CommandWrapper.cs @@ -44,12 +44,12 @@ public event EventHandler CanExecuteChanged { remove { wrappedCommand.CanExecuteChanged -= value; } } - public void Execute(object parameter) + public void Execute(object? parameter) { wrappedCommand.Execute(parameter); } - public bool CanExecute(object parameter) + public bool CanExecute(object? parameter) { return wrappedCommand.CanExecute(parameter); } diff --git a/ILSpy/Commands/DecompileAllCommand.cs b/ILSpy/Commands/DecompileAllCommand.cs index c905c9a87b..84d53a41f2 100644 --- a/ILSpy/Commands/DecompileAllCommand.cs +++ b/ILSpy/Commands/DecompileAllCommand.cs @@ -39,12 +39,12 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class DecompileAllCommand : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return System.IO.Directory.Exists("c:\\temp\\decompiled"); } - public override void Execute(object parameter) + public override void Execute(object? parameter) { Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task.Factory.StartNew(() => { AvalonEditTextOutput output = new AvalonEditTextOutput(); @@ -92,7 +92,7 @@ public override void Execute(object parameter) [PartCreationPolicy(CreationPolicy.Shared)] sealed class Decompile100TimesCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { const int numRuns = 100; var language = SettingsService.Instance.SessionSettings.LanguageSettings.Language; diff --git a/ILSpy/Commands/DelegateCommand.cs b/ILSpy/Commands/DelegateCommand.cs index 7e2516b1bc..41996e3270 100644 --- a/ILSpy/Commands/DelegateCommand.cs +++ b/ILSpy/Commands/DelegateCommand.cs @@ -28,12 +28,12 @@ public DelegateCommand(Action action, Func canExecute) this.canExecute = canExecute; } - public bool CanExecute(object parameter) + public bool CanExecute(object? parameter) { return canExecute(); } - public void Execute(object parameter) + public void Execute(object? parameter) { action(); } @@ -60,12 +60,12 @@ public DelegateCommand(Action action, Func canExecute) this.canExecute = canExecute; } - public bool CanExecute(object parameter) + public bool CanExecute(object? parameter) { return canExecute((T)parameter); } - public void Execute(object parameter) + public void Execute(object? parameter) { action((T)parameter); } diff --git a/ILSpy/Commands/DisassembleAllCommand.cs b/ILSpy/Commands/DisassembleAllCommand.cs index fc44d405a3..42f1089e2a 100644 --- a/ILSpy/Commands/DisassembleAllCommand.cs +++ b/ILSpy/Commands/DisassembleAllCommand.cs @@ -34,12 +34,12 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class DisassembleAllCommand : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return System.IO.Directory.Exists("c:\\temp\\disassembled"); } - public override void Execute(object parameter) + public override void Execute(object? parameter) { Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task.Factory.StartNew(() => { AvalonEditTextOutput output = new AvalonEditTextOutput(); diff --git a/ILSpy/Commands/ExitCommand.cs b/ILSpy/Commands/ExitCommand.cs index fb475ef015..06873b6f88 100644 --- a/ILSpy/Commands/ExitCommand.cs +++ b/ILSpy/Commands/ExitCommand.cs @@ -25,7 +25,7 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class ExitCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { MainWindow.Instance.Close(); } diff --git a/ILSpy/Commands/GeneratePdbContextMenuEntry.cs b/ILSpy/Commands/GeneratePdbContextMenuEntry.cs index b7c3997d06..245fc76637 100644 --- a/ILSpy/Commands/GeneratePdbContextMenuEntry.cs +++ b/ILSpy/Commands/GeneratePdbContextMenuEntry.cs @@ -108,14 +108,14 @@ internal static void GeneratePdbForAssembly(LoadedAssembly assembly) [PartCreationPolicy(CreationPolicy.Shared)] class GeneratePdbMainMenuEntry : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return MainWindow.Instance.SelectedNodes?.Count() == 1 && MainWindow.Instance.SelectedNodes?.FirstOrDefault() is AssemblyTreeNode tn && !tn.LoadedAssembly.HasLoadError; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { var assembly = (MainWindow.Instance.SelectedNodes?.FirstOrDefault() as AssemblyTreeNode)?.LoadedAssembly; if (assembly == null) diff --git a/ILSpy/Commands/ManageAssemblyListsCommand.cs b/ILSpy/Commands/ManageAssemblyListsCommand.cs index 0f2240e147..af5bf0465e 100644 --- a/ILSpy/Commands/ManageAssemblyListsCommand.cs +++ b/ILSpy/Commands/ManageAssemblyListsCommand.cs @@ -27,7 +27,7 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class ManageAssemblyListsCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { ManageAssemblyListsDialog dlg = new ManageAssemblyListsDialog(); dlg.Owner = MainWindow.Instance; diff --git a/ILSpy/Commands/OpenFromGacCommand.cs b/ILSpy/Commands/OpenFromGacCommand.cs index 393e00eeb5..a25fa14c01 100644 --- a/ILSpy/Commands/OpenFromGacCommand.cs +++ b/ILSpy/Commands/OpenFromGacCommand.cs @@ -27,12 +27,12 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class OpenFromGacCommand : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return AppEnvironment.IsWindows; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { OpenFromGacDialog dlg = new OpenFromGacDialog(); dlg.Owner = MainWindow.Instance; diff --git a/ILSpy/Commands/Pdb2XmlCommand.cs b/ILSpy/Commands/Pdb2XmlCommand.cs index c697773704..2ddf9b384f 100644 --- a/ILSpy/Commands/Pdb2XmlCommand.cs +++ b/ILSpy/Commands/Pdb2XmlCommand.cs @@ -38,14 +38,14 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class Pdb2XmlCommand : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { var selectedNodes = MainWindow.Instance.SelectedNodes; return selectedNodes?.Any() == true && selectedNodes.All(n => n is AssemblyTreeNode asm && !asm.LoadedAssembly.HasLoadError); } - public override void Execute(object parameter) + public override void Execute(object? parameter) { Execute(MainWindow.Instance.SelectedNodes.OfType()); } diff --git a/ILSpy/Commands/RemoveAssembliesWithLoadErrors.cs b/ILSpy/Commands/RemoveAssembliesWithLoadErrors.cs index c8696104bd..282c99098e 100644 --- a/ILSpy/Commands/RemoveAssembliesWithLoadErrors.cs +++ b/ILSpy/Commands/RemoveAssembliesWithLoadErrors.cs @@ -27,12 +27,12 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] class RemoveAssembliesWithLoadErrors : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return MainWindow.Instance.CurrentAssemblyList?.GetAssemblies().Any(l => l.HasLoadError) == true; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { foreach (var asm in MainWindow.Instance.CurrentAssemblyList.GetAssemblies()) { @@ -49,12 +49,12 @@ public override void Execute(object parameter) [PartCreationPolicy(CreationPolicy.Shared)] class ClearAssemblyList : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return MainWindow.Instance.CurrentAssemblyList?.Count > 0; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { MainWindow.Instance.CurrentAssemblyList?.Clear(); } diff --git a/ILSpy/Commands/SetThemeCommand.cs b/ILSpy/Commands/SetThemeCommand.cs index 2d1a0b32ac..8822ed67a0 100644 --- a/ILSpy/Commands/SetThemeCommand.cs +++ b/ILSpy/Commands/SetThemeCommand.cs @@ -4,7 +4,7 @@ namespace ICSharpCode.ILSpy.Commands { public class SetThemeCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { if (parameter is string theme) SettingsService.Instance.SessionSettings.Theme = theme; diff --git a/ILSpy/Commands/ShowPane.cs b/ILSpy/Commands/ShowPane.cs index 372081e0ba..de2f9adcf2 100644 --- a/ILSpy/Commands/ShowPane.cs +++ b/ILSpy/Commands/ShowPane.cs @@ -13,7 +13,7 @@ public ToolPaneCommand(string contentId) this.contentId = contentId; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { DockWorkspace.Instance.ShowToolPane(contentId); } @@ -28,7 +28,7 @@ public TabPageCommand(TabPageModel model) this.model = model; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { DockWorkspace.Instance.ActiveTabPage = model; } diff --git a/ILSpy/Commands/SimpleCommand.cs b/ILSpy/Commands/SimpleCommand.cs index 67c7f517e1..502d7ea9fe 100644 --- a/ILSpy/Commands/SimpleCommand.cs +++ b/ILSpy/Commands/SimpleCommand.cs @@ -29,9 +29,9 @@ public event EventHandler CanExecuteChanged { remove { CommandManager.RequerySuggested -= value; } } - public abstract void Execute(object parameter); + public abstract void Execute(object? parameter); - public virtual bool CanExecute(object parameter) + public virtual bool CanExecute(object? parameter) { return true; } @@ -48,7 +48,7 @@ public event EventHandler CanExecuteChanged { public event PropertyChangedEventHandler PropertyChanged; - void ICommand.Execute(object parameter) + void ICommand.Execute(object? parameter) { IsChecked = Execute(parameter); } @@ -64,9 +64,9 @@ public bool IsChecked { } } - public abstract bool Execute(object parameter); + public abstract bool Execute(object? parameter); - public virtual bool CanExecute(object parameter) + public virtual bool CanExecute(object? parameter) { return true; } diff --git a/ILSpy/Commands/SortAssemblyListCommand.cs b/ILSpy/Commands/SortAssemblyListCommand.cs index 7621778a77..3e5bce4aef 100644 --- a/ILSpy/Commands/SortAssemblyListCommand.cs +++ b/ILSpy/Commands/SortAssemblyListCommand.cs @@ -31,13 +31,13 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class SortAssemblyListCommand : SimpleCommand, IComparer { - public override void Execute(object parameter) + public override void Execute(object? parameter) { using (MainWindow.Instance.AssemblyTreeView.LockUpdates()) MainWindow.Instance.CurrentAssemblyList.Sort(this); } - int IComparer.Compare(LoadedAssembly x, LoadedAssembly y) + int IComparer.Compare(LoadedAssembly? x, LoadedAssembly? y) { return string.Compare(x.ShortName, y.ShortName, StringComparison.CurrentCulture); } @@ -48,7 +48,7 @@ int IComparer.Compare(LoadedAssembly x, LoadedAssembly y) [PartCreationPolicy(CreationPolicy.Shared)] sealed class CollapseAllCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { using (MainWindow.Instance.AssemblyTreeView.LockUpdates()) CollapseChildren(MainWindow.Instance.AssemblyTreeView.Root); diff --git a/ILSpy/Docking/CloseAllDocumentsCommand.cs b/ILSpy/Docking/CloseAllDocumentsCommand.cs index 2c0ceb41be..273eda623a 100644 --- a/ILSpy/Docking/CloseAllDocumentsCommand.cs +++ b/ILSpy/Docking/CloseAllDocumentsCommand.cs @@ -13,7 +13,7 @@ namespace ICSharpCode.ILSpy.Docking [PartCreationPolicy(CreationPolicy.Shared)] class CloseAllDocumentsCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { DockWorkspace.Instance.CloseAllTabs(); } @@ -23,7 +23,7 @@ public override void Execute(object parameter) [PartCreationPolicy(CreationPolicy.Shared)] class ResetLayoutCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { DockWorkspace.Instance.ResetLayout(); } diff --git a/ILSpy/Docking/TabPageGuardConverter.cs b/ILSpy/Docking/TabPageGuardConverter.cs index b6c2d23615..94a2f1b170 100644 --- a/ILSpy/Docking/TabPageGuardConverter.cs +++ b/ILSpy/Docking/TabPageGuardConverter.cs @@ -27,12 +27,12 @@ namespace ICSharpCode.ILSpy.Docking { public class TabPageGuardConverter : ValueConverter { - protected override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + protected override object Convert(object value, Type? targetType, object? parameter, System.Globalization.CultureInfo? culture) { return value is TabPageModel ? value : Binding.DoNothing; } - protected override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + protected override object ConvertBack(object value, Type? targetType, object? parameter, System.Globalization.CultureInfo? culture) { return value is TabPageModel ? value : Binding.DoNothing; } diff --git a/ILSpy/ILSpyTraceListener.cs b/ILSpy/ILSpyTraceListener.cs index 66bca55610..b68190b3b3 100644 --- a/ILSpy/ILSpyTraceListener.cs +++ b/ILSpy/ILSpyTraceListener.cs @@ -43,12 +43,12 @@ public ILSpyTraceListener() HashSet ignoredStacks = new HashSet(); bool dialogIsOpen; - public override void Fail(string message) + public override void Fail(string? message) { this.Fail(message, null); } - public override void Fail(string message, string detailMessage) + public override void Fail(string? message, string? detailMessage) { base.Fail(message, detailMessage); // let base class write the assert to the debug console string topFrame = ""; diff --git a/ILSpy/Metadata/FlagsFilterControl.xaml.cs b/ILSpy/Metadata/FlagsFilterControl.xaml.cs index 7a8225a698..6ebaf42f48 100644 --- a/ILSpy/Metadata/FlagsFilterControl.xaml.cs +++ b/ILSpy/Metadata/FlagsFilterControl.xaml.cs @@ -114,7 +114,7 @@ public FlagsContentFilter(int mask) this.Mask = mask; } - public bool IsMatch(object value) + public bool IsMatch(object? value) { if (value == null) return true; diff --git a/ILSpy/Metadata/HexFilterControl.xaml.cs b/ILSpy/Metadata/HexFilterControl.xaml.cs index 26f4d5ea7a..6c3a142175 100644 --- a/ILSpy/Metadata/HexFilterControl.xaml.cs +++ b/ILSpy/Metadata/HexFilterControl.xaml.cs @@ -71,7 +71,7 @@ public ContentFilter(string filter) this.filter = filter; } - public bool IsMatch(object value) + public bool IsMatch(object? value) { if (string.IsNullOrWhiteSpace(filter)) return true; diff --git a/ILSpy/Metadata/MetaDataGrid.cs b/ILSpy/Metadata/MetaDataGrid.cs index a87b065e3e..d9328842f4 100644 --- a/ILSpy/Metadata/MetaDataGrid.cs +++ b/ILSpy/Metadata/MetaDataGrid.cs @@ -32,7 +32,7 @@ namespace ICSharpCode.ILSpy.Metadata class MetaDataGrid : DataGrid, IHaveState { private readonly MouseHoverLogic hoverLogic; - private ToolTip toolTip; + private ToolTip? toolTip; public ILSpyTreeNode SelectedTreeNode { get; set; } @@ -76,7 +76,7 @@ private void HoverLogic_MouseHover(object sender, System.Windows.Input.MouseEven var pi = data?.GetType().GetProperty(name + "Tooltip"); if (pi == null) return; - object tooltip = pi.GetValue(data); + object? tooltip = pi.GetValue(data); if (tooltip is string s) { if (string.IsNullOrWhiteSpace(s)) @@ -107,7 +107,7 @@ private void ToolTipClosed(object sender, RoutedEventArgs e) } } - public ViewState GetState() + public ViewState? GetState() { return new ViewState { DecompiledNodes = SelectedTreeNode == null diff --git a/ILSpy/NavigationState.cs b/ILSpy/NavigationState.cs index e7400b40ee..e30ee7f639 100644 --- a/ILSpy/NavigationState.cs +++ b/ILSpy/NavigationState.cs @@ -49,7 +49,7 @@ public NavigationState(TabPageModel tabPage, IEnumerable treeNode } - public bool Equals(NavigationState other) + public bool Equals(NavigationState? other) { if (!this.treeNodes.SetEquals(other.treeNodes)) return false; diff --git a/ILSpy/Options/OptionsDialog.xaml.cs b/ILSpy/Options/OptionsDialog.xaml.cs index 72413f6725..c9226fdefd 100644 --- a/ILSpy/Options/OptionsDialog.xaml.cs +++ b/ILSpy/Options/OptionsDialog.xaml.cs @@ -124,7 +124,7 @@ public ExportOptionPageAttribute() : base("OptionPages", typeof(UIElement)) [PartCreationPolicy(CreationPolicy.Shared)] sealed class ShowOptionsCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { OptionsDialog dlg = new OptionsDialog(); dlg.Owner = MainWindow.Instance; diff --git a/ILSpy/ViewModels/PaneModel.cs b/ILSpy/ViewModels/PaneModel.cs index 8663688e44..eef9dca9fa 100644 --- a/ILSpy/ViewModels/PaneModel.cs +++ b/ILSpy/ViewModels/PaneModel.cs @@ -49,12 +49,12 @@ private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e) public event EventHandler CanExecuteChanged; - public bool CanExecute(object parameter) + public bool CanExecute(object? parameter) { return model.IsCloseable; } - public void Execute(object parameter) + public void Execute(object? parameter) { Docking.DockWorkspace.Instance.Remove(model); } diff --git a/ILSpy/ViewModels/TabPageModel.cs b/ILSpy/ViewModels/TabPageModel.cs index 10c28d47c0..7972b84b68 100644 --- a/ILSpy/ViewModels/TabPageModel.cs +++ b/ILSpy/ViewModels/TabPageModel.cs @@ -102,6 +102,6 @@ public static void ShowTextView(this TabPageModel tabPage, Action Date: Fri, 20 Sep 2024 15:08:16 -0400 Subject: [PATCH 05/15] focus on CS8714 --- .editorconfig | 1 + ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs | 3 ++- ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs | 3 ++- ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs | 12 ++++++------ .../Syntax/TypeMembers/ParameterDeclaration.cs | 12 ++++++------ 5 files changed, 17 insertions(+), 14 deletions(-) diff --git a/.editorconfig b/.editorconfig index 9516bd4f26..ec779b49f9 100644 --- a/.editorconfig +++ b/.editorconfig @@ -152,6 +152,7 @@ dotnet_diagnostic.MEF006.severity = silent dotnet_diagnostic.IDE2003.severity = silent #cleared null error types +dotnet_diagnostic.CS8714.severity = error dotnet_diagnostic.CS8765.severity = error dotnet_diagnostic.CS8766.severity = error dotnet_diagnostic.CS8767.severity = error diff --git a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs index 20cecc2ce3..64e2d090f5 100644 --- a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs @@ -1799,7 +1799,8 @@ void DecompileBody(IMethod method, EntityDeclaration entityDecl, DecompileRun de internal static void AddAnnotationsToDeclaration(IMethod method, EntityDeclaration entityDecl, ILFunction function) { int i = 0; - var parameters = function.Variables.Where(v => v.Kind == VariableKind.Parameter).ToDictionary(v => v.Index); + //if the variable is a parameter is a parameter then index "should not" be null, would indicate an deeper under lying problem if it is so we assert not null (!) + var parameters = function.Variables.Where(v => v.Kind == VariableKind.Parameter).ToDictionary(v => v.Index!.Value); foreach (var parameter in entityDecl.GetChildrenByRole(Roles.Parameter)) { if (parameters.TryGetValue(i, out var v)) diff --git a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs index 41fb3870e4..5923a37a0c 100644 --- a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs @@ -2544,7 +2544,8 @@ IType GetTaskType(IType resultType) IEnumerable MakeParameters(IReadOnlyList parameters, ILFunction function) { - var variables = function.Variables.Where(v => v.Kind == VariableKind.Parameter).ToDictionary(v => v.Index); + //if the variable is a parameter is a parameter then index "should not" be null, would indicate an deeper under lying problem if it is so we assert not null (!) + var variables = function.Variables.Where(v => v.Kind == VariableKind.Parameter).ToDictionary(v => v.Index!.Value); int i = 0; foreach (var parameter in parameters) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs index b11edf3996..73b76dc1f6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs @@ -340,7 +340,7 @@ IEnumerable GetDescendantsImpl(bool includeSelf, Func? d /// Gets the first child with the specified role. /// Returns the role's null object if the child is not found. /// - public T GetChildByRole(Role role) where T : AstNode? + public T? GetChildByRole(Role role) where T : AstNode { if (role == null) throw new ArgumentNullException(nameof(role)); @@ -348,7 +348,7 @@ public T GetChildByRole(Role role) where T : AstNode? for (var cur = firstChild; cur != null; cur = cur.nextSibling) { if ((cur.flags & roleIndexMask) == roleIndex) - return (T)cur; + return (T?)cur; } return role.NullObject; } @@ -368,16 +368,16 @@ public AstNodeCollection GetChildrenByRole(Role role) where T : AstNode return new AstNodeCollection(this, role); } - protected void SetChildByRole(Role role, T newChild) where T : AstNode + protected void SetChildByRole(Role role, T? newChild) where T : AstNode { - AstNode oldChild = GetChildByRole(role); - if (oldChild.IsNull) + AstNode? oldChild = GetChildByRole(role); + if (oldChild?.IsNull != false) AddChild(newChild, role); else oldChild.ReplaceWith(newChild); } - public void AddChild(T child, Role role) where T : AstNode + public void AddChild(T? child, Role role) where T : AstNode { if (role == null) throw new ArgumentNullException(nameof(role)); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ParameterDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ParameterDeclaration.cs index 98a86fd694..069e03e7a1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ParameterDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ParameterDeclaration.cs @@ -97,7 +97,7 @@ public AstNodeCollection Attributes { bool isParams; bool isScopedRef; - public CSharpTokenNode ThisKeyword { + public CSharpTokenNode? ThisKeyword { get { if (hasThisModifier) { @@ -141,21 +141,21 @@ public ReferenceKind ParameterModifier { } } - public AstType Type { + public AstType? Type { get { return GetChildByRole(Roles.Type); } set { SetChildByRole(Roles.Type, value); } } public string Name { get { - return GetChildByRole(Roles.Identifier).Name; + return GetChildByRole(Roles.Identifier)?.Name ?? ""; } set { SetChildByRole(Roles.Identifier, Identifier.Create(value)); } } - public Identifier NameToken { + public Identifier? NameToken { get { return GetChildByRole(Roles.Identifier); } @@ -164,11 +164,11 @@ public Identifier NameToken { } } - public CSharpTokenNode AssignToken { + public CSharpTokenNode? AssignToken { get { return GetChildByRole(Roles.Assign); } } - public Expression DefaultExpression { + public Expression? DefaultExpression { get { return GetChildByRole(Roles.Expression); } set { SetChildByRole(Roles.Expression, value); } } From 30421e7309786ce1d64d4211e0f7b220b1d0626c Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Fri, 20 Sep 2024 18:32:46 -0400 Subject: [PATCH 06/15] added notnullwhen annotations --- .editorconfig | 1 + .../Rewrite/ConnectionIdRewritePass.cs | 11 ++-- .../CSharp/CSharpDecompiler.cs | 5 +- ICSharpCode.Decompiler/CSharp/CallBuilder.cs | 6 +- .../CSharp/ExpressionBuilder.cs | 8 +-- .../CSharp/RecordDecompiler.cs | 54 +++++++++------- .../CSharp/Resolver/CSharpResolver.cs | 3 +- .../CSharp/StatementBuilder.cs | 3 +- .../CSharp/Syntax/TypeSystemAstBuilder.cs | 5 +- .../CSharp/Transforms/DeclareVariables.cs | 7 ++- .../Transforms/IntroduceQueryExpressions.cs | 3 +- .../Transforms/PatternStatementTransform.cs | 17 ++--- .../DebugInfo/IDebugInfoProvider.cs | 5 +- ICSharpCode.Decompiler/DecompilerSettings.cs | 2 +- .../IL/ControlFlow/AsyncAwaitDecompiler.cs | 16 ++--- .../IL/ControlFlow/AwaitInCatchTransform.cs | 13 ++-- .../IL/ControlFlow/ConditionDetection.cs | 3 +- .../IL/ControlFlow/DetectPinnedRegions.cs | 36 +++++------ .../IL/ControlFlow/LoopDetection.cs | 1 + .../IL/ControlFlow/SwitchAnalysis.cs | 2 +- .../IL/ControlFlow/YieldReturnDecompiler.cs | 3 +- ICSharpCode.Decompiler/IL/ILReader.cs | 2 +- .../IL/Instructions/DeconstructInstruction.cs | 5 +- .../IL/Transforms/DeconstructionTransform.cs | 17 ++--- .../IL/Transforms/DelegateConstruction.cs | 3 +- .../DetectCatchWhenConditionBlocks.cs | 6 +- .../IL/Transforms/DynamicCallSiteTransform.cs | 9 +-- .../DynamicIsEventAssignmentTransform.cs | 3 +- .../Transforms/EarlyExpressionTransforms.cs | 5 +- .../IL/Transforms/ExpressionTransforms.cs | 7 ++- .../IL/Transforms/HighLevelLoopTransform.cs | 14 ++--- .../IL/Transforms/IndexRangeTransform.cs | 13 ++-- .../Transforms/InterpolatedStringTransform.cs | 3 +- .../IL/Transforms/LocalFunctionDecompiler.cs | 3 +- .../IL/Transforms/LockTransform.cs | 14 +++-- .../IL/Transforms/NullPropagationTransform.cs | 10 +-- .../IL/Transforms/NullableLiftingTransform.cs | 63 ++++++++++--------- .../Transforms/SwitchOnNullableTransform.cs | 9 +-- .../IL/Transforms/SwitchOnStringTransform.cs | 43 ++++++------- .../Transforms/TransformArrayInitializers.cs | 36 +++++------ .../IL/Transforms/TransformAssignment.cs | 7 ++- .../Transforms/TransformDisplayClassUsage.cs | 13 ++-- .../IL/Transforms/TransformExpressionTrees.cs | 19 +++--- .../IL/Transforms/TupleTransform.cs | 3 +- .../Transforms/UserDefinedLogicTransform.cs | 3 +- .../IL/Transforms/UsingTransform.cs | 3 +- .../Metadata/MetadataExtensions.cs | 5 +- .../Metadata/ReferenceLoadInfo.cs | 3 +- .../TypeSystem/GenericContext.cs | 2 +- ICSharpCode.Decompiler/TypeSystem/TaskType.cs | 5 +- .../TreeNodes/AnalyzedEventTreeNode.cs | 4 +- 51 files changed, 297 insertions(+), 239 deletions(-) diff --git a/.editorconfig b/.editorconfig index ec779b49f9..660c2996b3 100644 --- a/.editorconfig +++ b/.editorconfig @@ -152,6 +152,7 @@ dotnet_diagnostic.MEF006.severity = silent dotnet_diagnostic.IDE2003.severity = silent #cleared null error types +dotnet_diagnostic.CS8612.severity = error dotnet_diagnostic.CS8714.severity = error dotnet_diagnostic.CS8765.severity = error dotnet_diagnostic.CS8766.severity = error diff --git a/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs b/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs index 104f6343b7..496080af18 100644 --- a/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs +++ b/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs @@ -22,15 +22,16 @@ using System.Reflection.Metadata; using System.Xml.Linq; +using ICSharpCode.BamlDecompiler.Xaml; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.IL; using ICSharpCode.Decompiler.IL.Transforms; using ICSharpCode.Decompiler.Util; -using ICSharpCode.BamlDecompiler.Xaml; - namespace ICSharpCode.BamlDecompiler.Rewrite { + using System.Diagnostics.CodeAnalysis; + using ICSharpCode.Decompiler.TypeSystem; internal class ConnectionIdRewritePass : IRewritePass @@ -249,7 +250,7 @@ FieldAssignment FindField(ILInstruction inst) } } - bool MatchFieldAssignment(ILInstruction inst, out FieldAssignment field) + bool MatchFieldAssignment(ILInstruction inst, [NotNullWhen(true)] out FieldAssignment field) { field = null; if (!inst.MatchStFld(out _, out var fld, out var value) || !value.MatchCastClass(out var arg, out _) @@ -293,7 +294,7 @@ void FindEvents(ILInstruction inst, List events) // callvirt set_Event(ldloc v, ldsfld eventName) // callvirt set_Handler(ldloc v, newobj RoutedEventHandler..ctor(ldloc this, ldftn eventHandler)) // callvirt Add(callvirt get_Setters(castclass System.Windows.Style(ldloc target)), ldloc v) - bool MatchEventSetterCreation(Block b, ref int pos, out EventRegistration @event) + bool MatchEventSetterCreation(Block b, ref int pos, [NotNullWhen(true)] out EventRegistration? @event) { @event = null; if (!b.FinalInstruction.MatchNop()) @@ -362,7 +363,7 @@ bool MatchEventSetterCreation(Block b, ref int pos, out EventRegistration @event return true; } - bool MatchSimpleEventRegistration(ILInstruction inst, out EventRegistration @event) + bool MatchSimpleEventRegistration(ILInstruction inst, [NotNullWhen(true)] out EventRegistration? @event) { @event = null; if (!(inst is CallInstruction call) || call.OpCode == OpCode.NewObj) diff --git a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs index 64e2d090f5..9939ce887e 100644 --- a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; @@ -406,7 +407,7 @@ static bool IsSwitchOnStringCache(SRM.FieldDefinition field, MetadataReader meta static readonly Regex automaticPropertyBackingFieldRegex = new Regex(@"^<(.*)>k__BackingField$", RegexOptions.Compiled | RegexOptions.CultureInvariant); - static bool IsAutomaticPropertyBackingField(FieldDefinition field, MetadataReader metadata, out string? propertyName) + static bool IsAutomaticPropertyBackingField(FieldDefinition field, MetadataReader metadata, [NotNullWhen(true)] out string? propertyName) { propertyName = null; var name = metadata.GetString(field.Name); @@ -1917,7 +1918,7 @@ internal static bool RemoveObsoleteAttribute(EntityDeclaration entityDecl, strin return found; } - bool FindAttribute(EntityDeclaration entityDecl, KnownAttribute attributeType, out Syntax.Attribute? attribute) + bool FindAttribute(EntityDeclaration entityDecl, KnownAttribute attributeType, [NotNullWhen(true)] out Syntax.Attribute? attribute) { attribute = null; foreach (var section in entityDecl.Attributes) diff --git a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs index c2dd6a7135..6a7cf06bc4 100644 --- a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs @@ -698,7 +698,7 @@ private static bool IsInterpolatedStringCreation(IMethod method, ArgumentList ar ); } - private bool TryGetStringInterpolationTokens(ArgumentList argumentList, out string? format, out List<(TokenKind Kind, int Index, int Alignment, string? Format)>? tokens) + private bool TryGetStringInterpolationTokens(ArgumentList argumentList, [NotNullWhen(true)] out string? format, [NotNullWhen(true)] out List<(TokenKind Kind, int Index, int Alignment, string? Format)>? tokens) { tokens = null; format = null; @@ -1823,7 +1823,7 @@ internal ExpressionWithResolveResult BuildMethodReference(IMethod method, bool i return expr.Expression.WithRR(new MemberResolveResult(null, method)); } - ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg) + ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod? invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg) { ExpressionBuilder expressionBuilder = this.expressionBuilder; ExpressionWithResolveResult targetExpression; @@ -1983,7 +1983,7 @@ TranslatedExpression HandleDelegateConstruction(IType delegateType, IMethod meth return oce; } - bool IsUnambiguousMethodReference(ExpectedTargetDetails expectedTargetDetails, IMethod method, ResolveResult target, IReadOnlyList typeArguments, bool isExtensionMethodReference, out ResolveResult result) + bool IsUnambiguousMethodReference(ExpectedTargetDetails expectedTargetDetails, IMethod method, ResolveResult target, IReadOnlyList typeArguments, bool isExtensionMethodReference, [NotNullWhen(true)] out ResolveResult result) { Log.WriteLine("IsUnambiguousMethodReference: Performing overload resolution for " + method); diff --git a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs index 5923a37a0c..e302399ae6 100644 --- a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs @@ -3545,7 +3545,7 @@ TranslatedExpression TranslateArrayInitializer(Block block) { var stloc = block.Instructions.FirstOrDefault() as StLoc; var final = block.FinalInstruction as LdLoc; - if (stloc == null || final == null || !stloc.Value.MatchNewArr(out IType type)) + if (stloc == null || final == null || !stloc.Value.MatchNewArr(out IType? type)) throw new ArgumentException("given Block is invalid!"); if (stloc.Variable != final.Variable || stloc.Variable.Kind != VariableKind.InitializerTarget) throw new ArgumentException("given Block is invalid!"); @@ -3564,11 +3564,11 @@ TranslatedExpression TranslateArrayInitializer(Block block) for (int i = 1; i < block.Instructions.Count; i++) { - if (!block.Instructions[i].MatchStObj(out ILInstruction target, out ILInstruction value, out IType t) || !type.Equals(t)) + if (!block.Instructions[i].MatchStObj(out ILInstruction? target, out ILInstruction? value, out IType? t) || !type.Equals(t)) throw new ArgumentException("given Block is invalid!"); - if (!target.MatchLdElema(out t, out ILInstruction array) || !type.Equals(t)) + if (!target.MatchLdElema(out t, out ILInstruction? array) || !type.Equals(t)) throw new ArgumentException("given Block is invalid!"); - if (!array.MatchLdLoc(out ILVariable v) || v != final.Variable) + if (!array.MatchLdLoc(out ILVariable? v) || v != final.Variable) throw new ArgumentException("given Block is invalid!"); while (container.Count < dimensions) { diff --git a/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs b/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs index 8fda6e1f00..f1788bb7cc 100644 --- a/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Metadata; using System.Threading; @@ -39,8 +40,8 @@ class RecordDecompiler readonly bool isInheritedRecord; readonly bool isStruct; readonly bool isSealed; - readonly IMethod primaryCtor; - readonly IType baseClass; + readonly IMethod? primaryCtor; + readonly IType? baseClass; readonly Dictionary backingFieldToAutoProperty = new Dictionary(); readonly Dictionary autoPropertyToBackingField = new Dictionary(); readonly Dictionary primaryCtorParameterToAutoPropertyOrBackingField = new Dictionary(); @@ -75,7 +76,7 @@ void DetectAutomaticProperties() } } - bool IsAutoProperty(IProperty p, out IField? field) + bool IsAutoProperty(IProperty p, [NotNullWhen(true)] out IField? field) { field = null; if (p.IsStatic) @@ -108,7 +109,7 @@ bool IsAutoProperty(IProperty p, out IField? field) return field.Name == $"<{p.Name}>k__BackingField"; } - bool IsAutoGetter(IMethod method, out IField? field) + bool IsAutoGetter(IMethod method, [NotNullWhen(true)] out IField? field) { field = null; var body = DecompileBody(method); @@ -129,7 +130,7 @@ bool IsAutoGetter(IMethod method, out IField? field) } } - bool IsAutoSetter(IMethod method, out IField? field) + bool IsAutoSetter(IMethod method, [NotNullWhen(true)] out IField? field) { field = null; Debug.Assert(!method.IsStatic); @@ -137,7 +138,7 @@ bool IsAutoSetter(IMethod method, out IField? field) if (body == null) return false; // this.field = value; - ILInstruction valueInst; + ILInstruction? valueInst; if (method.IsStatic) { if (!body.Instructions[0].MatchStsFld(out field, out valueInst)) @@ -158,7 +159,7 @@ bool IsAutoSetter(IMethod method, out IField? field) } } - IMethod DetectPrimaryConstructor() + IMethod? DetectPrimaryConstructor() { if (recordTypeDef.IsRecord) { @@ -373,7 +374,7 @@ public bool IsPropertyDeclaredByPrimaryConstructor(IProperty property) && autoPropertyOrBackingFieldToPrimaryCtorParameter.ContainsKey((IProperty)property.Specialize(subst)); } - internal (IProperty prop, IField field) GetPropertyInfoByPrimaryConstructorParameter(IParameter parameter) + internal (IProperty? prop, IField field) GetPropertyInfoByPrimaryConstructorParameter(IParameter parameter) { var member = primaryCtorParameterToAutoPropertyOrBackingField[parameter]; if (member is IField field) @@ -450,8 +451,14 @@ leave IL_0000 (nop) { if (!(member is IField field)) { - if (!autoPropertyToBackingField.TryGetValue((IProperty)member, out field)) + if (!autoPropertyToBackingField.TryGetValue((IProperty)member, out var fieldHolder)) + { continue; + } + else + { + field = fieldHolder; + } } if (pos >= body.Instructions.Count) return false; @@ -516,7 +523,7 @@ private bool IsGeneratedEqualityContract(IProperty property) if (!(body.Instructions.Single() is Leave leave)) return false; // leave IL_0000 (call GetTypeFromHandle(ldtypetoken R)) - if (!TransformExpressionTrees.MatchGetTypeFromHandle(leave.Value, out IType ty)) + if (!TransformExpressionTrees.MatchGetTypeFromHandle(leave.Value, out IType? ty)) return false; return IsRecordType(ty); } @@ -569,7 +576,7 @@ private bool IsGeneratedPrintMembers(IMethod method) trueInst = Block.Unwrap(trueInst); if (!MatchStringBuilderAppend(trueInst, builder, out var val)) return false; - if (!(val.MatchLdStr(out string text) && text == ", ")) + if (!(val.MatchLdStr(out string? text) && text == ", ")) return false; pos++; @@ -601,7 +608,7 @@ callvirt Append(ldloc builder, ldstr "B") callvirt Append(ldloc builder, ldstr " = ") callvirt Append(ldloc builder, constrained[System.Int32].callvirt ToString(ldflda B(ldloc this))) leave IL_0000 (ldc.i4 1) */ - if (!MatchStringBuilderAppendConstant(out string text)) + if (!MatchStringBuilderAppendConstant(out string? text)) return false; string expectedText = (needsComma ? ", " : "") + member.Name + " = "; if (text != expectedText) @@ -672,10 +679,10 @@ bool IsPrintedMember(IMember member) return true; } - bool MatchStringBuilderAppendConstant(out string? text) + bool MatchStringBuilderAppendConstant([NotNullWhen(true)] out string? text) { text = null; - while (MatchStringBuilderAppend(body.Instructions[pos], builder, out var val) && val.MatchLdStr(out string valText)) + while (MatchStringBuilderAppend(body.Instructions[pos], builder, out var val) && val.MatchLdStr(out string? valText)) { text += valText; pos++; @@ -684,7 +691,7 @@ bool MatchStringBuilderAppendConstant(out string? text) } } - private bool MatchStringBuilderAppend(ILInstruction inst, ILVariable sb, out ILInstruction? val) + private bool MatchStringBuilderAppend(ILInstruction inst, ILVariable sb, [NotNullWhen(true)] out ILInstruction? val) { val = null; if (!(inst is CallVirt { Method: { Name: "Append", DeclaringType: { Namespace: "System.Text", Name: "StringBuilder" } } } call)) @@ -760,7 +767,7 @@ bool MatchAppendCallWithValue(ILInstruction inst, string val) { return val != null && val.Length == 1 && call.Arguments[1].MatchLdcI4(val[0]); } - return call.Arguments[1].MatchLdStr(out string val1) && val1 == val; + return call.Arguments[1].MatchLdStr(out string? val1) && val1 == val; } } @@ -912,7 +919,7 @@ void Visit(ILInstruction inst) } } - private bool MatchGetEqualityContract(ILInstruction inst, out ILInstruction? target) + private bool MatchGetEqualityContract(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? target) { target = null; if (!(inst is CallInstruction { Method: { Name: "get_EqualityContract" } } call)) @@ -1099,7 +1106,7 @@ bool IsGeneratedDeconstruct(IMethod method) return returnInst != null && returnInst.MatchReturn(out var retVal) && retVal.MatchNop(); } - bool MatchMemberAccess(ILInstruction inst, out ILInstruction? target, out IMember? member) + bool MatchMemberAccess(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? target, [NotNullWhen(true)] out IMember? member) { target = null; member = null; @@ -1116,12 +1123,17 @@ bool MatchMemberAccess(ILInstruction inst, out ILInstruction? target, out IMembe member = property; return true; } - else if (inst.MatchLdFld(out target, out IField field)) + else if (inst.MatchLdFld(out target, out IField? field)) { - if (backingFieldToAutoProperty.TryGetValue(field, out property)) + if (backingFieldToAutoProperty.TryGetValue(field, out var propertyHolder)) + { + property = propertyHolder; member = property; + } else + { member = field; + } return true; } else @@ -1130,7 +1142,7 @@ bool MatchMemberAccess(ILInstruction inst, out ILInstruction? target, out IMembe } } - Block DecompileBody(IMethod method) + Block? DecompileBody(IMethod method) { if (method == null || method.MetadataToken.IsNil) return null; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs index bfe1860004..f78997d14a 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs @@ -20,6 +20,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; @@ -1597,7 +1598,7 @@ public ResolveResult LookupSimpleNameOrTypeName(string identifier, IReadOnlyList } } - public bool IsVariableReferenceWithSameType(ResolveResult rr, string identifier, out TypeResolveResult? trr) + public bool IsVariableReferenceWithSameType(ResolveResult rr, string identifier, [NotNullWhen(true)] out TypeResolveResult? trr) { if (!(rr is MemberResolveResult || rr is LocalResolveResult)) { diff --git a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs index 5d1df3fc20..e75785415c 100644 --- a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -875,7 +876,7 @@ static bool EqualErasedType(IType a, IType b) return NormalizeTypeVisitor.TypeErasure.EquivalentTypes(a, b); } - private bool IsDynamicCastToIEnumerable(Expression expr, out Expression? dynamicExpr) + private bool IsDynamicCastToIEnumerable(Expression expr, [NotNullWhen(true)] out Expression? dynamicExpr) { if (!(expr is CastExpression cast)) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs index 97c0e72292..4c88b0eb40 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs @@ -20,6 +20,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; @@ -1081,7 +1082,7 @@ public Expression ConvertConstantValue(IType expectedType, IType type, object co } } - bool IsSpecialConstant(IType expectedType, object constant, out Expression? expression) + bool IsSpecialConstant(IType expectedType, object constant, [NotNullWhen(true)] out Expression? expression) { expression = null; if (!specialConstants.TryGetValue(constant, out var info)) @@ -2492,7 +2493,7 @@ NamespaceDeclaration ConvertNamespaceDeclaration(INamespace ns) return new NamespaceDeclaration(ns.FullName); } - AstType GetExplicitInterfaceType(IMember member) + AstType? GetExplicitInterfaceType(IMember member) { if (member.IsExplicitInterfaceImplementation) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs index 787b97d996..7756a26cda 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; @@ -552,7 +553,7 @@ bool IsDeclarableVariable(ILInstruction inst) } } - bool IsMatchingAssignment(VariableToDeclare v, out AssignmentExpression assignment) + bool IsMatchingAssignment(VariableToDeclare v, [NotNullWhen(true)] out AssignmentExpression? assignment) { assignment = v.InsertionPoint.nextNode as AssignmentExpression; if (assignment == null) @@ -731,7 +732,7 @@ void InsertVariableDeclarations(TransformContext context) } } - private bool CanBeDeclaredAsOutVariable(VariableToDeclare v, out DirectionExpression dirExpr) + private bool CanBeDeclaredAsOutVariable(VariableToDeclare v, [NotNullWhen(true)] out DirectionExpression? dirExpr) { dirExpr = v.FirstUse.Parent as DirectionExpression; if (dirExpr == null || dirExpr.FieldDirection != FieldDirection.Out) @@ -740,7 +741,7 @@ private bool CanBeDeclaredAsOutVariable(VariableToDeclare v, out DirectionExpres return false; if (v.DefaultInitialization != VariableInitKind.None) return false; - for (AstNode node = v.FirstUse; node != null; node = node.Parent) + for (AstNode? node = v.FirstUse; node != null; node = node.Parent) { if (node.Role == Roles.EmbeddedStatement) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs index 04455f5f3c..dc1bc4794f 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs @@ -18,6 +18,7 @@ using System; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; @@ -370,7 +371,7 @@ bool ValidateThenByChain(InvocationExpression invocation, string expectedParamet } /// Matches simple lambdas of the form "a => b" - bool MatchSimpleLambda(Expression expr, out ParameterDeclaration? parameter, out Expression? body) + bool MatchSimpleLambda(Expression expr, [NotNullWhen(true)] out ParameterDeclaration? parameter, [NotNullWhen(true)] out Expression? body) { if (expr is LambdaExpression lambda && lambda.Parameters.Count == 1 && lambda.Body is Expression) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs index 2d1d28376a..d4456e9525 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; @@ -431,7 +432,7 @@ Statement TransformForeachOnArray(ForStatement forStatement) ) ))); - bool MatchLowerBound(int indexNum, out IL.ILVariable? index, IL.ILVariable collection, Statement statement) + bool MatchLowerBound(int indexNum, [NotNullWhen(true)] out IL.ILVariable? index, IL.ILVariable collection, Statement statement) { index = null; var m = variableAssignLowerBoundPattern.Match(statement); @@ -443,7 +444,7 @@ bool MatchLowerBound(int indexNum, out IL.ILVariable? index, IL.ILVariable colle return m.Get("collection").Single().GetILVariable() == collection; } - bool MatchForeachOnMultiDimArray(IL.ILVariable[] upperBounds, IL.ILVariable collection, Statement firstInitializerStatement, out IdentifierExpression? foreachVariable, out IList? statements, out IL.ILVariable[] lowerBounds) + bool MatchForeachOnMultiDimArray(IL.ILVariable[] upperBounds, IL.ILVariable collection, Statement firstInitializerStatement, [NotNullWhen(true)] out IdentifierExpression? foreachVariable, [NotNullWhen(true)] out IList? statements, out IL.ILVariable[] lowerBounds) { int i = 0; foreachVariable = null; @@ -451,7 +452,7 @@ bool MatchForeachOnMultiDimArray(IL.ILVariable[] upperBounds, IL.ILVariable coll lowerBounds = new IL.ILVariable[upperBounds.Length]; Statement stmt = firstInitializerStatement; Match m = default(Match); - while (i < upperBounds.Length && MatchLowerBound(i, out IL.ILVariable indexVariable, collection, stmt)) + while (i < upperBounds.Length && MatchLowerBound(i, out IL.ILVariable? indexVariable, collection, stmt)) { m = forOnArrayMultiDimPattern.Match(stmt.GetNextStatement()); if (!m.Success) @@ -702,16 +703,16 @@ public override AstNode VisitIdentifier(Identifier identifier) return base.VisitIdentifier(identifier); } - internal static bool IsBackingFieldOfAutomaticProperty(IField field, out IProperty? property) + internal static bool IsBackingFieldOfAutomaticProperty(IField field, [NotNullWhen(true)] out IProperty? property) { property = null; - if (!NameCouldBeBackingFieldOfAutomaticProperty(field.Name, out string propertyName)) + if (!NameCouldBeBackingFieldOfAutomaticProperty(field.Name, out string? propertyName)) return false; if (!field.IsCompilerGenerated()) return false; - property = field.DeclaringTypeDefinition + property = field.DeclaringTypeDefinition? .GetProperties(p => p.Name == propertyName, GetMemberOptions.IgnoreInheritedMembers) - .FirstOrDefault(); + ?.FirstOrDefault(); return property != null; } @@ -725,7 +726,7 @@ internal static bool IsBackingFieldOfAutomaticProperty(IField field, out IProper static readonly System.Text.RegularExpressions.Regex automaticPropertyBackingFieldNameRegex = new System.Text.RegularExpressions.Regex(@"^(<(?.+)>k__BackingField|_(?.+))$"); - static bool NameCouldBeBackingFieldOfAutomaticProperty(string name, out string? propertyName) + static bool NameCouldBeBackingFieldOfAutomaticProperty(string name, [NotNullWhen(true)] out string? propertyName) { propertyName = null; var m = automaticPropertyBackingFieldNameRegex.Match(name); diff --git a/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs b/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs index 810919e567..04de5d8d72 100644 --- a/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs +++ b/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using System.Text; @@ -28,8 +29,8 @@ public interface IDebugInfoProvider string Description { get; } IList GetSequencePoints(MethodDefinitionHandle method); IList GetVariables(MethodDefinitionHandle method); - bool TryGetName(MethodDefinitionHandle method, int index, out string name); - bool TryGetExtraTypeInfo(MethodDefinitionHandle method, int index, out PdbExtraTypeInfo extraTypeInfo); + bool TryGetName(MethodDefinitionHandle method, int index, [NotNullWhen(true)] out string? name); + bool TryGetExtraTypeInfo(MethodDefinitionHandle method, int index, [NotNullWhen(true)] out PdbExtraTypeInfo extraTypeInfo); string SourceFileName { get; } } } diff --git a/ICSharpCode.Decompiler/DecompilerSettings.cs b/ICSharpCode.Decompiler/DecompilerSettings.cs index 97e87da107..f910afa848 100644 --- a/ICSharpCode.Decompiler/DecompilerSettings.cs +++ b/ICSharpCode.Decompiler/DecompilerSettings.cs @@ -2173,7 +2173,7 @@ public CSharpFormattingOptions CSharpFormattingOptions { } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) { diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs index 7a02039b22..5e71463ee9 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs @@ -20,6 +20,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Metadata; @@ -482,7 +483,7 @@ bool MatchVisualBasicStateMachineFieldAssignements(IList body, IL /// /// Matches a (potentially virtual) instance method call. /// - static bool MatchCall(ILInstruction inst, string name, out InstructionCollection? args) + static bool MatchCall(ILInstruction inst, string name, [NotNullWhen(true)] out InstructionCollection? args) { if (inst is CallInstruction call && (call.OpCode == OpCode.Call || call.OpCode == OpCode.CallVirt) && call.Method.Name == name && !call.Method.IsStatic) @@ -497,7 +498,7 @@ static bool MatchCall(ILInstruction inst, string name, out InstructionCollection /// /// Matches a store to the state machine. /// - static bool MatchStFld(ILInstruction stfld, ILVariable stateMachineVar, out IField field, out ILInstruction value) + static bool MatchStFld(ILInstruction stfld, ILVariable stateMachineVar, [NotNullWhen(true)] out IField? field, [NotNullWhen(true)] out ILInstruction? value) { if (!stfld.MatchStFld(out var target, out field, out value)) return false; @@ -869,7 +870,7 @@ private Block CheckSetResultReturnBlock(BlockContainer blockContainer, int setRe return blockContainer.Blocks[setResultReturnBlockIndex]; } - private bool MatchDisposeCombinedTokens(BlockContainer blockContainer, ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst, bool[] blocksAnalyzed, out Block? setResultAndExitBlock) + private bool MatchDisposeCombinedTokens(BlockContainer blockContainer, ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst, bool[] blocksAnalyzed, [NotNullWhen(true)] out Block? setResultAndExitBlock) { setResultAndExitBlock = null; // ... @@ -1423,7 +1424,7 @@ bool MatchLdDisposeMode(ILInstruction inst) } } - bool AnalyzeAwaitBlock(Block block, out ILVariable? awaiter, out IField? awaiterField, out int state, out int yieldOffset) + bool AnalyzeAwaitBlock(Block block, [NotNullWhen(true)] out ILVariable? awaiter, [NotNullWhen(true)] out IField? awaiterField, out int state, out int yieldOffset) { awaiter = null; awaiterField = null; @@ -1522,6 +1523,7 @@ bool AnalyzeAwaitBlock(Block block, out ILVariable? awaiter, out IField? awaiter { pos--; } + block.Instructions.RemoveRange(pos, block.Instructions.Count - pos); return true; } @@ -1538,7 +1540,7 @@ static ILInstruction StackSlotValue(ILInstruction inst) return inst; } - private bool AnalyzeYieldReturn(Block block, out ILInstruction? yieldValue, out int newState) + private bool AnalyzeYieldReturn(Block block, [NotNullWhen(true)] out ILInstruction? yieldValue, out int newState) { yieldValue = default; newState = default; @@ -1584,7 +1586,7 @@ private bool AnalyzeYieldReturn(Block block, out ILInstruction? yieldValue, out return true; } - bool MatchCurrentAssignment(ILInstruction inst, out ILInstruction value) + bool MatchCurrentAssignment(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? value) { if (!inst.MatchStFld(out var target, out var field, out value)) return false; @@ -1701,7 +1703,7 @@ static ILInstruction UnwrapConvUnknown(ILInstruction inst) return inst; } - bool CheckAwaitBlock(Block block, out Block? resumeBlock, out IField? stackField) + bool CheckAwaitBlock(Block block, [NotNullWhen(true)] out Block? resumeBlock, out IField? stackField) { // awaitBlock: // (pre-roslyn: save stack) diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs index 88fe3c6973..147ce41429 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.IL.Transforms; @@ -223,7 +224,7 @@ static void MoveBlock(Block block, BlockContainer target) /// Analyzes all catch handlers and returns every handler that follows the await catch handler pattern. /// static bool AnalyzeHandlers(InstructionCollection handlers, out ILVariable? catchHandlerIdentifier, - out List transformableCatchBlocks) + [NotNullWhen(true)] out List transformableCatchBlocks) { transformableCatchBlocks = new List(); catchHandlerIdentifier = null; @@ -254,9 +255,9 @@ static bool AnalyzeHandlers(InstructionCollection handlers, out /// stloc V_5(ldc.i4 2) - store id of catch block in 'identifierVariable' /// br IL_0075 - jump out of catch block to the head of the catch-handler jump table /// - static bool MatchAwaitCatchHandler(TryCatchHandler handler, out int id, out ILVariable? identifierVariable, - out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, - out ILInstruction? jumpTableEntry, out ILVariable? objectVariable) + static bool MatchAwaitCatchHandler(TryCatchHandler handler, out int id, [NotNullWhen(true)] out ILVariable? identifierVariable, + [NotNullWhen(true)] out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, + [NotNullWhen(true)] out ILInstruction? jumpTableEntry, out ILVariable? objectVariable) { id = 0; identifierVariable = null; @@ -266,7 +267,7 @@ static bool MatchAwaitCatchHandler(TryCatchHandler handler, out int id, out ILVa nextBlockOrExitContainer = null; var exceptionVariable = handler.Variable; var catchBlock = ((BlockContainer)handler.Body).EntryPoint; - ILInstruction value; + ILInstruction? value; switch (catchBlock.Instructions.Count) { case 3: @@ -326,7 +327,7 @@ static bool MatchAwaitCatchHandler(TryCatchHandler handler, out int id, out ILVa return false; } - bool ParseSwitchJumpTable(int id, SwitchInstruction jumpTable, ILVariable identifierVariable, out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, out ILInstruction? jumpTableEntry) + bool ParseSwitchJumpTable(int id, SwitchInstruction jumpTable, ILVariable identifierVariable, [NotNullWhen(true)] out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, [NotNullWhen(true)] out ILInstruction? jumpTableEntry) { realEntryPoint = null; nextBlockOrExitContainer = null; diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs index 03a22b151a..6276011fc7 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.FlowAnalysis; @@ -610,7 +611,7 @@ private bool IsKeywordExit(ILInstruction exitInst, out Keyword keyword) /// Determine if the specified instruction necessarily exits (EndPointUnreachable) /// and if so return last (or single) exit instruction /// - private static bool TryGetExit(ILInstruction inst, out ILInstruction? exitInst) + private static bool TryGetExit(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? exitInst) { if (inst is Block block && block.Instructions.Count > 0) inst = block.Instructions.Last(); diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs index d67b9ad7cd..3674b323aa 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices.ComTypes; @@ -241,8 +242,8 @@ void DetectNullSafeArrayToPointerOrCustomRefPin(BlockContainer container) // stloc V_1(get.pinnable.reference(ldloc mem)) // stloc ptr(conv ref->u (ldloc V_1)) // br targetBlock - private bool IsCustomRefPinPattern(Block block, out ILInstruction? ldlocMem, out CallInstruction? callGPR, - out ILVariable? v, out StLoc? ptrAssign, out Block? targetBlock, out Block? nullBlock, out Block? notNullBlock) + private bool IsCustomRefPinPattern(Block block, [NotNullWhen(true)] out ILInstruction? ldlocMem, [NotNullWhen(true)] out CallInstruction? callGPR, + [NotNullWhen(true)] out ILVariable? v, out StLoc? ptrAssign, [NotNullWhen(true)] out Block? targetBlock, out Block? nullBlock, [NotNullWhen(true)] out Block? notNullBlock) { ldlocMem = null; callGPR = null; @@ -356,7 +357,7 @@ private bool IsCustomRefPinPattern(Block block, out ILInstruction? ldlocMem, out // ... // stloc P(array.to.pointer(V)) // br B_target - bool IsNullSafeArrayToPointerPattern(Block block, out ILVariable? v, out ILVariable? p, out Block? targetBlock) + bool IsNullSafeArrayToPointerPattern(Block block, [NotNullWhen(true)] out ILVariable? v, [NotNullWhen(true)] out ILVariable? p, [NotNullWhen(true)] out Block? targetBlock) { v = null; p = null; @@ -384,7 +385,7 @@ bool IsNullSafeArrayToPointerPattern(Block block, out ILVariable? v, out ILVaria usingPreviousVar = true; } } - if (!ifInst.TrueInst.MatchBranch(out Block nullOrEmptyBlock)) + if (!ifInst.TrueInst.MatchBranch(out Block? nullOrEmptyBlock)) return false; if (!ifInst.FalseInst.MatchNop()) return false; @@ -394,7 +395,7 @@ bool IsNullSafeArrayToPointerPattern(Block block, out ILVariable? v, out ILVaria return false; if (!(p.Kind == VariableKind.PinnedLocal || (usingPreviousVar && v.Kind == VariableKind.PinnedLocal))) return false; - if (!block.Instructions.Last().MatchBranch(out Block notNullBlock)) + if (!block.Instructions.Last().MatchBranch(out Block? notNullBlock)) return false; if (notNullBlock.Parent != block.Parent) return false; @@ -409,7 +410,7 @@ bool IsNullSafeArrayToPointerNotNullBlock(Block block, ILVariable v, ILVariable // } if (block.Instructions.Count != 2) return false; - if (!block.Instructions[0].MatchIfInstruction(out ILInstruction condition, out ILInstruction trueInst)) + if (!block.Instructions[0].MatchIfInstruction(out var condition, out var trueInst)) return false; var falseInst = block.Instructions[1]; if (condition is Comp comp && comp.Right.MatchLdcI(0)) @@ -495,7 +496,7 @@ bool IsNullSafeArrayToPointerNotNullAndNotEmptyBlock(Block block, ILVariable v, return block.Instructions[1].MatchBranch(targetBlock); } - bool IsNullSafeArrayToPointerNullOrEmptyBlock(Block block, out ILVariable? p, out Block? targetBlock) + bool IsNullSafeArrayToPointerNullOrEmptyBlock(Block block, [NotNullWhen(true)] out ILVariable? p, [NotNullWhen(true)] out Block? targetBlock) { p = null; targetBlock = null; @@ -503,7 +504,7 @@ bool IsNullSafeArrayToPointerNullOrEmptyBlock(Block block, out ILVariable? p, ou // stloc P(conv i4->u(ldc.i4 0)) // br B_target // } - ILInstruction value; + ILInstruction? value; return block.Instructions.Count == 2 && block.Instructions[0].MatchStLoc(out p, out value) && (p.Kind == VariableKind.PinnedLocal || p.Kind == VariableKind.Local) @@ -863,13 +864,12 @@ private bool IsSlotAcceptingBothManagedAndUnmanagedPointers(SlotInfo slotInfo) return slotInfo == Block.InstructionSlot || slotInfo == LdObj.TargetSlot || slotInfo == StObj.TargetSlot; } - bool IsBranchOnNull(ILInstruction condBranch, ILVariable nativeVar, out Block? targetBlock) + bool IsBranchOnNull(ILInstruction condBranch, ILVariable nativeVar, [NotNullWhen(true)] out Block? targetBlock) { targetBlock = null; // if (comp(ldloc nativeVar == conv i4->i (ldc.i4 0))) br targetBlock - ILInstruction condition, trueInst, left, right; - return condBranch.MatchIfInstruction(out condition, out trueInst) - && condition.MatchCompEquals(out left, out right) + return condBranch.MatchIfInstruction(out var condition, out var trueInst) + && condition.MatchCompEquals(out var left, out var right) && left.MatchLdLoc(nativeVar) && IsNullOrZero(right) && trueInst.MatchBranch(out targetBlock); } @@ -884,7 +884,7 @@ void HandleStringToPointer(PinnedRegion pinnedRegion) // if (comp(ldloc nativeVar == conv i4->i (ldc.i4 0))) br targetBlock // br adjustOffsetToStringData ILVariable newVar; - if (!body.EntryPoint.Instructions[0].MatchStLoc(out ILVariable nativeVar, out ILInstruction initInst)) + if (!body.EntryPoint.Instructions[0].MatchStLoc(out var nativeVar, out var initInst)) { // potentially a special case with legacy csc and an unused pinned variable: if (pinnedRegion.Variable.AddressCount == 0 && pinnedRegion.Variable.LoadCount == 0) @@ -902,11 +902,11 @@ void HandleStringToPointer(PinnedRegion pinnedRegion) if (nativeVar.Type.GetStackType() != StackType.I) return; - Block targetBlock; + Block? targetBlock; Block? adjustOffsetToStringData = null; if (body.EntryPoint.Instructions.Count == 2) { - if (!initInst.MatchBinaryNumericInstruction(BinaryNumericOperator.Add, out ILInstruction left, out ILInstruction right)) + if (!initInst.MatchBinaryNumericInstruction(BinaryNumericOperator.Add, out var left, out var right)) return; if (!left.UnwrapConv(ConversionKind.StopGCTracking).MatchLdLoc(pinnedRegion.Variable)) return; @@ -977,13 +977,13 @@ void HandleStringToPointer(PinnedRegion pinnedRegion) ReplacePinnedVar(pinnedRegion.Variable, newVar, pinnedRegion); } - bool IsOffsetToStringDataBlock(Block block, ILVariable nativeVar, Block targetBlock) + bool IsOffsetToStringDataBlock(Block block, ILVariable nativeVar, Block? targetBlock) { // stloc nativeVar(add(ldloc nativeVar, conv i4->i (call [Accessor System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData():System.Int32]()))) // br IL_0011 if (block.Instructions.Count != 2) return false; - ILInstruction value; + ILInstruction? value; if (nativeVar.IsSingleDefinition && nativeVar.LoadCount == 2) { // If there are no loads (except for the two in the string-to-pointer pattern), @@ -1003,7 +1003,7 @@ bool IsOffsetToStringDataBlock(Block block, ILVariable nativeVar, Block targetBl { return false; } - if (!value.MatchBinaryNumericInstruction(BinaryNumericOperator.Add, out ILInstruction left, out ILInstruction right)) + if (!value.MatchBinaryNumericInstruction(BinaryNumericOperator.Add, out var left, out var right)) return false; if (!left.MatchLdLoc(nativeVar)) return false; diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs index ec6697ca21..1c82568013 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs @@ -613,6 +613,7 @@ static bool IsPossibleForeachLoop(Block loopHead, out Branch? exitBranch) // skip blocks that only branch to another block entryPoint = targetBlock; } + return entryPoint == loopHead; } #endregion diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs index cd40c92236..8114f1e21a 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs @@ -314,7 +314,7 @@ private bool AnalyzeCondition(ILInstruction condition, out LongSet trueValues) trueValues = new LongSet(0).Invert(); return true; } - else if (condition.MatchLogicNot(out ILInstruction arg)) + else if (condition.MatchLogicNot(out var arg)) { // if (logic.not(X)) --> branch for all values where if (X) does not branch bool res = AnalyzeCondition(arg, out LongSet falseValues); diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs index ecfc976b6d..4856bdbb35 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Metadata; @@ -1426,7 +1427,7 @@ private void CleanSkipFinallyBodies(ILFunction function) } context.StepEndGroup(keepIfEmpty: true); - bool IsCallToMonoFinallyMethod(Call call, out IMethod? finallyMethod) + bool IsCallToMonoFinallyMethod(Call call, [NotNullWhen(true)] out IMethod? finallyMethod) { finallyMethod = default; if (call == null) diff --git a/ICSharpCode.Decompiler/IL/ILReader.cs b/ICSharpCode.Decompiler/IL/ILReader.cs index 2ec9da40ac..99b2419e08 100644 --- a/ICSharpCode.Decompiler/IL/ILReader.cs +++ b/ICSharpCode.Decompiler/IL/ILReader.cs @@ -312,7 +312,7 @@ ILVariable CreateILVariable(int index, IType type) } ILVariable ilVar = new ILVariable(kind, type, index); - if (!UseDebugSymbols || DebugInfo == null || !DebugInfo.TryGetName((MethodDefinitionHandle)method.MetadataToken, index, out string name)) + if (!UseDebugSymbols || DebugInfo == null || !DebugInfo.TryGetName((MethodDefinitionHandle)method.MetadataToken, index, out string? name)) { ilVar.Name = "V_" + index; ilVar.HasGeneratedName = true; diff --git a/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs b/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs index bcaea6c769..055b91bc6f 100644 --- a/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs +++ b/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; @@ -190,7 +191,7 @@ public override void WriteTo(ITextOutput output, ILAstWritingOptions options) output.MarkFoldEnd(); } - internal static bool IsConversionStLoc(ILInstruction inst, out ILVariable variable, out ILVariable? inputVariable) + internal static bool IsConversionStLoc(ILInstruction inst, [NotNullWhen(true)] out ILVariable? variable, [NotNullWhen(true)] out ILVariable? inputVariable) { inputVariable = null; if (!inst.MatchStLoc(out variable, out var value)) @@ -210,7 +211,7 @@ internal static bool IsConversionStLoc(ILInstruction inst, out ILVariable variab return input.MatchLdLoc(out inputVariable) || input.MatchLdLoca(out inputVariable); } - internal static bool IsAssignment(ILInstruction inst, ICompilation typeSystem, out IType? expectedType, out ILInstruction? value) + internal static bool IsAssignment(ILInstruction inst, ICompilation typeSystem, [NotNullWhen(true)] out IType? expectedType, [NotNullWhen(true)] out ILInstruction? value) { expectedType = null; value = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs index c2b5cde12e..30fa9dc150 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Resources; @@ -35,9 +36,9 @@ class DeconstructionTransform : IStatementTransform { StatementTransformContext context; readonly Dictionary deconstructionResultsLookup = new Dictionary(); - ILVariable[] deconstructionResults; - ILVariable tupleVariable; - TupleType tupleType; + ILVariable[]? deconstructionResults; + ILVariable? tupleVariable; + TupleType? tupleType; /* stloc tuple(call MakeIntIntTuple(ldloc this)) @@ -262,8 +263,8 @@ bool TransformDeconstruction(Block block, int pos) return true; } - bool MatchDeconstruction(ILInstruction inst, out IMethod? deconstructMethod, - out ILInstruction? testedOperand) + bool MatchDeconstruction(ILInstruction inst, [NotNullWhen(true)] out IMethod? deconstructMethod, + [NotNullWhen(true)] out ILInstruction? testedOperand) { testedOperand = null; deconstructMethod = null; @@ -328,8 +329,8 @@ bool MatchConversions(Block block, ref int pos, return true; } - bool MatchConversion(ILInstruction inst, out ILInstruction? inputInstruction, - out ILVariable outputVariable, out ConversionInfo info) + bool MatchConversion(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? inputInstruction, + [NotNullWhen(true)] out ILVariable? outputVariable, [NotNullWhen(true)] out ConversionInfo info) { info = default; inputInstruction = null; @@ -433,7 +434,7 @@ void AddMissingAssignmentsForConversions(int index, ref Action? addAssignment) + bool MatchAssignment(ILInstruction inst, out IType? targetType, [NotNullWhen(true)] out ILInstruction? valueInst, [NotNullWhen(true)] out Action? addAssignment) { targetType = null; valueInst = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs b/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs index 4b606fa02a..a3b8caa159 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs @@ -17,6 +17,7 @@ // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Metadata; @@ -80,7 +81,7 @@ void IILTransform.Run(ILFunction function, ILTransformContext context) } internal static bool MatchDelegateConstruction(ILInstruction inst, out IMethod? targetMethod, - out ILInstruction? target, out IType? delegateType, bool allowTransformed = false) + [NotNullWhen(true)] out ILInstruction? target, [NotNullWhen(true)] out IType? delegateType, bool allowTransformed = false) { targetMethod = null; target = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs b/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs index 4d4e410202..d539039d02 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; @@ -162,7 +163,7 @@ void PropagateExceptionInstance(StLoc store) /// br falseBlock /// } /// - bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, Block entryPoint, out IType? exceptionType, out ILInstruction? exceptionSlot, out Block? whenConditionBlock) + bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, Block entryPoint, [NotNullWhen(true)] out IType? exceptionType, [NotNullWhen(true)] out ILInstruction? exceptionSlot, [NotNullWhen(true)] out Block? whenConditionBlock) { exceptionType = null; exceptionSlot = null; @@ -206,6 +207,7 @@ bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, return false; if (right.MatchLdNull()) { + return branch.MatchBranch(out whenConditionBlock); } } @@ -218,7 +220,7 @@ bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, /// br exitBlock /// } /// - bool MatchFalseBlock(BlockContainer container, Block falseBlock, out ILVariable? returnVar, out Block? exitBlock) + bool MatchFalseBlock(BlockContainer container, Block falseBlock, [NotNullWhen(true)] out ILVariable? returnVar, [NotNullWhen(true)] out Block? exitBlock) { returnVar = null; exitBlock = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs index 6a2e686b9c..2bd7b5ea04 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; @@ -272,7 +273,7 @@ ILInstruction MakeDynamicInstruction(CallSiteInfo callsite, CallVirt targetInvok } } - bool ScanCallSiteInitBlock(Block callSiteInitBlock, IField callSiteCacheField, IType callSiteDelegateType, out CallSiteInfo callSiteInfo, out Block? blockAfterInit) + bool ScanCallSiteInitBlock(Block callSiteInitBlock, IField callSiteCacheField, IType callSiteDelegateType, out CallSiteInfo callSiteInfo, [NotNullWhen(true)] out Block? blockAfterInit) { callSiteInfo = default(CallSiteInfo); blockAfterInit = null; @@ -300,7 +301,7 @@ bool ScanCallSiteInitBlock(Block callSiteInitBlock, IField callSiteCacheField, I if (!binderCall.Arguments[0].MatchLdcI4(out int binderFlagsInteger)) return false; callSiteInfo.Flags = (CSharpBinderFlags)binderFlagsInteger; - if (!binderCall.Arguments[1].MatchLdStr(out string name)) + if (!binderCall.Arguments[1].MatchLdStr(out var name)) return false; callSiteInfo.MemberName = name; if (!TransformExpressionTrees.MatchGetTypeFromHandle(binderCall.Arguments[2], out var contextType)) @@ -551,7 +552,7 @@ bool ExtractArgumentInfo(ILInstruction value, ref CallSiteInfo callSiteInfo, int return false; if (!createCall.Arguments[0].MatchLdcI4(out var argumentInfoFlags)) return false; - if (!createCall.Arguments[1].MatchLdStr(out string argumentName)) + if (!createCall.Arguments[1].MatchLdStr(out var argumentName)) if (!createCall.Arguments[1].MatchLdNull()) return false; callSiteInfo.ArgumentInfos[i] = new CSharpArgumentInfo { Flags = (CSharpArgumentInfoFlags)argumentInfoFlags, Name = argumentName, CompileTimeType = compileTimeTypes[i + 1] }; @@ -560,7 +561,7 @@ bool ExtractArgumentInfo(ILInstruction value, ref CallSiteInfo callSiteInfo, int return true; } - bool MatchCallSiteCacheNullCheck(ILInstruction condition, out IField? callSiteCacheField, out IType? callSiteDelegate, out bool invertBranches) + bool MatchCallSiteCacheNullCheck(ILInstruction condition, [NotNullWhen(true)] out IField? callSiteCacheField, [NotNullWhen(true)] out IType? callSiteDelegate, out bool invertBranches) { callSiteCacheField = null; callSiteDelegate = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs index 050da61467..f81355becd 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DynamicIsEventAssignmentTransform.cs @@ -16,6 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace ICSharpCode.Decompiler.IL.Transforms @@ -121,7 +122,7 @@ static bool MatchIsEventAssignmentIfInstruction(ILInstruction ifInst, DynamicIsE /// stloc V_2(dynamic.getmember B(target)) /// } /// - static bool MatchLhsCacheIfInstruction(ILInstruction ifInst, ILVariable flagVar, out StLoc? cacheStore) + static bool MatchLhsCacheIfInstruction(ILInstruction ifInst, ILVariable flagVar, [NotNullWhen(true)] out StLoc? cacheStore) { cacheStore = null; if (!ifInst.MatchIfInstruction(out var condition, out var trueInst)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs b/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs index 17944d8f3d..412c047a6c 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs @@ -16,6 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; @@ -175,7 +176,7 @@ internal static void AddressOfLdLocToLdLoca(LdObj inst, ILTransformContext conte protected internal override void VisitNewObj(NewObj inst) { - if (TransformDecimalCtorToConstant(inst, out LdcDecimal decimalConstant)) + if (TransformDecimalCtorToConstant(inst, out var decimalConstant)) { context.Step("TransformDecimalCtorToConstant", inst); inst.ReplaceWith(decimalConstant); @@ -185,7 +186,7 @@ protected internal override void VisitNewObj(NewObj inst) base.VisitNewObj(inst); } - bool TransformDecimalCtorToConstant(NewObj inst, out LdcDecimal? result) + bool TransformDecimalCtorToConstant(NewObj inst, [NotNullWhen(true)] out LdcDecimal? result) { IType t = inst.Method.DeclaringType; result = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs b/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs index 277df2cb45..e65bac4fe0 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; @@ -342,7 +343,7 @@ protected internal override void VisitNewObj(NewObj inst) /// => /// ldvirtdelegate System.Delegate TargetMethod(target) /// - bool TransformDelegateCtorLdVirtFtnToLdVirtDelegate(NewObj inst, out LdVirtDelegate? ldVirtDelegate) + bool TransformDelegateCtorLdVirtFtnToLdVirtDelegate(NewObj inst, [NotNullWhen(true)] out LdVirtDelegate? ldVirtDelegate) { ldVirtDelegate = null; if (inst.Method.DeclaringType.Kind != TypeKind.Delegate) @@ -379,7 +380,7 @@ bool TransformDelegateCtorLdVirtFtnToLdVirtDelegate(NewObj inst, out LdVirtDeleg /// final: ldloc I_0 /// } /// - bool TransformSpanTCtorContainingStackAlloc(NewObj newObj, out ILInstruction? locallocSpan) + bool TransformSpanTCtorContainingStackAlloc(NewObj newObj, [NotNullWhen(true)] out ILInstruction? locallocSpan) { locallocSpan = null; IType type = newObj.Method.DeclaringType; @@ -428,7 +429,7 @@ bool MatchesElementCount(ILInstruction sizeInBytesInstr, IType elementType, ILIn return true; } - bool TransformDecimalFieldToConstant(LdObj inst, out LdcDecimal? result) + bool TransformDecimalFieldToConstant(LdObj inst, [NotNullWhen(true)] out LdcDecimal? result) { if (inst.MatchLdsFld(out var field) && field.DeclaringType.IsKnownType(KnownTypeCode.Decimal)) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs index 047940188f..c637979aa0 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.IL.ControlFlow; @@ -53,7 +54,7 @@ public void Run(ILFunction function, ILTransformContext context) } } - bool MatchWhileLoop(BlockContainer loop, out IfInstruction? condition, out Block loopBody) + bool MatchWhileLoop(BlockContainer loop, [NotNullWhen(true)] out IfInstruction? condition, out Block loopBody) { // ConditionDetection favours leave inside if and branch at end of block // while-loop: @@ -115,7 +116,6 @@ bool MatchWhileLoop(BlockContainer loop, out IfInstruction? condition, out Block ExpressionTransforms.RunOnSingleStatment(inst, context); } }*/ - return true; } @@ -156,7 +156,7 @@ void SplitConditions(ILInstruction expression, List conditions) /// bool MatchDoWhileLoop(BlockContainer loop) { - (List conditions, ILInstruction exit, bool swap, bool split, bool unwrap) = AnalyzeDoWhileConditions(loop); + (List? conditions, ILInstruction exit, bool swap, bool split, bool unwrap) = AnalyzeDoWhileConditions(loop); // not a do-while loop, exit. if (conditions == null || conditions.Count == 0) return false; @@ -240,7 +240,7 @@ bool MatchDoWhileLoop(BlockContainer loop) return true; } - static (List conditions, ILInstruction exit, bool swap, bool split, bool unwrap) AnalyzeDoWhileConditions(BlockContainer loop) + static (List? conditions, ILInstruction? exit, bool swap, bool split, bool unwrap) AnalyzeDoWhileConditions(BlockContainer loop) { // we iterate over all blocks from the bottom, because the entry-point // should only be considered as condition block, if there are no other blocks. @@ -356,7 +356,7 @@ static bool MatchDoWhileConditionBlock(BlockContainer loop, Block block, out boo } // early match before block containers have been constructed - internal static bool MatchDoWhileConditionBlock(Block block, out Block target1, out Block? target2) + internal static bool MatchDoWhileConditionBlock(Block block, out Block? target1, out Block? target2) { target1 = target2 = null; if (block.Instructions.Count < 2) @@ -370,7 +370,7 @@ internal static bool MatchDoWhileConditionBlock(Block block, out Block target1, (last.MatchBranch(out target2) || last.MatchReturn(out var _)); } - internal static Block GetIncrementBlock(BlockContainer loop, Block whileLoopBody) => + internal static Block? GetIncrementBlock(BlockContainer loop, Block whileLoopBody) => loop.Blocks.SingleOrDefault(b => b != whileLoopBody && b.Instructions.Last().MatchBranch(loop.EntryPoint) && b.Instructions.SkipLast(1).All(IsSimpleStatement)); @@ -480,7 +480,7 @@ bool IsAssignment(ILInstruction inst) /// Returns true if the instruction is stloc v(add(ldloc v, arg)) /// or compound.assign(ldloca v, arg) /// - public static bool MatchIncrement(ILInstruction inst, out ILVariable variable) + public static bool MatchIncrement(ILInstruction inst, [NotNullWhen(true)] out ILVariable? variable) { if (inst.MatchStLoc(out variable, out var value)) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs index f23b750005..2b8607cc28 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs @@ -17,6 +17,7 @@ // DEALINGS IN THE SOFTWARE. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; @@ -152,7 +153,7 @@ void IStatementTransform.Run(Block block, int pos, StatementTransformContext con int startPos = pos; ILVariable? containerVar = null; // The container length access may be a separate instruction, or it may be inline with the variable's use - if (MatchContainerLengthStore(block.Instructions[pos], out ILVariable containerLengthVar, ref containerVar)) + if (MatchContainerLengthStore(block.Instructions[pos], out var containerLengthVar, ref containerVar)) { // stloc containerLengthVar(call get_Length/get_Count(ldloc container)) pos++; @@ -465,7 +466,7 @@ void ExtendSlicing() } } - private bool MatchIndexImplicitConv(ILInstruction inst, out ILInstruction? offsetInst) + private bool MatchIndexImplicitConv(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? offsetInst) { offsetInst = null; if (!(inst is CallInstruction call)) @@ -607,7 +608,7 @@ private bool CSharpWillGenerateIndexer(IType declaringType, bool slicing) /// Matches the instruction: /// stloc containerLengthVar(call get_Length/get_Count(ldloc containerVar)) /// - static bool MatchContainerLengthStore(ILInstruction inst, out ILVariable lengthVar, ref ILVariable containerVar) + static bool MatchContainerLengthStore(ILInstruction inst, [NotNullWhen(true)] out ILVariable? lengthVar, ref ILVariable? containerVar) { if (!inst.MatchStLoc(out lengthVar, out var init)) return false; @@ -624,7 +625,7 @@ static bool MatchContainerLengthStore(ILInstruction inst, out ILVariable lengthV /// Otherwise, matches the instruction: /// call get_Length/get_Count(ldloc containerVar) /// - static bool MatchContainerLength(ILInstruction init, ILVariable lengthVar, ref ILVariable containerVar) + static bool MatchContainerLength(ILInstruction init, ILVariable? lengthVar, ref ILVariable? containerVar) { if (lengthVar != null) { @@ -658,7 +659,7 @@ static bool MatchContainerLength(ILInstruction init, ILVariable lengthVar, ref I return MatchContainerVar(call.Arguments[0], ref containerVar); } - static bool MatchContainerVar(ILInstruction inst, ref ILVariable containerVar) + static bool MatchContainerVar(ILInstruction inst, [NotNullWhen(true)] ref ILVariable? containerVar) { if (containerVar != null) { @@ -745,7 +746,7 @@ static IndexKind MatchGetOffset(ILInstruction inst, out ILInstruction indexLoad, /// Matches an instruction computing a slice length: /// binary.sub.i4(call GetOffset(endIndexLoad, ldloc length), ldloc startOffset)) /// - static bool MatchSliceLength(ILInstruction inst, out IndexKind endIndexKind, out ILInstruction? endIndexLoad, ILVariable containerLengthVar, ref ILVariable containerVar, ILVariable startOffsetVar) + static bool MatchSliceLength(ILInstruction inst, out IndexKind endIndexKind, [NotNullWhen(true)] out ILInstruction? endIndexLoad, ILVariable containerLengthVar, ref ILVariable containerVar, ILVariable startOffsetVar) { endIndexKind = default; endIndexLoad = default; diff --git a/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs index 864af3c279..03e1d62a81 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs @@ -18,6 +18,7 @@ using System; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using ICSharpCode.Decompiler.TypeSystem; @@ -104,7 +105,7 @@ private bool IsKnownCall(Block block, int pos, ILVariable v) return true; } - private bool FindToStringAndClear(Block block, int pos, int interpolationStart, int interpolationEnd, ILVariable v, out ILInstruction? insertionPoint) + private bool FindToStringAndClear(Block block, int pos, int interpolationStart, int interpolationEnd, ILVariable v, [NotNullWhen(true)] out ILInstruction? insertionPoint) { insertionPoint = null; if (pos >= block.Instructions.Count) diff --git a/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs b/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs index f2ab98f1a5..f74c0cf0bc 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs @@ -20,6 +20,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Reflection.Metadata; @@ -831,7 +832,7 @@ public static bool IsLocalFunctionDisplayClass(MetadataFile module, TypeDefiniti /// static readonly Regex functionNameRegex = new Regex(@"^<(.*)>g__([^\|]*)\|{0,1}\d+(_\d+)?$", RegexOptions.Compiled); - internal static bool ParseLocalFunctionName(string name, out string? callerName, out string? functionName) + internal static bool ParseLocalFunctionName(string name, [NotNullWhen(true)] out string? callerName, [NotNullWhen(true)] out string? functionName) { callerName = null; functionName = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs index 116ca50d70..2d3d54ac50 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs @@ -16,6 +16,8 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +using System.Diagnostics.CodeAnalysis; + using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.IL.Transforms @@ -331,7 +333,7 @@ bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, ILVariable obj) return true; } - bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out StLoc? obj) + bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, [NotNullWhen(true)] out StLoc? obj) { obj = null; if (entryPoint.Instructions.Count == 0 || entryPoint.IncomingEdgeCount != 1) @@ -341,14 +343,14 @@ bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out StLoc? obj) return true; } - bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out ILVariable? exitVairable, out StLoc? obj) + bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, [NotNullWhen(true)] out ILVariable? exitVariable, [NotNullWhen(true)] out StLoc? obj) { // This pattern is commonly seen in yield return state machines emitted by the legacy C# compiler. obj = null; - exitVairable = null; + exitVariable = null; if (entryPoint.Instructions.Count < 1 || entryPoint.IncomingEdgeCount != 1) return false; - if (entryPoint.Instructions[0].MatchStLoc(out exitVairable, out var value) && value is StLoc nestedStloc) + if (entryPoint.Instructions[0].MatchStLoc(out exitVariable, out var value) && value is StLoc nestedStloc) { obj = nestedStloc; if (!MatchCall(entryPoint.Instructions[1] as Call, "Enter", nestedStloc.Variable, flag)) @@ -358,7 +360,7 @@ bool MatchLockEntryPoint(Block entryPoint, ILVariable flag, out ILVariable? exit return false; } - bool MatchCall(Call call, string methodName, ILVariable flag, out StLoc? obj) + bool MatchCall(Call? call, string methodName, ILVariable flag, [NotNullWhen(true)] out StLoc? obj) { obj = null; const string ThreadingMonitor = "System.Threading.Monitor"; @@ -371,7 +373,7 @@ bool MatchCall(Call call, string methodName, ILVariable flag, out StLoc? obj) return true; } - bool MatchCall(Call call, string methodName, params ILVariable[] variables) + bool MatchCall(Call? call, string methodName, params ILVariable[] variables) { const string ThreadingMonitor = "System.Threading.Monitor"; if (call == null || call.Method.Name != methodName || call.Method.DeclaringType.FullName != ThreadingMonitor || diff --git a/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs index 5f35409c60..cdf0a7de9a 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs @@ -18,6 +18,7 @@ using System; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; @@ -237,7 +238,7 @@ void TryNullPropForVoidCall(ILVariable testedVar, Mode mode, Block body, IfInstr ).WithILRange(ifInst)); } - bool IsValidAccessChain(ILVariable testedVar, Mode mode, ILInstruction inst, out ILInstruction? finalLoad) + bool IsValidAccessChain(ILVariable testedVar, Mode mode, ILInstruction inst, [NotNullWhen(true)] out ILInstruction? finalLoad) { finalLoad = null; int chainLength = 0; @@ -475,7 +476,7 @@ private bool TransformNullPropagationOnUnconstrainedGenericExpression(Block bloc // stloc resultTemporary(constrained[type].call_instruction(ldloc target, ...)) // br endBlock - private bool MatchStLocResultTemporary(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, out ILInstruction? nonNullInst, out ILInstruction? nullInst, out Block? endBlock) + private bool MatchStLocResultTemporary(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, [NotNullWhen(true)] out ILInstruction? nonNullInst, [NotNullWhen(true)] out ILInstruction? nullInst, [NotNullWhen(true)] out Block? endBlock) { endBlock = null; nonNullInst = null; @@ -496,7 +497,7 @@ private bool MatchStLocResultTemporary(Block block, int pos, IType type, ILVaria return true; } - private bool MatchLeaveResult(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, out ILInstruction? nonNullInst, out ILInstruction? nullInst) + private bool MatchLeaveResult(Block block, int pos, IType type, ILVariable target, ILVariable defaultTemporary, ILInstruction fallbackBlock, [NotNullWhen(true)] out ILInstruction? nonNullInst, [NotNullWhen(true)] out ILInstruction? nullInst) { nonNullInst = null; nullInst = null; @@ -508,6 +509,7 @@ private bool MatchLeaveResult(Block block, int pos, IType type, ILVariable targe // Analyze Block fallbackBlock if (!(fallbackBlock is Block b && IsFallbackBlock(b, type, target, defaultTemporary, null, leave.TargetContainer, out nullInst))) return false; + return true; } @@ -519,7 +521,7 @@ private bool MatchLeaveResult(Block block, int pos, IType type, ILVariable targe // br endBlock // } // } - private bool IsFallbackBlock(Block block, IType type, ILVariable target, ILVariable defaultTemporary, ILVariable resultTemporary, ILInstruction endBlockOrLeaveContainer, out ILInstruction? nullInst) + private bool IsFallbackBlock(Block block, IType type, ILVariable target, ILVariable defaultTemporary, ILVariable? resultTemporary, ILInstruction endBlockOrLeaveContainer, [NotNullWhen(true)] out ILInstruction? nullInst) { nullInst = null; if (!(block.Instructions.Count == 3)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs index 41d4aac38c..ed01185268 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; @@ -371,7 +372,7 @@ private bool IsGenericNewPattern(ILInstruction compLeft, ILInstruction compRight compRight.MatchLdNull(); } - private bool MatchThreeValuedLogicConditionPattern(ILInstruction condition, out ILVariable? nullable1, out ILVariable? nullable2) + private bool MatchThreeValuedLogicConditionPattern(ILInstruction condition, [NotNullWhen(true)] out ILVariable? nullable1, [NotNullWhen(true)] out ILVariable? nullable2) { // Try to match: nullable1.GetValueOrDefault() || (!nullable2.GetValueOrDefault() && !nullable1.HasValue) nullable1 = null; @@ -518,7 +519,7 @@ internal ILInstruction MakeLifted(ComparisonKind newComparisonKind, ILInstructio #endregion #region Lift...Comparison - ILInstruction LiftCSharpEqualityComparison(CompOrDecimal valueComp, ComparisonKind newComparisonKind, ILInstruction hasValueTest) + ILInstruction? LiftCSharpEqualityComparison(CompOrDecimal valueComp, ComparisonKind newComparisonKind, ILInstruction hasValueTest) { Debug.Assert(newComparisonKind.IsEqualityOrInequality()); bool hasValueTestNegated = false; @@ -535,9 +536,9 @@ ILInstruction LiftCSharpEqualityComparison(CompOrDecimal valueComp, ComparisonKi // Comparing two nullables: HasValue comparison must be the same operator as the Value comparison if ((hasValueTestNegated ? hasValueComp.Kind.Negate() : hasValueComp.Kind) != newComparisonKind) return null; - if (!MatchHasValueCall(hasValueComp.Left, out ILVariable leftVar)) + if (!MatchHasValueCall(hasValueComp.Left, out ILVariable? leftVar)) return null; - if (!MatchHasValueCall(hasValueComp.Right, out ILVariable rightVar)) + if (!MatchHasValueCall(hasValueComp.Right, out ILVariable? rightVar)) return null; nullableVars = new List { leftVar }; var (left, leftBits) = DoLift(valueComp.Left); @@ -551,7 +552,7 @@ ILInstruction LiftCSharpEqualityComparison(CompOrDecimal valueComp, ComparisonKi return valueComp.MakeLifted(newComparisonKind, left, right); } } - else if (newComparisonKind == ComparisonKind.Equality && !hasValueTestNegated && MatchHasValueCall(hasValueTest, out ILVariable v)) + else if (newComparisonKind == ComparisonKind.Equality && !hasValueTestNegated && MatchHasValueCall(hasValueTest, out ILVariable? v)) { // Comparing nullable with non-nullable -> we can fall back to the normal comparison code. nullableVars = new List { v }; @@ -578,7 +579,7 @@ ILInstruction LiftCSharpEqualityComparison(CompOrDecimal valueComp, ComparisonKi /// This means unlike LiftNormal(), we cannot rely on the input instruction not being evaluated if /// a variable is null. /// - ILInstruction LiftCSharpComparison(CompOrDecimal comp, ComparisonKind newComparisonKind) + ILInstruction? LiftCSharpComparison(CompOrDecimal comp, ComparisonKind newComparisonKind) { if (comp.IsLifted) { @@ -614,7 +615,7 @@ ILInstruction LiftCSharpComparison(CompOrDecimal comp, ComparisonKind newCompari return null; } - ILInstruction LiftCSharpUserEqualityComparison(CompOrDecimal hasValueComp, ComparisonKind newComparisonKind, ILInstruction nestedIfInst) + ILInstruction? LiftCSharpUserEqualityComparison(CompOrDecimal hasValueComp, ComparisonKind newComparisonKind, ILInstruction nestedIfInst) { // User-defined equality operator: // if (comp(call get_HasValue(ldloca nullable1) == call get_HasValue(ldloca nullable2))) @@ -635,13 +636,13 @@ ILInstruction LiftCSharpUserEqualityComparison(CompOrDecimal hasValueComp, Compa // ldc.i4 0 if (hasValueComp.IsLifted) return null; - if (!MatchHasValueCall(hasValueComp.Left, out ILVariable nullable1)) + if (!MatchHasValueCall(hasValueComp.Left, out ILVariable? nullable1)) return null; - if (!MatchHasValueCall(hasValueComp.Right, out ILVariable nullable2)) + if (!MatchHasValueCall(hasValueComp.Right, out ILVariable? nullable2)) return null; if (!nestedIfInst.MatchIfInstructionPositiveCondition(out var condition, out var trueInst, out var falseInst)) return null; - if (!MatchHasValueCall(condition, out ILVariable nullable)) + if (!MatchHasValueCall(condition, out ILVariable? nullable)) return null; if (nullable != nullable1 && nullable != nullable2) return null; @@ -687,7 +688,7 @@ ILInstruction LiftCSharpUserEqualityComparison(CompOrDecimal hasValueComp, Compa return null; } - ILInstruction LiftCSharpUserComparison(ILInstruction trueInst, ILInstruction falseInst) + ILInstruction? LiftCSharpUserComparison(ILInstruction trueInst, ILInstruction falseInst) { // (v1 != null && ... && vn != null) ? trueInst : falseInst bool trueInstNegated = false; @@ -745,13 +746,13 @@ ILInstruction LiftCSharpUserComparison(ILInstruction trueInst, ILInstruction fal /// where the v1,...,vn are the this.nullableVars. /// If lifting fails, returns null. /// - ILInstruction LiftNormal(ILInstruction trueInst, ILInstruction falseInst) + ILInstruction? LiftNormal(ILInstruction trueInst, ILInstruction falseInst) { if (trueInst.MatchIfInstructionPositiveCondition(out var nestedCondition, out var nestedTrue, out var nestedFalse)) { // Sometimes Roslyn generates pointless conditions like: // if (nullable.HasValue && (!nullable.HasValue || nullable.GetValueOrDefault() == b)) - if (MatchHasValueCall(nestedCondition, out ILVariable v) && nullableVars.Contains(v)) + if (MatchHasValueCall(nestedCondition, out ILVariable? v) && nullableVars.Contains(v)) { trueInst = nestedTrue; } @@ -851,9 +852,9 @@ ILInstruction LiftNormal(ILInstruction trueInst, ILInstruction falseInst) /// If any relevant variable is null, the new instruction is guaranteed to evaluate to null /// without having any other effect. /// - (ILInstruction, BitSet) DoLift(ILInstruction inst) + (ILInstruction?, BitSet?) DoLift(ILInstruction inst) { - if (MatchGetValueOrDefault(inst, out ILVariable inputVar)) + if (MatchGetValueOrDefault(inst, out ILVariable? inputVar)) { // n.GetValueOrDefault() lifted => n. BitSet foundIndices = new BitSet(nullableVars.Count); @@ -916,7 +917,7 @@ ILInstruction LiftNormal(ILInstruction trueInst, ILInstruction falseInst) } } else if (inst is Comp comp && !comp.IsLifted && comp.Kind == ComparisonKind.Equality - && MatchGetValueOrDefault(comp.Left, out ILVariable v) && nullableVars.Contains(v) + && MatchGetValueOrDefault(comp.Left, out ILVariable? v) && nullableVars.Contains(v) && NullableType.GetUnderlyingType(v.Type).IsKnownType(KnownTypeCode.Boolean) && comp.Right.MatchLdcI4(0) ) @@ -934,8 +935,8 @@ ILInstruction LiftNormal(ILInstruction trueInst, ILInstruction falseInst) var liftedOperator = CSharp.Resolver.CSharpOperators.LiftUserDefinedOperator(call.Method); if (liftedOperator == null || !NullableType.IsNullable(liftedOperator.ReturnType)) return (null, null); - ILInstruction[] newArgs; - BitSet newBits; + ILInstruction?[] newArgs; + BitSet? newBits; if (call.Arguments.Count == 1) { var (arg, bits) = DoLift(call.Arguments[0]); @@ -969,7 +970,7 @@ ILInstruction LiftNormal(ILInstruction trueInst, ILInstruction falseInst) return (null, null); } - (ILInstruction, ILInstruction, BitSet) DoLiftBinary(ILInstruction lhs, ILInstruction rhs, IType leftExpectedType, IType rightExpectedType) + (ILInstruction?, ILInstruction?, BitSet?) DoLiftBinary(ILInstruction lhs, ILInstruction rhs, IType leftExpectedType, IType rightExpectedType) { var (left, leftBits) = DoLift(lhs); var (right, rightBits) = DoLift(rhs); @@ -1018,7 +1019,7 @@ private ILInstruction NewNullable(ILInstruction inst, IType underlyingType) /// /// Matches 'call get_HasValue(arg)' /// - internal static bool MatchHasValueCall(ILInstruction inst, out ILInstruction? arg) + internal static bool MatchHasValueCall(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? arg) { arg = null; if (!(inst is Call call)) @@ -1036,9 +1037,9 @@ internal static bool MatchHasValueCall(ILInstruction inst, out ILInstruction? ar /// /// Matches 'call get_HasValue(ldloca v)' /// - internal static bool MatchHasValueCall(ILInstruction inst, out ILVariable? v) + internal static bool MatchHasValueCall(ILInstruction inst, [NotNullWhen(true)] out ILVariable? v) { - if (MatchHasValueCall(inst, out ILInstruction arg)) + if (MatchHasValueCall(inst, out ILInstruction? arg)) { return arg.MatchLdLoca(out v); } @@ -1051,7 +1052,7 @@ internal static bool MatchHasValueCall(ILInstruction inst, out ILVariable? v) /// internal static bool MatchHasValueCall(ILInstruction inst, ILVariable v) { - return MatchHasValueCall(inst, out ILVariable v2) && v == v2; + return MatchHasValueCall(inst, out ILVariable? v2) && v == v2; } /// @@ -1065,7 +1066,7 @@ internal static bool MatchNegatedHasValueCall(ILInstruction inst, ILVariable v) /// /// Matches 'newobj Nullable{underlyingType}.ctor(arg)' /// - internal static bool MatchNullableCtor(ILInstruction inst, out IType? underlyingType, out ILInstruction? arg) + internal static bool MatchNullableCtor(ILInstruction inst, [NotNullWhen(true)] out IType? underlyingType, [NotNullWhen(true)] out ILInstruction? arg) { underlyingType = null; arg = null; @@ -1083,7 +1084,7 @@ internal static bool MatchNullableCtor(ILInstruction inst, out IType? underlying /// /// Matches 'call Nullable{T}.GetValueOrDefault(arg)' /// - internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstruction? arg) + internal static bool MatchGetValueOrDefault(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? arg) { arg = null; if (!(inst is Call call)) @@ -1099,7 +1100,7 @@ internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstructio /// /// Matches 'call nullableValue.GetValueOrDefault(fallback)' /// - internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstruction? nullableValue, out ILInstruction? fallback) + internal static bool MatchGetValueOrDefault(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? nullableValue, [NotNullWhen(true)] out ILInstruction? fallback) { nullableValue = null; fallback = null; @@ -1117,10 +1118,10 @@ internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILInstructio /// /// Matches 'call Nullable{T}.GetValueOrDefault(ldloca v)' /// - internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILVariable? v) + internal static bool MatchGetValueOrDefault(ILInstruction inst, [NotNullWhen(true)] out ILVariable? v) { v = null; - return MatchGetValueOrDefault(inst, out ILInstruction arg) + return MatchGetValueOrDefault(inst, out ILInstruction? arg) && arg.MatchLdLoca(out v); } @@ -1129,13 +1130,13 @@ internal static bool MatchGetValueOrDefault(ILInstruction inst, out ILVariable? /// internal static bool MatchGetValueOrDefault(ILInstruction inst, ILVariable v) { - return MatchGetValueOrDefault(inst, out ILVariable v2) && v == v2; + return MatchGetValueOrDefault(inst, out ILVariable? v2) && v == v2; } - static bool MatchNull(ILInstruction inst, out IType? underlyingType) + static bool MatchNull(ILInstruction inst, [NotNullWhen(true)] out IType? underlyingType) { underlyingType = null; - if (inst.MatchDefaultValue(out IType type)) + if (inst.MatchDefaultValue(out var type)) { underlyingType = NullableType.GetUnderlyingType(type); return NullableType.IsNullable(type); diff --git a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs index 827824abe8..efbbd13099 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.IL.ControlFlow; @@ -77,7 +78,7 @@ public void Run(ILFunction function, ILTransformContext context) /// /// Matches legacy C# switch on nullable. /// - bool MatchSwitchOnNullable(InstructionCollection instructions, int i, out SwitchInstruction? newSwitch) + bool MatchSwitchOnNullable(InstructionCollection instructions, int i, [NotNullWhen(true)] out SwitchInstruction? newSwitch) { newSwitch = null; // match first block: @@ -133,7 +134,7 @@ static SwitchInstruction BuildLiftedSwitch(Block nullCaseBlock, SwitchInstructio /// /// Matches Roslyn C# switch on nullable. /// - bool MatchRoslynSwitchOnNullable(InstructionCollection instructions, int i, out SwitchInstruction? newSwitch) + bool MatchRoslynSwitchOnNullable(InstructionCollection instructions, int i, [NotNullWhen(true)] out SwitchInstruction? newSwitch) { newSwitch = null; // match first block: @@ -143,7 +144,7 @@ bool MatchRoslynSwitchOnNullable(InstructionCollection instructio return false; if (!instructions[i + 1].MatchBranch(out var switchBlock) || !trueInst.MatchBranch(out var nullCaseBlock)) return false; - if (!condition.MatchLogicNot(out var getHasValue) || !NullableLiftingTransform.MatchHasValueCall(getHasValue, out ILInstruction target) || !SemanticHelper.IsPure(target.Flags)) + if (!condition.MatchLogicNot(out var getHasValue) || !NullableLiftingTransform.MatchHasValueCall(getHasValue, out ILInstruction? target) || !SemanticHelper.IsPure(target.Flags)) return false; // match second block: switchBlock // note: I have seen cases where switchVar is inlined into the switch. @@ -165,7 +166,7 @@ bool MatchRoslynSwitchOnNullable(InstructionCollection instructio return false; if (!switchVar.IsSingleDefinition || switchVar.LoadCount != 1) return false; - if (!(NullableLiftingTransform.MatchGetValueOrDefault(getValueOrDefault, out ILInstruction target2) && target2.Match(target).Success)) + if (!(NullableLiftingTransform.MatchGetValueOrDefault(getValueOrDefault, out ILInstruction? target2) && target2.Match(target).Success)) return false; if (!(switchBlock.Instructions[1] is SwitchInstruction si)) return false; diff --git a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs index eb21baff88..1546ec54e0 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.IL.ControlFlow; @@ -473,7 +474,7 @@ bool SimplifyCSharp1CascadingIfStatements(InstructionCollection i return true; } - bool IsIsInternedCall(Call call, out ILInstruction? argument) + bool IsIsInternedCall(Call call, [NotNullWhen(true)] out ILInstruction? argument) { if (call != null && call.Method.DeclaringType.IsKnownType(KnownTypeCode.String) @@ -503,7 +504,7 @@ bool IsIsInternedCall(Call call, out ILInstruction? argument) /// The is updated if the value gets copied to a different variable. /// See comments below for more info. /// - ILInstruction MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out string? value, out bool emptyStringEqualsNull, out ILInstruction? caseBlockOrLeave) + ILInstruction? MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out string? value, out bool emptyStringEqualsNull, out ILInstruction? caseBlockOrLeave) { value = null; caseBlockOrLeave = null; @@ -534,12 +535,12 @@ ILInstruction MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out { return null; } - if (nextBlockBranch.MatchBranch(out Block nextBlock)) + if (nextBlockBranch.MatchBranch(out Block? nextBlock)) { // success return nextBlock; } - else if (nextBlockBranch.MatchLeave(out BlockContainer blockContainer)) + else if (nextBlockBranch.MatchLeave(out BlockContainer? blockContainer)) { // success return blockContainer; @@ -740,7 +741,7 @@ bool HasLabel(SwitchSection section) return true; } - bool AddNullSection(List sections, List<(string Value, int Index)> stringValues, Block nullValueCaseBlock) + bool AddNullSection(List sections, List<(string? Value, int Index)> stringValues, Block nullValueCaseBlock) { var label = new LongSet(stringValues.Max(item => item.Index) + 1); var possibleConflicts = sections.Where(sec => sec.Labels.Overlaps(label)).ToArray(); @@ -760,7 +761,7 @@ bool AddNullSection(List sections, List<(string Value, int Index) /// /// Matches 'volatile.ldobj dictionaryType(ldsflda dictField)' /// - bool MatchDictionaryFieldLoad(ILInstruction inst, Func typeMatcher, out IField? dictField, out IType? dictionaryType) + bool MatchDictionaryFieldLoad(ILInstruction inst, Func typeMatcher, [NotNullWhen(true)] out IField? dictField, [NotNullWhen(true)] out IType? dictionaryType) { dictField = null; dictionaryType = null; @@ -773,7 +774,7 @@ bool MatchDictionaryFieldLoad(ILInstruction inst, Func typeMatcher, /// /// Matches and extracts values from Add-call sequences. /// - bool ExtractStringValuesFromInitBlock(Block block, out List<(string, int)>? values, out Block? blockAfterInit, IType dictionaryType, IField dictionaryField, bool isHashtablePattern) + bool ExtractStringValuesFromInitBlock(Block block, [NotNullWhen(true)] out List<(string?, int)>? values, [NotNullWhen(true)] out Block? blockAfterInit, IType dictionaryType, IField dictionaryField, bool isHashtablePattern) { values = null; blockAfterInit = null; @@ -797,7 +798,7 @@ bool ExtractStringValuesFromInitBlock(Block block, out List<(string, int)>? valu if (!newObj.Arguments[0].MatchLdcI4(out valuesLength)) return false; } - values = new List<(string, int)>(valuesLength); + values = new List<(string?, int)>(valuesLength); int i = 0; while (MatchAddCall(dictionaryType, block.Instructions[i + 1], dictVar, out var index, out var value)) { @@ -822,7 +823,7 @@ bool ExtractStringValuesFromInitBlock(Block block, out List<(string, int)>? valu /// -or- /// call Add(ldloc dictVar, ldstr value, box System.Int32(ldc.i4 index)) /// - bool MatchAddCall(IType dictionaryType, ILInstruction inst, ILVariable dictVar, out int index, out string? value) + bool MatchAddCall(IType dictionaryType, ILInstruction inst, ILVariable dictVar, out int index, [NotNullWhen(true)] out string? value) { value = null; index = -1; @@ -941,7 +942,7 @@ bool MatchLegacySwitchOnStringWithHashtable(Block block, HashtableInitializer ha return true; } - bool FindHashtableInitBlock(Block entryPoint, out List<(string, int)>? stringValues, out IField? dictField, out Block? blockAfterThisInitBlock, out ILInstruction? thisSwitchInitJumpInst, out ILInstruction? nextSwitchInitJumpInst) + bool FindHashtableInitBlock(Block entryPoint, out List<(string?, int)>? stringValues, out IField? dictField, out Block? blockAfterThisInitBlock, out ILInstruction? thisSwitchInitJumpInst, out ILInstruction? nextSwitchInitJumpInst) { stringValues = null; dictField = null; @@ -1310,7 +1311,7 @@ bool MatchGetChars(ILInstruction instruction, ILVariable switchValueVar, out int } } - bool MatchSwitchOnCharBlock(Block block, int length, ILVariable switchValueVar, out List<(string StringValue, ILInstruction BodyOrLeave)>? results) + bool MatchSwitchOnCharBlock(Block block, int length, ILVariable switchValueVar, [NotNullWhen(true)] out List<(string StringValue, ILInstruction BodyOrLeave)>? results) { results = null; if (block.IncomingEdgeCount != 1) @@ -1399,12 +1400,12 @@ bool MatchSwitchOnCharBlock(Block block, int length, ILVariable switchValueVar, return results?.Count > 0; } - bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengthBlock, int startOffset, out List<(LongSet Length, Block TargetBlock)>? blocks) + bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengthBlock, int startOffset, [NotNullWhen(true)] out List<(LongSet Length, Block TargetBlock)>? blocks) { blocks = null; SwitchInstruction? @switch; - ILInstruction getLengthCall; - ILVariable lengthVar; + ILInstruction? getLengthCall; + ILVariable? lengthVar; switch (switchOnLengthBlock.Instructions.Count - startOffset) { case 1: @@ -1506,7 +1507,7 @@ bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengt /// br newDefaultBlock /// } /// - private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable switchVar, out Block? nullValueCaseBlock) + private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable switchVar, [NotNullWhen(true)] out Block? nullValueCaseBlock) { nullValueCaseBlock = null; if (exitOrDefaultBlock == null) @@ -1532,7 +1533,7 @@ private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable /// if (call op_Equality(ldloc switchValueVar, stringValue)) br body /// br exit /// - bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, out ILInstruction? bodyOrLeave, out Block? defaultOrExitBlock, out string? stringValue, out bool emptyStringEqualsNull) + bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, [NotNullWhen(true)] out ILInstruction? bodyOrLeave, [NotNullWhen(true)] out Block? defaultOrExitBlock, [NotNullWhen(true)] out string? stringValue, out bool emptyStringEqualsNull) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1592,7 +1593,7 @@ bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, out ILIns /// br exit /// } /// - bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar, out ILInstruction? bodyOrLeave, out Block? defaultOrExitBlock) + bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar, [NotNullWhen(true)] out ILInstruction? bodyOrLeave, [NotNullWhen(true)] out Block? defaultOrExitBlock) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1602,7 +1603,7 @@ bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar return false; if (!nullComparisonCondition.MatchCompEqualsNull(out var arg) || !arg.MatchLdLoc(switchValueVar)) return false; - if (!target.Instructions[1].MatchBranch(out Block lengthCheckBlock)) + if (!target.Instructions[1].MatchBranch(out Block? lengthCheckBlock)) return false; if (lengthCheckBlock.Instructions.Count != 2 || lengthCheckBlock.IncomingEdgeCount != 1) return false; @@ -1660,7 +1661,7 @@ bool MatchStringLengthCall(ILInstruction inst, ILVariable switchValueVar) /// - or - /// 'stloc(targetVar, call ComputeReadOnlySpanHash(ldloc switchValue))' /// - internal static bool MatchComputeStringOrReadOnlySpanHashCall(ILInstruction inst, ILVariable targetVar, out LdLoc? switchValue) + internal static bool MatchComputeStringOrReadOnlySpanHashCall(ILInstruction inst, ILVariable targetVar, [NotNullWhen(true)] out LdLoc? switchValue) { switchValue = null; if (!inst.MatchStLoc(targetVar, out var value)) @@ -1682,7 +1683,7 @@ internal static bool MatchComputeStringOrReadOnlySpanHashCall(ILInstruction inst /// or 'comp(ldloc(variable) == ldnull)' /// or 'call SequenceEqual(ldloc variable, call AsSpan(ldstr stringValue))' /// - bool MatchStringEqualityComparison(ILInstruction condition, ILVariable variable, out string stringValue, out bool isVBCompareString) + bool MatchStringEqualityComparison(ILInstruction condition, ILVariable variable, out string? stringValue, out bool isVBCompareString) { return MatchStringEqualityComparison(condition, out var v, out stringValue, out isVBCompareString) && v == variable; } @@ -1692,7 +1693,7 @@ bool MatchStringEqualityComparison(ILInstruction condition, ILVariable variable, /// or 'comp(ldloc(variable) == ldnull)' /// or 'call SequenceEqual(ldloc variable, call AsSpan(ldstr stringValue))' /// - bool MatchStringEqualityComparison(ILInstruction condition, out ILVariable? variable, out string? stringValue, out bool isVBCompareString) + bool MatchStringEqualityComparison(ILInstruction condition, [NotNullWhen(true)] out ILVariable? variable, out string? stringValue, out bool isVBCompareString) { stringValue = null; variable = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs index 9a78754686..665d64cd4b 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Metadata; using System.Text; @@ -114,7 +115,7 @@ bool DoTransform(ILFunction function, Block body, int pos) return false; } - internal static bool TransformSpanTArrayInitialization(NewObj inst, StatementTransformContext context, out ILInstruction? replacement) + internal static bool TransformSpanTArrayInitialization(NewObj inst, StatementTransformContext context, [NotNullWhen(true)] out ILInstruction? replacement) { replacement = null; if (!context.Settings.ArrayInitializers) @@ -143,7 +144,7 @@ internal static bool TransformSpanTArrayInitialization(NewObj inst, StatementTra return false; } - private static unsafe bool DecodeUTF8String(BlobReader blob, int size, out string? text) + private static unsafe bool DecodeUTF8String(BlobReader blob, int size, [NotNullWhen(true)] out string? text) { if (size > blob.RemainingBytes) { @@ -166,7 +167,7 @@ private static unsafe bool DecodeUTF8String(BlobReader blob, int size, out strin return MemoryExtensions.SequenceEqual(bytes, new ReadOnlySpan(blob.CurrentPointer, size)); } - static bool MatchSpanTCtorWithPointerAndSize(NewObj newObj, StatementTransformContext context, out IType? elementType, out FieldDefinition field, out int size) + static bool MatchSpanTCtorWithPointerAndSize(NewObj newObj, StatementTransformContext context, [NotNullWhen(true)] out IType? elementType, [NotNullWhen(true)] out FieldDefinition field, out int size) { field = default; size = default; @@ -288,7 +289,7 @@ private ILInstruction ReadElement(ref BlobReader blob, IType elementType) } } - bool HandleCpblkInitializer(Block block, int pos, ILVariable v, long length, out BlobReader blob, out IType? elementType) + bool HandleCpblkInitializer(Block block, int pos, ILVariable v, long length, [NotNullWhen(true)] out BlobReader blob, [NotNullWhen(true)] out IType? elementType) { blob = default; elementType = null; @@ -334,7 +335,7 @@ bool HandleCpblkInitializer(Block block, int pos, ILVariable v, long length, out return true; } - bool MatchGetStaticFieldAddress(ILInstruction input, out IField field) + bool MatchGetStaticFieldAddress(ILInstruction input, [NotNullWhen(true)] out IField? field) { if (input.MatchLdsFlda(out field)) return true; @@ -359,7 +360,7 @@ bool MatchGetStaticFieldAddress(ILInstruction input, out IField field) static bool IsRuntimeHelpers(IType type) => type is { Name: "RuntimeHelpers", Namespace: "System.Runtime.CompilerServices" }; - unsafe bool HandleSequentialLocAllocInitializer(Block block, int pos, ILVariable store, ILInstruction locAllocInstruction, out IType? elementType, out StObj[]? values, out int instructionsToRemove) + unsafe bool HandleSequentialLocAllocInitializer(Block block, int pos, ILVariable store, ILInstruction locAllocInstruction, [NotNullWhen(true)] out IType? elementType, [NotNullWhen(true)] out StObj[]? values, out int instructionsToRemove) { int elementCount = 0; long minExpectedOffset = 0; @@ -399,7 +400,7 @@ unsafe bool HandleSequentialLocAllocInitializer(Block block, int pos, ILVariable for (int i = pos; i < block.Instructions.Count; i++) { // match the basic stobj pattern - if (!block.Instructions[i].MatchStObj(out ILInstruction target, out var value, out var currentType) + if (!block.Instructions[i].MatchStObj(out ILInstruction? target, out var value, out var currentType) || value.Descendants.OfType().Any(inst => inst.Variable == store)) break; // first @@ -462,7 +463,6 @@ unsafe bool HandleSequentialLocAllocInitializer(Block block, int pos, ILVariable elementType = ((PointerType)finalStore.Variable.Type).ElementType; } instructionsToRemove += elementCount; - return elementCount <= values.Length; } @@ -498,7 +498,7 @@ StObj StElemPtr(ILVariable target, int offset, ILInstruction value, IType type) /// /// Handle simple case where RuntimeHelpers.InitializeArray is not used. /// - internal static bool HandleSimpleArrayInitializer(ILFunction function, Block block, int pos, ILVariable store, int[] arrayLength, out (ILInstruction[] Indices, ILInstruction Value)[]? values, out int instructionsToRemove) + internal static bool HandleSimpleArrayInitializer(ILFunction function, Block block, int pos, ILVariable store, int[] arrayLength, [NotNullWhen(true)] out (ILInstruction[] Indices, ILInstruction? Value)[]? values, out int instructionsToRemove) { instructionsToRemove = 0; int elementCount = 0; @@ -508,11 +508,11 @@ internal static bool HandleSimpleArrayInitializer(ILFunction function, Block blo // To prevent excessive allocations, use min(|block|, arraySize) als initial capacity. // This should prevent list-resizing as well as out-of-memory errors. values = null; - var valuesList = new List<(ILInstruction[] Indices, ILInstruction Value)>(Math.Min(block.Instructions.Count, length)); + var valuesList = new List<(ILInstruction[] Indices, ILInstruction? Value)>(Math.Min(block.Instructions.Count, length)); int[] nextMinimumIndex = new int[arrayLength.Length]; - ILInstruction[] CalculateNextIndices(InstructionCollection indices, out bool exactMatch) + ILInstruction[]? CalculateNextIndices(InstructionCollection? indices, out bool exactMatch) { var nextIndices = new ILInstruction[arrayLength.Length]; exactMatch = true; @@ -565,7 +565,7 @@ ILInstruction[] CalculateNextIndices(InstructionCollection indice { InstructionCollection indices; // stobj elementType(ldelema elementType(ldloc store, indices), value) - if (block.Instructions[i].MatchStObj(out ILInstruction target, out ILInstruction value, out IType type)) + if (block.Instructions[i].MatchStObj(out var target, out var value, out var type)) { if (!(target is LdElema ldelem && ldelem.Array.MatchLdLoc(store))) break; @@ -620,7 +620,7 @@ ILInstruction[] CalculateNextIndices(InstructionCollection indice } if (i < block.Instructions.Count) { - if (block.Instructions[i].MatchStObj(out ILInstruction target, out ILInstruction value, out IType type)) + if (block.Instructions[i].MatchStObj(out var target, out var value, out var type)) { // An element of the array is modified directly after the initializer: // Abort transform, so that partial initializers are not constructed. @@ -671,7 +671,7 @@ bool HandleJaggedArrayInitializer(Block block, int pos, ILVariable store, IType { // 1. Instruction: (optional) temporary copy of store bool hasTemporaryCopy = block.Instructions[pos].MatchStLoc(out var temp, out var storeLoad) && storeLoad.MatchLdLoc(store); - ILInstruction initializer; + ILInstruction? initializer; if (hasTemporaryCopy) { if (!MatchJaggedArrayStore(block, pos + 1, temp, i, out initializer, out _)) @@ -703,7 +703,7 @@ bool HandleJaggedArrayInitializer(Block block, int pos, ILVariable store, IType return true; } - bool MatchJaggedArrayStore(Block block, int pos, ILVariable store, int index, out ILInstruction? initializer, out IType? type) + bool MatchJaggedArrayStore(Block block, int pos, ILVariable store, int index, [NotNullWhen(true)] out ILInstruction? initializer, [NotNullWhen(true)] out IType? type) { initializer = null; type = null; @@ -751,7 +751,7 @@ static Block BlockFromInitializer(ILVariable v, IType elementType, int[] arrayLe return block; } - static bool MatchNewArr(ILInstruction instruction, out IType? arrayType, out int[]? length) + static bool MatchNewArr(ILInstruction instruction, [NotNullWhen(true)] out IType? arrayType, [NotNullWhen(true)] out int[]? length) { length = null; arrayType = null; @@ -769,7 +769,7 @@ static bool MatchNewArr(ILInstruction instruction, out IType? arrayType, out int return true; } - bool MatchInitializeArrayCall(ILInstruction instruction, out ILInstruction? array, out FieldDefinition field) + bool MatchInitializeArrayCall(ILInstruction instruction, [NotNullWhen(true)] out ILInstruction? array, [NotNullWhen(true)] out FieldDefinition field) { array = null; field = default; @@ -789,7 +789,7 @@ bool MatchInitializeArrayCall(ILInstruction instruction, out ILInstruction? arra return true; } - bool HandleRuntimeHelpersInitializeArray(Block body, int pos, ILVariable array, IType arrayType, int[] arrayLength, out ILInstruction[]? values, out int foundPos) + bool HandleRuntimeHelpersInitializeArray(Block body, int pos, ILVariable array, IType arrayType, int[] arrayLength, [NotNullWhen(true)] out ILInstruction[]? values, out int foundPos) { if (MatchInitializeArrayCall(body.Instructions[pos], out var arrayInst, out var field) && arrayInst.MatchLdLoc(array)) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs index d084b09f76..4dd4c33996 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs @@ -18,6 +18,7 @@ using System; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; @@ -677,8 +678,8 @@ private static ImplicitTruncationResult CommonImplicitTruncation(ImplicitTruncat /// /// Every IsCompoundStore() call should be followed by an IsMatchingCompoundLoad() call. /// - static bool IsCompoundStore(ILInstruction inst, out IType? storeType, - out ILInstruction? value, ICompilation compilation) + static bool IsCompoundStore(ILInstruction inst, [NotNullWhen(true)] out IType? storeType, + [NotNullWhen(true)] out ILInstruction? value, ICompilation compilation) { value = null; storeType = null; @@ -1025,7 +1026,7 @@ bool TransformPostIncDecOperator(Block block, int i) return true; } - static bool IsSameMember(IMember a, IMember b) + static bool IsSameMember(IMember? a, IMember? b) { if (a == null || b == null) return false; diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs index 0d6edf78dc..34b1294a15 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Metadata; @@ -588,7 +589,7 @@ private void Transform(ILFunction function) } } - internal static bool IsClosure(ILTransformContext context, ILVariable variable, out ITypeDefinition? closureType, out ILInstruction? initializer) + internal static bool IsClosure(ILTransformContext context, ILVariable variable, [NotNullWhen(true)] out ITypeDefinition? closureType, [NotNullWhen(true)] out ILInstruction? initializer) { closureType = null; initializer = null; @@ -610,7 +611,7 @@ internal static bool IsClosure(ILTransformContext context, ILVariable variable, return false; } - static bool IsClosureInit(ILTransformContext context, StLoc inst, out ITypeDefinition? closureType) + static bool IsClosureInit(ILTransformContext context, StLoc inst, [NotNullWhen(true)] out ITypeDefinition? closureType) { if (inst.Value is NewObj newObj) { @@ -840,18 +841,18 @@ protected internal override void VisitLdObj(LdObj inst) EarlyExpressionTransforms.LdObjToLdLoc(inst, context); } - private bool IsDisplayClassLoad(ILInstruction target, out ILVariable variable) + private bool IsDisplayClassLoad(ILInstruction target, [NotNullWhen(true)] out ILVariable? variable) { // We cannot use MatchLdLocRef here because local functions use ref parameters if (!target.MatchLdLoc(out variable) && !target.MatchLdLoca(out variable)) return false; - if (displayClassCopyMap.TryGetValue(variable, out ILVariable other)) + if (displayClassCopyMap.TryGetValue(variable, out ILVariable? other)) variable = other; return true; } private bool IsDisplayClassFieldAccess(ILInstruction inst, - out ILVariable? displayClassVar, out DisplayClass? displayClass, out IField? field) + [NotNullWhen(true)] out ILVariable? displayClassVar, [NotNullWhen(true)] out DisplayClass? displayClass, [NotNullWhen(true)] out IField? field) { displayClass = null; displayClassVar = null; @@ -867,7 +868,7 @@ protected internal override void VisitLdFlda(LdFlda inst) { base.VisitLdFlda(inst); // Get display class info - if (!IsDisplayClassFieldAccess(inst, out _, out DisplayClass displayClass, out IField field)) + if (!IsDisplayClassFieldAccess(inst, out _, out DisplayClass? displayClass, out IField? field)) return; var keyField = (IField)field.MemberDefinition; var v = displayClass.VariablesToDeclare[keyField]; diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs index 690a001504..e054391517 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.CSharp.Resolver; @@ -63,7 +64,7 @@ static bool IsEmptyParameterList(ILInstruction inst) return false; } - bool MatchParameterVariableAssignment(ILInstruction expr, out ILVariable parameterReferenceVar, out IType? type, out string? name) + bool MatchParameterVariableAssignment(ILInstruction expr, [NotNullWhen(true)] out ILVariable? parameterReferenceVar, [NotNullWhen(true)] out IType? type, [NotNullWhen(true)] out string? name) { // stloc(v, call(Expression::Parameter, call(Type::GetTypeFromHandle, ldtoken(...)), ldstr(...))) type = null; @@ -1124,7 +1125,7 @@ ILInstruction BuildInitializer() return (BuildInitializer, arrayType); } - bool MatchNew(CallInstruction invocation, out IMethod? ctor) + bool MatchNew(CallInstruction invocation, [NotNullWhen(true)] out IMethod? ctor) { ctor = null; if (invocation.Method.Name != "New") @@ -1413,7 +1414,7 @@ bool IsExpressionTreeParameter(ILVariable variable) return variable.Type.FullName == "System.Linq.Expressions.ParameterExpression"; } - bool MatchConstantCall(ILInstruction inst, out ILInstruction? value, out IType? type) + bool MatchConstantCall(ILInstruction inst, [NotNullWhen(true)] out ILInstruction? value, [NotNullWhen(true)] out IType? type) { value = null; type = null; @@ -1436,7 +1437,7 @@ bool MatchConstantCall(ILInstruction inst, out ILInstruction? value, out IType? return false; } - internal static bool MatchGetTypeFromHandle(ILInstruction inst, out IType? type) + internal static bool MatchGetTypeFromHandle(ILInstruction inst, [NotNullWhen(true)] out IType? type) { type = null; return inst is CallInstruction getTypeCall @@ -1445,7 +1446,7 @@ internal static bool MatchGetTypeFromHandle(ILInstruction inst, out IType? type) && getTypeCall.Arguments[0].MatchLdTypeToken(out type); } - bool MatchGetMethodFromHandle(ILInstruction inst, out IMember? member) + bool MatchGetMethodFromHandle(ILInstruction inst, [NotNullWhen(true)] out IMember? member) { member = null; //castclass System.Reflection.MethodInfo(call GetMethodFromHandle(ldmembertoken op_Addition)) @@ -1458,7 +1459,7 @@ bool MatchGetMethodFromHandle(ILInstruction inst, out IMember? member) return MatchFromHandleParameterList(call, out member); } - bool MatchGetConstructorFromHandle(ILInstruction inst, out IMember? member) + bool MatchGetConstructorFromHandle(ILInstruction inst, [NotNullWhen(true)] out IMember? member) { member = null; //castclass System.Reflection.ConstructorInfo(call GetMethodFromHandle(ldmembertoken op_Addition)) @@ -1471,7 +1472,7 @@ bool MatchGetConstructorFromHandle(ILInstruction inst, out IMember? member) return MatchFromHandleParameterList(call, out member); } - bool MatchGetFieldFromHandle(ILInstruction inst, out IMember? member) + bool MatchGetFieldFromHandle(ILInstruction inst, [NotNullWhen(true)] out IMember? member) { member = null; if (!(inst is CallInstruction call && call.Method.FullName == "System.Reflection.FieldInfo.GetFieldFromHandle")) @@ -1479,7 +1480,7 @@ bool MatchGetFieldFromHandle(ILInstruction inst, out IMember? member) return MatchFromHandleParameterList(call, out member); } - static bool MatchFromHandleParameterList(CallInstruction call, out IMember? member) + static bool MatchFromHandleParameterList(CallInstruction call, [NotNullWhen(true)] out IMember? member) { member = null; switch (call.Arguments.Count) @@ -1500,7 +1501,7 @@ static bool MatchFromHandleParameterList(CallInstruction call, out IMember? memb return true; } - bool MatchArgumentList(ILInstruction inst, out IList? arguments) + bool MatchArgumentList(ILInstruction inst, [NotNullWhen(true)] out IList? arguments) { arguments = null; if (!(inst is Block block && block.Kind == BlockKind.ArrayInitializer)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs index 304678625f..d7e3497ac5 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TupleTransform.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Text; using ICSharpCode.Decompiler.TypeSystem; @@ -59,7 +60,7 @@ public static bool MatchTupleFieldAccess(LdFlda inst, out IType tupleType, out I /// Matches 'newobj TupleType(...)'. /// Takes care of flattening long tuples. /// - public static bool MatchTupleConstruction(NewObj? newobj, out ILInstruction[]? arguments) + public static bool MatchTupleConstruction(NewObj? newobj, [NotNullWhen(true)] out ILInstruction[]? arguments) { arguments = null; if (newobj == null) diff --git a/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs index 974943d299..86ed3d3010 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; @@ -116,7 +117,7 @@ bool LegacyPattern(Block block, int pos, StatementTransformContext context) return false; } - static bool MatchCondition(ILInstruction condition, out ILVariable? v, out string? name) + static bool MatchCondition(ILInstruction condition, [NotNullWhen(true)] out ILVariable? v, [NotNullWhen(true)] out string? name) { v = null; name = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs index b78e39189a..c6148085b9 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs @@ -16,6 +16,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; @@ -488,7 +489,7 @@ private bool TransformAsyncUsing(Block block, int i) return true; } - bool CheckAsyncResourceType(IType type, out string? disposeMethodFullName) + bool CheckAsyncResourceType(IType type, [NotNullWhen(true)] out string? disposeMethodFullName) { disposeMethodFullName = null; IType t = NullableType.GetUnderlyingType(type); diff --git a/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs b/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs index a7522a0f6f..fa41f50278 100644 --- a/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs +++ b/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs @@ -19,6 +19,7 @@ using System; using System.Buffers.Binary; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -73,7 +74,7 @@ public static string GetFullAssemblyName(this MetadataReader reader) $"PublicKeyToken={publicKey}"; } - public static bool TryGetFullAssemblyName(this MetadataReader reader, out string? assemblyName) + public static bool TryGetFullAssemblyName(this MetadataReader reader, [NotNullWhen(true)] out string? assemblyName) { try { @@ -124,7 +125,7 @@ public static string GetFullAssemblyName(this SRM.AssemblyReference reference, M return builder.ToString(); } - public static bool TryGetFullAssemblyName(this SRM.AssemblyReference reference, MetadataReader reader, out string? assemblyName) + public static bool TryGetFullAssemblyName(this SRM.AssemblyReference reference, MetadataReader reader, [NotNullWhen(true)] out string? assemblyName) { try { diff --git a/ICSharpCode.Decompiler/Metadata/ReferenceLoadInfo.cs b/ICSharpCode.Decompiler/Metadata/ReferenceLoadInfo.cs index 53ef9ea6f9..306a8c31e0 100644 --- a/ICSharpCode.Decompiler/Metadata/ReferenceLoadInfo.cs +++ b/ICSharpCode.Decompiler/Metadata/ReferenceLoadInfo.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace ICSharpCode.Decompiler.Metadata @@ -58,7 +59,7 @@ public void AddMessageOnce(string fullName, MessageKind kind, string message) } } - public bool TryGetInfo(string fullName, out UnresolvedAssemblyNameReference info) + public bool TryGetInfo(string fullName, [NotNullWhen(true)] out UnresolvedAssemblyNameReference? info) { lock (loadedAssemblyReferences) { diff --git a/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs b/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs index 1521753999..40a4f1c8f9 100644 --- a/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs +++ b/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs @@ -34,7 +34,7 @@ public GenericContext(IReadOnlyList? classTypeParameters) this.MethodTypeParameters = null; } - public GenericContext(IReadOnlyList classTypeParameters, IReadOnlyList methodTypeParameters) + public GenericContext(IReadOnlyList? classTypeParameters, IReadOnlyList? methodTypeParameters) { this.ClassTypeParameters = classTypeParameters; this.MethodTypeParameters = methodTypeParameters; diff --git a/ICSharpCode.Decompiler/TypeSystem/TaskType.cs b/ICSharpCode.Decompiler/TypeSystem/TaskType.cs index ee87d33bcd..76db1389ee 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TaskType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TaskType.cs @@ -17,6 +17,7 @@ // DEALINGS IN THE SOFTWARE. using System; +using System.Diagnostics.CodeAnalysis; namespace ICSharpCode.Decompiler.TypeSystem { @@ -59,10 +60,10 @@ public static bool IsTask(IType type) /// /// Gets whether the specified type is a Task-like type. /// - public static bool IsCustomTask(IType type, out IType? builderType) + public static bool IsCustomTask(IType type, [NotNullWhen(true)] out IType? builderType) { builderType = null; - ITypeDefinition def = type.GetDefinition(); + ITypeDefinition? def = type.GetDefinition(); if (def != null) { if (def.TypeParameterCount > 1) diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs index 8b6ff6f033..e5f88adcb1 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs @@ -23,6 +23,8 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes { + using System.Diagnostics.CodeAnalysis; + using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX.Analyzers; @@ -68,7 +70,7 @@ protected override void LoadChildren() } } - bool TryFindBackingField(IEvent analyzedEvent, out IField backingField) + bool TryFindBackingField(IEvent analyzedEvent, [NotNullWhen(true)] out IField? backingField) { backingField = null; foreach (var field in analyzedEvent.DeclaringTypeDefinition.GetFields(options: GetMemberOptions.IgnoreInheritedMembers)) From dc2af218e4e8ab30137a667c1a46b1c9081d1825 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 10:29:12 -0400 Subject: [PATCH 07/15] Focus on CS8600 (not even close to done thee is a ton of these) --- .editorconfig | 1 + ICSharpCode.Decompiler/CSharp/Annotations.cs | 8 +- .../CSharp/CSharpDecompiler.cs | 10 +- ICSharpCode.Decompiler/CSharp/CallBuilder.cs | 2 +- .../CSharp/ExpressionBuilder.cs | 11 +- .../OutputVisitor/CSharpOutputVisitor.cs | 8 +- .../GenericGrammarAmbiguityVisitor.cs | 2 +- .../OutputVisitor/InsertSpecialsDecorator.cs | 6 +- .../ProjectFileWriterSdkStyle.cs | 2 +- .../ProjectDecompiler/TargetFramework.cs | 2 +- .../ProjectDecompiler/TargetServices.cs | 4 +- .../WholeProjectDecompiler.cs | 4 +- .../CSharp/RequiredNamespaceCollector.cs | 2 +- .../CSharp/Resolver/CSharpConversions.cs | 10 +- .../CSharp/Resolver/CSharpResolver.cs | 42 +- .../CSharp/Resolver/MemberLookup.cs | 8 +- .../CSharp/Resolver/OverloadResolution.cs | 2 +- .../CSharp/Resolver/TypeInference.cs | 2 +- .../CSharp/SequencePointBuilder.cs | 2 +- .../CSharp/StatementBuilder.cs | 15 +- .../CSharp/Syntax/AstNode.cs | 2 +- .../CSharp/Syntax/AstNodeCollection.cs | 12 +- .../CSharp/Syntax/DepthFirstAstVisitor.cs | 272 ++++----- .../CSharp/Syntax/IAnnotatable.cs | 22 +- .../CSharp/Syntax/IAstVisitor.cs | 568 +++++++++--------- .../CSharp/Syntax/PatternMatching/INode.cs | 2 +- .../CSharp/Syntax/PatternMatching/Pattern.cs | 10 +- .../CSharp/Syntax/PatternMatching/Repeat.cs | 2 +- .../CSharp/Syntax/Statements/Statement.cs | 6 +- .../CSharp/Syntax/SyntaxExtensions.cs | 2 +- .../CSharp/Syntax/TypeMembers/Accessor.cs | 2 +- .../Syntax/TypeMembers/EntityDeclaration.cs | 2 +- .../Syntax/TypeMembers/MethodDeclaration.cs | 2 +- .../CSharp/Syntax/TypeSystemAstBuilder.cs | 16 +- .../CSharp/Transforms/AddCheckedBlocks.cs | 6 +- .../AddXmlDocumentationTransform.cs | 4 +- .../Transforms/CombineQueryExpressions.cs | 4 +- .../CSharp/Transforms/DeclareVariables.cs | 6 +- .../CSharp/Transforms/FixNameCollisions.cs | 4 +- .../Transforms/IntroduceQueryExpressions.cs | 24 +- .../Transforms/PatternStatementTransform.cs | 8 +- ...ransformFieldAndConstructorInitializers.cs | 4 +- .../CSharp/TranslatedExpression.cs | 2 +- .../CSharp/TypeSystem/ResolvedUsingScope.cs | 2 +- ICSharpCode.Decompiler/DecompilerException.cs | 10 +- .../Disassembler/ReflectionDisassembler.cs | 8 +- .../GetPotentiallyNestedClassTypeReference.cs | 2 +- .../Documentation/IdStringProvider.cs | 2 +- .../Documentation/XmlDocLoader.cs | 2 +- .../IL/ControlFlow/AsyncAwaitDecompiler.cs | 4 +- .../IL/ControlFlow/AwaitInCatchTransform.cs | 12 +- .../IL/ControlFlow/AwaitInFinallyTransform.cs | 4 +- .../IL/ControlFlow/ConditionDetection.cs | 8 +- .../ControlFlow/ControlFlowSimplification.cs | 8 +- .../IL/ControlFlow/DetectPinnedRegions.cs | 2 +- .../CachedDelegateInitialization.cs | 16 +- .../IL/Transforms/CopyPropagation.cs | 2 +- .../Transforms/EarlyExpressionTransforms.cs | 3 +- .../IL/Transforms/IndexRangeTransform.cs | 4 +- .../IL/Transforms/SwitchOnStringTransform.cs | 67 ++- .../Semantics/ConstantResolveResult.cs | 6 +- .../TypeSystem/ReflectionHelper.cs | 2 +- ICSharpCode.Decompiler/TypeSystem/TaskType.cs | 4 +- .../BamlResourceNodeFactory.cs | 2 +- ILSpy/Languages/ILAstLanguage.cs | 4 +- ILSpy/MainWindow.xaml.cs | 14 +- ILSpy/TextView/DocumentationUIBuilder.cs | 2 +- .../ResourceNodes/CursorResourceEntryNode.cs | 4 +- .../ResourceNodes/IResourceNodeFactory.cs | 2 +- .../ResourceNodes/IconResourceEntryNode.cs | 4 +- .../ImageListResourceEntryNode.cs | 4 +- .../ResourceNodes/ImageResourceEntryNode.cs | 4 +- .../ResourceNodes/ResourceEntryNode.cs | 11 +- .../ResourceNodes/ResourcesFileTreeNode.cs | 4 +- .../ResourceNodes/XamlResourceNode.cs | 6 +- .../ResourceNodes/XmlResourceNode.cs | 8 +- ILSpy/Views/DebugSteps.xaml.cs | 4 +- 77 files changed, 686 insertions(+), 680 deletions(-) diff --git a/.editorconfig b/.editorconfig index 660c2996b3..7f28f99087 100644 --- a/.editorconfig +++ b/.editorconfig @@ -154,6 +154,7 @@ dotnet_diagnostic.IDE2003.severity = silent #cleared null error types dotnet_diagnostic.CS8612.severity = error dotnet_diagnostic.CS8714.severity = error +dotnet_diagnostic.CS8762.severity = error dotnet_diagnostic.CS8765.severity = error dotnet_diagnostic.CS8766.severity = error dotnet_diagnostic.CS8767.severity = error diff --git a/ICSharpCode.Decompiler/CSharp/Annotations.cs b/ICSharpCode.Decompiler/CSharp/Annotations.cs index 30f221db17..9359634547 100644 --- a/ICSharpCode.Decompiler/CSharp/Annotations.cs +++ b/ICSharpCode.Decompiler/CSharp/Annotations.cs @@ -134,7 +134,7 @@ internal static TranslatedExpression WithRR(this ExpressionWithILInstruction exp /// Retrieves the associated with this AstNode, or null if no symbol /// is associated with the node. /// - public static ISymbol GetSymbol(this AstNode node) + public static ISymbol? GetSymbol(this AstNode node) { var rr = node.Annotation(); if (rr is MethodGroupResolveResult) @@ -175,7 +175,7 @@ public static ResolveResult GetResolveResult(this AstNode node) /// Retrieves the associated with this , /// or null if no variable is associated with this identifier. /// - public static ILVariable GetILVariable(this IdentifierExpression expr) + public static ILVariable? GetILVariable(this IdentifierExpression expr) { if (expr.Annotation() is ILVariableResolveResult rr) return rr.Variable; @@ -187,7 +187,7 @@ public static ILVariable GetILVariable(this IdentifierExpression expr) /// Retrieves the associated with this , /// or null if no variable is associated with this initializer. /// - public static ILVariable GetILVariable(this VariableInitializer vi) + public static ILVariable? GetILVariable(this VariableInitializer vi) { if (vi.Annotation() is ILVariableResolveResult rr) return rr.Variable; @@ -199,7 +199,7 @@ public static ILVariable GetILVariable(this VariableInitializer vi) /// Retrieves the associated with this , /// or null if no variable is associated with this foreach statement. /// - public static ILVariable GetILVariable(this ForeachStatement loop) + public static ILVariable? GetILVariable(this ForeachStatement loop) { if (loop.Annotation() is ILVariableResolveResult rr) return rr.Variable; diff --git a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs index 9939ce887e..d2be2971e6 100644 --- a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs @@ -1213,7 +1213,7 @@ Expression ForwardParameter(ParameterDeclaration p) /// The node of the member which new modifier state should be determined. void SetNewModifier(EntityDeclaration member) { - var entity = (IEntity)member.GetSymbol(); + var entity = member.GetSymbol() as IEntity; var lookup = new MemberLookup(entity.DeclaringTypeDefinition, entity.ParentModule); var baseTypes = entity.DeclaringType.GetNonInterfaceBaseTypes().Where(t => entity.DeclaringType != t).ToList(); @@ -1325,7 +1325,7 @@ EntityDeclaration DoDecompile(ITypeDefinition typeDef, DecompileRun decompileRun foreach (var p in recordDecompiler.PrimaryConstructor.Parameters) { ParameterDeclaration pd = typeSystemAstBuilder.ConvertParameter(p); - (IProperty prop, IField field) = recordDecompiler.GetPropertyInfoByPrimaryConstructorParameter(p); + (IProperty? prop, IField field) = recordDecompiler.GetPropertyInfoByPrimaryConstructorParameter(p); if (prop != null) { @@ -1567,7 +1567,7 @@ EnumValueDisplayMode DetectBestEnumValueDisplayMode(ITypeDefinition typeDef, Met { if (MemberIsHidden(module, field.MetadataToken, settings)) continue; - object constantValue = field.GetConstantValue(); + object? constantValue = field.GetConstantValue(); if (constantValue == null) continue; long currentValue = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, constantValue, false); @@ -1958,7 +1958,7 @@ EntityDeclaration DoDecompile(IField field, DecompileRun decompileRun, ITypeReso if (decompilationContext.CurrentTypeDefinition.Kind == TypeKind.Enum && field.IsConst) { var enumDec = new EnumMemberDeclaration { Name = field.Name }; - object constantValue = field.GetConstantValue(); + object? constantValue = field.GetConstantValue(); if (constantValue != null) { enumDec.Initializer = typeSystemAstBuilder.ConvertConstantValue(decompilationContext.CurrentTypeDefinition.EnumUnderlyingType, constantValue); @@ -2022,7 +2022,7 @@ internal static bool IsFixedField(IField field, out IType? type, out int element { type = null; elementCount = 0; - IAttribute attr = field.GetAttribute(KnownAttribute.FixedBuffer); + IAttribute? attr = field.GetAttribute(KnownAttribute.FixedBuffer); if (attr != null && attr.FixedArguments.Length == 2) { if (attr.FixedArguments[0].Value is IType trr && attr.FixedArguments[1].Value is int length) diff --git a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs index 6a7cf06bc4..5e2d7c6ee2 100644 --- a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs @@ -1574,7 +1574,7 @@ ExpressionWithResolveResult HandleAccessorCall(ExpectedTargetDetails expectedTar arguments.Remove(value); } - IMember foundMember; + IMember? foundMember; while (!IsUnambiguousAccess(expectedTargetDetails, targetResolveResult, method, arguments, argumentNames, out foundMember)) { if (!argumentsCasted) diff --git a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs index e302399ae6..b85f053d84 100644 --- a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs @@ -2535,7 +2535,7 @@ IType GetTaskType(IType resultType) if (resultType.Kind == TypeKind.Void) return compilation.FindType(KnownTypeCode.Task); - ITypeDefinition def = compilation.FindType(KnownTypeCode.TaskOfT).GetDefinition(); + ITypeDefinition? def = compilation.FindType(KnownTypeCode.TaskOfT).GetDefinition(); if (def != null) return new ParameterizedType(def, new[] { resultType }); else @@ -2988,7 +2988,7 @@ protected internal override TranslatedExpression VisitLdLen(LdLen inst, Translat memberName = "LongLength"; code = KnownTypeCode.Int64; } - IProperty member = arrayType.GetProperties(p => p.Name == memberName).FirstOrDefault(); + IProperty? member = arrayType.GetProperties(p => p.Name == memberName).FirstOrDefault(); ResolveResult rr = member == null ? new ResolveResult(compilation.FindType(code)) : new MemberResolveResult(arrayExpr.ResolveResult, member); @@ -3917,7 +3917,8 @@ protected internal override TranslatedExpression VisitSwitchInstruction(SwitchIn { TranslatedExpression value; IType type; - if (inst.Value is StringToInt strToInt) + var strToInt = inst.Value as StringToInt; + if (strToInt != null) { value = Translate(strToInt.Argument) .ConvertTo( @@ -4534,7 +4535,7 @@ TupleExpression ConstructTuple(MatchInstruction matchInstruction) { if (subPattern.HasDesignator) { - if (!conversionMapping.TryGetValue(subPattern.Variable, out ILVariable value)) + if (!conversionMapping.TryGetValue(subPattern.Variable, out ILVariable? value)) { value = subPattern.Variable; } @@ -4639,7 +4640,7 @@ ExpressionWithILInstruction TranslatePattern(ILInstruction pattern, IType leftHa Debug.Fail("Invalid sub pattern"); continue; } - IMember member; + IMember? member; if (testedOperand is CallInstruction call) { member = call.Method.AccessorOwner; diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs index 2ed3cec002..be451afa2c 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs @@ -92,7 +92,7 @@ protected virtual void EndNode(AstNode node) /// /// The next node after the comma. /// When set prevents printing a space after comma. - protected virtual void Comma(AstNode nextNode, bool noSpaceAfterComma = false) + protected virtual void Comma(AstNode? nextNode, bool noSpaceAfterComma = false) { Space(policy.SpaceBeforeBracketComma); // TODO: Comma policy has changed. @@ -105,7 +105,7 @@ protected virtual void Comma(AstNode nextNode, bool noSpaceAfterComma = false) /// /// Writes an optional comma, e.g. at the end of an enum declaration or in an array initializer /// - protected virtual void OptionalComma(AstNode pos) + protected virtual void OptionalComma(AstNode? pos) { // Look if there's a comma after the current node, and insert it if it exists. while (pos != null && pos.NodeType == NodeType.Whitespace) @@ -121,7 +121,7 @@ protected virtual void OptionalComma(AstNode pos) /// /// Writes an optional semicolon, e.g. at the end of a type or namespace declaration. /// - protected virtual void OptionalSemicolon(AstNode pos) + protected virtual void OptionalSemicolon(AstNode? pos) { // Look if there's a semicolon after the current node, and insert it if it exists. while (pos != null && pos.NodeType == NodeType.Whitespace) @@ -1947,7 +1947,7 @@ public virtual void VisitLabelStatement(LabelStatement labelStatement) WriteIdentifier(labelStatement.GetChildByRole(Roles.Identifier)); WriteToken(Roles.Colon); bool foundLabelledStatement = false; - for (AstNode tmp = labelStatement.NextSibling; tmp != null; tmp = tmp.NextSibling) + for (AstNode? tmp = labelStatement.NextSibling; tmp != null; tmp = tmp.NextSibling) { if (tmp.Role == labelStatement.Role) { diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs index e7f372f96d..b56c4f6deb 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs @@ -53,7 +53,7 @@ public static bool CausesAmbiguityWithGenerics(BinaryOperatorExpression binaryOp var v = new GenericGrammarAmbiguityVisitor(); v.genericNestingLevel = 1; - for (AstNode node = binaryOperatorExpression.Right; node != null; node = node.GetNextNode()) + for (AstNode? node = binaryOperatorExpression.Right; node != null; node = node.GetNextNode()) { if (node.AcceptVisitor(v)) return v.ambiguityFound; diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs index 61901cc9c6..b4d0051434 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs @@ -84,7 +84,7 @@ public override void NewLine() /// void WriteSpecials(AstNode start, AstNode end) { - for (AstNode pos = start; pos != end; pos = pos.NextSibling) + for (AstNode? pos = start; pos != end; pos = pos.NextSibling) { if (pos.Role == Roles.Comment) { @@ -125,7 +125,7 @@ void WriteSpecialsUpToRole(Role role, AstNode nextNode) return; } // Look for the role between the current position and the nextNode. - for (AstNode pos = positionStack.Peek(); pos != null && pos != nextNode; pos = pos.NextSibling) + for (AstNode? pos = positionStack.Peek(); pos != null && pos != nextNode; pos = pos.NextSibling) { if (pos.Role == role) { @@ -149,7 +149,7 @@ void WriteSpecialsUpToNode(AstNode node) { return; } - for (AstNode pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) + for (AstNode? pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) { if (pos == node) { diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs index ee0029dc94..fc169285e3 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs @@ -272,7 +272,7 @@ static void WriteReferences(XmlTextWriter xml, MetadataFile module, IProjectInfo foreach (var reference in module.AssemblyReferences.Where(r => !ImplicitReferences.Contains(r.Name))) { - if (isNetCoreApp && project.AssemblyReferenceClassifier.IsSharedAssembly(reference, out string runtimePack) && targetPacks.Contains(runtimePack)) + if (isNetCoreApp && project.AssemblyReferenceClassifier.IsSharedAssembly(reference, out string? runtimePack) && targetPacks.Contains(runtimePack)) { continue; } diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs index 66279bbd34..793b70e7a8 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs @@ -52,7 +52,7 @@ public TargetFramework(string identifier, int version, string profile) /// /// Gets the target framework identifier. Can be null if not defined. /// - public string Identifier { get; } + public string? Identifier { get; } /// /// Gets the target framework moniker. Can be null if not supported. diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs index e2458b8021..b36a043adb 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs @@ -74,7 +74,7 @@ public static TargetFramework DetectTargetFramework(MetadataFile module) { string[] frameworkParts = targetFramework.Split(','); targetFrameworkIdentifier = frameworkParts.FirstOrDefault(a => !a.StartsWith(VersionToken, StringComparison.OrdinalIgnoreCase) && !a.StartsWith(ProfileToken, StringComparison.OrdinalIgnoreCase)); - string frameworkVersion = frameworkParts.FirstOrDefault(a => a.StartsWith(VersionToken, StringComparison.OrdinalIgnoreCase)); + string? frameworkVersion = frameworkParts.FirstOrDefault(a => a.StartsWith(VersionToken, StringComparison.OrdinalIgnoreCase)); if (frameworkVersion != null) { @@ -83,7 +83,7 @@ public static TargetFramework DetectTargetFramework(MetadataFile module) versionNumber *= 10; } - string frameworkProfile = frameworkParts.FirstOrDefault(a => a.StartsWith(ProfileToken, StringComparison.OrdinalIgnoreCase)); + string? frameworkProfile = frameworkParts.FirstOrDefault(a => a.StartsWith(ProfileToken, StringComparison.OrdinalIgnoreCase)); if (frameworkProfile != null) targetFrameworkProfile = frameworkProfile.Substring(ProfileToken.Length); } diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs index a61a71459e..a55980cf5c 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs @@ -325,7 +325,7 @@ protected virtual IEnumerable WriteResourceFilesInProject(Metad { foreach (var r in module.Resources.Where(r => r.ResourceType == ResourceType.Embedded)) { - Stream stream = r.TryOpenStream(); + Stream? stream = r.TryOpenStream(); stream.Position = 0; if (r.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) @@ -341,7 +341,7 @@ protected virtual IEnumerable WriteResourceFilesInProject(Metad { string fileName = SanitizeFileName(name) .Replace('/', Path.DirectorySeparatorChar); - string dirName = Path.GetDirectoryName(fileName); + string? dirName = Path.GetDirectoryName(fileName); if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName)) { Directory.CreateDirectory(Path.Combine(TargetDirectory, dirName)); diff --git a/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs b/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs index d964179ba2..e181d98050 100644 --- a/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs +++ b/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs @@ -37,7 +37,7 @@ public static void CollectNamespaces(MetadataModule module, HashSet name var collector = new RequiredNamespaceCollector(namespaces); foreach (var type in module.TypeDefinitions) { - collector.CollectNamespaces(type, module, (CodeMappingInfo)null); + collector.CollectNamespaces(type, module, (CodeMappingInfo?)null); } collector.HandleAttributes(module.GetAssemblyAttributes()); collector.HandleAttributes(module.GetModuleAttributes()); diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs index 1d96a9bab7..f3a37e8411 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs @@ -56,7 +56,7 @@ public static CSharpConversions Get(ICompilation compilation) if (compilation == null) throw new ArgumentNullException(nameof(compilation)); CacheManager cache = compilation.CacheManager; - CSharpConversions operators = (CSharpConversions)cache.GetShared(typeof(CSharpConversions)); + CSharpConversions? operators = (CSharpConversions)cache.GetShared(typeof(CSharpConversions)); if (operators == null) { operators = (CSharpConversions)cache.GetOrAddShared(typeof(CSharpConversions), new CSharpConversions(compilation)); @@ -182,7 +182,7 @@ public Conversion ImplicitConversion(IType fromType, IType toType) throw new ArgumentNullException(nameof(toType)); TypePair pair = new TypePair(fromType, toType); - if (implicitConversionCache.TryGetValue(pair, out Conversion c)) + if (implicitConversionCache.TryGetValue(pair, out Conversion? c)) return c; c = ImplicitConversion(fromType, toType, allowUserDefined: true, allowTuple: true); @@ -600,7 +600,7 @@ bool IsSubtypeOf(IType s, IType t, int subtypeCheckNestingDepth) bool IdentityOrVarianceConversion(IType s, IType t, int subtypeCheckNestingDepth) { - ITypeDefinition def = s.GetDefinition(); + ITypeDefinition? def = s.GetDefinition(); if (def != null) { if (!def.Equals(t.GetDefinition())) @@ -697,7 +697,7 @@ bool ExplicitReferenceConversion(IType fromType, IType toType) } else if (fromType.Kind == TypeKind.Delegate && toType.Kind == TypeKind.Delegate) { - ITypeDefinition def = fromType.GetDefinition(); + ITypeDefinition? def = fromType.GetDefinition(); if (def == null || !def.Equals(toType.GetDefinition())) return false; ParameterizedType? ps = fromType as ParameterizedType; @@ -811,7 +811,7 @@ bool ImplicitConstantExpressionConversion(ResolveResult rr, IType toType) } else if (fromTypeCode == TypeCode.Int32) { - object cv = rr.ConstantValue; + object? cv = rr.ConstantValue; if (cv == null) return false; int val = (int)cv; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs index f78997d14a..b4ed267ba2 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs @@ -506,7 +506,7 @@ public ResolveResult ResolveUnaryOperator(UnaryOperatorType op, ResolveResult ex } else if (expression.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) { - object val; + object? val; try { val = m.Invoke(this, expression.ConstantValue); @@ -923,7 +923,7 @@ public ResolveResult ResolveBinaryOperator(BinaryOperatorType op, ResolveResult } else if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) { - object val; + object? val; try { val = m.Invoke(this, lhs.ConstantValue, rhs.ConstantValue); @@ -982,7 +982,7 @@ CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, #region Enum helper methods IType GetEnumUnderlyingType(IType enumType) { - ITypeDefinition def = enumType.GetDefinition(); + ITypeDefinition? def = enumType.GetDefinition(); return def != null ? def.EnumUnderlyingType : SpecialType.UnknownType; } @@ -1609,12 +1609,12 @@ public bool IsVariableReferenceWithSameType(ResolveResult rr, string identifier, return trr != null && trr.Type.Equals(rr.Type); } - ResolveResult LookInCurrentType(string identifier, IReadOnlyList typeArguments, NameLookupMode lookupMode, bool parameterizeResultType) + ResolveResult? LookInCurrentType(string identifier, IReadOnlyList typeArguments, NameLookupMode lookupMode, bool parameterizeResultType) { int k = typeArguments.Count; MemberLookup lookup = CreateMemberLookup(lookupMode); // look in current type definitions - for (ITypeDefinition t = this.CurrentTypeDefinition; t != null; t = t.DeclaringTypeDefinition) + for (ITypeDefinition? t = this.CurrentTypeDefinition; t != null; t = t.DeclaringTypeDefinition) { if (k == 0) { @@ -1651,7 +1651,7 @@ ResolveResult LookInCurrentType(string identifier, IReadOnlyList typeArgu return null; } - ResolveResult LookInCurrentUsingScope(string identifier, IReadOnlyList typeArguments, bool isInUsingDeclaration, bool parameterizeResultType) + ResolveResult? LookInCurrentUsingScope(string identifier, IReadOnlyList typeArguments, bool isInUsingDeclaration, bool parameterizeResultType) { // look in current namespace definitions ResolvedUsingScope currentUsingScope = this.CurrentUsingScope; @@ -1684,7 +1684,7 @@ ResolveResult LookInCurrentUsingScope(string identifier, IReadOnlyList ty IType? firstResult = null; foreach (var importedNamespace in u.Usings) { - ITypeDefinition def = importedNamespace.GetTypeDefinition(identifier, typeArguments.Count); + ITypeDefinition? def = importedNamespace.GetTypeDefinition(identifier, typeArguments.Count); if (def != null) { IType resultType; @@ -1712,7 +1712,7 @@ ResolveResult LookInCurrentUsingScope(string identifier, IReadOnlyList ty return null; } - ResolveResult LookInUsingScopeNamespace(ResolvedUsingScope usingScope, INamespace n, string identifier, IReadOnlyList typeArguments, bool parameterizeResultType) + ResolveResult? LookInUsingScopeNamespace(ResolvedUsingScope usingScope, INamespace n, string identifier, IReadOnlyList typeArguments, bool parameterizeResultType) { if (n == null) return null; @@ -1720,7 +1720,7 @@ ResolveResult LookInUsingScopeNamespace(ResolvedUsingScope usingScope, INamespac int k = typeArguments.Count; if (k == 0) { - INamespace childNamespace = n.GetChildNamespace(identifier); + INamespace? childNamespace = n.GetChildNamespace(identifier); if (childNamespace != null) { if (usingScope != null && usingScope.HasAlias(identifier)) @@ -1729,7 +1729,7 @@ ResolveResult LookInUsingScopeNamespace(ResolvedUsingScope usingScope, INamespac } } // then look for a type - ITypeDefinition def = n.GetTypeDefinition(identifier, k); + ITypeDefinition? def = n.GetTypeDefinition(identifier, k); if (def != null && TopLevelTypeDefinitionIsAccessible(def)) { IType result = def; @@ -1781,7 +1781,7 @@ public ResolveResult ResolveAlias(string identifier) ResolveResult ResolveExternAlias(string alias) { - INamespace ns = compilation.GetNamespaceForExternAlias(alias); + INamespace? ns = compilation.GetNamespaceForExternAlias(alias); if (ns != null) return new NamespaceResolveResult(ns); else @@ -1854,11 +1854,11 @@ ResolveResult ResolveMemberAccessOnNamespace(NamespaceResolveResult nrr, string { if (typeArguments.Count == 0) { - INamespace childNamespace = nrr.Namespace.GetChildNamespace(identifier); + INamespace? childNamespace = nrr.Namespace.GetChildNamespace(identifier); if (childNamespace != null) return new NamespaceResolveResult(childNamespace); } - ITypeDefinition def = nrr.Namespace.GetTypeDefinition(identifier, typeArguments.Count); + ITypeDefinition? def = nrr.Namespace.GetTypeDefinition(identifier, typeArguments.Count); if (def != null) { if (parameterizeResultType && typeArguments.Count > 0) @@ -1985,13 +1985,13 @@ void CheckForEnumerableInterface(ResolveResult expression, out IType collectionT elementType = expression.Type.GetElementTypeFromIEnumerable(compilation, false, out bool? isGeneric); if (isGeneric == true) { - ITypeDefinition enumerableOfT = compilation.FindType(KnownTypeCode.IEnumerableOfT).GetDefinition(); + ITypeDefinition? enumerableOfT = compilation.FindType(KnownTypeCode.IEnumerableOfT).GetDefinition(); if (enumerableOfT != null) collectionType = new ParameterizedType(enumerableOfT, new[] { elementType }); else collectionType = SpecialType.UnknownType; - ITypeDefinition enumeratorOfT = compilation.FindType(KnownTypeCode.IEnumeratorOfT).GetDefinition(); + ITypeDefinition? enumeratorOfT = compilation.FindType(KnownTypeCode.IEnumeratorOfT).GetDefinition(); if (enumeratorOfT != null) enumeratorType = new ParameterizedType(enumeratorOfT, new[] { elementType }); else @@ -2060,7 +2060,7 @@ public List> GetExtensionMethods(string? name = null, IReadOnlyLis /// new List { all extensions from SomeExtensions } /// } /// - public List> GetExtensionMethods(IType targetType, string? name = null, IReadOnlyList? typeArguments = null, bool substituteInferredTypes = false) + public List> GetExtensionMethods(IType? targetType, string? name = null, IReadOnlyList? typeArguments = null, bool substituteInferredTypes = false) { var lookup = CreateMemberLookup(); List> extensionMethodGroups = new List>(); @@ -2073,7 +2073,7 @@ public List> GetExtensionMethods(IType targetType, string? name = continue; if (!lookup.IsAccessible(method, false)) continue; - IType[] inferredTypes; + IType[]? inferredTypes; if (typeArguments != null && typeArguments.Count > 0) { if (method.TypeParameters.Count != typeArguments.Count) @@ -2118,7 +2118,7 @@ public List> GetExtensionMethods(IType targetType, string? name = /// If an array is returned, any slot with an uninferred type argument will be set to the method's /// corresponding type parameter. /// - public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes) + public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[]? outInferredTypes) { if (targetType == null) throw new ArgumentNullException(nameof(targetType)); @@ -2128,7 +2128,7 @@ public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, b return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes); } - static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType targetType, IMethod method, bool useTypeInference, out IType[]? outInferredTypes) + static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType? targetType, IMethod method, bool useTypeInference, out IType[]? outInferredTypes) { outInferredTypes = null; if (targetType == null) @@ -2814,9 +2814,9 @@ public ResolveResult ResolveDefaultValue(IType type) return new ConstantResolveResult(type, GetDefaultValue(type)); } - public static object GetDefaultValue(IType type) + public static object? GetDefaultValue(IType type) { - ITypeDefinition typeDef = type.GetDefinition(); + ITypeDefinition? typeDef = type.GetDefinition(); if (typeDef == null) return null; if (typeDef.Kind == TypeKind.Enum) diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs index 994aba2bf7..d08f85522b 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs @@ -79,7 +79,7 @@ public bool IsProtectedAccessAllowed(IType targetType) { if (targetType.Kind == TypeKind.TypeParameter) targetType = ((ITypeParameter)targetType).EffectiveBaseClass; - ITypeDefinition typeDef = targetType.GetDefinition(); + ITypeDefinition? typeDef = targetType.GetDefinition(); if (typeDef == null) return false; for (ITypeDefinition c = currentTypeDefinition; c != null; c = c.DeclaringTypeDefinition) @@ -195,7 +195,7 @@ public IEnumerable GetAccessibleMembers(ResolveResult targetResolveResu foreach (var entityGroup in entities.GroupBy(e => e.Name)) { - List lookupGroups = new List(); + List? lookupGroups = new List(); if (!lookupGroupDict.TryGetValue(entityGroup.Key, out lookupGroups)) lookupGroupDict.Add(entityGroup.Key, lookupGroups = new List()); @@ -243,7 +243,7 @@ public IEnumerable GetAccessibleMembers(ResolveResult targetResolveResu { foreach (IType type in lookupGroup.NestedTypes) { - ITypeDefinition typeDef = type.GetDefinition(); + ITypeDefinition? typeDef = type.GetDefinition(); if (typeDef != null) yield return typeDef; } @@ -691,7 +691,7 @@ static bool IsInterfaceOrSystemObject(IType type) // return true if type is an interface or System.Object if (type.Kind == TypeKind.Interface) return true; - ITypeDefinition d = type.GetDefinition(); + ITypeDefinition? d = type.GetDefinition(); return d != null && d.KnownTypeCode == KnownTypeCode.Object; } #endregion diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs index 3eaf041bee..690033469e 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs @@ -582,7 +582,7 @@ internal static bool ValidateConstraints(ITypeParameter typeParameter, IType typ } if (typeParameter.HasDefaultConstructorConstraint) { - ITypeDefinition def = typeArgument.GetDefinition(); + ITypeDefinition? def = typeArgument.GetDefinition(); if (def != null && def.IsAbstract) return false; var ctors = typeArgument.GetConstructors( diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs index 846922884d..280c968f65 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs @@ -1109,7 +1109,7 @@ IReadOnlyList FindTypesInBounds(IReadOnlyList lowerBounds, IReadOn // Now filter out candidates that violate the upper bounds: foreach (IType ub in upperBounds) { - ITypeDefinition ubDef = ub.GetDefinition(); + ITypeDefinition? ubDef = ub.GetDefinition(); if (ubDef != null) { candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef)); diff --git a/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs b/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs index 6bf75e3509..61186bb496 100644 --- a/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs @@ -547,7 +547,7 @@ internal static bool HasUsableILRange(ILInstruction inst) } - List sequencePointCandidates = function.SequencePointCandidates; + List? sequencePointCandidates = function.SequencePointCandidates; int currSPCandidateIndex = 0; for (int i = 0; i < newList.Count - 1; i++) diff --git a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs index e75785415c..37db21cda1 100644 --- a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs @@ -213,7 +213,8 @@ SwitchStatement TranslateSwitch(BlockContainer switchContainer, SwitchInstructio TranslatedExpression value; IType type; - if (inst.Value is StringToInt strToInt) + var strToInt = inst.Value as StringToInt; + if (strToInt != null) { value = exprBuilder.Translate(strToInt.Argument) .ConvertTo( @@ -328,7 +329,7 @@ SwitchStatement TranslateSwitch(BlockContainer switchContainer, SwitchInstructio } Debug.Assert(block.FinalInstruction.OpCode == OpCode.Nop); } - if (endContainerLabels.TryGetValue(switchContainer, out string label)) + if (endContainerLabels.TryGetValue(switchContainer, out string? label)) { lastSectionStatements.Add(new LabelStatement { Label = label }); lastSectionStatements.Add(new BreakStatement()); @@ -411,7 +412,7 @@ protected internal override TranslatedStatement VisitLeave(Leave inst) else return new ReturnStatement().WithILInstruction(inst); } - if (!endContainerLabels.TryGetValue(inst.TargetContainer, out string label)) + if (!endContainerLabels.TryGetValue(inst.TargetContainer, out string? label)) { label = "end_" + inst.TargetLabel; if (!duplicateLabels.TryGetValue(label, out int count)) @@ -1261,8 +1262,8 @@ protected internal override TranslatedStatement VisitBlockContainer(BlockContain Statement ConvertLoop(BlockContainer container) { - ILInstruction condition; - Block loopBody; + ILInstruction? condition; + Block? loopBody; BlockStatement blockStatement; continueCount = 0; breakTarget = container; @@ -1480,7 +1481,7 @@ BlockStatement ConvertBlockContainer(BlockStatement blockStatement, BlockContain blockStatement.Add(Convert(block.FinalInstruction)); } } - if (endContainerLabels.TryGetValue(container, out string label)) + if (endContainerLabels.TryGetValue(container, out string? label)) { if (isLoop && !(blockStatement.LastOrDefault() is ContinueStatement)) { @@ -1500,7 +1501,7 @@ BlockStatement ConvertBlockContainer(BlockStatement blockStatement, BlockContain string EnsureUniqueLabel(Block block) { - if (labels.TryGetValue(block, out string label)) + if (labels.TryGetValue(block, out string? label)) return label; if (!duplicateLabels.TryGetValue(block.Label, out int count)) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs index 73b76dc1f6..02383e97ca 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs @@ -202,7 +202,7 @@ public AstNode? Parent { get { return parent; } } - public Role Role { + public Role? Role { get { return Role.GetByIndex(flags & roleIndexMask); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs index d63e778847..bccffa798f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs @@ -49,7 +49,7 @@ public int Count { get { int count = 0; uint roleIndex = role.Index; - for (AstNode cur = node.FirstChild; cur != null; cur = cur.NextSibling) + for (AstNode? cur = node.FirstChild; cur != null; cur = cur.NextSibling) { if (cur.RoleIndex == roleIndex) count++; @@ -177,8 +177,8 @@ bool ICollection.IsReadOnly { public IEnumerator GetEnumerator() { uint roleIndex = role.Index; - AstNode next; - for (AstNode cur = node.FirstChild; cur != null; cur = next) + AstNode? next; + for (AstNode? cur = node.FirstChild; cur != null; cur = next) { Debug.Assert(cur.Parent == node); // Remember next before yielding cur. @@ -214,7 +214,7 @@ internal bool DoMatch(AstNodeCollection other, Match match) return Pattern.DoMatchCollection(role, node.FirstChild, other.node.FirstChild, match); } - public void InsertAfter(T existingItem, T newItem) + public void InsertAfter(T? existingItem, T newItem) { node.InsertChildAfter(existingItem, newItem, role); } @@ -230,8 +230,8 @@ public void InsertBefore(T existingItem, T newItem) public void AcceptVisitor(IAstVisitor visitor) { uint roleIndex = role.Index; - AstNode next; - for (AstNode cur = node.FirstChild; cur != null; cur = next) + AstNode? next; + for (AstNode? cur = node.FirstChild; cur != null; cur = next) { Debug.Assert(cur.Parent == node); // Remember next before yielding cur. diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs index 2016b429c1..7dc80d576c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs @@ -34,7 +34,7 @@ public abstract class DepthFirstAstVisitor : IAstVisitor { protected virtual void VisitChildren(AstNode node) { - AstNode next; + AstNode? next; for (var child = node.FirstChild; child != null; child = next) { // Store next to allow the loop to continue @@ -715,7 +715,7 @@ public abstract class DepthFirstAstVisitor : IAstVisitor { protected virtual T VisitChildren(AstNode node) { - AstNode next; + AstNode? next; for (var child = node.FirstChild; child != null; child = next) { // Store next to allow the loop to continue @@ -1396,9 +1396,9 @@ public virtual T VisitWithInitializerExpression(WithInitializerExpression withIn /// public abstract class DepthFirstAstVisitor : IAstVisitor { - protected virtual S VisitChildren(AstNode node, T data) + protected virtual S? VisitChildren(AstNode node, T data) { - AstNode next; + AstNode? next; for (var child = node.FirstChild; child != null; child = next) { // Store next to allow the loop to continue @@ -1409,7 +1409,7 @@ protected virtual S VisitChildren(AstNode node, T data) return default(S); } - public virtual S VisitNullNode(AstNode nullNode, T data) + public virtual S? VisitNullNode(AstNode nullNode, T data) { // Should we call VisitChildren here? // We usually want to ignore null nodes. @@ -1418,657 +1418,657 @@ public virtual S VisitNullNode(AstNode nullNode, T data) return default(S); } - public virtual S VisitSyntaxTree(SyntaxTree unit, T data) + public virtual S? VisitSyntaxTree(SyntaxTree unit, T data) { return VisitChildren(unit, data); } - public virtual S VisitComment(Comment comment, T data) + public virtual S? VisitComment(Comment comment, T data) { return VisitChildren(comment, data); } - public virtual S VisitDocumentationReference(DocumentationReference documentationReference, T data) + public virtual S? VisitDocumentationReference(DocumentationReference documentationReference, T data) { return VisitChildren(documentationReference, data); } - public virtual S VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective, T data) + public virtual S? VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective, T data) { return VisitChildren(preProcessorDirective, data); } - public virtual S VisitIdentifier(Identifier identifier, T data) + public virtual S? VisitIdentifier(Identifier identifier, T data) { return VisitChildren(identifier, data); } - public virtual S VisitCSharpTokenNode(CSharpTokenNode token, T data) + public virtual S? VisitCSharpTokenNode(CSharpTokenNode token, T data) { return VisitChildren(token, data); } - public virtual S VisitPrimitiveType(PrimitiveType primitiveType, T data) + public virtual S? VisitPrimitiveType(PrimitiveType primitiveType, T data) { return VisitChildren(primitiveType, data); } - public virtual S VisitComposedType(ComposedType composedType, T data) + public virtual S? VisitComposedType(ComposedType composedType, T data) { return VisitChildren(composedType, data); } - public virtual S VisitSimpleType(SimpleType simpleType, T data) + public virtual S? VisitSimpleType(SimpleType simpleType, T data) { return VisitChildren(simpleType, data); } - public virtual S VisitMemberType(MemberType memberType, T data) + public virtual S? VisitMemberType(MemberType memberType, T data) { return VisitChildren(memberType, data); } - public virtual S VisitTupleType(TupleAstType tupleType, T data) + public virtual S? VisitTupleType(TupleAstType tupleType, T data) { return VisitChildren(tupleType, data); } - public virtual S VisitTupleTypeElement(TupleTypeElement tupleTypeElement, T data) + public virtual S? VisitTupleTypeElement(TupleTypeElement tupleTypeElement, T data) { return VisitChildren(tupleTypeElement, data); } - public virtual S VisitFunctionPointerType(FunctionPointerAstType functionPointerType, T data) + public virtual S? VisitFunctionPointerType(FunctionPointerAstType functionPointerType, T data) { return VisitChildren(functionPointerType, data); } - public virtual S VisitInvocationType(InvocationAstType invocationType, T data) + public virtual S? VisitInvocationType(InvocationAstType invocationType, T data) { return VisitChildren(invocationType, data); } - public virtual S VisitAttribute(Attribute attribute, T data) + public virtual S? VisitAttribute(Attribute attribute, T data) { return VisitChildren(attribute, data); } - public virtual S VisitAttributeSection(AttributeSection attributeSection, T data) + public virtual S? VisitAttributeSection(AttributeSection attributeSection, T data) { return VisitChildren(attributeSection, data); } - public virtual S VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, T data) + public virtual S? VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, T data) { return VisitChildren(delegateDeclaration, data); } - public virtual S VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, T data) + public virtual S? VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, T data) { return VisitChildren(namespaceDeclaration, data); } - public virtual S VisitTypeDeclaration(TypeDeclaration typeDeclaration, T data) + public virtual S? VisitTypeDeclaration(TypeDeclaration typeDeclaration, T data) { return VisitChildren(typeDeclaration, data); } - public virtual S VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration, T data) + public virtual S? VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration, T data) { return VisitChildren(typeParameterDeclaration, data); } - public virtual S VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, T data) + public virtual S? VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, T data) { return VisitChildren(enumMemberDeclaration, data); } - public virtual S VisitUsingDeclaration(UsingDeclaration usingDeclaration, T data) + public virtual S? VisitUsingDeclaration(UsingDeclaration usingDeclaration, T data) { return VisitChildren(usingDeclaration, data); } - public virtual S VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration, T data) + public virtual S? VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration, T data) { return VisitChildren(usingDeclaration, data); } - public virtual S VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, T data) + public virtual S? VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, T data) { return VisitChildren(externAliasDeclaration, data); } - public virtual S VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, T data) + public virtual S? VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, T data) { return VisitChildren(constructorDeclaration, data); } - public virtual S VisitConstructorInitializer(ConstructorInitializer constructorInitializer, T data) + public virtual S? VisitConstructorInitializer(ConstructorInitializer constructorInitializer, T data) { return VisitChildren(constructorInitializer, data); } - public virtual S VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, T data) + public virtual S? VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, T data) { return VisitChildren(destructorDeclaration, data); } - public virtual S VisitEventDeclaration(EventDeclaration eventDeclaration, T data) + public virtual S? VisitEventDeclaration(EventDeclaration eventDeclaration, T data) { return VisitChildren(eventDeclaration, data); } - public virtual S VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration, T data) + public virtual S? VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration, T data) { return VisitChildren(eventDeclaration, data); } - public virtual S VisitFieldDeclaration(FieldDeclaration fieldDeclaration, T data) + public virtual S? VisitFieldDeclaration(FieldDeclaration fieldDeclaration, T data) { return VisitChildren(fieldDeclaration, data); } - public virtual S VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, T data) + public virtual S? VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, T data) { return VisitChildren(fixedFieldDeclaration, data); } - public virtual S VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, T data) + public virtual S? VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, T data) { return VisitChildren(fixedVariableInitializer, data); } - public virtual S VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, T data) + public virtual S? VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, T data) { return VisitChildren(indexerDeclaration, data); } - public virtual S VisitMethodDeclaration(MethodDeclaration methodDeclaration, T data) + public virtual S? VisitMethodDeclaration(MethodDeclaration methodDeclaration, T data) { return VisitChildren(methodDeclaration, data); } - public virtual S VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, T data) + public virtual S? VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, T data) { return VisitChildren(operatorDeclaration, data); } - public virtual S VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, T data) + public virtual S? VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, T data) { return VisitChildren(propertyDeclaration, data); } - public virtual S VisitAccessor(Accessor accessor, T data) + public virtual S? VisitAccessor(Accessor accessor, T data) { return VisitChildren(accessor, data); } - public virtual S VisitVariableInitializer(VariableInitializer variableInitializer, T data) + public virtual S? VisitVariableInitializer(VariableInitializer variableInitializer, T data) { return VisitChildren(variableInitializer, data); } - public virtual S VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, T data) + public virtual S? VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, T data) { return VisitChildren(parameterDeclaration, data); } - public virtual S VisitConstraint(Constraint constraint, T data) + public virtual S? VisitConstraint(Constraint constraint, T data) { return VisitChildren(constraint, data); } - public virtual S VisitBlockStatement(BlockStatement blockStatement, T data) + public virtual S? VisitBlockStatement(BlockStatement blockStatement, T data) { return VisitChildren(blockStatement, data); } - public virtual S VisitExpressionStatement(ExpressionStatement expressionStatement, T data) + public virtual S? VisitExpressionStatement(ExpressionStatement expressionStatement, T data) { return VisitChildren(expressionStatement, data); } - public virtual S VisitBreakStatement(BreakStatement breakStatement, T data) + public virtual S? VisitBreakStatement(BreakStatement breakStatement, T data) { return VisitChildren(breakStatement, data); } - public virtual S VisitCheckedStatement(CheckedStatement checkedStatement, T data) + public virtual S? VisitCheckedStatement(CheckedStatement checkedStatement, T data) { return VisitChildren(checkedStatement, data); } - public virtual S VisitContinueStatement(ContinueStatement continueStatement, T data) + public virtual S? VisitContinueStatement(ContinueStatement continueStatement, T data) { return VisitChildren(continueStatement, data); } - public virtual S VisitDoWhileStatement(DoWhileStatement doWhileStatement, T data) + public virtual S? VisitDoWhileStatement(DoWhileStatement doWhileStatement, T data) { return VisitChildren(doWhileStatement, data); } - public virtual S VisitEmptyStatement(EmptyStatement emptyStatement, T data) + public virtual S? VisitEmptyStatement(EmptyStatement emptyStatement, T data) { return VisitChildren(emptyStatement, data); } - public virtual S VisitFixedStatement(FixedStatement fixedStatement, T data) + public virtual S? VisitFixedStatement(FixedStatement fixedStatement, T data) { return VisitChildren(fixedStatement, data); } - public virtual S VisitForeachStatement(ForeachStatement foreachStatement, T data) + public virtual S? VisitForeachStatement(ForeachStatement foreachStatement, T data) { return VisitChildren(foreachStatement, data); } - public virtual S VisitForStatement(ForStatement forStatement, T data) + public virtual S? VisitForStatement(ForStatement forStatement, T data) { return VisitChildren(forStatement, data); } - public virtual S VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, T data) + public virtual S? VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, T data) { return VisitChildren(gotoCaseStatement, data); } - public virtual S VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, T data) + public virtual S? VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, T data) { return VisitChildren(gotoDefaultStatement, data); } - public virtual S VisitGotoStatement(GotoStatement gotoStatement, T data) + public virtual S? VisitGotoStatement(GotoStatement gotoStatement, T data) { return VisitChildren(gotoStatement, data); } - public virtual S VisitIfElseStatement(IfElseStatement ifElseStatement, T data) + public virtual S? VisitIfElseStatement(IfElseStatement ifElseStatement, T data) { return VisitChildren(ifElseStatement, data); } - public virtual S VisitLabelStatement(LabelStatement labelStatement, T data) + public virtual S? VisitLabelStatement(LabelStatement labelStatement, T data) { return VisitChildren(labelStatement, data); } - public virtual S VisitLockStatement(LockStatement lockStatement, T data) + public virtual S? VisitLockStatement(LockStatement lockStatement, T data) { return VisitChildren(lockStatement, data); } - public virtual S VisitReturnStatement(ReturnStatement returnStatement, T data) + public virtual S? VisitReturnStatement(ReturnStatement returnStatement, T data) { return VisitChildren(returnStatement, data); } - public virtual S VisitSwitchStatement(SwitchStatement switchStatement, T data) + public virtual S? VisitSwitchStatement(SwitchStatement switchStatement, T data) { return VisitChildren(switchStatement, data); } - public virtual S VisitSwitchSection(SwitchSection switchSection, T data) + public virtual S? VisitSwitchSection(SwitchSection switchSection, T data) { return VisitChildren(switchSection, data); } - public virtual S VisitCaseLabel(CaseLabel caseLabel, T data) + public virtual S? VisitCaseLabel(CaseLabel caseLabel, T data) { return VisitChildren(caseLabel, data); } - public virtual S VisitSwitchExpression(SwitchExpression switchExpression, T data) + public virtual S? VisitSwitchExpression(SwitchExpression switchExpression, T data) { return VisitChildren(switchExpression, data); } - public virtual S VisitSwitchExpressionSection(SwitchExpressionSection switchExpressionSection, T data) + public virtual S? VisitSwitchExpressionSection(SwitchExpressionSection switchExpressionSection, T data) { return VisitChildren(switchExpressionSection, data); } - public virtual S VisitThrowStatement(ThrowStatement throwStatement, T data) + public virtual S? VisitThrowStatement(ThrowStatement throwStatement, T data) { return VisitChildren(throwStatement, data); } - public virtual S VisitTryCatchStatement(TryCatchStatement tryCatchStatement, T data) + public virtual S? VisitTryCatchStatement(TryCatchStatement tryCatchStatement, T data) { return VisitChildren(tryCatchStatement, data); } - public virtual S VisitCatchClause(CatchClause catchClause, T data) + public virtual S? VisitCatchClause(CatchClause catchClause, T data) { return VisitChildren(catchClause, data); } - public virtual S VisitUncheckedStatement(UncheckedStatement uncheckedStatement, T data) + public virtual S? VisitUncheckedStatement(UncheckedStatement uncheckedStatement, T data) { return VisitChildren(uncheckedStatement, data); } - public virtual S VisitUnsafeStatement(UnsafeStatement unsafeStatement, T data) + public virtual S? VisitUnsafeStatement(UnsafeStatement unsafeStatement, T data) { return VisitChildren(unsafeStatement, data); } - public virtual S VisitUsingStatement(UsingStatement usingStatement, T data) + public virtual S? VisitUsingStatement(UsingStatement usingStatement, T data) { return VisitChildren(usingStatement, data); } - public virtual S VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, T data) + public virtual S? VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, T data) { return VisitChildren(variableDeclarationStatement, data); } - public virtual S VisitLocalFunctionDeclarationStatement(LocalFunctionDeclarationStatement localFunctionDeclarationStatement, T data) + public virtual S? VisitLocalFunctionDeclarationStatement(LocalFunctionDeclarationStatement localFunctionDeclarationStatement, T data) { return VisitChildren(localFunctionDeclarationStatement, data); } - public virtual S VisitWhileStatement(WhileStatement whileStatement, T data) + public virtual S? VisitWhileStatement(WhileStatement whileStatement, T data) { return VisitChildren(whileStatement, data); } - public virtual S VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, T data) + public virtual S? VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, T data) { return VisitChildren(yieldBreakStatement, data); } - public virtual S VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement, T data) + public virtual S? VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement, T data) { return VisitChildren(yieldReturnStatement, data); } - public virtual S VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, T data) + public virtual S? VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, T data) { return VisitChildren(anonymousMethodExpression, data); } - public virtual S VisitLambdaExpression(LambdaExpression lambdaExpression, T data) + public virtual S? VisitLambdaExpression(LambdaExpression lambdaExpression, T data) { return VisitChildren(lambdaExpression, data); } - public virtual S VisitAssignmentExpression(AssignmentExpression assignmentExpression, T data) + public virtual S? VisitAssignmentExpression(AssignmentExpression assignmentExpression, T data) { return VisitChildren(assignmentExpression, data); } - public virtual S VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, T data) + public virtual S? VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, T data) { return VisitChildren(baseReferenceExpression, data); } - public virtual S VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, T data) + public virtual S? VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, T data) { return VisitChildren(binaryOperatorExpression, data); } - public virtual S VisitCastExpression(CastExpression castExpression, T data) + public virtual S? VisitCastExpression(CastExpression castExpression, T data) { return VisitChildren(castExpression, data); } - public virtual S VisitCheckedExpression(CheckedExpression checkedExpression, T data) + public virtual S? VisitCheckedExpression(CheckedExpression checkedExpression, T data) { return VisitChildren(checkedExpression, data); } - public virtual S VisitConditionalExpression(ConditionalExpression conditionalExpression, T data) + public virtual S? VisitConditionalExpression(ConditionalExpression conditionalExpression, T data) { return VisitChildren(conditionalExpression, data); } - public virtual S VisitIdentifierExpression(IdentifierExpression identifierExpression, T data) + public virtual S? VisitIdentifierExpression(IdentifierExpression identifierExpression, T data) { return VisitChildren(identifierExpression, data); } - public virtual S VisitIndexerExpression(IndexerExpression indexerExpression, T data) + public virtual S? VisitIndexerExpression(IndexerExpression indexerExpression, T data) { return VisitChildren(indexerExpression, data); } - public virtual S VisitInterpolatedStringExpression(InterpolatedStringExpression interpolatedStringExpression, T data) + public virtual S? VisitInterpolatedStringExpression(InterpolatedStringExpression interpolatedStringExpression, T data) { return VisitChildren(interpolatedStringExpression, data); } - public virtual S VisitInterpolation(Interpolation interpolation, T data) + public virtual S? VisitInterpolation(Interpolation interpolation, T data) { return VisitChildren(interpolation, data); } - public virtual S VisitInterpolatedStringText(InterpolatedStringText interpolatedStringText, T data) + public virtual S? VisitInterpolatedStringText(InterpolatedStringText interpolatedStringText, T data) { return VisitChildren(interpolatedStringText, data); } - public virtual S VisitInvocationExpression(InvocationExpression invocationExpression, T data) + public virtual S? VisitInvocationExpression(InvocationExpression invocationExpression, T data) { return VisitChildren(invocationExpression, data); } - public virtual S VisitDirectionExpression(DirectionExpression directionExpression, T data) + public virtual S? VisitDirectionExpression(DirectionExpression directionExpression, T data) { return VisitChildren(directionExpression, data); } - public virtual S VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, T data) + public virtual S? VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, T data) { return VisitChildren(memberReferenceExpression, data); } - public virtual S VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, T data) + public virtual S? VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, T data) { return VisitChildren(nullReferenceExpression, data); } - public virtual S VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, T data) + public virtual S? VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, T data) { return VisitChildren(objectCreateExpression, data); } - public virtual S VisitDeclarationExpression(DeclarationExpression declarationExpression, T data) + public virtual S? VisitDeclarationExpression(DeclarationExpression declarationExpression, T data) { return VisitChildren(declarationExpression, data); } - public virtual S VisitRecursivePatternExpression(RecursivePatternExpression recursivePatternExpression, T data) + public virtual S? VisitRecursivePatternExpression(RecursivePatternExpression recursivePatternExpression, T data) { return VisitChildren(recursivePatternExpression, data); } - public virtual S VisitOutVarDeclarationExpression(OutVarDeclarationExpression outVarDeclarationExpression, T data) + public virtual S? VisitOutVarDeclarationExpression(OutVarDeclarationExpression outVarDeclarationExpression, T data) { return VisitChildren(outVarDeclarationExpression, data); } - public virtual S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data) + public virtual S? VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data) { return VisitChildren(anonymousTypeCreateExpression, data); } - public virtual S VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, T data) + public virtual S? VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, T data) { return VisitChildren(arrayCreateExpression, data); } - public virtual S VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, T data) + public virtual S? VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, T data) { return VisitChildren(parenthesizedExpression, data); } - public virtual S VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, T data) + public virtual S? VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, T data) { return VisitChildren(pointerReferenceExpression, data); } - public virtual S VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, T data) + public virtual S? VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, T data) { return VisitChildren(primitiveExpression, data); } - public virtual S VisitSizeOfExpression(SizeOfExpression sizeOfExpression, T data) + public virtual S? VisitSizeOfExpression(SizeOfExpression sizeOfExpression, T data) { return VisitChildren(sizeOfExpression, data); } - public virtual S VisitStackAllocExpression(StackAllocExpression stackAllocExpression, T data) + public virtual S? VisitStackAllocExpression(StackAllocExpression stackAllocExpression, T data) { return VisitChildren(stackAllocExpression, data); } - public virtual S VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, T data) + public virtual S? VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, T data) { return VisitChildren(thisReferenceExpression, data); } - public virtual S VisitThrowExpression(ThrowExpression throwExpression, T data) + public virtual S? VisitThrowExpression(ThrowExpression throwExpression, T data) { return VisitChildren(throwExpression, data); } - public virtual S VisitTupleExpression(TupleExpression tupleExpression, T data) + public virtual S? VisitTupleExpression(TupleExpression tupleExpression, T data) { return VisitChildren(tupleExpression, data); } - public virtual S VisitTypeOfExpression(TypeOfExpression typeOfExpression, T data) + public virtual S? VisitTypeOfExpression(TypeOfExpression typeOfExpression, T data) { return VisitChildren(typeOfExpression, data); } - public virtual S VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, T data) + public virtual S? VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, T data) { return VisitChildren(typeReferenceExpression, data); } - public virtual S VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, T data) + public virtual S? VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, T data) { return VisitChildren(unaryOperatorExpression, data); } - public virtual S VisitUncheckedExpression(UncheckedExpression uncheckedExpression, T data) + public virtual S? VisitUncheckedExpression(UncheckedExpression uncheckedExpression, T data) { return VisitChildren(uncheckedExpression, data); } - public virtual S VisitQueryExpression(QueryExpression queryExpression, T data) + public virtual S? VisitQueryExpression(QueryExpression queryExpression, T data) { return VisitChildren(queryExpression, data); } - public virtual S VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, T data) + public virtual S? VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, T data) { return VisitChildren(queryContinuationClause, data); } - public virtual S VisitQueryFromClause(QueryFromClause queryFromClause, T data) + public virtual S? VisitQueryFromClause(QueryFromClause queryFromClause, T data) { return VisitChildren(queryFromClause, data); } - public virtual S VisitQueryLetClause(QueryLetClause queryLetClause, T data) + public virtual S? VisitQueryLetClause(QueryLetClause queryLetClause, T data) { return VisitChildren(queryLetClause, data); } - public virtual S VisitQueryWhereClause(QueryWhereClause queryWhereClause, T data) + public virtual S? VisitQueryWhereClause(QueryWhereClause queryWhereClause, T data) { return VisitChildren(queryWhereClause, data); } - public virtual S VisitQueryJoinClause(QueryJoinClause queryJoinClause, T data) + public virtual S? VisitQueryJoinClause(QueryJoinClause queryJoinClause, T data) { return VisitChildren(queryJoinClause, data); } - public virtual S VisitQueryOrderClause(QueryOrderClause queryOrderClause, T data) + public virtual S? VisitQueryOrderClause(QueryOrderClause queryOrderClause, T data) { return VisitChildren(queryOrderClause, data); } - public virtual S VisitQueryOrdering(QueryOrdering queryOrdering, T data) + public virtual S? VisitQueryOrdering(QueryOrdering queryOrdering, T data) { return VisitChildren(queryOrdering, data); } - public virtual S VisitQuerySelectClause(QuerySelectClause querySelectClause, T data) + public virtual S? VisitQuerySelectClause(QuerySelectClause querySelectClause, T data) { return VisitChildren(querySelectClause, data); } - public virtual S VisitQueryGroupClause(QueryGroupClause queryGroupClause, T data) + public virtual S? VisitQueryGroupClause(QueryGroupClause queryGroupClause, T data) { return VisitChildren(queryGroupClause, data); } - public virtual S VisitAsExpression(AsExpression asExpression, T data) + public virtual S? VisitAsExpression(AsExpression asExpression, T data) { return VisitChildren(asExpression, data); } - public virtual S VisitIsExpression(IsExpression isExpression, T data) + public virtual S? VisitIsExpression(IsExpression isExpression, T data) { return VisitChildren(isExpression, data); } - public virtual S VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, T data) + public virtual S? VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, T data) { return VisitChildren(defaultValueExpression, data); } - public virtual S VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, T data) + public virtual S? VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, T data) { return VisitChildren(undocumentedExpression, data); } - public virtual S VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, T data) + public virtual S? VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, T data) { return VisitChildren(arrayInitializerExpression, data); } - public virtual S VisitArraySpecifier(ArraySpecifier arraySpecifier, T data) + public virtual S? VisitArraySpecifier(ArraySpecifier arraySpecifier, T data) { return VisitChildren(arraySpecifier, data); } - public virtual S VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, T data) + public virtual S? VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, T data) { return VisitChildren(namedArgumentExpression, data); } - public virtual S VisitNamedExpression(NamedExpression namedExpression, T data) + public virtual S? VisitNamedExpression(NamedExpression namedExpression, T data) { return VisitChildren(namedExpression, data); } - public virtual S VisitSingleVariableDesignation(SingleVariableDesignation singleVariableDesignation, T data) + public virtual S? VisitSingleVariableDesignation(SingleVariableDesignation singleVariableDesignation, T data) { return VisitChildren(singleVariableDesignation, data); } - public virtual S VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignation parenthesizedVariableDesignation, T data) + public virtual S? VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignation parenthesizedVariableDesignation, T data) { return VisitChildren(parenthesizedVariableDesignation, data); } - public virtual S VisitErrorNode(AstNode errorNode, T data) + public virtual S? VisitErrorNode(AstNode errorNode, T data) { return VisitChildren(errorNode, data); } - public virtual S VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern, T data) + public virtual S? VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern, T data) { return VisitChildren(placeholder, data); } - public virtual S VisitWithInitializerExpression(WithInitializerExpression withInitializerExpression, T data) + public virtual S? VisitWithInitializerExpression(WithInitializerExpression withInitializerExpression, T data) { return VisitChildren(withInitializerExpression, data); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs b/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs index 8256661a57..6a033f8e13 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs @@ -42,7 +42,7 @@ IEnumerable Annotations { /// /// The type of the annotation. /// - T Annotation() where T : class; + T? Annotation() where T : class; /// /// Gets the first annotation of the specified type. @@ -51,7 +51,7 @@ IEnumerable Annotations { /// /// The type of the annotation. /// - object Annotation(Type type); + object? Annotation(Type type); /// /// Adds an annotation to this instance. @@ -89,7 +89,7 @@ public abstract class AbstractAnnotatable : IAnnotatable // or to an AnnotationList. // Once it is pointed at an AnnotationList, it will never change (this allows thread-safety support by locking the list) - object annotations; + object? annotations; /// /// Clones all annotations. @@ -136,7 +136,7 @@ public virtual void AddAnnotation(object annotation) if (annotation == null) throw new ArgumentNullException(nameof(annotation)); retry: // Retry until successful - object oldAnnotation = Interlocked.CompareExchange(ref this.annotations, annotation, null); + object? oldAnnotation = Interlocked.CompareExchange(ref this.annotations, annotation, null); if (oldAnnotation == null) { return; // we successfully added a single annotation @@ -167,7 +167,7 @@ public virtual void AddAnnotation(object annotation) public virtual void RemoveAnnotations() where T : class { retry: // Retry until successful - object oldAnnotations = this.annotations; + object? oldAnnotations = this.annotations; AnnotationList? list = oldAnnotations as AnnotationList; if (list != null) { @@ -189,7 +189,7 @@ public virtual void RemoveAnnotations(Type type) if (type == null) throw new ArgumentNullException(nameof(type)); retry: // Retry until successful - object oldAnnotations = this.annotations; + object? oldAnnotations = this.annotations; AnnotationList? list = oldAnnotations as AnnotationList; if (list != null) { @@ -206,9 +206,9 @@ public virtual void RemoveAnnotations(Type type) } } - public T Annotation() where T : class + public T? Annotation() where T : class { - object annotations = this.annotations; + object? annotations = this.annotations; AnnotationList? list = annotations as AnnotationList; if (list != null) { @@ -229,11 +229,11 @@ public T Annotation() where T : class } } - public object Annotation(Type type) + public object? Annotation(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); - object annotations = this.annotations; + object? annotations = this.annotations; AnnotationList? list = annotations as AnnotationList; if (list != null) { @@ -259,7 +259,7 @@ public object Annotation(Type type) /// public IEnumerable Annotations { get { - object annotations = this.annotations; + object? annotations = this.annotations; AnnotationList? list = annotations as AnnotationList; if (list != null) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs index 37dfd40a33..48e419e9e8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs @@ -173,148 +173,148 @@ public interface IAstVisitor /// public interface IAstVisitor { - S VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression); - S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression); - S VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression); - S VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression); - S VisitAsExpression(AsExpression asExpression); - S VisitAssignmentExpression(AssignmentExpression assignmentExpression); - S VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression); - S VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression); - S VisitCastExpression(CastExpression castExpression); - S VisitCheckedExpression(CheckedExpression checkedExpression); - S VisitConditionalExpression(ConditionalExpression conditionalExpression); - S VisitDeclarationExpression(DeclarationExpression declarationExpression); - S VisitRecursivePatternExpression(RecursivePatternExpression recursivePatternExpression); - S VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression); - S VisitDirectionExpression(DirectionExpression directionExpression); - S VisitIdentifierExpression(IdentifierExpression identifierExpression); - S VisitIndexerExpression(IndexerExpression indexerExpression); - S VisitInterpolatedStringExpression(InterpolatedStringExpression interpolatedStringExpression); - S VisitInvocationExpression(InvocationExpression invocationExpression); - S VisitIsExpression(IsExpression isExpression); - S VisitLambdaExpression(LambdaExpression lambdaExpression); - S VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression); - S VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression); - S VisitNamedExpression(NamedExpression namedExpression); - S VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression); - S VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression); - S VisitOutVarDeclarationExpression(OutVarDeclarationExpression outVarDeclarationExpression); - S VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression); - S VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression); - S VisitPrimitiveExpression(PrimitiveExpression primitiveExpression); - S VisitSizeOfExpression(SizeOfExpression sizeOfExpression); - S VisitStackAllocExpression(StackAllocExpression stackAllocExpression); - S VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression); - S VisitThrowExpression(ThrowExpression throwExpression); - S VisitTupleExpression(TupleExpression tupleExpression); - S VisitTypeOfExpression(TypeOfExpression typeOfExpression); - S VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression); - S VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression); - S VisitUncheckedExpression(UncheckedExpression uncheckedExpression); - S VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression); - S VisitWithInitializerExpression(WithInitializerExpression withInitializerExpression); - - S VisitQueryExpression(QueryExpression queryExpression); - S VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause); - S VisitQueryFromClause(QueryFromClause queryFromClause); - S VisitQueryLetClause(QueryLetClause queryLetClause); - S VisitQueryWhereClause(QueryWhereClause queryWhereClause); - S VisitQueryJoinClause(QueryJoinClause queryJoinClause); - S VisitQueryOrderClause(QueryOrderClause queryOrderClause); - S VisitQueryOrdering(QueryOrdering queryOrdering); - S VisitQuerySelectClause(QuerySelectClause querySelectClause); - S VisitQueryGroupClause(QueryGroupClause queryGroupClause); - - S VisitAttribute(Attribute attribute); - S VisitAttributeSection(AttributeSection attributeSection); - S VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration); - S VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration); - S VisitTypeDeclaration(TypeDeclaration typeDeclaration); - S VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration); - S VisitUsingDeclaration(UsingDeclaration usingDeclaration); - S VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration); - - S VisitBlockStatement(BlockStatement blockStatement); - S VisitBreakStatement(BreakStatement breakStatement); - S VisitCheckedStatement(CheckedStatement checkedStatement); - S VisitContinueStatement(ContinueStatement continueStatement); - S VisitDoWhileStatement(DoWhileStatement doWhileStatement); - S VisitEmptyStatement(EmptyStatement emptyStatement); - S VisitExpressionStatement(ExpressionStatement expressionStatement); - S VisitFixedStatement(FixedStatement fixedStatement); - S VisitForeachStatement(ForeachStatement foreachStatement); - S VisitForStatement(ForStatement forStatement); - S VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement); - S VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement); - S VisitGotoStatement(GotoStatement gotoStatement); - S VisitIfElseStatement(IfElseStatement ifElseStatement); - S VisitLabelStatement(LabelStatement labelStatement); - S VisitLockStatement(LockStatement lockStatement); - S VisitReturnStatement(ReturnStatement returnStatement); - S VisitSwitchStatement(SwitchStatement switchStatement); - S VisitSwitchSection(SwitchSection switchSection); - S VisitCaseLabel(CaseLabel caseLabel); - S VisitSwitchExpression(SwitchExpression switchExpression); - S VisitSwitchExpressionSection(SwitchExpressionSection switchExpressionSection); - S VisitThrowStatement(ThrowStatement throwStatement); - S VisitTryCatchStatement(TryCatchStatement tryCatchStatement); - S VisitCatchClause(CatchClause catchClause); - S VisitUncheckedStatement(UncheckedStatement uncheckedStatement); - S VisitUnsafeStatement(UnsafeStatement unsafeStatement); - S VisitUsingStatement(UsingStatement usingStatement); - S VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement); - S VisitLocalFunctionDeclarationStatement(LocalFunctionDeclarationStatement localFunctionDeclarationStatement); - S VisitWhileStatement(WhileStatement whileStatement); - S VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement); - S VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement); - - S VisitAccessor(Accessor accessor); - S VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration); - S VisitConstructorInitializer(ConstructorInitializer constructorInitializer); - S VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration); - S VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration); - S VisitEventDeclaration(EventDeclaration eventDeclaration); - S VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration); - S VisitFieldDeclaration(FieldDeclaration fieldDeclaration); - S VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration); - S VisitMethodDeclaration(MethodDeclaration methodDeclaration); - S VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration); - S VisitParameterDeclaration(ParameterDeclaration parameterDeclaration); - S VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration); - S VisitVariableInitializer(VariableInitializer variableInitializer); - S VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration); - S VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer); - - S VisitSyntaxTree(SyntaxTree syntaxTree); - S VisitSimpleType(SimpleType simpleType); - S VisitMemberType(MemberType memberType); - S VisitTupleType(TupleAstType tupleType); - S VisitTupleTypeElement(TupleTypeElement tupleTypeElement); - S VisitFunctionPointerType(FunctionPointerAstType functionPointerType); - S VisitInvocationType(InvocationAstType invocationType); - S VisitComposedType(ComposedType composedType); - S VisitArraySpecifier(ArraySpecifier arraySpecifier); - S VisitPrimitiveType(PrimitiveType primitiveType); - - S VisitComment(Comment comment); - S VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective); - S VisitDocumentationReference(DocumentationReference documentationReference); - - S VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration); - S VisitConstraint(Constraint constraint); - S VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode); - S VisitIdentifier(Identifier identifier); - - S VisitInterpolation(Interpolation interpolation); - S VisitInterpolatedStringText(InterpolatedStringText interpolatedStringText); - - S VisitSingleVariableDesignation(SingleVariableDesignation singleVariableDesignation); - S VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignation parenthesizedVariableDesignation); - - S VisitNullNode(AstNode nullNode); - S VisitErrorNode(AstNode errorNode); - S VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern); + S? VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression); + S? VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression); + S? VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression); + S? VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression); + S? VisitAsExpression(AsExpression asExpression); + S? VisitAssignmentExpression(AssignmentExpression assignmentExpression); + S? VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression); + S? VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression); + S? VisitCastExpression(CastExpression castExpression); + S? VisitCheckedExpression(CheckedExpression checkedExpression); + S? VisitConditionalExpression(ConditionalExpression conditionalExpression); + S? VisitDeclarationExpression(DeclarationExpression declarationExpression); + S? VisitRecursivePatternExpression(RecursivePatternExpression recursivePatternExpression); + S? VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression); + S? VisitDirectionExpression(DirectionExpression directionExpression); + S? VisitIdentifierExpression(IdentifierExpression identifierExpression); + S? VisitIndexerExpression(IndexerExpression indexerExpression); + S? VisitInterpolatedStringExpression(InterpolatedStringExpression interpolatedStringExpression); + S? VisitInvocationExpression(InvocationExpression invocationExpression); + S? VisitIsExpression(IsExpression isExpression); + S? VisitLambdaExpression(LambdaExpression lambdaExpression); + S? VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression); + S? VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression); + S? VisitNamedExpression(NamedExpression namedExpression); + S? VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression); + S? VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression); + S? VisitOutVarDeclarationExpression(OutVarDeclarationExpression outVarDeclarationExpression); + S? VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression); + S? VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression); + S? VisitPrimitiveExpression(PrimitiveExpression primitiveExpression); + S? VisitSizeOfExpression(SizeOfExpression sizeOfExpression); + S? VisitStackAllocExpression(StackAllocExpression stackAllocExpression); + S? VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression); + S? VisitThrowExpression(ThrowExpression throwExpression); + S? VisitTupleExpression(TupleExpression tupleExpression); + S? VisitTypeOfExpression(TypeOfExpression typeOfExpression); + S? VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression); + S? VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression); + S? VisitUncheckedExpression(UncheckedExpression uncheckedExpression); + S? VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression); + S? VisitWithInitializerExpression(WithInitializerExpression withInitializerExpression); + + S? VisitQueryExpression(QueryExpression queryExpression); + S? VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause); + S? VisitQueryFromClause(QueryFromClause queryFromClause); + S? VisitQueryLetClause(QueryLetClause queryLetClause); + S? VisitQueryWhereClause(QueryWhereClause queryWhereClause); + S? VisitQueryJoinClause(QueryJoinClause queryJoinClause); + S? VisitQueryOrderClause(QueryOrderClause queryOrderClause); + S? VisitQueryOrdering(QueryOrdering queryOrdering); + S? VisitQuerySelectClause(QuerySelectClause querySelectClause); + S? VisitQueryGroupClause(QueryGroupClause queryGroupClause); + + S? VisitAttribute(Attribute attribute); + S? VisitAttributeSection(AttributeSection attributeSection); + S? VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration); + S? VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration); + S? VisitTypeDeclaration(TypeDeclaration typeDeclaration); + S? VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration); + S? VisitUsingDeclaration(UsingDeclaration usingDeclaration); + S? VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration); + + S? VisitBlockStatement(BlockStatement blockStatement); + S? VisitBreakStatement(BreakStatement breakStatement); + S? VisitCheckedStatement(CheckedStatement checkedStatement); + S? VisitContinueStatement(ContinueStatement continueStatement); + S? VisitDoWhileStatement(DoWhileStatement doWhileStatement); + S? VisitEmptyStatement(EmptyStatement emptyStatement); + S? VisitExpressionStatement(ExpressionStatement expressionStatement); + S? VisitFixedStatement(FixedStatement fixedStatement); + S? VisitForeachStatement(ForeachStatement foreachStatement); + S? VisitForStatement(ForStatement forStatement); + S? VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement); + S? VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement); + S? VisitGotoStatement(GotoStatement gotoStatement); + S? VisitIfElseStatement(IfElseStatement ifElseStatement); + S? VisitLabelStatement(LabelStatement labelStatement); + S? VisitLockStatement(LockStatement lockStatement); + S? VisitReturnStatement(ReturnStatement returnStatement); + S? VisitSwitchStatement(SwitchStatement switchStatement); + S? VisitSwitchSection(SwitchSection switchSection); + S? VisitCaseLabel(CaseLabel caseLabel); + S? VisitSwitchExpression(SwitchExpression switchExpression); + S? VisitSwitchExpressionSection(SwitchExpressionSection switchExpressionSection); + S? VisitThrowStatement(ThrowStatement throwStatement); + S? VisitTryCatchStatement(TryCatchStatement tryCatchStatement); + S? VisitCatchClause(CatchClause catchClause); + S? VisitUncheckedStatement(UncheckedStatement uncheckedStatement); + S? VisitUnsafeStatement(UnsafeStatement unsafeStatement); + S? VisitUsingStatement(UsingStatement usingStatement); + S? VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement); + S? VisitLocalFunctionDeclarationStatement(LocalFunctionDeclarationStatement localFunctionDeclarationStatement); + S? VisitWhileStatement(WhileStatement whileStatement); + S? VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement); + S? VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement); + + S? VisitAccessor(Accessor accessor); + S? VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration); + S? VisitConstructorInitializer(ConstructorInitializer constructorInitializer); + S? VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration); + S? VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration); + S? VisitEventDeclaration(EventDeclaration eventDeclaration); + S? VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration); + S? VisitFieldDeclaration(FieldDeclaration fieldDeclaration); + S? VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration); + S? VisitMethodDeclaration(MethodDeclaration methodDeclaration); + S? VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration); + S? VisitParameterDeclaration(ParameterDeclaration parameterDeclaration); + S? VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration); + S? VisitVariableInitializer(VariableInitializer variableInitializer); + S? VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration); + S? VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer); + + S? VisitSyntaxTree(SyntaxTree syntaxTree); + S? VisitSimpleType(SimpleType simpleType); + S? VisitMemberType(MemberType memberType); + S? VisitTupleType(TupleAstType tupleType); + S? VisitTupleTypeElement(TupleTypeElement tupleTypeElement); + S? VisitFunctionPointerType(FunctionPointerAstType functionPointerType); + S? VisitInvocationType(InvocationAstType invocationType); + S? VisitComposedType(ComposedType composedType); + S? VisitArraySpecifier(ArraySpecifier arraySpecifier); + S? VisitPrimitiveType(PrimitiveType primitiveType); + + S? VisitComment(Comment comment); + S? VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective); + S? VisitDocumentationReference(DocumentationReference documentationReference); + + S? VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration); + S? VisitConstraint(Constraint constraint); + S? VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode); + S? VisitIdentifier(Identifier identifier); + + S? VisitInterpolation(Interpolation interpolation); + S? VisitInterpolatedStringText(InterpolatedStringText interpolatedStringText); + + S? VisitSingleVariableDesignation(SingleVariableDesignation singleVariableDesignation); + S? VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignation parenthesizedVariableDesignation); + + S? VisitNullNode(AstNode nullNode); + S? VisitErrorNode(AstNode errorNode); + S? VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern); } /// @@ -322,147 +322,147 @@ public interface IAstVisitor /// public interface IAstVisitor { - S VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, T data); - S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data); - S VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, T data); - S VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, T data); - S VisitAsExpression(AsExpression asExpression, T data); - S VisitAssignmentExpression(AssignmentExpression assignmentExpression, T data); - S VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, T data); - S VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, T data); - S VisitCastExpression(CastExpression castExpression, T data); - S VisitCheckedExpression(CheckedExpression checkedExpression, T data); - S VisitConditionalExpression(ConditionalExpression conditionalExpression, T data); - S VisitDeclarationExpression(DeclarationExpression declarationExpression, T data); - S VisitRecursivePatternExpression(RecursivePatternExpression recursivePatternExpression, T data); - S VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, T data); - S VisitDirectionExpression(DirectionExpression directionExpression, T data); - S VisitIdentifierExpression(IdentifierExpression identifierExpression, T data); - S VisitIndexerExpression(IndexerExpression indexerExpression, T data); - S VisitInterpolatedStringExpression(InterpolatedStringExpression interpolatedStringExpression, T data); - S VisitInvocationExpression(InvocationExpression invocationExpression, T data); - S VisitIsExpression(IsExpression isExpression, T data); - S VisitLambdaExpression(LambdaExpression lambdaExpression, T data); - S VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, T data); - S VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, T data); - S VisitNamedExpression(NamedExpression namedExpression, T data); - S VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, T data); - S VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, T data); - S VisitOutVarDeclarationExpression(OutVarDeclarationExpression outVarDeclarationExpression, T data); - S VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, T data); - S VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, T data); - S VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, T data); - S VisitSizeOfExpression(SizeOfExpression sizeOfExpression, T data); - S VisitStackAllocExpression(StackAllocExpression stackAllocExpression, T data); - S VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, T data); - S VisitThrowExpression(ThrowExpression throwExpression, T data); - S VisitTupleExpression(TupleExpression tupleExpression, T data); - S VisitTypeOfExpression(TypeOfExpression typeOfExpression, T data); - S VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, T data); - S VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, T data); - S VisitUncheckedExpression(UncheckedExpression uncheckedExpression, T data); - S VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, T data); - S VisitWithInitializerExpression(WithInitializerExpression withInitializerExpression, T data); - - S VisitQueryExpression(QueryExpression queryExpression, T data); - S VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, T data); - S VisitQueryFromClause(QueryFromClause queryFromClause, T data); - S VisitQueryLetClause(QueryLetClause queryLetClause, T data); - S VisitQueryWhereClause(QueryWhereClause queryWhereClause, T data); - S VisitQueryJoinClause(QueryJoinClause queryJoinClause, T data); - S VisitQueryOrderClause(QueryOrderClause queryOrderClause, T data); - S VisitQueryOrdering(QueryOrdering queryOrdering, T data); - S VisitQuerySelectClause(QuerySelectClause querySelectClause, T data); - S VisitQueryGroupClause(QueryGroupClause queryGroupClause, T data); - - S VisitAttribute(Attribute attribute, T data); - S VisitAttributeSection(AttributeSection attributeSection, T data); - S VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, T data); - S VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, T data); - S VisitTypeDeclaration(TypeDeclaration typeDeclaration, T data); - S VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration, T data); - S VisitUsingDeclaration(UsingDeclaration usingDeclaration, T data); - S VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, T data); - - S VisitBlockStatement(BlockStatement blockStatement, T data); - S VisitBreakStatement(BreakStatement breakStatement, T data); - S VisitCheckedStatement(CheckedStatement checkedStatement, T data); - S VisitContinueStatement(ContinueStatement continueStatement, T data); - S VisitDoWhileStatement(DoWhileStatement doWhileStatement, T data); - S VisitEmptyStatement(EmptyStatement emptyStatement, T data); - S VisitExpressionStatement(ExpressionStatement expressionStatement, T data); - S VisitFixedStatement(FixedStatement fixedStatement, T data); - S VisitForeachStatement(ForeachStatement foreachStatement, T data); - S VisitForStatement(ForStatement forStatement, T data); - S VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, T data); - S VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, T data); - S VisitGotoStatement(GotoStatement gotoStatement, T data); - S VisitIfElseStatement(IfElseStatement ifElseStatement, T data); - S VisitLabelStatement(LabelStatement labelStatement, T data); - S VisitLockStatement(LockStatement lockStatement, T data); - S VisitReturnStatement(ReturnStatement returnStatement, T data); - S VisitSwitchStatement(SwitchStatement switchStatement, T data); - S VisitSwitchSection(SwitchSection switchSection, T data); - S VisitCaseLabel(CaseLabel caseLabel, T data); - S VisitSwitchExpression(SwitchExpression switchExpression, T data); - S VisitSwitchExpressionSection(SwitchExpressionSection switchExpressionSection, T data); - S VisitThrowStatement(ThrowStatement throwStatement, T data); - S VisitTryCatchStatement(TryCatchStatement tryCatchStatement, T data); - S VisitCatchClause(CatchClause catchClause, T data); - S VisitUncheckedStatement(UncheckedStatement uncheckedStatement, T data); - S VisitUnsafeStatement(UnsafeStatement unsafeStatement, T data); - S VisitUsingStatement(UsingStatement usingStatement, T data); - S VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, T data); - S VisitLocalFunctionDeclarationStatement(LocalFunctionDeclarationStatement localFunctionDeclarationStatement, T data); - S VisitWhileStatement(WhileStatement whileStatement, T data); - S VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, T data); - S VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement, T data); - - S VisitAccessor(Accessor accessor, T data); - S VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, T data); - S VisitConstructorInitializer(ConstructorInitializer constructorInitializer, T data); - S VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, T data); - S VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, T data); - S VisitEventDeclaration(EventDeclaration eventDeclaration, T data); - S VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration, T data); - S VisitFieldDeclaration(FieldDeclaration fieldDeclaration, T data); - S VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, T data); - S VisitMethodDeclaration(MethodDeclaration methodDeclaration, T data); - S VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, T data); - S VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, T data); - S VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, T data); - S VisitVariableInitializer(VariableInitializer variableInitializer, T data); - S VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, T data); - S VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, T data); - - S VisitSyntaxTree(SyntaxTree syntaxTree, T data); - S VisitSimpleType(SimpleType simpleType, T data); - S VisitMemberType(MemberType memberType, T data); - S VisitTupleType(TupleAstType tupleType, T data); - S VisitTupleTypeElement(TupleTypeElement tupleTypeElement, T data); - S VisitFunctionPointerType(FunctionPointerAstType functionPointerType, T data); - S VisitInvocationType(InvocationAstType invocationType, T data); - S VisitComposedType(ComposedType composedType, T data); - S VisitArraySpecifier(ArraySpecifier arraySpecifier, T data); - S VisitPrimitiveType(PrimitiveType primitiveType, T data); - - S VisitComment(Comment comment, T data); - S VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective, T data); - S VisitDocumentationReference(DocumentationReference documentationReference, T data); - - S VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration, T data); - S VisitConstraint(Constraint constraint, T data); - S VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode, T data); - S VisitIdentifier(Identifier identifier, T data); - - S VisitInterpolation(Interpolation interpolation, T data); - S VisitInterpolatedStringText(InterpolatedStringText interpolatedStringText, T data); - - S VisitSingleVariableDesignation(SingleVariableDesignation singleVariableDesignation, T data); - S VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignation parenthesizedVariableDesignation, T data); - - S VisitNullNode(AstNode nullNode, T data); - S VisitErrorNode(AstNode errorNode, T data); - S VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern, T data); + S? VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, T data); + S? VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data); + S? VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, T data); + S? VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, T data); + S? VisitAsExpression(AsExpression asExpression, T data); + S? VisitAssignmentExpression(AssignmentExpression assignmentExpression, T data); + S? VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, T data); + S? VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, T data); + S? VisitCastExpression(CastExpression castExpression, T data); + S? VisitCheckedExpression(CheckedExpression checkedExpression, T data); + S? VisitConditionalExpression(ConditionalExpression conditionalExpression, T data); + S? VisitDeclarationExpression(DeclarationExpression declarationExpression, T data); + S? VisitRecursivePatternExpression(RecursivePatternExpression recursivePatternExpression, T data); + S? VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, T data); + S? VisitDirectionExpression(DirectionExpression directionExpression, T data); + S? VisitIdentifierExpression(IdentifierExpression identifierExpression, T data); + S? VisitIndexerExpression(IndexerExpression indexerExpression, T data); + S? VisitInterpolatedStringExpression(InterpolatedStringExpression interpolatedStringExpression, T data); + S? VisitInvocationExpression(InvocationExpression invocationExpression, T data); + S? VisitIsExpression(IsExpression isExpression, T data); + S? VisitLambdaExpression(LambdaExpression lambdaExpression, T data); + S? VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, T data); + S? VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, T data); + S? VisitNamedExpression(NamedExpression namedExpression, T data); + S? VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, T data); + S? VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, T data); + S? VisitOutVarDeclarationExpression(OutVarDeclarationExpression outVarDeclarationExpression, T data); + S? VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, T data); + S? VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, T data); + S? VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, T data); + S? VisitSizeOfExpression(SizeOfExpression sizeOfExpression, T data); + S? VisitStackAllocExpression(StackAllocExpression stackAllocExpression, T data); + S? VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, T data); + S? VisitThrowExpression(ThrowExpression throwExpression, T data); + S? VisitTupleExpression(TupleExpression tupleExpression, T data); + S? VisitTypeOfExpression(TypeOfExpression typeOfExpression, T data); + S? VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, T data); + S? VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, T data); + S? VisitUncheckedExpression(UncheckedExpression uncheckedExpression, T data); + S? VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, T data); + S? VisitWithInitializerExpression(WithInitializerExpression withInitializerExpression, T data); + + S? VisitQueryExpression(QueryExpression queryExpression, T data); + S? VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, T data); + S? VisitQueryFromClause(QueryFromClause queryFromClause, T data); + S? VisitQueryLetClause(QueryLetClause queryLetClause, T data); + S? VisitQueryWhereClause(QueryWhereClause queryWhereClause, T data); + S? VisitQueryJoinClause(QueryJoinClause queryJoinClause, T data); + S? VisitQueryOrderClause(QueryOrderClause queryOrderClause, T data); + S? VisitQueryOrdering(QueryOrdering queryOrdering, T data); + S? VisitQuerySelectClause(QuerySelectClause querySelectClause, T data); + S? VisitQueryGroupClause(QueryGroupClause queryGroupClause, T data); + + S? VisitAttribute(Attribute attribute, T data); + S? VisitAttributeSection(AttributeSection attributeSection, T data); + S? VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, T data); + S? VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, T data); + S? VisitTypeDeclaration(TypeDeclaration typeDeclaration, T data); + S? VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration, T data); + S? VisitUsingDeclaration(UsingDeclaration usingDeclaration, T data); + S? VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, T data); + + S? VisitBlockStatement(BlockStatement blockStatement, T data); + S? VisitBreakStatement(BreakStatement breakStatement, T data); + S? VisitCheckedStatement(CheckedStatement checkedStatement, T data); + S? VisitContinueStatement(ContinueStatement continueStatement, T data); + S? VisitDoWhileStatement(DoWhileStatement doWhileStatement, T data); + S? VisitEmptyStatement(EmptyStatement emptyStatement, T data); + S? VisitExpressionStatement(ExpressionStatement expressionStatement, T data); + S? VisitFixedStatement(FixedStatement fixedStatement, T data); + S? VisitForeachStatement(ForeachStatement foreachStatement, T data); + S? VisitForStatement(ForStatement forStatement, T data); + S? VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, T data); + S? VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, T data); + S? VisitGotoStatement(GotoStatement gotoStatement, T data); + S? VisitIfElseStatement(IfElseStatement ifElseStatement, T data); + S? VisitLabelStatement(LabelStatement labelStatement, T data); + S? VisitLockStatement(LockStatement lockStatement, T data); + S? VisitReturnStatement(ReturnStatement returnStatement, T data); + S? VisitSwitchStatement(SwitchStatement switchStatement, T data); + S? VisitSwitchSection(SwitchSection switchSection, T data); + S? VisitCaseLabel(CaseLabel caseLabel, T data); + S? VisitSwitchExpression(SwitchExpression switchExpression, T data); + S? VisitSwitchExpressionSection(SwitchExpressionSection switchExpressionSection, T data); + S? VisitThrowStatement(ThrowStatement throwStatement, T data); + S? VisitTryCatchStatement(TryCatchStatement tryCatchStatement, T data); + S? VisitCatchClause(CatchClause catchClause, T data); + S? VisitUncheckedStatement(UncheckedStatement uncheckedStatement, T data); + S? VisitUnsafeStatement(UnsafeStatement unsafeStatement, T data); + S? VisitUsingStatement(UsingStatement usingStatement, T data); + S? VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, T data); + S? VisitLocalFunctionDeclarationStatement(LocalFunctionDeclarationStatement localFunctionDeclarationStatement, T data); + S? VisitWhileStatement(WhileStatement whileStatement, T data); + S? VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, T data); + S? VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement, T data); + + S? VisitAccessor(Accessor accessor, T data); + S? VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, T data); + S? VisitConstructorInitializer(ConstructorInitializer constructorInitializer, T data); + S? VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, T data); + S? VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, T data); + S? VisitEventDeclaration(EventDeclaration eventDeclaration, T data); + S? VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration, T data); + S? VisitFieldDeclaration(FieldDeclaration fieldDeclaration, T data); + S? VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, T data); + S? VisitMethodDeclaration(MethodDeclaration methodDeclaration, T data); + S? VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, T data); + S? VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, T data); + S? VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, T data); + S? VisitVariableInitializer(VariableInitializer variableInitializer, T data); + S? VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, T data); + S? VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, T data); + + S? VisitSyntaxTree(SyntaxTree syntaxTree, T data); + S? VisitSimpleType(SimpleType simpleType, T data); + S? VisitMemberType(MemberType memberType, T data); + S? VisitTupleType(TupleAstType tupleType, T data); + S? VisitTupleTypeElement(TupleTypeElement tupleTypeElement, T data); + S? VisitFunctionPointerType(FunctionPointerAstType functionPointerType, T data); + S? VisitInvocationType(InvocationAstType invocationType, T data); + S? VisitComposedType(ComposedType composedType, T data); + S? VisitArraySpecifier(ArraySpecifier arraySpecifier, T data); + S? VisitPrimitiveType(PrimitiveType primitiveType, T data); + + S? VisitComment(Comment comment, T data); + S? VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective, T data); + S? VisitDocumentationReference(DocumentationReference documentationReference, T data); + + S? VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration, T data); + S? VisitConstraint(Constraint constraint, T data); + S? VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode, T data); + S? VisitIdentifier(Identifier identifier, T data); + + S? VisitInterpolation(Interpolation interpolation, T data); + S? VisitInterpolatedStringText(InterpolatedStringText interpolatedStringText, T data); + + S? VisitSingleVariableDesignation(SingleVariableDesignation singleVariableDesignation, T data); + S? VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignation parenthesizedVariableDesignation, T data); + + S? VisitNullNode(AstNode nullNode, T data); + S? VisitErrorNode(AstNode errorNode, T data); + S? VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern, T data); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs index 327204e3eb..d3a68e43dd 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs @@ -25,7 +25,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching /// public interface INode { - Role Role { get; } + Role? Role { get; } INode? FirstChild { get; } INode? NextSibling { get; } bool IsNull { get; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs index 7e02f50631..b196d94832 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs @@ -52,15 +52,15 @@ bool INode.IsNull { get { return false; } } - Role INode.Role { + Role? INode.Role { get { return null; } } - INode INode.NextSibling { + INode? INode.NextSibling { get { return null; } } - INode INode.FirstChild { + INode? INode.FirstChild { get { return null; } } @@ -80,8 +80,8 @@ public static bool DoMatchCollection(Role role, INode firstPatternChild, INode f stack.Push(new PossibleMatch(firstOtherChild, match.CheckPoint())); while (stack.Count > 0) { - INode cur1 = patternStack.Pop(); - INode cur2 = stack.Peek().NextOther; + INode? cur1 = patternStack.Pop(); + INode? cur2 = stack.Peek().NextOther; match.RestoreCheckPoint(stack.Pop().Checkpoint); bool success = true; while (cur1 != null && success) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs index a99c60be07..2faf4150b7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs @@ -44,7 +44,7 @@ public Repeat(INode childNode) this.MaxCount = int.MaxValue; } - public override bool DoMatchCollection(Role role, INode pos, Match match, BacktrackingInfo backtrackingInfo) + public override bool DoMatchCollection(Role role, INode? pos, Match match, BacktrackingInfo backtrackingInfo) { var backtrackingStack = backtrackingInfo.backtrackingStack; Debug.Assert(pos == null || pos.Role == role); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs index 959431ad5a..75ecaad58e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs @@ -63,7 +63,7 @@ protected internal override bool DoMatch(AstNode? other, PatternMatching.Match m #endregion #region PatternPlaceholder - public static implicit operator Statement(PatternMatching.Pattern pattern) + public static implicit operator Statement?(PatternMatching.Pattern? pattern) { return pattern != null ? new PatternPlaceholder(pattern) : null; } @@ -86,12 +86,12 @@ public override void AcceptVisitor(IAstVisitor visitor) visitor.VisitPatternPlaceholder(this, child); } - public override T AcceptVisitor(IAstVisitor visitor) + public override T? AcceptVisitor(IAstVisitor visitor) { return visitor.VisitPatternPlaceholder(this, child); } - public override S AcceptVisitor(IAstVisitor visitor, T data) + public override S? AcceptVisitor(IAstVisitor visitor, T data) { return visitor.VisitPatternPlaceholder(this, child, data); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs index 8d6cc4bc6e..41a506d311 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs @@ -54,7 +54,7 @@ public static bool IsBitwise(this BinaryOperatorType operatorType) public static Statement GetNextStatement(this Statement statement) { - AstNode next = statement.NextSibling; + AstNode? next = statement.NextSibling; while (next != null && !(next is Statement)) next = next.NextSibling; return (Statement)next; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs index 8b37f582c8..890666c8e1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs @@ -76,7 +76,7 @@ public override SymbolKind SymbolKind { /// public CSharpTokenNode Keyword { get { - for (AstNode child = this.FirstChild; child != null; child = child.NextSibling) + for (AstNode? child = this.FirstChild; child != null; child = child.NextSibling) { if (child.Role == PropertyDeclaration.GetKeywordRole || child.Role == PropertyDeclaration.SetKeywordRole || child.Role == PropertyDeclaration.InitKeywordRole diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs index 28cfb07983..5507fbc756 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs @@ -89,7 +89,7 @@ internal static Modifiers GetModifiers(AstNode node) internal static void SetModifiers(AstNode node, Modifiers newValue) { Modifiers oldValue = GetModifiers(node); - AstNode insertionPos = node.GetChildrenByRole(AttributeRole).LastOrDefault(); + AstNode? insertionPos = node.GetChildrenByRole(AttributeRole).LastOrDefault(); foreach (Modifiers m in CSharpModifierToken.AllModifiers) { if ((m & newValue) != 0) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs index bb86a18fd0..dd6666a03b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs @@ -70,7 +70,7 @@ public BlockStatement Body { public bool IsExtensionMethod { get { - ParameterDeclaration pd = (ParameterDeclaration)GetChildByRole(Roles.Parameter); + ParameterDeclaration? pd = GetChildByRole(Roles.Parameter) as ParameterDeclaration; return pd != null && pd.HasThisModifier; } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs index 4c88b0eb40..cc70cac437 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs @@ -462,13 +462,13 @@ AstType ConvertTypeHelper(IType type) AstType ConvertTypeHelper(IType genericType, IReadOnlyList typeArguments) { - ITypeDefinition typeDef = genericType.GetDefinition(); + ITypeDefinition? typeDef = genericType.GetDefinition(); Debug.Assert(typeDef != null || genericType.Kind == TypeKind.Unknown); Debug.Assert(typeArguments.Count >= genericType.TypeParameterCount); if (UseKeywordsForBuiltinTypes && typeDef != null) { - string keyword = KnownTypeReference.GetCSharpNameByTypeCode(typeDef.KnownTypeCode); + string? keyword = KnownTypeReference.GetCSharpNameByTypeCode(typeDef.KnownTypeCode); if (keyword != null) { return new PrimitiveType(keyword); @@ -1053,7 +1053,7 @@ public Expression ConvertConstantValue(IType expectedType, IType type, object co } if (underlyingType.IsKnownType(KnownTypeCode.Double) || underlyingType.IsKnownType(KnownTypeCode.Single)) return ConvertFloatingPointLiteral(underlyingType, constantValue); - IType literalType = underlyingType; + IType? literalType = underlyingType; bool integerTypeMismatch = underlyingType.IsCSharpSmallIntegerType() || underlyingType.IsCSharpNativeIntegerType(); if (integerTypeMismatch) { @@ -1213,7 +1213,7 @@ bool IsFlagsEnum(ITypeDefinition type) Expression ConvertEnumValue(IType type, long val) { - ITypeDefinition enumDefinition = type.GetDefinition(); + ITypeDefinition? enumDefinition = type.GetDefinition(); TypeCode enumBaseTypeCode = ReflectionHelper.GetTypeCode(enumDefinition.EnumUnderlyingType); var fields = enumDefinition.Fields .Select(PrepareConstant) @@ -1295,7 +1295,7 @@ Expression ConvertEnumValue(IType type, long val) { if (!field.IsConst) return (-1, null); - object constantValue = field.GetConstantValue(); + object? constantValue = field.GetConstantValue(); if (constantValue == null) return (-1, null); return ((long)CSharpPrimitiveCast.Cast(TypeCode.Int64, constantValue, checkForOverflow: false), field); @@ -1890,7 +1890,7 @@ EntityDeclaration ConvertTypeDefinition(ITypeDefinition typeDefinition) DelegateDeclaration ConvertDelegate(IMethod invokeMethod, Modifiers modifiers) { - ITypeDefinition d = invokeMethod.DeclaringTypeDefinition; + ITypeDefinition? d = invokeMethod.DeclaringTypeDefinition; DelegateDeclaration decl = new DelegateDeclaration(); decl.Modifiers = modifiers & ~Modifiers.Sealed; @@ -2019,7 +2019,7 @@ Accessor ConvertAccessor(IMethod accessor, MethodSemanticsAttributes kind, Acces decl.Modifiers = ModifierFromAccessibility(accessor.Accessibility); if (this.ShowModifiers && accessor.HasReadonlyModifier()) decl.Modifiers |= Modifiers.Readonly; - TokenRole keywordRole = kind switch { + TokenRole? keywordRole = kind switch { MethodSemanticsAttributes.Getter => PropertyDeclaration.GetKeywordRole, MethodSemanticsAttributes.Setter => PropertyDeclaration.SetKeywordRole, MethodSemanticsAttributes.Adder => CustomEventDeclaration.AddKeywordRole, @@ -2460,7 +2460,7 @@ internal Constraint ConvertTypeParameterConstraint(ITypeParameter tp) static bool IsObjectOrValueType(IType type) { - ITypeDefinition d = type.GetDefinition(); + ITypeDefinition? d = type.GetDefinition(); return d != null && (d.KnownTypeCode == KnownTypeCode.Object || d.KnownTypeCode == KnownTypeCode.ValueType); } #endregion diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs b/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs index 8cf6280758..eb181384f6 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs @@ -244,7 +244,7 @@ public void Run(AstNode node, TransformContext context) BlockStatement? block = node as BlockStatement; if (block == null) { - for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) + for (AstNode? child = node.FirstChild; child != null; child = child.NextSibling) { Run(child, context); } @@ -275,7 +275,7 @@ Result GetResultFromBlock(BlockStatement block) InsertedNode? nodesUncheckedContextCheckedBlockOpen = null; Statement? checkedBlockStart = null; - Statement statement = block.Statements.FirstOrDefault(); + Statement? statement = block.Statements.FirstOrDefault(); while (true) { // Blocks can be closed 'for free'. We use '<=' so that blocks are closed as late as possible (goal 4b) @@ -340,7 +340,7 @@ Result GetResult(AstNode node) if (node is BlockStatement) return GetResultFromBlock((BlockStatement)node); Result result = new Result(); - for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) + for (AstNode? child = node.FirstChild; child != null; child = child.NextSibling) { Result childResult = GetResult(child); result.CostInCheckedContext += childResult.CostInCheckedContext; diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs b/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs index b3f02dee0c..4a76fbb98d 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs @@ -63,7 +63,7 @@ public void Run(AstNode rootNode, TransformContext context) static void InsertXmlDocumentation(AstNode node, StringReader r) { // Find the first non-empty line: - string firstLine; + string? firstLine; do { firstLine = r.ReadLine(); @@ -71,7 +71,7 @@ static void InsertXmlDocumentation(AstNode node, StringReader r) return; } while (string.IsNullOrWhiteSpace(firstLine)); string indentation = firstLine.Substring(0, firstLine.Length - firstLine.TrimStart().Length); - string line = firstLine; + string? line = firstLine; int skippedWhitespaceLines = 0; // Copy all lines from input to output, except for empty lines at the end. while (line != null) diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs index 1d9002811c..842f16103f 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs @@ -47,8 +47,8 @@ public void Run(AstNode rootNode, TransformContext context) void CombineQueries(AstNode node, Dictionary fromOrLetIdentifiers) { - AstNode next; - for (AstNode child = node.FirstChild; child != null; child = next) + AstNode? next; + for (AstNode? child = node.FirstChild; child != null; child = next) { // store reference to next child before transformation next = child.NextSibling; diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs index 7756a26cda..d73ed5ef01 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs @@ -297,7 +297,7 @@ void FindInsertionPoints(AstNode node, int nodeLevel) } try { - for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) + for (AstNode? child = node.FirstChild; child != null; child = child.NextSibling) { FindInsertionPoints(child, nodeLevel + 1); } @@ -321,7 +321,7 @@ void FindInsertionPointForVariable(ILVariable variable) { InsertionPoint newPoint; int startIndex = scopeTracking.Count - 1; - BlockContainer captureScope = variable.CaptureScope; + BlockContainer? captureScope = variable.CaptureScope; while (captureScope != null && !IsRelevantScope(captureScope)) { captureScope = BlockContainer.FindClosestContainer(captureScope.Parent); @@ -356,7 +356,7 @@ void FindInsertionPointForVariable(ILVariable variable) } } } - if (variableDict.TryGetValue(variable, out VariableToDeclare v)) + if (variableDict.TryGetValue(variable, out VariableToDeclare? v)) { v.InsertionPoint = FindCommonParent(v.InsertionPoint, newPoint); } diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs index 4048df940d..b5edb964d8 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs @@ -67,8 +67,8 @@ public void Run(AstNode rootNode, TransformContext context) { if (node is IdentifierExpression || node is MemberReferenceExpression) { - ISymbol symbol = node.GetSymbol(); - if (symbol != null && renamedSymbols.TryGetValue(symbol, out string newName)) + ISymbol? symbol = node.GetSymbol(); + if (symbol != null && renamedSymbols.TryGetValue(symbol, out string? newName)) { node.GetChildByRole(Roles.Identifier).Name = newName; } diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs index dc1bc4794f..457b5331a5 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs @@ -88,8 +88,8 @@ void DecompileQueries(AstNode node) node.ReplaceWith(query); } - AstNode next; - for (AstNode child = (query ?? node).FirstChild; child != null; child = next) + AstNode? next; + for (AstNode? child = (query ?? node).FirstChild; child != null; child = next) { // store reference to next child before transformation next = child.NextSibling; @@ -103,7 +103,7 @@ bool CanUseDiscardAssignment() return context.Settings.Discards; } - QueryExpression DecompileQuery(InvocationExpression invocation) + QueryExpression? DecompileQuery(InvocationExpression? invocation) { if (invocation == null) return null; @@ -119,7 +119,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) if (!IsComplexQuery(mre)) return null; Expression expr = invocation.Arguments.Single(); - if (MatchSimpleLambda(expr, out ParameterDeclaration parameter, out Expression body)) + if (MatchSimpleLambda(expr, out ParameterDeclaration? parameter, out Expression? body)) { QueryExpression query = new QueryExpression(); query.Clauses.Add(MakeFromClause(parameter, mre.Target.Detach())); @@ -134,8 +134,8 @@ QueryExpression DecompileQuery(InvocationExpression invocation) { Expression keyLambda = invocation.Arguments.ElementAt(0); Expression projectionLambda = invocation.Arguments.ElementAt(1); - if (MatchSimpleLambda(keyLambda, out ParameterDeclaration parameter1, out Expression keySelector) - && MatchSimpleLambda(projectionLambda, out ParameterDeclaration parameter2, out Expression elementSelector) + if (MatchSimpleLambda(keyLambda, out ParameterDeclaration? parameter1, out Expression? keySelector) + && MatchSimpleLambda(projectionLambda, out ParameterDeclaration? parameter2, out Expression? elementSelector) && parameter1.Name == parameter2.Name) { QueryExpression query = new QueryExpression(); @@ -152,7 +152,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) else if (invocation.Arguments.Count == 1) { Expression lambda = invocation.Arguments.Single(); - if (MatchSimpleLambda(lambda, out ParameterDeclaration parameter, out Expression keySelector)) + if (MatchSimpleLambda(lambda, out ParameterDeclaration? parameter, out Expression? keySelector)) { QueryExpression query = new QueryExpression(); query.Clauses.Add(MakeFromClause(parameter, mre.Target.Detach())); @@ -167,7 +167,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) if (invocation.Arguments.Count != 2) return null; var fromExpressionLambda = invocation.Arguments.ElementAt(0); - if (!MatchSimpleLambda(fromExpressionLambda, out ParameterDeclaration parameter, out Expression collectionSelector)) + if (!MatchSimpleLambda(fromExpressionLambda, out ParameterDeclaration? parameter, out Expression? collectionSelector)) return null; if (IsNullConditional(collectionSelector)) return null; @@ -194,7 +194,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) if (!IsComplexQuery(mre)) return null; Expression expr = invocation.Arguments.Single(); - if (MatchSimpleLambda(expr, out ParameterDeclaration parameter, out Expression body)) + if (MatchSimpleLambda(expr, out ParameterDeclaration? parameter, out Expression? body)) { QueryExpression query = new QueryExpression(); query.Clauses.Add(MakeFromClause(parameter, mre.Target.Detach())); @@ -213,7 +213,7 @@ QueryExpression DecompileQuery(InvocationExpression invocation) if (!IsComplexQuery(mre)) return null; var lambda = invocation.Arguments.Single(); - if (MatchSimpleLambda(lambda, out ParameterDeclaration parameter, out Expression orderExpression)) + if (MatchSimpleLambda(lambda, out ParameterDeclaration? parameter, out Expression? orderExpression)) { if (ValidateThenByChain(invocation, parameter.Name)) { @@ -257,10 +257,10 @@ QueryExpression DecompileQuery(InvocationExpression invocation) if (IsNullConditional(source2)) return null; Expression outerLambda = invocation.Arguments.ElementAt(1); - if (!MatchSimpleLambda(outerLambda, out ParameterDeclaration element1, out Expression key1)) + if (!MatchSimpleLambda(outerLambda, out ParameterDeclaration? element1, out Expression? key1)) return null; Expression innerLambda = invocation.Arguments.ElementAt(2); - if (!MatchSimpleLambda(innerLambda, out ParameterDeclaration element2, out Expression key2)) + if (!MatchSimpleLambda(innerLambda, out ParameterDeclaration? element2, out Expression? key2)) return null; LambdaExpression? lambda = invocation.Arguments.ElementAt(3) as LambdaExpression; if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs index d4456e9525..114e60dafa 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs @@ -62,7 +62,7 @@ protected override AstNode VisitChildren(AstNode node) // Go through the children, and keep visiting a node as long as it changes. // Because some transforms delete/replace nodes before and after the node being transformed, we rely // on the transform's return value to know where we need to keep iterating. - for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) + for (AstNode? child = node.FirstChild; child != null; child = child.NextSibling) { AstNode oldChild; do @@ -88,7 +88,7 @@ public override AstNode VisitExpressionStatement(ExpressionStatement expressionS public override AstNode VisitForStatement(ForStatement forStatement) { - AstNode result = TransformForeachOnArray(forStatement); + AstNode? result = TransformForeachOnArray(forStatement); if (result != null) return result; return base.VisitForStatement(forStatement); @@ -174,7 +174,7 @@ public override AstNode VisitTryCatchStatement(TryCatchStatement tryCatchStateme } }; - public ForStatement TransformFor(ExpressionStatement node) + public ForStatement? TransformFor(ExpressionStatement node) { if (!context.Settings.ForStatement) return null; @@ -339,7 +339,7 @@ static bool AddressUsedForSingleCall(IL.ILVariable v, IL.BlockContainer loop) return false; } - Statement TransformForeachOnArray(ForStatement forStatement) + Statement? TransformForeachOnArray(ForStatement forStatement) { if (!context.Settings.ForEachStatement) return null; diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs index 219f671ca2..5ac5dba868 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs @@ -206,7 +206,7 @@ record = null; Match m = fieldInitializerPattern.Match(instanceCtorsNotChainingWithThis[0].Body.FirstOrDefault()); if (!m.Success) break; - IMember fieldOrPropertyOrEvent = (m.Get("fieldAccess").Single().GetSymbol() as IMember)?.MemberDefinition; + IMember? fieldOrPropertyOrEvent = (m.Get("fieldAccess").Single().GetSymbol() as IMember)?.MemberDefinition; if (!(fieldOrPropertyOrEvent is IField) && !(fieldOrPropertyOrEvent is IProperty) && !(fieldOrPropertyOrEvent is IEvent)) break; var fieldOrPropertyOrEventDecl = members.FirstOrDefault(f => f.GetSymbol() == fieldOrPropertyOrEvent) as EntityDeclaration; @@ -346,7 +346,7 @@ void HandleStaticFieldInitializers(IEnumerable members) AssignmentExpression? assignment = es.Expression as AssignmentExpression; if (assignment == null || assignment.Operator != AssignmentOperatorType.Assign) break; - IMember fieldOrProperty = (assignment.Left.GetSymbol() as IMember)?.MemberDefinition; + IMember? fieldOrProperty = (assignment.Left.GetSymbol() as IMember)?.MemberDefinition; if (!(fieldOrProperty is IField || fieldOrProperty is IProperty) || !fieldOrProperty.IsStatic) break; // Only move fields that are constants, if the declaring type is not marked beforefieldinit. diff --git a/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs b/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs index 680dbd88c2..8ad8b704cc 100644 --- a/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs @@ -156,7 +156,7 @@ public TranslatedExpression UnwrapChild(Expression descendant) { if (descendant == Expression) return this; - for (AstNode parent = descendant.Parent; parent != null; parent = parent.Parent) + for (AstNode? parent = descendant.Parent; parent != null; parent = parent.Parent) { foreach (var inst in parent.Annotations.OfType()) descendant.AddAnnotation(inst); diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs index c6e10cfbd0..87441be6e3 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs @@ -70,7 +70,7 @@ public UsingScope UnresolvedUsingScope { public INamespace Namespace { get { - INamespace result = LazyInit.VolatileRead(ref this.@namespace); + INamespace? result = LazyInit.VolatileRead(ref this.@namespace); if (result != null) { return result; diff --git a/ICSharpCode.Decompiler/DecompilerException.cs b/ICSharpCode.Decompiler/DecompilerException.cs index d536148b4f..412a1d395b 100644 --- a/ICSharpCode.Decompiler/DecompilerException.cs +++ b/ICSharpCode.Decompiler/DecompilerException.cs @@ -98,7 +98,7 @@ string ToString(Exception exception) static string GetTypeName(Exception exception) { - string type = exception.GetType().FullName; + string? type = exception.GetType().FullName; if (exception is ExternalException || exception is IOException) return type + " (" + Marshal.GetHRForException(exception).ToString("x8") + ")"; else @@ -114,8 +114,8 @@ static string GetStackTrace(Exception exception) StringBuilder b = new StringBuilder(); for (int i = 0; i < stackTrace.FrameCount; i++) { - StackFrame frame = stackTrace.GetFrame(i); - MethodBase method = frame.GetMethod(); + StackFrame? frame = stackTrace.GetFrame(i); + MethodBase? method = frame.GetMethod(); if (method == null) continue; @@ -123,7 +123,7 @@ static string GetStackTrace(Exception exception) b.AppendLine(); b.Append(" at "); - Type declaringType = method.DeclaringType; + Type? declaringType = method.DeclaringType; if (declaringType != null) { b.Append(declaringType.FullName.Replace('+', '.')); @@ -173,7 +173,7 @@ static string GetStackTrace(Exception exception) string? filename = null; try { - string fullpath = frame.GetFileName(); + string? fullpath = frame.GetFileName(); if (fullpath != null) filename = Path.GetFileName(fullpath); } diff --git a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs index 9815de4d60..9e130ead26 100644 --- a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs @@ -1040,10 +1040,10 @@ void WriteNativeType(ref BlobReader blob) output.Write("lpstruct"); break; case 0x2c: // CustomMarshaler - string guidValue = blob.ReadSerializedString(); - string unmanagedType = blob.ReadSerializedString(); - string managedType = blob.ReadSerializedString(); - string cookie = blob.ReadSerializedString(); + string? guidValue = blob.ReadSerializedString(); + string? unmanagedType = blob.ReadSerializedString(); + string? managedType = blob.ReadSerializedString(); + string? cookie = blob.ReadSerializedString(); var guid = !string.IsNullOrEmpty(guidValue) ? new Guid(guidValue) : Guid.Empty; diff --git a/ICSharpCode.Decompiler/Documentation/GetPotentiallyNestedClassTypeReference.cs b/ICSharpCode.Decompiler/Documentation/GetPotentiallyNestedClassTypeReference.cs index 754fe1f9a7..8422b93a17 100644 --- a/ICSharpCode.Decompiler/Documentation/GetPotentiallyNestedClassTypeReference.cs +++ b/ICSharpCode.Decompiler/Documentation/GetPotentiallyNestedClassTypeReference.cs @@ -57,7 +57,7 @@ public IType Resolve(ITypeResolveContext context) { if (asm == null) continue; - ITypeDefinition typeDef = asm.GetTypeDefinition(new TopLevelTypeName(ns, name, topLevelTPC)); + ITypeDefinition? typeDef = asm.GetTypeDefinition(new TopLevelTypeName(ns, name, topLevelTPC)); for (int j = i + 1; j < parts.Length && typeDef != null; j++) { int tpc = (j == parts.Length - 1 ? typeParameterCount : 0); diff --git a/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs b/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs index 64c3ec881f..59000a1f99 100644 --- a/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs +++ b/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs @@ -155,7 +155,7 @@ static void AppendTypeName(StringBuilder b, IType type, bool explicitInterfaceIm b.Append('@'); break; default: - IType declType = type.DeclaringType; + IType? declType = type.DeclaringType; if (declType != null) { AppendTypeName(b, declType, explicitInterfaceImpl); diff --git a/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs index 3d4c9ce6cd..de2b116f0f 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs @@ -54,7 +54,7 @@ public static XmlDocumentationProvider LoadDocumentation(MetadataFile module) throw new ArgumentNullException(nameof(module)); lock (cache) { - if (!cache.TryGetValue(module, out XmlDocumentationProvider xmlDoc)) + if (!cache.TryGetValue(module, out XmlDocumentationProvider? xmlDoc)) { string xmlDocFile = LookupLocalizedXmlDoc(module.FileName); if (xmlDocFile == null) diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs index 5e71463ee9..68459498d3 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs @@ -1084,8 +1084,8 @@ private void MatchCompleteCall(Block block, ref int pos) bool IsBuilderFieldOnThis(ILInstruction inst) { - IField field; - ILInstruction target; + IField? field; + ILInstruction? target; if (builderType.IsReferenceType == true) { // ldfld(StateMachine::<>t__builder, ldloc(this)) diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs index 147ce41429..031f0ff730 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs @@ -102,7 +102,7 @@ public static void Run(ILFunction function, ILTransformContext context) break; case SwitchSection jumpTableEntry: Debug.Assert(switchInstructionOpt == null || jumpTableEntry.Parent == switchInstructionOpt); - switchInstructionOpt = (SwitchInstruction)jumpTableEntry.Parent; + switchInstructionOpt = jumpTableEntry.Parent as SwitchInstruction; break; } @@ -142,7 +142,7 @@ public static void Run(ILFunction function, ILTransformContext context) if (result.NextBlockOrExitContainer is Block nextBlock && nextBlock.IncomingEdgeCount == 0) { List dependentBlocks = new List(); - Block current = nextBlock; + Block? current = nextBlock; do { @@ -201,8 +201,8 @@ private static void TransformAsyncThrowToThrow(ILTransformContext context, HashS { ILVariable? v = null; if (MatchExceptionCaptureBlock(context, block, - ref v, out StLoc typedExceptionVariableStore, - out Block captureBlock, out Block throwBlock)) + ref v, out StLoc? typedExceptionVariableStore, + out Block? captureBlock, out Block? throwBlock)) { context.Step($"ExceptionDispatchInfo.Capture({v.Name}).Throw() => throw;", typedExceptionVariableStore); block.Instructions.RemoveRange(typedExceptionVariableStore.ChildIndex + 1, 2); @@ -355,7 +355,7 @@ bool ParseSwitchJumpTable(int id, SwitchInstruction jumpTable, ILVariable identi return false; } - bool ParseIfJumpTable(int id, Block jumpTableEntryBlock, ILVariable identifierVariable, out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, out ILInstruction? jumpTableEntry) + bool ParseIfJumpTable(int id, Block jumpTableEntryBlock, ILVariable identifierVariable, [NotNullWhen(true)] out Block? realEntryPoint, out ILInstruction? nextBlockOrExitContainer, [NotNullWhen(true)] out ILInstruction? jumpTableEntry) { realEntryPoint = null; nextBlockOrExitContainer = null; @@ -420,7 +420,7 @@ bool ParseIfJumpTable(int id, Block jumpTableEntryBlock, ILVariable identifierVa // => // throw(ldloc result.Handler.Variable) internal static bool MatchExceptionCaptureBlock(ILTransformContext context, Block block, - ref ILVariable objectVariable, out StLoc? typedExceptionVariableStore, out Block? captureBlock, out Block? throwBlock) + ref ILVariable? objectVariable, out StLoc? typedExceptionVariableStore, out Block? captureBlock, out Block? throwBlock) { bool DerivesFromException(IType t) => t.GetAllBaseTypes().Any(ty => ty.IsKnownType(KnownTypeCode.Exception)); diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs index 7cccce8bde..e70846af5f 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs @@ -81,7 +81,7 @@ public static void Run(ILFunction function, ILTransformContext context) // stloc V_6(ldloc V_3) - store exception in 'global' object variable // br IL_0075 - jump out of catch block to the head of the finallyBlock var catchBlockEntry = catchBlockContainer.EntryPoint; - ILVariable objectVariable; + ILVariable? objectVariable; switch (catchBlockEntry.Instructions.Count) { case 2: @@ -127,7 +127,7 @@ public static void Run(ILFunction function, ILTransformContext context) StateRangeAnalysis sra = new StateRangeAnalysis(StateRangeAnalysisMode.AwaitInFinally, null, stateVariable); sra.AssignStateRanges(noThrowBlock, Util.LongSet.Universe); - var mapping = sra.GetBlockStateSetMapping((BlockContainer)noThrowBlock.Parent); + var mapping = sra.GetBlockStateSetMapping(noThrowBlock.Parent as BlockContainer); var mappingForLeave = sra.GetBlockStateSetMappingForLeave(); context.StepStartGroup("Inline finally block with await", tryCatch.Handlers[0]); diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs index 6276011fc7..265516c01f 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/ConditionDetection.cs @@ -45,9 +45,9 @@ private enum Keyword Other } - private BlockTransformContext context; - private ControlFlowNode cfgNode; - private BlockContainer currentContainer; + private BlockTransformContext? context; + private ControlFlowNode? cfgNode; + private BlockContainer? currentContainer; /// /// Builds structured control flow for the block associated with the control flow node. @@ -59,7 +59,7 @@ private enum Keyword public void Run(Block block, BlockTransformContext context) { this.context = context; - currentContainer = (BlockContainer)block.Parent; + currentContainer = block.Parent as BlockContainer; // We only embed blocks into this block if they aren't referenced anywhere else, // so those blocks are dominated by this block. diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs b/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs index 9dd4aa74fd..282e198fc2 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs @@ -120,11 +120,11 @@ void InlineVariableInReturnBlock(Block block, ILTransformContext context) // (where 'v' has no other uses) // Simplify these to a simple `ret()` so that they match the release build version. // - if (block.Instructions.Count == 2 && block.Instructions[1].MatchReturn(out ILInstruction value)) + if (block.Instructions.Count == 2 && block.Instructions[1].MatchReturn(out ILInstruction? value)) { var ret = (Leave)block.Instructions[1]; - if (value.MatchLdLoc(out ILVariable v) - && v.IsSingleDefinition && v.LoadCount == 1 && block.Instructions[0].MatchStLoc(v, out ILInstruction inst)) + if (value.MatchLdLoc(out ILVariable? v) + && v.IsSingleDefinition && v.LoadCount == 1 && block.Instructions[0].MatchStLoc(v, out ILInstruction? inst)) { context.Step("Inline variable in return block", block); inst.AddILRange(ret.Value); @@ -228,7 +228,7 @@ bool IsBranchToReturnBlock(Branch branch) if (!value.MatchLdLoc(out var returnVar)) return false; var container = branch.TargetContainer; - for (ILInstruction inst = branch; inst != container; inst = inst.Parent) + for (ILInstruction? inst = branch; inst != container; inst = inst.Parent) { if (inst.Parent is TryFinally tryFinally && inst.SlotInfo == TryFinally.TryBlockSlot) { diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs index 3674b323aa..53e5f2c1c5 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs @@ -106,7 +106,7 @@ void SplitBlocksAtWritesToPinnedLocals(BlockContainer container) for (int j = 0; j < block.Instructions.Count - 1; j++) { var inst = block.Instructions[j]; - if (inst.MatchStLoc(out ILVariable v, out var value) && v.Kind == VariableKind.PinnedLocal) + if (inst.MatchStLoc(out ILVariable? v, out var value) && v.Kind == VariableKind.PinnedLocal) { if (block.Instructions[j + 1].OpCode != OpCode.Branch) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs b/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs index 5f4171de96..22c064254a 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs @@ -88,9 +88,9 @@ bool CachedDelegateInitializationWithField(IfInstruction inst) if (trueInst == null || trueInst.Instructions.Count != 1 || !inst.FalseInst.MatchNop()) return false; var storeInst = trueInst.Instructions[0]; - if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdsFld(out IField field) || !right.MatchLdNull()) + if (!inst.Condition.MatchCompEquals(out ILInstruction? left, out ILInstruction? right) || !left.MatchLdsFld(out IField? field) || !right.MatchLdNull()) return false; - if (!storeInst.MatchStsFld(out IField field2, out ILInstruction value) || !field.Equals(field2) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass()) + if (!storeInst.MatchStsFld(out IField? field2, out ILInstruction? value) || !field.Equals(field2) || !field.IsCompilerGeneratedOrIsInCompilerGeneratedClass()) return false; if (!DelegateConstruction.MatchDelegateConstruction(value.UnwrapConv(ConversionKind.Invalid) as NewObj, out _, out _, out _, true)) return false; @@ -117,10 +117,10 @@ bool CachedDelegateInitializationWithLocal(IfInstruction inst) Block? trueInst = inst.TrueInst as Block; if (trueInst == null || (trueInst.Instructions.Count != 1) || !inst.FalseInst.MatchNop()) return false; - if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdLoc(out ILVariable v) || !right.MatchLdNull()) + if (!inst.Condition.MatchCompEquals(out ILInstruction? left, out ILInstruction? right) || !left.MatchLdLoc(out ILVariable? v) || !right.MatchLdNull()) return false; var storeInst = trueInst.Instructions.Last(); - if (!storeInst.MatchStLoc(v, out ILInstruction value)) + if (!storeInst.MatchStLoc(v, out ILInstruction? value)) return false; if (!DelegateConstruction.MatchDelegateConstruction(value as NewObj, out _, out _, out _, true)) return false; @@ -157,7 +157,7 @@ bool CachedDelegateInitializationRoslynInStaticWithLocal(IfInstruction inst) Block? trueInst = inst.TrueInst as Block; if (trueInst == null || (trueInst.Instructions.Count != 1) || !inst.FalseInst.MatchNop()) return false; - if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdLoc(out ILVariable s) || !right.MatchLdNull()) + if (!inst.Condition.MatchCompEquals(out ILInstruction? left, out ILInstruction? right) || !left.MatchLdLoc(out ILVariable? s) || !right.MatchLdNull()) return false; var storeInst = trueInst.Instructions.Last() as StLoc; var storeBeforeIf = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex - 1) as StLoc; @@ -189,7 +189,7 @@ bool CachedDelegateInitializationRoslynWithLocal(IfInstruction inst) Block? trueInst = inst.TrueInst as Block; if (trueInst == null || (trueInst.Instructions.Count != 1) || !inst.FalseInst.MatchNop()) return false; - if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !left.MatchLdLoc(out ILVariable s) || !right.MatchLdNull()) + if (!inst.Condition.MatchCompEquals(out ILInstruction? left, out ILInstruction? right) || !left.MatchLdLoc(out ILVariable? s) || !right.MatchLdNull()) return false; var storeInst = trueInst.Instructions.Last() as StLoc; var storeBeforeIf = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex - 1) as StLoc; @@ -240,7 +240,7 @@ bool CachedDelegateInitializationVB(IfInstruction inst) { return false; } - if (!inst.Condition.MatchCompEquals(out ILInstruction left, out ILInstruction right) || !right.MatchLdNull()) + if (!inst.Condition.MatchCompEquals(out ILInstruction? left, out ILInstruction? right) || !right.MatchLdNull()) return false; if (!ldobj.Match(left).Success) return false; @@ -311,7 +311,7 @@ bool CachedDelegateInitializationVBWithClosure(IfInstruction inst) { return false; } - if (!inst.Condition.MatchCompNotEqualsNull(out ILInstruction left)) + if (!inst.Condition.MatchCompNotEqualsNull(out ILInstruction? left)) return false; if (!ldobj.Match(left).Success) return false; diff --git a/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs b/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs index be27d32973..33e90a01e0 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs @@ -65,7 +65,7 @@ static void RunOnBlock(Block block, ILTransformContext context, HashSet instruct ExtensionMethods.Swap(ref firstBlockOrDefaultJump, ref nextCaseJump); } // match call to operator ==(string, string) - if (!MatchStringEqualityComparison(condition, out var switchValueVar, out string firstBlockValue, out bool isVBCompareString)) + if (!MatchStringEqualityComparison(condition, out var switchValueVar, out string? firstBlockValue, out bool isVBCompareString)) return false; if (isVBCompareString) { @@ -217,13 +217,13 @@ bool SimplifyCascadingIfStatements(InstructionCollection instruct return false; } - var values = new List<(string, ILInstruction)>(); - var uniqueValues = new HashSet(); + var values = new List<(string?, ILInstruction)>(); + var uniqueValues = new HashSet(); int numberOfUniqueMatchesWithCurrentVariable = 0; HashSet caseBlocks = new HashSet(); caseBlocks.Add((Block)instructions[i].Parent); - bool AddSwitchSection(string value, ILInstruction inst) + bool AddSwitchSection(string? value, ILInstruction inst) { if (!uniqueValues.Add(value)) return false; @@ -306,14 +306,14 @@ bool AddSwitchSection(string value, ILInstruction inst) } } // if instruction must be followed by a branch to the next case - if (!nextCaseJump.MatchBranch(out Block currentCaseBlock)) + if (!nextCaseJump.MatchBranch(out Block? currentCaseBlock)) return false; // extract all cases and add them to the values list. ILInstruction nextCaseBlock; do { - nextCaseBlock = MatchCaseBlock(currentCaseBlock, switchValueVar, out string value, out bool emptyStringEqualsNull, out ILInstruction block); - if (nextCaseBlock == null) + (nextCaseBlock, var block) = MatchCaseBlock(currentCaseBlock, switchValueVar, out string? value, out bool emptyStringEqualsNull); + if (nextCaseBlock == null || block == null) break; if (emptyStringEqualsNull && string.IsNullOrEmpty(value)) { @@ -474,7 +474,7 @@ bool SimplifyCSharp1CascadingIfStatements(InstructionCollection i return true; } - bool IsIsInternedCall(Call call, [NotNullWhen(true)] out ILInstruction? argument) + bool IsIsInternedCall(Call? call, [NotNullWhen(true)] out ILInstruction? argument) { if (call != null && call.Method.DeclaringType.IsKnownType(KnownTypeCode.String) @@ -504,19 +504,20 @@ bool IsIsInternedCall(Call call, [NotNullWhen(true)] out ILInstruction? argument /// The is updated if the value gets copied to a different variable. /// See comments below for more info. /// - ILInstruction? MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out string? value, out bool emptyStringEqualsNull, out ILInstruction? caseBlockOrLeave) + + (ILInstruction? NextBlock, ILInstruction? CaseBlockOrLeave) MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out string? value, out bool emptyStringEqualsNull) { value = null; - caseBlockOrLeave = null; + ILInstruction? caseBlockOrLeave = null; emptyStringEqualsNull = false; if (currentBlock.IncomingEdgeCount != 1 || currentBlock.Instructions.Count != 2) - return null; + return (null, null); if (!currentBlock.MatchIfAtEndOfBlock(out var condition, out var caseBlockBranch, out var nextBlockBranch)) - return null; + return (null, null); if (!MatchStringEqualityComparison(condition, switchVariable, out value, out bool isVBCompareString)) { - return null; + return (null, null); } if (isVBCompareString) { @@ -533,21 +534,21 @@ bool IsIsInternedCall(Call call, [NotNullWhen(true)] out ILInstruction? argument } else { - return null; + return (null, null); } if (nextBlockBranch.MatchBranch(out Block? nextBlock)) { // success - return nextBlock; + return (nextBlock, caseBlockOrLeave); } else if (nextBlockBranch.MatchLeave(out BlockContainer? blockContainer)) { // success - return blockContainer; + return (blockContainer, caseBlockOrLeave); } else { - return null; + return (null, caseBlockOrLeave); } } @@ -1030,20 +1031,20 @@ bool MatchRoslynSwitchOnString(InstructionCollection instructions return false; } - var stringValues = new List<(string Value, ILInstruction TargetBlockOrLeave)>(); + var stringValues = new List<(string? Value, ILInstruction TargetBlockOrLeave)>(); SwitchSection defaultSection = switchInst.GetDefaultSection(); - if (!(defaultSection.Body.MatchBranch(out Block exitOrDefaultBlock) || defaultSection.Body.MatchLeave(out _))) + if (!(defaultSection.Body.MatchBranch(out Block? exitOrDefaultBlock) || defaultSection.Body.MatchLeave(out _))) return false; foreach (var section in switchInst.Sections) { if (section == defaultSection) continue; // extract target block - if (!section.Body.MatchBranch(out Block target)) + if (!section.Body.MatchBranch(out Block? target)) return false; - string stringValue; + string? stringValue; bool emptyStringEqualsNull; - if (MatchRoslynEmptyStringCaseBlockHead(target, switchValueLoad.Variable, out ILInstruction targetOrLeave, out Block currentExitBlock)) + if (MatchRoslynEmptyStringCaseBlockHead(target, switchValueLoad.Variable, out ILInstruction? targetOrLeave, out Block? currentExitBlock)) { stringValue = ""; emptyStringEqualsNull = false; @@ -1168,7 +1169,7 @@ private bool MatchRoslynSwitchOnStringUsingLengthAndChar(Block block, int i) // implements https://github.com/dotnet/roslyn/pull/66081 // if (comp(ldloc switchValueVar == ldnull)) br nullCase // br nextBlock - Block switchOnLengthBlock; + Block? switchOnLengthBlock; int switchOnLengthBlockStartOffset; Block? nullCase = null; if (instructions[i].MatchIfInstruction(out var condition, out var exitBlockJump) @@ -1206,7 +1207,7 @@ private bool MatchRoslynSwitchOnStringUsingLengthAndChar(Block block, int i) Block? defaultCase = null; if (!MatchSwitchOnLengthBlock(ref switchValueVar, switchOnLengthBlock, switchOnLengthBlockStartOffset, out var blocksByLength)) return false; - List<(string, ILInstruction)> stringValues = new(); + List<(string?, ILInstruction)> stringValues = new(); foreach (var b in blocksByLength) { if (b.Length.Count() != 1) @@ -1231,7 +1232,7 @@ private bool MatchRoslynSwitchOnStringUsingLengthAndChar(Block block, int i) } } } - else if (MatchRoslynCaseBlockHead(b.TargetBlock, switchValueVar, out var bodyOrLeave, out var exit, out string stringValue, out _)) + else if (MatchRoslynCaseBlockHead(b.TargetBlock, switchValueVar, out var bodyOrLeave, out var exit, out string? stringValue, out _)) { if (exit != defaultCase) return false; @@ -1269,7 +1270,7 @@ private bool MatchRoslynSwitchOnStringUsingLengthAndChar(Block block, int i) context.Step(nameof(MatchRoslynSwitchOnStringUsingLengthAndChar), instructions[i]); var defaultLabel = new LongSet(new LongInterval(0, stringValues.Count)).Invert(); - var values = new string[stringValues.Count]; + var values = new string?[stringValues.Count]; var sections = new SwitchSection[stringValues.Count]; foreach (var (idx, (value, bodyInstruction)) in stringValues.WithIndex()) { @@ -1400,7 +1401,7 @@ bool MatchSwitchOnCharBlock(Block block, int length, ILVariable switchValueVar, return results?.Count > 0; } - bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengthBlock, int startOffset, [NotNullWhen(true)] out List<(LongSet Length, Block TargetBlock)>? blocks) + bool MatchSwitchOnLengthBlock(ref ILVariable? switchValueVar, Block switchOnLengthBlock, int startOffset, out List<(LongSet Length, Block TargetBlock)>? blocks) { blocks = null; SwitchInstruction? @switch; @@ -1476,6 +1477,7 @@ bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengt default: return false; } + if (@switch == null) return true; blocks = new(@switch.Sections.Count); @@ -1507,7 +1509,7 @@ bool MatchSwitchOnLengthBlock(ref ILVariable switchValueVar, Block switchOnLengt /// br newDefaultBlock /// } /// - private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable switchVar, [NotNullWhen(true)] out Block? nullValueCaseBlock) + private bool IsNullCheckInDefaultBlock(ref Block? exitOrDefaultBlock, ILVariable switchVar, [NotNullWhen(true)] out Block? nullValueCaseBlock) { nullValueCaseBlock = null; if (exitOrDefaultBlock == null) @@ -1533,7 +1535,7 @@ private bool IsNullCheckInDefaultBlock(ref Block exitOrDefaultBlock, ILVariable /// if (call op_Equality(ldloc switchValueVar, stringValue)) br body /// br exit /// - bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, [NotNullWhen(true)] out ILInstruction? bodyOrLeave, [NotNullWhen(true)] out Block? defaultOrExitBlock, [NotNullWhen(true)] out string? stringValue, out bool emptyStringEqualsNull) + bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, [NotNullWhen(true)] out ILInstruction? bodyOrLeave, out Block? defaultOrExitBlock, out string? stringValue, out bool emptyStringEqualsNull) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1593,7 +1595,7 @@ bool MatchRoslynCaseBlockHead(Block target, ILVariable switchValueVar, [NotNullW /// br exit /// } /// - bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar, [NotNullWhen(true)] out ILInstruction? bodyOrLeave, [NotNullWhen(true)] out Block? defaultOrExitBlock) + bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar, [NotNullWhen(true)] out ILInstruction? bodyOrLeave, out Block? defaultOrExitBlock) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1628,6 +1630,7 @@ bool MatchRoslynEmptyStringCaseBlockHead(Block target, ILVariable switchValueVar return false; if (bodyBranch.MatchLeave(out _)) { + bodyOrLeave = bodyBranch; return true; } diff --git a/ICSharpCode.Decompiler/Semantics/ConstantResolveResult.cs b/ICSharpCode.Decompiler/Semantics/ConstantResolveResult.cs index d475de1aee..5336def6ca 100644 --- a/ICSharpCode.Decompiler/Semantics/ConstantResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/ConstantResolveResult.cs @@ -32,9 +32,9 @@ namespace ICSharpCode.Decompiler.Semantics /// public class ConstantResolveResult : ResolveResult { - object constantValue; + object? constantValue; - public ConstantResolveResult(IType type, object constantValue) : base(type) + public ConstantResolveResult(IType type, object? constantValue) : base(type) { this.constantValue = constantValue; } @@ -43,7 +43,7 @@ public override bool IsCompileTimeConstant { get { return true; } } - public override object ConstantValue { + public override object? ConstantValue { get { return constantValue; } } diff --git a/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs b/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs index 8a55aa119e..b7309ba738 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs @@ -227,7 +227,7 @@ public static ITypeReference ToTypeReference(this TypeCode typeCode) /// /// Gets the type code for the specified type, or TypeCode.Empty if none of the other type codes match. /// - public static TypeCode GetTypeCode(this IType type) + public static TypeCode GetTypeCode(this IType? type) { ITypeDefinition? def = type as ITypeDefinition; if (def != null) diff --git a/ICSharpCode.Decompiler/TypeSystem/TaskType.cs b/ICSharpCode.Decompiler/TypeSystem/TaskType.cs index 76db1389ee..2ab3a2fcac 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TaskType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TaskType.cs @@ -74,8 +74,8 @@ public static bool IsCustomTask(IType type, [NotNullWhen(true)] out IType? build var arg = attribute.FixedArguments[0]; if (!arg.Type.IsKnownType(KnownTypeCode.Type)) return false; - builderType = (IType)arg.Value; - return true; + builderType = arg.Value as IType; + return builderType != null; } return false; } diff --git a/ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs b/ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs index ecb1e25d14..85d85fdcc9 100644 --- a/ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs +++ b/ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs @@ -35,7 +35,7 @@ namespace ILSpy.BamlDecompiler [PartCreationPolicy(CreationPolicy.Shared)] public sealed class BamlResourceNodeFactory : IResourceNodeFactory { - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { if (resource.Name.EndsWith(".baml", StringComparison.OrdinalIgnoreCase)) return new BamlResourceEntryNode(resource.Name, resource.TryOpenStream); diff --git a/ILSpy/Languages/ILAstLanguage.cs b/ILSpy/Languages/ILAstLanguage.cs index b0f467b4b5..c3fa7755b4 100644 --- a/ILSpy/Languages/ILAstLanguage.cs +++ b/ILSpy/Languages/ILAstLanguage.cs @@ -39,9 +39,9 @@ namespace ICSharpCode.ILSpy /// abstract class ILAstLanguage : Language { - public event EventHandler StepperUpdated; + public event EventHandler? StepperUpdated; - protected virtual void OnStepperUpdated(EventArgs e = null) + protected virtual void OnStepperUpdated(EventArgs? e = null) { StepperUpdated?.Invoke(this, e ?? new EventArgs()); } diff --git a/ILSpy/MainWindow.xaml.cs b/ILSpy/MainWindow.xaml.cs index 235594f7a9..21271efeb7 100644 --- a/ILSpy/MainWindow.xaml.cs +++ b/ILSpy/MainWindow.xaml.cs @@ -44,6 +44,7 @@ using ICSharpCode.Decompiler.TypeSystem.Implementation; using ICSharpCode.ILSpy.AppEnv; using ICSharpCode.ILSpy.Commands; +using ICSharpCode.ILSpy.Controls.TreeView; using ICSharpCode.ILSpy.Docking; using ICSharpCode.ILSpy.Options; using ICSharpCode.ILSpy.Search; @@ -51,16 +52,15 @@ using ICSharpCode.ILSpy.Themes; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpy.Updates; +using ICSharpCode.ILSpy.Util; using ICSharpCode.ILSpy.ViewModels; using ICSharpCode.ILSpyX; +using ICSharpCode.ILSpyX.Extensions; using ICSharpCode.ILSpyX.FileLoaders; using ICSharpCode.ILSpyX.Settings; -using ICSharpCode.ILSpy.Controls.TreeView; -using ICSharpCode.ILSpy.Util; -using ICSharpCode.ILSpyX.Extensions; +using ICSharpCode.ILSpyX.TreeView; using Microsoft.Win32; -using ICSharpCode.ILSpyX.TreeView; using TomsToolbox.Composition; @@ -749,10 +749,10 @@ async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSp } } - internal static IEntity FindEntityInRelevantAssemblies(string navigateTo, IEnumerable relevantAssemblies) + internal static IEntity? FindEntityInRelevantAssemblies(string navigateTo, IEnumerable relevantAssemblies) { - ITypeReference typeRef = null; - IMemberReference memberRef = null; + ITypeReference? typeRef = null; + IMemberReference? memberRef = null; if (navigateTo.StartsWith("T:", StringComparison.Ordinal)) { typeRef = IdStringProvider.ParseTypeName(navigateTo); diff --git a/ILSpy/TextView/DocumentationUIBuilder.cs b/ILSpy/TextView/DocumentationUIBuilder.cs index bc7a9a4092..e8527c858c 100644 --- a/ILSpy/TextView/DocumentationUIBuilder.cs +++ b/ILSpy/TextView/DocumentationUIBuilder.cs @@ -128,7 +128,7 @@ public void AddSignatureBlock(string signature, RichTextModel highlighting = nul AddBlock(block); } - public void AddXmlDocumentation(string xmlDocumentation, IEntity declaringEntity, Func resolver) + public void AddXmlDocumentation(string xmlDocumentation, IEntity declaringEntity, Func resolver) { if (xmlDocumentation == null) return; diff --git a/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs b/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs index 993c22bdfc..640d373e3e 100644 --- a/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs @@ -36,7 +36,7 @@ sealed class CursorResourceNodeFactory : IResourceNodeFactory { static readonly string[] imageFileExtensions = { ".cur" }; - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { string key = resource.Name; foreach (string fileExt in imageFileExtensions) @@ -70,7 +70,7 @@ public override bool View(TabPageModel tabPage) return false; //HACK: windows imaging does not understand that .cur files have the same layout as .ico // so load to data, and modify the ResourceType in the header to make look like an icon... - MemoryStream s = data as MemoryStream; + MemoryStream? s = data as MemoryStream; if (s == null) { // data was stored in another stream type (e.g. PinnedBufferedMemoryStream) diff --git a/ILSpy/TreeNodes/ResourceNodes/IResourceNodeFactory.cs b/ILSpy/TreeNodes/ResourceNodes/IResourceNodeFactory.cs index a9dba6c6fa..9989fccd1b 100644 --- a/ILSpy/TreeNodes/ResourceNodes/IResourceNodeFactory.cs +++ b/ILSpy/TreeNodes/ResourceNodes/IResourceNodeFactory.cs @@ -26,6 +26,6 @@ namespace ICSharpCode.ILSpy.TreeNodes /// public interface IResourceNodeFactory { - ITreeNode CreateNode(Resource resource); + ITreeNode? CreateNode(Resource resource); } } diff --git a/ILSpy/TreeNodes/ResourceNodes/IconResourceEntryNode.cs b/ILSpy/TreeNodes/ResourceNodes/IconResourceEntryNode.cs index 075aa1ca02..b3618772d3 100644 --- a/ILSpy/TreeNodes/ResourceNodes/IconResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/IconResourceEntryNode.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.ILSpy.TreeNodes [PartCreationPolicy(CreationPolicy.Shared)] sealed class IconResourceNodeFactory : IResourceNodeFactory { - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { if (resource.Name.EndsWith(".ico", StringComparison.OrdinalIgnoreCase)) { @@ -46,7 +46,7 @@ public ITreeNode CreateNode(Resource resource) sealed class IconResourceEntryNode : ResourceEntryNode { - public IconResourceEntryNode(string key, Func data) + public IconResourceEntryNode(string key, Func data) : base(key, data) { } diff --git a/ILSpy/TreeNodes/ResourceNodes/ImageListResourceEntryNode.cs b/ILSpy/TreeNodes/ResourceNodes/ImageListResourceEntryNode.cs index 7a3d9c7950..be339b801b 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ImageListResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ImageListResourceEntryNode.cs @@ -31,12 +31,12 @@ namespace ICSharpCode.ILSpy.TreeNodes [PartCreationPolicy(CreationPolicy.Shared)] sealed class ImageListResourceEntryNodeFactory : IResourceNodeFactory { - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { return null; } - public ILSpyTreeNode CreateNode(string key, object data) + public ILSpyTreeNode? CreateNode(string key, object data) { if (data is ImageListStreamer) return new ImageListResourceEntryNode(key, (ImageListStreamer)data); diff --git a/ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs b/ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs index cad4098eb5..c98e36d8ee 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs @@ -36,7 +36,7 @@ sealed class ImageResourceNodeFactory : IResourceNodeFactory { static readonly string[] imageFileExtensions = { ".png", ".gif", ".bmp", ".jpg" }; - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { string key = resource.Name; foreach (string fileExt in imageFileExtensions) @@ -50,7 +50,7 @@ public ITreeNode CreateNode(Resource resource) sealed class ImageResourceEntryNode : ResourceEntryNode { - public ImageResourceEntryNode(string key, Func openStream) + public ImageResourceEntryNode(string key, Func openStream) : base(key, openStream) { } diff --git a/ILSpy/TreeNodes/ResourceNodes/ResourceEntryNode.cs b/ILSpy/TreeNodes/ResourceNodes/ResourceEntryNode.cs index 5786c88c82..6b0e34633e 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ResourceEntryNode.cs @@ -34,18 +34,18 @@ namespace ICSharpCode.ILSpy.TreeNodes public class ResourceEntryNode : ILSpyTreeNode { private readonly string key; - private readonly Func openStream; + private readonly Func openStream; public override object Text => Language.EscapeName(key); public override object Icon => Images.Resource; - protected Stream OpenStream() + protected Stream? OpenStream() { return openStream(); } - public ResourceEntryNode(string key, Func openStream) + public ResourceEntryNode(string key, Func openStream) { if (key == null) throw new ArgumentNullException(nameof(key)); @@ -57,7 +57,7 @@ public ResourceEntryNode(string key, Func openStream) public static ILSpyTreeNode Create(Resource resource) { - ILSpyTreeNode result = null; + ILSpyTreeNode? result = null; foreach (var factory in App.ExportProvider.GetExportedValues()) { result = factory.CreateNode(resource) as ILSpyTreeNode; @@ -78,13 +78,14 @@ public override void Decompile(Language language, ITextOutput output, Decompilat language.WriteCommentLine(output, string.Format("{0} = {1}", key, data)); } - public override bool Save(ViewModels.TabPageModel tabPage) + public override bool Save(ViewModels.TabPageModel? tabPage) { SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = Path.GetFileName(WholeProjectDecompiler.SanitizeFileName(key)); if (dlg.ShowDialog() == true) { using var data = OpenStream(); + using var fs = dlg.OpenFile(); data.CopyTo(fs); } diff --git a/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs b/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs index 324390af2e..eb3ab6e17c 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs @@ -41,7 +41,7 @@ namespace ICSharpCode.ILSpy.TreeNodes [PartCreationPolicy(CreationPolicy.Shared)] sealed class ResourcesFileTreeNodeFactory : IResourceNodeFactory { - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { if (resource.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) { @@ -50,7 +50,7 @@ public ITreeNode CreateNode(Resource resource) return null; } - public ILSpyTreeNode CreateNode(string key, object data) + public ILSpyTreeNode? CreateNode(string key, object data) { return null; } diff --git a/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs b/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs index e017948df8..a582b43b57 100644 --- a/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.ILSpy.Xaml [PartCreationPolicy(CreationPolicy.Shared)] sealed class XamlResourceNodeFactory : IResourceNodeFactory { - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { if (resource.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase)) return new XamlResourceEntryNode(resource.Name, resource.TryOpenStream); @@ -45,9 +45,9 @@ public ITreeNode CreateNode(Resource resource) sealed class XamlResourceEntryNode : ResourceEntryNode { - string xaml; + string? xaml; - public XamlResourceEntryNode(string key, Func openStream) : base(key, openStream) + public XamlResourceEntryNode(string key, Func openStream) : base(key, openStream) { } diff --git a/ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs b/ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs index 740947602a..32947bc18f 100644 --- a/ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs @@ -36,7 +36,7 @@ sealed class XmlResourceNodeFactory : IResourceNodeFactory { private readonly static string[] xmlFileExtensions = { ".xml", ".xsd", ".xslt" }; - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { string key = resource.Name; foreach (string fileExt in xmlFileExtensions) @@ -50,9 +50,9 @@ public ITreeNode CreateNode(Resource resource) sealed class XmlResourceEntryNode : ResourceEntryNode { - string xml; + string? xml; - public XmlResourceEntryNode(string key, Func data) + public XmlResourceEntryNode(string key, Func data) : base(key, data) { } @@ -74,7 +74,7 @@ public override object Icon { public override bool View(TabPageModel tabPage) { AvalonEditTextOutput output = new AvalonEditTextOutput(); - IHighlightingDefinition highlighting = null; + IHighlightingDefinition? highlighting = null; tabPage.ShowTextView(textView => textView.RunWithCancellation( token => Task.Factory.StartNew( diff --git a/ILSpy/Views/DebugSteps.xaml.cs b/ILSpy/Views/DebugSteps.xaml.cs index b619cc6b71..e69199aff3 100644 --- a/ILSpy/Views/DebugSteps.xaml.cs +++ b/ILSpy/Views/DebugSteps.xaml.cs @@ -48,7 +48,7 @@ public DebugSteps() #endif } - private void WritingOptions_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + private void WritingOptions_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { DecompileAsync(lastSelectedStep); } @@ -80,7 +80,7 @@ private void LanguageSettings_PropertyChanged(object sender, System.ComponentMod #endif } - private void ILAstStepperUpdated(object sender, EventArgs e) + private void ILAstStepperUpdated(object? sender, EventArgs? e) { #if DEBUG if (language == null) From d89f85087efbb94595891f6989543eaaf8924cdb Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 10:29:34 -0400 Subject: [PATCH 08/15] focus on CS8603, return null from method --- .../CSharp/CSharpDecompiler.cs | 4 ++-- .../CSharp/ExpressionBuilder.cs | 2 +- .../OutputVisitor/TextWriterTokenWriter.cs | 2 +- .../ProjectDecompiler/TargetFramework.cs | 2 +- .../WholeProjectDecompiler.cs | 2 +- .../CSharp/Resolver/CSharpConversions.cs | 8 +++---- .../CSharp/Resolver/CSharpResolver.cs | 6 ++--- .../CSharp/Resolver/OverloadResolution.cs | 8 +++---- .../CSharp/Resolver/TypeInference.cs | 2 +- .../CSharp/StatementBuilder.cs | 2 +- .../CSharp/Syntax/DepthFirstAstVisitor.cs | 4 ++-- .../Expressions/UnaryOperatorExpression.cs | 2 +- .../Syntax/TypeMembers/OperatorDeclaration.cs | 2 +- .../CSharp/Syntax/TypeSystemAstBuilder.cs | 6 ++--- .../Transforms/IntroduceUnsafeModifier.cs | 4 ++-- .../Transforms/PatternStatementTransform.cs | 22 +++++++++---------- .../CSharp/TypeSystem/ResolvedUsingScope.cs | 4 ++-- .../TypeSystem/TypeOrNamespaceReference.cs | 2 +- .../Disassembler/DisassemblerHelpers.cs | 4 ++-- .../Documentation/IdStringMemberReference.cs | 2 +- .../Documentation/XmlDocLoader.cs | 4 ++-- .../Documentation/XmlDocumentationProvider.cs | 14 ++++++------ .../FlowAnalysis/DataFlowVisitor.cs | 10 ++++----- .../Humanizer/Vocabulary.cs | 4 ++-- .../IL/ControlFlow/LoopDetection.cs | 2 +- .../IL/ControlFlow/SwitchAnalysis.cs | 8 +++---- .../IL/ControlFlow/SwitchDetection.cs | 8 +++---- .../IL/ControlFlow/YieldReturnDecompiler.cs | 8 +++---- .../IL/PointerArithmeticOffset.cs | 2 +- .../IL/Transforms/AssignVariableNames.cs | 10 ++++----- .../IL/Transforms/CombineExitsTransform.cs | 2 +- .../IL/Transforms/DeconstructionTransform.cs | 4 ++-- .../IL/Transforms/DelegateConstruction.cs | 4 ++-- .../IL/Transforms/DynamicCallSiteTransform.cs | 2 +- .../IL/Transforms/ExpressionTransforms.cs | 16 +++++++------- .../IL/Transforms/HighLevelLoopTransform.cs | 6 ++--- .../IL/Transforms/ILExtraction.cs | 2 +- .../IL/Transforms/ILInlining.cs | 6 ++--- .../Transforms/InterpolatedStringTransform.cs | 2 +- .../IL/Transforms/LocalFunctionDecompiler.cs | 10 ++++----- .../IL/Transforms/NullPropagationTransform.cs | 4 ++-- .../IL/Transforms/NullableLiftingTransform.cs | 4 ++-- .../IL/Transforms/ReduceNestingTransform.cs | 2 +- .../IL/Transforms/SplitVariables.cs | 2 +- .../Transforms/TransformDisplayClassUsage.cs | 10 ++++----- .../IL/Transforms/TransformExpressionTrees.cs | 6 ++--- .../Transforms/UserDefinedLogicTransform.cs | 4 ++-- .../Metadata/DotNetCorePathFinder.cs | 6 ++--- .../Metadata/LightJson/JsonValue.cs | 12 +++++----- ICSharpCode.Decompiler/NRExtensions.cs | 2 +- .../Output/TextTokenWriter.cs | 10 ++++----- .../Semantics/LocalResolveResult.cs | 2 +- .../TypeSystem/FunctionPointerType.cs | 2 +- .../Implementation/AttributeListBuilder.cs | 2 +- .../Implementation/CustomAttribute.cs | 2 +- .../Implementation/DecimalConstantHelper.cs | 2 +- .../DefaultAssemblyReference.cs | 2 +- .../Implementation/DummyTypeParameter.cs | 2 +- .../TypeSystem/Implementation/FakeMember.cs | 4 ++-- .../Implementation/GetClassTypeReference.cs | 2 +- .../Implementation/MergedNamespace.cs | 2 +- .../Implementation/MetadataNamespace.cs | 2 +- .../Implementation/MetadataParameter.cs | 2 +- .../Implementation/SpecializedMember.cs | 2 +- .../TypeSystem/InheritanceHelper.cs | 6 ++--- .../TypeSystem/MetadataModule.cs | 22 +++++++++---------- .../TypeSystem/ReflectionHelper.cs | 2 +- .../TypeSystem/TupleType.cs | 2 +- .../TypeSystem/TypeProvider.cs | 2 +- .../TypeSystem/TypeSystemExtensions.cs | 12 +++++----- .../Util/CSharpPrimitiveCast.cs | 2 +- .../TreeNodes/AnalyzedModuleTreeNode.cs | 2 +- ILSpy/App.xaml.cs | 2 +- ILSpy/AppEnv/CommandLineTools.cs | 2 +- .../CopyFullyQualifiedNameContextMenuEntry.cs | 2 +- ILSpy/Commands/SaveCodeContextMenuEntry.cs | 2 +- ILSpy/Commands/ScopeSearchToNamespace.cs | 2 +- ILSpy/Controls/ExtensionMethods.cs | 2 +- ILSpy/Controls/TreeView/LinesRenderer.cs | 2 +- ILSpy/Controls/TreeView/SharpTreeNodeView.cs | 2 +- ILSpy/Controls/TreeView/SharpTreeView.cs | 4 ++-- ILSpy/Controls/TreeView/SharpTreeViewItem.cs | 2 +- ILSpy/Docking/DockLayoutSettings.cs | 2 +- ILSpy/Languages/CSharpBracketSearcher.cs | 2 +- .../CSharpHighlightingTokenWriter.cs | 4 ++-- ILSpy/Languages/CSharpLanguage.cs | 4 ++-- ILSpy/Languages/ILLanguage.cs | 4 ++-- ILSpy/Languages/Language.cs | 6 ++--- ILSpy/MainWindow.xaml.cs | 12 +++++----- ILSpy/Metadata/CoffHeaderTreeNode.cs | 2 +- .../CorTables/AssemblyRefTableTreeNode.cs | 2 +- .../CorTables/ConstantTableTreeNode.cs | 2 +- .../CorTables/CustomAttributeTableTreeNode.cs | 2 +- .../CorTables/DeclSecurityTableTreeNode.cs | 2 +- ILSpy/Metadata/CorTables/FileTableTreeNode.cs | 2 +- .../Metadata/CorTables/MethodTableTreeNode.cs | 2 +- .../Metadata/CorTables/ModuleTableTreeNode.cs | 4 ++-- .../CorTables/TypeDefTableTreeNode.cs | 6 ++--- .../CustomDebugInformationTableTreeNode.cs | 2 +- .../DebugTables/DocumentTableTreeNode.cs | 6 ++--- .../MethodDebugInformationTableTreeNode.cs | 6 ++--- ILSpy/Metadata/GoToTokenCommand.cs | 2 +- ILSpy/Metadata/MetadataProtocolHandler.cs | 2 +- ILSpy/Metadata/MetadataTableTreeNode.cs | 2 +- ILSpy/Search/SearchPane.xaml.cs | 4 ++-- ILSpy/TextView/BracketHighlightRenderer.cs | 2 +- ILSpy/TextView/ReferenceElementGenerator.cs | 2 +- ILSpy/TextView/UIElementGenerator.cs | 2 +- ILSpy/TreeNodes/AssemblyListTreeNode.cs | 20 ++++++++--------- ILSpy/TreeNodes/AssemblyTreeNode.cs | 6 ++--- ILSpy/Updates/NotifyOfUpdatesStrategy.cs | 4 ++-- 111 files changed, 247 insertions(+), 247 deletions(-) diff --git a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs index d2be2971e6..7fd38be1a6 100644 --- a/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs @@ -541,7 +541,7 @@ static TypeSystemAstBuilder CreateAstBuilder(DecompilerSettings settings) return typeSystemAstBuilder; } - IDocumentationProvider CreateDefaultDocumentationProvider() + IDocumentationProvider? CreateDefaultDocumentationProvider() { try { @@ -1096,7 +1096,7 @@ public SyntaxTree Decompile(IEnumerable definitions) return syntaxTree; } - ITypeDefinition FindCommonDeclaringTypeDefinition(ITypeDefinition a, ITypeDefinition b) + ITypeDefinition? FindCommonDeclaringTypeDefinition(ITypeDefinition a, ITypeDefinition b) { if (a == null || b == null) return null; diff --git a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs index b85f053d84..f187b3c430 100644 --- a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs @@ -265,7 +265,7 @@ bool HidesVariableOrNestedFunction(ILFunction function) } } - internal ILFunction ResolveLocalFunction(IMethod method) + internal ILFunction? ResolveLocalFunction(IMethod method) { Debug.Assert(method.IsLocalFunction); method = (IMethod)((IMethod)method.MemberDefinition).ReducedFrom.MemberDefinition; diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs index e305cb98ed..477ba3a6f2 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs @@ -437,7 +437,7 @@ public static string ConvertCharLiteral(char ch) /// Gets the escape sequence for the specified character. /// /// This method does not convert ' or ". - static string ConvertChar(char ch) + static string? ConvertChar(char ch) { switch (ch) { diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs index 793b70e7a8..ff8a2ecefb 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs @@ -79,7 +79,7 @@ public TargetFramework(string identifier, int version, string profile) /// public bool IsPortableClassLibrary { get; } - static string GetTargetFrameworkMoniker(string frameworkIdentifier, int version) + static string? GetTargetFrameworkMoniker(string frameworkIdentifier, int version) { // Reference: https://docs.microsoft.com/en-us/dotnet/standard/frameworks switch (frameworkIdentifier) diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs index a55980cf5c..b9e619830b 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs @@ -488,7 +488,7 @@ protected virtual IEnumerable WriteMiscellaneousFilesInProject( const int RT_ICON = 3; const int RT_GROUP_ICON = 14; - unsafe static byte[] CreateApplicationIcon(Win32ResourceDirectory resources) + unsafe static byte[]? CreateApplicationIcon(Win32ResourceDirectory resources) { var iconGroup = resources.Find(new Win32ResourceName(RT_GROUP_ICON))?.FirstDirectory()?.FirstData()?.Data; if (iconGroup == null) diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs index f3a37e8411..9cfe6918de 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs @@ -554,7 +554,7 @@ bool ImplicitReferenceConversion(IType fromType, IType toType, int subtypeCheckN /// For IList{T}, ICollection{T}, IEnumerable{T} and IReadOnlyList{T}, returns T. /// Otherwise, returns null. /// - IType UnpackGenericArrayInterface(IType interfaceType) + IType? UnpackGenericArrayInterface(IType interfaceType) { ParameterizedType? pt = interfaceType as ParameterizedType; if (pt != null) @@ -938,7 +938,7 @@ bool IsEncompassingOrEncompassedBy(IType a, IType b) && (StandardImplicitConversion(a, b).IsValid || StandardImplicitConversion(b, a).IsValid); } - IType FindMostEncompassedType(IEnumerable candidates) + IType? FindMostEncompassedType(IEnumerable candidates) { IType? best = null; foreach (var current in candidates) @@ -951,7 +951,7 @@ IType FindMostEncompassedType(IEnumerable candidates) return best; } - IType FindMostEncompassingType(IEnumerable candidates) + IType? FindMostEncompassingType(IEnumerable candidates) { IType? best = null; foreach (var current in candidates) @@ -1482,7 +1482,7 @@ public int BetterConversion(ResolveResult resolveResult, IType t1, IType t2) /// /// Unpacks the generic Task[T]. Returns null if the input is not Task[T]. /// - static IType UnpackTask(IType type) + static IType? UnpackTask(IType type) { ParameterizedType? pt = type as ParameterizedType; if (pt != null && pt.TypeParameterCount == 1 && pt.Name == "Task" && pt.Namespace == "System.Threading.Tasks") diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs index b4ed267ba2..431cbdae06 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs @@ -565,7 +565,7 @@ ResolveResult UnaryNumericPromotion(UnaryOperatorType op, ref IType type, bool i #endregion #region GetOverloadableOperatorName - static string GetOverloadableOperatorName(UnaryOperatorType op) + static string? GetOverloadableOperatorName(UnaryOperatorType op) { switch (op) { @@ -980,7 +980,7 @@ CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, #endregion #region Enum helper methods - IType GetEnumUnderlyingType(IType enumType) + IType? GetEnumUnderlyingType(IType enumType) { ITypeDefinition? def = enumType.GetDefinition(); return def != null ? def.EnumUnderlyingType : SpecialType.UnknownType; @@ -1203,7 +1203,7 @@ ResolveResult CastTo(IType targetType, bool isNullable, ResolveResult expression #endregion #region GetOverloadableOperatorName - static string GetOverloadableOperatorName(BinaryOperatorType op) + static string? GetOverloadableOperatorName(BinaryOperatorType op) { switch (op) { diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs index 690033469e..311b66b671 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs @@ -891,7 +891,7 @@ void ConsiderIfNewCandidateIsBest(Candidate candidate) #endregion #region Output Properties - public IParameterizedMember BestCandidate { + public IParameterizedMember? BestCandidate { get { return bestCandidate != null ? bestCandidate.Member : null; } } @@ -919,7 +919,7 @@ public bool FoundApplicableCandidate { get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); } } - public IParameterizedMember BestCandidateAmbiguousWith { + public IParameterizedMember? BestCandidateAmbiguousWith { get { return bestCandidateAmbiguousWith != null ? bestCandidateAmbiguousWith.Member : null; } } @@ -958,7 +958,7 @@ public IList ArgumentConversions { /// /// parameterIndex = GetArgumentToParameterMap()[argumentIndex] /// - public IReadOnlyList GetArgumentToParameterMap() + public IReadOnlyList? GetArgumentToParameterMap() { if (bestCandidate != null) return bestCandidate.ArgumentToParameterMap; @@ -1037,7 +1037,7 @@ IList GetArgumentsWithConversions(ResolveResult targetResolveResu return args; } - public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments() + public IParameterizedMember? GetBestCandidateWithSubstitutedTypeArguments() { if (bestCandidate == null) return null; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs index 280c968f65..3942c2d1e4 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs @@ -698,7 +698,7 @@ void MakeExactInference(IType U, IType V) } } - TP GetTPForType(IType v) + TP? GetTPForType(IType v) { if (v is NullabilityAnnotatedTypeParameter natp) { diff --git a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs index 37db21cda1..e335af2198 100644 --- a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs @@ -624,7 +624,7 @@ bool IsValidInCSharp(UsingInstruction inst, KnownTypeCode code) } } - Statement TransformToForeach(UsingInstruction inst, Expression resource) + Statement? TransformToForeach(UsingInstruction inst, Expression resource) { if (!settings.ForEachStatement) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs index 7dc80d576c..2a4317d4d0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs @@ -713,7 +713,7 @@ public virtual void VisitWithInitializerExpression(WithInitializerExpression wit /// public abstract class DepthFirstAstVisitor : IAstVisitor { - protected virtual T VisitChildren(AstNode node) + protected virtual T? VisitChildren(AstNode node) { AstNode? next; for (var child = node.FirstChild; child != null; child = next) @@ -726,7 +726,7 @@ protected virtual T VisitChildren(AstNode node) return default(T); } - public virtual T VisitNullNode(AstNode nullNode) + public virtual T? VisitNullNode(AstNode nullNode) { // Should we call VisitChildren here? // We usually want to ignore null nodes. diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs index 3052e1bf78..596b13b771 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs @@ -94,7 +94,7 @@ protected internal override bool DoMatch(AstNode? other, PatternMatching.Match m && this.Expression.DoMatch(o.Expression, match); } - public static TokenRole GetOperatorRole(UnaryOperatorType op) + public static TokenRole? GetOperatorRole(UnaryOperatorType op) { switch (op) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs index 70343f3ace..e004eabc22 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs @@ -293,7 +293,7 @@ public static TokenRole GetRole(OperatorType type) /// /// Gets the method name for the operator type. ("op_Addition", "op_Implicit", etc.) /// - public static string GetName(OperatorType? type) + public static string? GetName(OperatorType? type) { if (type == null) return null; diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs index cc70cac437..3b5320f862 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs @@ -1443,7 +1443,7 @@ Expression MakeConstant(IType type, long c) const float MathF_PI = 3.14159274f; const float MathF_E = 2.71828175f; - Expression TryExtractExpression(IType mathType, IType type, object literalValue, string memberName, bool isDouble) + Expression? TryExtractExpression(IType mathType, IType type, object literalValue, string memberName, bool isDouble) { Expression MakeFieldReference() { @@ -1464,7 +1464,7 @@ Expression MakeFieldReference() return new CastExpression(ConvertType(type), fieldRef); } - Expression ExtractExpression(long n, long d) + Expression? ExtractExpression(long n, long d) { Expression fieldReference = MakeFieldReference(); @@ -2400,7 +2400,7 @@ internal TypeParameterDeclaration ConvertTypeParameter(ITypeParameter tp) return decl; } - internal Constraint ConvertTypeParameterConstraint(ITypeParameter tp) + internal Constraint? ConvertTypeParameterConstraint(ITypeParameter tp) { if (!tp.HasDefaultConstructorConstraint && !tp.HasReferenceTypeConstraint && !tp.HasValueTypeConstraint && tp.NullabilityConstraint != Nullability.NotNullable && tp.DirectBaseTypes.All(IsObjectOrValueType)) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs index 0688e9c49a..7a7e3ab258 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs @@ -40,8 +40,8 @@ public static bool IsUnsafe(AstNode node) protected override bool VisitChildren(AstNode node) { bool result = false; - AstNode next; - for (AstNode child = node.FirstChild; child != null; child = next) + AstNode? next; + for (AstNode? child = node.FirstChild; child != null; child = next) { // Store next to allow the loop to continue // if the visitor removes/replaces child. diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs index 114e60dafa..5424ececc0 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs @@ -77,7 +77,7 @@ protected override AstNode VisitChildren(AstNode node) public override AstNode VisitExpressionStatement(ExpressionStatement expressionStatement) { - AstNode result = TransformForeachOnMultiDimArray(expressionStatement); + AstNode? result = TransformForeachOnMultiDimArray(expressionStatement); if (result != null) return result; result = TransformFor(expressionStatement); @@ -182,7 +182,7 @@ public override AstNode VisitTryCatchStatement(TryCatchStatement tryCatchStateme if (!m1.Success) return null; var variable = m1.Get("variable").Single().GetILVariable(); - AstNode next = node.NextSibling; + AstNode? next = node.NextSibling; if (next is ForStatement forStatement && ForStatementUsesVariable(forStatement, variable)) { node.Remove(); @@ -477,7 +477,7 @@ bool MatchForeachOnMultiDimArray(IL.ILVariable[] upperBounds, IL.ILVariable coll return true; } - Statement TransformForeachOnMultiDimArray(ExpressionStatement expressionStatement) + Statement? TransformForeachOnMultiDimArray(ExpressionStatement expressionStatement) { if (!context.Settings.ForEachStatement) return null; @@ -609,7 +609,7 @@ bool CanTransformToAutomaticProperty(IProperty property, bool accessorsMustBeCom return true; } - PropertyDeclaration TransformAutomaticProperty(PropertyDeclaration propertyDeclaration) + PropertyDeclaration? TransformAutomaticProperty(PropertyDeclaration propertyDeclaration) { IProperty? property = propertyDeclaration.GetSymbol() as IProperty; if (!CanTransformToAutomaticProperty(property, !property.DeclaringTypeDefinition.Fields.Any(f => f.Name == "_" + property.Name && f.IsCompilerGenerated()))) @@ -736,7 +736,7 @@ static bool NameCouldBeBackingFieldOfAutomaticProperty(string name, [NotNullWhen return true; } - Identifier ReplaceBackingFieldUsage(Identifier identifier) + Identifier? ReplaceBackingFieldUsage(Identifier identifier) { if (NameCouldBeBackingFieldOfAutomaticProperty(identifier.Name, out _)) { @@ -757,7 +757,7 @@ Identifier ReplaceBackingFieldUsage(Identifier identifier) return null; } - Identifier ReplaceEventFieldAnnotation(Identifier identifier) + Identifier? ReplaceEventFieldAnnotation(Identifier identifier) { var parent = identifier.Parent; var mrr = parent.Annotation(); @@ -995,7 +995,7 @@ bool CheckAutomaticEventV4MCS(CustomEventDeclaration ev) return true; } - EventDeclaration TransformAutomaticEvents(CustomEventDeclaration ev) + EventDeclaration? TransformAutomaticEvents(CustomEventDeclaration ev) { if (!ev.PrivateImplementationType.IsNull) return null; @@ -1055,7 +1055,7 @@ EventDeclaration TransformAutomaticEvents(CustomEventDeclaration ev) Body = destructorBodyPattern }; - DestructorDeclaration TransformDestructor(MethodDeclaration methodDef) + DestructorDeclaration? TransformDestructor(MethodDeclaration methodDef) { Match m = destructorPattern.Match(methodDef); if (m.Success) @@ -1072,7 +1072,7 @@ DestructorDeclaration TransformDestructor(MethodDeclaration methodDef) return null; } - DestructorDeclaration TransformDestructorBody(DestructorDeclaration dtorDef) + DestructorDeclaration? TransformDestructorBody(DestructorDeclaration dtorDef) { Match m = destructorBodyPattern.Match(dtorDef.Body); if (m.Success) @@ -1099,7 +1099,7 @@ DestructorDeclaration TransformDestructorBody(DestructorDeclaration dtorDef) /// Simplify nested 'try { try {} catch {} } finally {}'. /// This transformation must run after the using/lock tranformations. /// - TryCatchStatement TransformTryCatchFinally(TryCatchStatement tryFinally) + TryCatchStatement? TransformTryCatchFinally(TryCatchStatement tryFinally) { if (tryCatchFinallyPattern.IsMatch(tryFinally)) { @@ -1130,7 +1130,7 @@ TryCatchStatement TransformTryCatchFinally(TryCatchStatement tryFinally) } }; - AstNode SimplifyCascadingIfElseStatements(IfElseStatement node) + AstNode? SimplifyCascadingIfElseStatements(IfElseStatement node) { Match m = cascadingIfElsePattern.Match(node); if (m.Success) diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs index 87441be6e3..0d42b97863 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs @@ -213,12 +213,12 @@ ICompilation ICompilationProvider.Compilation { get { return parentNamespace.Compilation; } } - INamespace INamespace.GetChildNamespace(string name) + INamespace? INamespace.GetChildNamespace(string name) { return null; } - ITypeDefinition INamespace.GetTypeDefinition(string name, int typeParameterCount) + ITypeDefinition? INamespace.GetTypeDefinition(string name, int typeParameterCount) { return null; } diff --git a/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs index aa69222f3f..749aeee14d 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs @@ -43,7 +43,7 @@ public abstract class TypeOrNamespaceReference : ITypeReference /// /// Returns the namespace that is referenced; or null if no such namespace is found. /// - public INamespace ResolveNamespace(CSharpResolver resolver) + public INamespace? ResolveNamespace(CSharpResolver resolver) { NamespaceResolveResult? nrr = Resolve(resolver) as NamespaceResolveResult; return nrr != null ? nrr.Namespace : null; diff --git a/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs b/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs index 3f3aea4e5a..78d1f8259a 100644 --- a/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs +++ b/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs @@ -150,7 +150,7 @@ public static void WriteParameterReference(ITextOutput writer, MetadataReader me writer.WriteLocalReference(name, "param_" + index); } - string GetParameterName(int parameterNumber) + string? GetParameterName(int parameterNumber) { var methodDefinition = metadata.GetMethodDefinition(handle); if ((methodDefinition.Attributes & System.Reflection.MethodAttributes.Static) != 0) @@ -339,7 +339,7 @@ public static string EscapeString(string str) } return sb.ToString(); } - public static string PrimitiveTypeName(string fullName) + public static string? PrimitiveTypeName(string fullName) { switch (fullName) { diff --git a/ICSharpCode.Decompiler/Documentation/IdStringMemberReference.cs b/ICSharpCode.Decompiler/Documentation/IdStringMemberReference.cs index 3b0ad8bdc5..a9226da95f 100644 --- a/ICSharpCode.Decompiler/Documentation/IdStringMemberReference.cs +++ b/ICSharpCode.Decompiler/Documentation/IdStringMemberReference.cs @@ -61,7 +61,7 @@ public ITypeReference DeclaringTypeReference { get { return declaringTypeReference; } } - public IMember Resolve(ITypeResolveContext context) + public IMember? Resolve(ITypeResolveContext context) { IType declaringType = declaringTypeReference.Resolve(context); foreach (var member in declaringType.GetMembers(CanMatch, GetMemberOptions.IgnoreInheritedMembers)) diff --git a/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs index de2b116f0f..1a7d16695a 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs @@ -34,7 +34,7 @@ public static class XmlDocLoader static readonly Lazy mscorlibDocumentation = new Lazy(LoadMscorlibDocumentation); static readonly ConditionalWeakTable cache = new(); - static XmlDocumentationProvider LoadMscorlibDocumentation() + static XmlDocumentationProvider? LoadMscorlibDocumentation() { string xmlDocFile = FindXmlDocumentation("mscorlib.dll", TargetRuntime.Net_4_0) ?? FindXmlDocumentation("mscorlib.dll", TargetRuntime.Net_2_0); @@ -120,7 +120,7 @@ static string FindXmlDocumentation(string assemblyFileName, TargetRuntime runtim /// Given the assembly file name, looks up the XML documentation file name. /// Returns null if no XML documentation file is found. /// - internal static string LookupLocalizedXmlDoc(string fileName) + internal static string? LookupLocalizedXmlDoc(string fileName) { if (string.IsNullOrEmpty(fileName)) return null; diff --git a/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs b/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs index af9bf21f79..40f39261e4 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs @@ -81,7 +81,7 @@ internal bool TryGet(string key, out string? value) return false; } - internal void Add(string key, string value) + internal void Add(string key, string? value) { entries[pos++] = new KeyValuePair(key, value); if (pos == entries.Length) @@ -279,7 +279,7 @@ static void ReadMembersSection(XmlTextReader reader, LinePositionMapper linePosM if (reader.LocalName == "member") { int pos = linePosMapper.GetPositionForLine(reader.LineNumber) + Math.Max(reader.LinePosition - 2, 0); - string memberAttr = reader.GetAttribute("name"); + string? memberAttr = reader.GetAttribute("name"); if (memberAttr != null) indexList.Add(new IndexEntry(GetHashCode(memberAttr), pos)); reader.Skip(); @@ -330,7 +330,7 @@ public string GetDocumentation(IEntity entity) return GetDocumentation(entity.GetIdString()); } - string GetDocumentation(string key, bool allowReload) + string? GetDocumentation(string key, bool allowReload) { int hashcode = GetHashCode(key); var index = this.index; // read volatile field @@ -347,7 +347,7 @@ string GetDocumentation(string key, bool allowReload) XmlDocumentationCache cache = this.cache; lock (cache) { - if (!cache.TryGet(key, out string val)) + if (!cache.TryGet(key, out string? val)) { try { @@ -376,7 +376,7 @@ string GetDocumentation(string key, bool allowReload) } } - string ReloadAndGetDocumentation(string key) + string? ReloadAndGetDocumentation(string key) { try { @@ -407,7 +407,7 @@ string ReloadAndGetDocumentation(string key) #endregion #region Load / Read XML - string LoadDocumentation(string key, int positionInFile) + string? LoadDocumentation(string key, int positionInFile) { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { @@ -420,7 +420,7 @@ string LoadDocumentation(string key, int positionInFile) { if (r.NodeType == XmlNodeType.Element) { - string memberAttr = r.GetAttribute("name"); + string? memberAttr = r.GetAttribute("name"); if (memberAttr == key) { return r.ReadInnerXml(); diff --git a/ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs b/ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs index 06d4a24d36..fd050c3491 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs @@ -237,7 +237,7 @@ void DebugPoint(Dictionary debugDict, ILInstruction inst) #if DEBUG Debug.Assert(initialized, "Initialize() was not called"); - if (debugDict.TryGetValue(inst, out State previousState)) + if (debugDict.TryGetValue(inst, out State? previousState)) { Debug.Assert(previousState.LessThanOrEqual(state)); previousState.JoinWith(state); @@ -350,7 +350,7 @@ protected void MarkUnreachable() /// State GetBlockInputState(Block block) { - if (stateOnBranch.TryGetValue(block, out State s)) + if (stateOnBranch.TryGetValue(block, out State? s)) { return s; } @@ -398,7 +398,7 @@ protected internal override void VisitBlockContainer(BlockContainer container) state.ReplaceWith(stateOnBranch[block]); block.AcceptVisitor(this); } - if (stateOnLeave.TryGetValue(container, out State stateOnExit)) + if (stateOnLeave.TryGetValue(container, out State? stateOnExit)) { state.ReplaceWith(stateOnExit); } @@ -463,7 +463,7 @@ protected internal override void VisitLeave(Leave inst) void MergeBranchStateIntoStateOnLeave(Leave inst, State branchState) { - if (stateOnLeave.TryGetValue(inst.TargetContainer, out State targetState)) + if (stateOnLeave.TryGetValue(inst.TargetContainer, out State? targetState)) { targetState.JoinWith(branchState); } @@ -505,7 +505,7 @@ protected internal override void VisitInvalidBranch(InvalidBranch inst) protected State HandleTryBlock(TryInstruction inst) { State oldStateOnException = currentStateOnException; - if (stateOnException.TryGetValue(inst, out State newStateOnException)) + if (stateOnException.TryGetValue(inst, out State? newStateOnException)) { newStateOnException.JoinWith(state); } diff --git a/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs b/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs index f901254161..620107f2b9 100644 --- a/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs +++ b/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs @@ -119,7 +119,7 @@ public string Singularize(string word, bool inputIsKnownToBePlural = true, bool return result ?? word; } - private string ApplyRules(IList rules, string word, bool skipFirstRule) + private string? ApplyRules(IList rules, string word, bool skipFirstRule) { if (word == null) { @@ -164,7 +164,7 @@ public Rule(string pattern, string replacement) _replacement = replacement; } - public string Apply(string word) + public string? Apply(string word) { if (!_regex.IsMatch(word)) { diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs index 1c82568013..099d5325ca 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs @@ -311,7 +311,7 @@ void ExtendLoop(ControlFlowNode loopHead, List loop, out Contro /// 3) otherwise (exit point unknown, heuristically extend loop): null /// /// This method must not write to the Visited flags on the CFG. - internal ControlFlowNode FindExitPoint(ControlFlowNode loopHead, IReadOnlyList naturalLoop) + internal ControlFlowNode? FindExitPoint(ControlFlowNode loopHead, IReadOnlyList naturalLoop) { bool hasReachableExit = HasReachableExit(loopHead); if (!hasReachableExit) diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs index 8114f1e21a..42c0f668df 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs @@ -126,7 +126,7 @@ bool AnalyzeBlock(Block block, LongSet inputValues, bool tailOnly = false) trueValues = trueValues.IntersectWith(inputValues); if (trueValues.SetEquals(inputValues) || trueValues.IsEmpty) return false; - Block trueBlock; + Block? trueBlock; if (trueInst.MatchBranch(out trueBlock) && AnalyzeBlock(trueBlock, trueValues)) { // OK, true block was further analyzed. @@ -159,7 +159,7 @@ bool AnalyzeBlock(Block block, LongSet inputValues, bool tailOnly = false) var remainingValues = inputValues.ExceptWith(trueValues); ILInstruction falseInst = block.Instructions.Last(); - Block falseBlock; + Block? falseBlock; if (falseInst.MatchBranch(out falseBlock) && AnalyzeBlock(falseBlock, remainingValues)) { // OK, false block was further analyzed. @@ -237,7 +237,7 @@ void AddSection(LongSet values, ILInstruction inst) { return; } - if (inst.MatchBranch(out Block targetBlock)) + if (inst.MatchBranch(out Block? targetBlock)) { if (targetBlockToSectionIndex.TryGetValue(targetBlock, out int index)) { @@ -252,7 +252,7 @@ void AddSection(LongSet values, ILInstruction inst) Sections.Add(new KeyValuePair(values, inst)); } } - else if (inst.MatchLeave(out BlockContainer targetContainer)) + else if (inst.MatchLeave(out BlockContainer? targetContainer)) { if (targetContainerToSectionIndex.TryGetValue(targetContainer, out int index)) { diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs index 88f316daf4..2f00105162 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs @@ -233,9 +233,9 @@ internal static void SimplifySwitchInstruction(Block block, ILTransformContext c var dict = new Dictionary(); // branch target -> switch section sw.Sections.RemoveAll( section => { - if (section.Body.MatchBranch(out Block target)) + if (section.Body.MatchBranch(out Block? target)) { - if (dict.TryGetValue(target, out SwitchSection primarySection)) + if (dict.TryGetValue(target, out SwitchSection? primarySection)) { primarySection.Labels = primarySection.Labels.UnionWith(section.Labels); primarySection.HasNullLabel |= section.HasNullLabel; @@ -438,13 +438,13 @@ private void AddNullCase(List flowNodes, List // if (comp(logic.not(call get_HasValue(ldloca nullableVar))) br NullCase // br RootBlock - var nullableBlock = (Block)controlFlowGraph.GetNode(analysis.RootBlock).Predecessors.SingleOrDefault()?.UserData; + var nullableBlock = (Block?)controlFlowGraph.GetNode(analysis.RootBlock).Predecessors.SingleOrDefault()?.UserData; if (nullableBlock == null || nullableBlock.Instructions.Count < 2 || !nullableBlock.Instructions.Last().MatchBranch(analysis.RootBlock) || !nullableBlock.Instructions.SecondToLastOrDefault().MatchIfInstruction(out var cond, out var trueInst) || !cond.MatchLogicNot(out var getHasValue) || - !NullableLiftingTransform.MatchHasValueCall(getHasValue, out ILInstruction nullableInst)) + !NullableLiftingTransform.MatchHasValueCall(getHasValue, out ILInstruction? nullableInst)) return; // could check that nullableInst is ldloc or ldloca and that the switch variable matches a GetValueOrDefault diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs index 4856bdbb35..a018bfe283 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs @@ -269,7 +269,7 @@ bool MatchEnumeratorCreationPattern(ILFunction function) return false; } - ILInstruction newObj; + ILInstruction? newObj; if (body.Instructions.Count == 1) { // No parameters passed to enumerator (not even 'this'): @@ -943,7 +943,7 @@ private BlockContainer ConvertBody(BlockContainer oldBody, StateRangeAnalysis ra void ConvertBranchAfterYieldReturn(Block newBlock, Block oldBlock, int pos) { - Block targetBlock; + Block? targetBlock; if (isCompiledWithMono && disposingField != null) { // Mono skips over the state assignment if 'this.disposing' is set: @@ -1233,7 +1233,7 @@ void ReconstructTryFinallyBlocks(ILFunction iteratorFunction) { context.CancellationToken.ThrowIfCancellationRequested(); int oldState = blockState[block.ChildIndex]; - BlockContainer container; // new container for the block + BlockContainer? container; // new container for the block if (GetNewState(block) is int newState) { // OK, state change @@ -1436,7 +1436,7 @@ bool IsCallToMonoFinallyMethod(Call call, [NotNullWhen(true)] out IMethod? final return false; if (!call.Method.Name.StartsWith("<>__Finally")) return false; - ITypeDefinition declaringTypeDefinition = call.Method.DeclaringTypeDefinition; + ITypeDefinition? declaringTypeDefinition = call.Method.DeclaringTypeDefinition; if (declaringTypeDefinition.MetadataToken != this.enumeratorType) return false; if (declaringTypeDefinition.ParentModule.MetadataFile.Metadata != metadata) diff --git a/ICSharpCode.Decompiler/IL/PointerArithmeticOffset.cs b/ICSharpCode.Decompiler/IL/PointerArithmeticOffset.cs index b4c4008b3a..344ab6db83 100644 --- a/ICSharpCode.Decompiler/IL/PointerArithmeticOffset.cs +++ b/ICSharpCode.Decompiler/IL/PointerArithmeticOffset.cs @@ -35,7 +35,7 @@ struct PointerArithmeticOffset /// The target type of the pointer type. /// Whether the pointer arithmetic operation checks for overflow. /// Whether to allow zero extensions in the mul argument. - public static ILInstruction Detect(ILInstruction byteOffsetInst, IType pointerElementType, + public static ILInstruction? Detect(ILInstruction byteOffsetInst, IType pointerElementType, bool checkForOverflow, bool unwrapZeroExtension = false) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs b/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs index b54ecfc8f8..ecc2194002 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs @@ -227,7 +227,7 @@ void PerformAssignment(ILFunction function) { var v = i.Variable; // if there is already a valid name for the variable slot, just use it - if (variableMapping.TryGetValue(v, out string name)) + if (variableMapping.TryGetValue(v, out string? name)) { v.Name = name; continue; @@ -463,7 +463,7 @@ string GenerateNameForVariable(ILVariable variable) return SplitName(proposedName, out _); } - static string GetNameFromInstruction(ILInstruction inst) + static string? GetNameFromInstruction(ILInstruction inst) { switch (inst) { @@ -506,7 +506,7 @@ static string GetNameFromInstruction(ILInstruction inst) return null; } - static string GetNameForArgument(ILInstruction parent, int i) + static string? GetNameForArgument(ILInstruction parent, int i) { switch (parent) { @@ -566,7 +566,7 @@ static string GetNameByType(IType type) type = NullableType.GetUnderlyingType(((TypeWithElementType)type).ElementType); } - string name = type.Kind switch { + string? name = type.Kind switch { TypeKind.Array => "array", TypeKind.Pointer => "ptr", TypeKind.TypeParameter => "val", @@ -637,7 +637,7 @@ static string SplitName(string name, out int number) return name; } - static string CleanUpVariableName(string name) + static string? CleanUpVariableName(string name) { // remove the backtick (generics) int pos = name.IndexOf('`'); diff --git a/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs index 03e6ffbf13..fa067c882e 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs @@ -30,7 +30,7 @@ public void Run(ILFunction function, ILTransformContext context) ExpressionTransforms.RunOnSingleStatement(combinedExit, context); } - static Leave CombineExits(Block block) + static Leave? CombineExits(Block block) { if (!(block.Instructions.SecondToLastOrDefault() is IfInstruction ifInst && block.Instructions.LastOrDefault() is Leave leaveElse)) return null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs index 30fa9dc150..78181b4a7a 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs @@ -191,8 +191,8 @@ bool TransformDeconstruction(Block block, int pos) { int startPos = pos; Action? delayedActions = null; - if (MatchDeconstruction(block.Instructions[pos], out IMethod deconstructMethod, - out ILInstruction rootTestedOperand)) + if (MatchDeconstruction(block.Instructions[pos], out IMethod? deconstructMethod, + out ILInstruction? rootTestedOperand)) { pos++; } diff --git a/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs b/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs index a3b8caa159..6d09091586 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DelegateConstruction.cs @@ -80,7 +80,7 @@ void IILTransform.Run(ILFunction function, ILTransformContext context) } } - internal static bool MatchDelegateConstruction(ILInstruction inst, out IMethod? targetMethod, + internal static bool MatchDelegateConstruction(ILInstruction? inst, out IMethod? targetMethod, [NotNullWhen(true)] out ILInstruction? target, [NotNullWhen(true)] out IType? delegateType, bool allowTransformed = false) { targetMethod = null; @@ -165,7 +165,7 @@ static bool ContainsAnonymousType(IMethod method) return new GenericContext(classTypeParameters, methodTypeParameters); } - ILFunction TransformDelegateConstruction( + ILFunction? TransformDelegateConstruction( ILInstruction value, IMethod targetMethod, ILInstruction target, IType delegateType) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs index 2bd7b5ea04..54b8cd5cf2 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs @@ -147,7 +147,7 @@ public void Run(ILFunction function, ILTransformContext context) container.SortBlocks(deleteUnreachableBlocks: true); } - ILInstruction MakeDynamicInstruction(CallSiteInfo callsite, CallVirt targetInvokeCall, List deadArguments) + ILInstruction? MakeDynamicInstruction(CallSiteInfo callsite, CallVirt targetInvokeCall, List deadArguments) { switch (callsite.Kind) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs b/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs index e65bac4fe0..5a28917a60 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs @@ -141,7 +141,7 @@ protected internal override void VisitComp(Comp inst) } else if (rightWithoutConv.MatchLdcI4(0) && inst.Kind.IsEqualityOrInequality()) { - if (inst.Left.MatchLdLen(StackType.I, out ILInstruction array)) + if (inst.Left.MatchLdLen(StackType.I, out ILInstruction? array)) { // comp.unsigned(ldlen array == conv i4->i(ldc.i4 0)) // => comp(ldlen.i4 array == ldc.i4 0) @@ -167,7 +167,7 @@ protected internal override void VisitComp(Comp inst) protected internal override void VisitConv(Conv inst) { inst.Argument.AcceptVisitor(this); - if (inst.Argument.MatchLdLen(StackType.I, out ILInstruction array) && inst.TargetType.IsIntegerType() + if (inst.Argument.MatchLdLen(StackType.I, out ILInstruction? array) && inst.TargetType.IsIntegerType() && (!inst.CheckForOverflow || context.Settings.AssumeArrayLengthFitsIntoInt32)) { context.Step("conv.i4(ldlen array) => ldlen.i4(array)", inst); @@ -303,7 +303,7 @@ protected internal override void VisitCallVirt(CallVirt inst) protected internal override void VisitNewObj(NewObj inst) { Block? block; - if (TransformSpanTCtorContainingStackAlloc(inst, out ILInstruction locallocSpan)) + if (TransformSpanTCtorContainingStackAlloc(inst, out ILInstruction? locallocSpan)) { context.Step("new Span(stackalloc) -> stackalloc Span", inst); inst.ReplaceWith(locallocSpan); @@ -329,7 +329,7 @@ protected internal override void VisitNewObj(NewObj inst) inst.ReplaceWith(replacement); return; } - if (TransformDelegateCtorLdVirtFtnToLdVirtDelegate(inst, out LdVirtDelegate ldVirtDelegate)) + if (TransformDelegateCtorLdVirtFtnToLdVirtDelegate(inst, out LdVirtDelegate? ldVirtDelegate)) { context.Step("new Delegate(target, ldvirtftn Method) -> ldvirtdelegate Delegate Method(target)", inst); inst.ReplaceWith(ldVirtDelegate); @@ -462,7 +462,7 @@ protected internal override void VisitLdObj(LdObj inst) EarlyExpressionTransforms.AddressOfLdLocToLdLoca(inst, context); if (EarlyExpressionTransforms.LdObjToLdLoc(inst, context)) return; - if (TransformDecimalFieldToConstant(inst, out LdcDecimal decimalConstant)) + if (TransformDecimalFieldToConstant(inst, out LdcDecimal? decimalConstant)) { context.Step("TransformDecimalFieldToConstant", inst); inst.ReplaceWith(decimalConstant); @@ -549,8 +549,8 @@ IfInstruction HandleConditionalOperator(IfInstruction inst) Block? falseInst = inst.FalseInst as Block; if (falseInst == null || falseInst.Instructions.Count != 1) return inst; - ILVariable v; - ILInstruction value1, value2; + ILVariable? v; + ILInstruction? value1, value2; if (trueInst.Instructions[0].MatchStLoc(out v, out value1) && falseInst.Instructions[0].MatchStLoc(v, out value2)) { context.Step("conditional operator", inst); @@ -629,7 +629,7 @@ private void HandleSwitchExpression(BlockContainer container, SwitchInstruction { // validate that each integer is used for exactly one value var integersUsed = new HashSet(); - foreach ((string key, int val) in str2int.Map) + foreach ((string? key, int val) in str2int.Map) { if (!integersUsed.Add(val)) return; diff --git a/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs index c637979aa0..7ed3818d27 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/HighLevelLoopTransform.cs @@ -156,21 +156,21 @@ void SplitConditions(ILInstruction expression, List conditions) /// bool MatchDoWhileLoop(BlockContainer loop) { - (List? conditions, ILInstruction exit, bool swap, bool split, bool unwrap) = AnalyzeDoWhileConditions(loop); + (List? conditions, ILInstruction? exit, bool swap, bool split, bool unwrap) = AnalyzeDoWhileConditions(loop); // not a do-while loop, exit. if (conditions == null || conditions.Count == 0) return false; context.Step("Transform to do-while loop: " + loop.EntryPoint.Label, loop); Block conditionBlock; // first we remove all extracted instructions from the original block. - var originalBlock = (Block)exit.Parent; + var originalBlock = exit.Parent as Block; if (unwrap) { // we found a condition block nested in a condition that is followed by a return statement: // we flip the condition and swap the blocks Debug.Assert(originalBlock.Parent is IfInstruction); var returnCondition = (IfInstruction)originalBlock.Parent; - var topLevelBlock = (Block)returnCondition.Parent; + var topLevelBlock = returnCondition.Parent as Block; Debug.Assert(topLevelBlock.Parent == loop); var leaveFunction = topLevelBlock.Instructions[returnCondition.ChildIndex + 1]; Debug.Assert(leaveFunction.MatchReturn(out _)); diff --git a/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs b/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs index a3627a2213..12432ff90f 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs @@ -97,7 +97,7 @@ public bool CanReorderWithInstructionsBeingMoved(ILInstruction predecessor) /// /// May return null if extraction is not possible. /// - public static ILVariable Extract(ILInstruction instToExtract, ILTransformContext context) + public static ILVariable? Extract(ILInstruction instToExtract, ILTransformContext context) { var function = instToExtract.Ancestors.OfType().First(); ExtractionContext ctx = new ExtractionContext(function, context); diff --git a/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs b/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs index b94826d999..bc4ccdf3bc 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs @@ -577,7 +577,7 @@ static bool NonAggressiveInlineInto(ILInstruction next, FindResult findResult, I { if (findResult.Type == FindResultType.NamedArgument) { - var originalStore = (StLoc)inlinedExpression.Parent; + var originalStore = inlinedExpression.Parent as StLoc; return !originalStore.ILStackWasEmpty; } Debug.Assert(findResult.Type == FindResultType.Found); @@ -784,7 +784,7 @@ internal static FindResult FindLoadInNext(ILInstruction expr, ILVariable v, ILIn if (expr.MatchLdLoc(v) || expr.MatchLdLoca(v)) { // Match found, we can inline - if (expr.SlotInfo == StObj.TargetSlot && !((StObj)expr.Parent).CanInlineIntoTargetSlot(expressionBeingMoved)) + if (expr.SlotInfo == StObj.TargetSlot && !(expr.Parent as StObj).CanInlineIntoTargetSlot(expressionBeingMoved)) { if ((options & InliningOptions.AllowChangingOrderOfEvaluationForExceptions) != 0) { @@ -867,7 +867,7 @@ static bool IsSafeForInlineOver(ILInstruction expr, ILInstruction expressionBein /// /// Finds the first call instruction within the instructions that were inlined into inst. /// - internal static CallInstruction FindFirstInlinedCall(ILInstruction inst) + internal static CallInstruction? FindFirstInlinedCall(ILInstruction inst) { foreach (var child in inst.Children) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs index 03e1d62a81..640f9a8720 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs @@ -32,7 +32,7 @@ void IStatementTransform.Run(Block block, int pos, StatementTransformContext con return; int interpolationStart = pos; int interpolationEnd; - ILInstruction insertionPoint; + ILInstruction? insertionPoint; // stloc v(newobj DefaultInterpolatedStringHandler..ctor(ldc.i4 literalLength, ldc.i4 formattedCount)) if (block.Instructions[pos] is StLoc { Variable: ILVariable { Kind: VariableKind.Local } v, diff --git a/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs b/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs index f74c0cf0bc..a68dc8cc48 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs @@ -308,7 +308,7 @@ void AddAsArgument(int index, ILInstruction argument) } } - private ILInstruction FindCompatibleArgument(LocalFunctionInfo info, IList arguments, bool ignoreStructure = false) + private ILInstruction? FindCompatibleArgument(LocalFunctionInfo info, IList arguments, bool ignoreStructure = false) { foreach (var arg in arguments) { @@ -321,7 +321,7 @@ private ILInstruction FindCompatibleArgument(LocalFunctionInfo info, IList(function.DeclarationScope, closureVar.CaptureScope); return true; - ILInstruction GetClosureInitializer(ILVariable variable) + ILInstruction? GetClosureInitializer(ILVariable variable) { var type = variable.Type.UnwrapByRef().GetDefinition(); if (type == null) diff --git a/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs index cdf0a7de9a..6e988f7242 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs @@ -71,7 +71,7 @@ enum Mode /// Check if "condition ? trueInst : falseInst" can be simplified using the null-conditional operator. /// Returns the replacement instruction, or null if no replacement is possible. /// - internal ILInstruction Run(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) + internal ILInstruction? Run(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) { Debug.Assert(context.Settings.NullPropagation); Debug.Assert(!condition.MatchLogicNot(out _), "Caller should pass in positive condition"); @@ -107,7 +107,7 @@ internal ILInstruction Run(ILInstruction condition, ILInstruction trueInst, ILIn /// /// testedVar != null ? nonNullInst : nullInst /// - ILInstruction TryNullPropagation(ILVariable testedVar, ILInstruction nonNullInst, ILInstruction nullInst, + ILInstruction? TryNullPropagation(ILVariable testedVar, ILInstruction nonNullInst, ILInstruction nullInst, Mode mode) { bool removedRewrapOrNullableCtor = false; diff --git a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs index ed01185268..d721e08c99 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs @@ -176,7 +176,7 @@ bool AnalyzeNegatedCondition(ILInstruction condition) /// Main entry point for lifting; called by both the expression-transform /// and the block transform. /// - ILInstruction Lift(ILInstruction ifInst, ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) + ILInstruction? Lift(ILInstruction ifInst, ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) { // ifInst is usually the IfInstruction to which condition belongs; // but can also be a BinaryNumericInstruction. @@ -479,7 +479,7 @@ public IType RightExpectedType { } } - internal ILInstruction MakeLifted(ComparisonKind newComparisonKind, ILInstruction left, ILInstruction right) + internal ILInstruction? MakeLifted(ComparisonKind newComparisonKind, ILInstruction left, ILInstruction right) { if (Instruction is Comp comp) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs index 5a92f5cb24..d0a88b74c0 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs @@ -451,7 +451,7 @@ private void RemoveRedundantExit(Block block, ILInstruction implicitExit) /// /// [else-]if (parent-cond) else { ifInst } /// - private IfInstruction GetElseIfParent(IfInstruction ifInst) + private IfInstruction? GetElseIfParent(IfInstruction ifInst) { Debug.Assert(ifInst.Parent is Block); if (Block.Unwrap(ifInst.Parent) == ifInst && // only instruction in block diff --git a/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs b/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs index 4f3bbd6981..ce24e3a318 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs @@ -175,7 +175,7 @@ static AddressUse HandleCall(ILInstruction addressLoadingInstruction, ILVariable /// Given 'ldloc ref_local' and 'ldloca target; stloc ref_local', returns the ldloca. /// This function must return a non-null LdLoca for every use of a SupportedRefLocal. /// - static LdLoca GetAddressLoadForRefLocalUse(LdLoc ldloc) + static LdLoca? GetAddressLoadForRefLocalUse(LdLoc ldloc) { if (!ldloc.Variable.IsSingleDefinition) return null; // only single-definition variables can be supported ref locals diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs index 34b1294a15..74bdd9c52c 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs @@ -246,7 +246,7 @@ bool ValidateUse(DisplayClass container, ILInstruction use) } } - private DisplayClass AnalyzeVariable(ILVariable v) + private DisplayClass? AnalyzeVariable(ILVariable v) { switch (v.Kind) { @@ -265,7 +265,7 @@ private DisplayClass AnalyzeVariable(ILVariable v) } } - DisplayClass DetectDisplayClass(ILVariable v) + DisplayClass? DetectDisplayClass(ILVariable v) { ITypeDefinition? definition; if (v.Kind != VariableKind.StackSlot) @@ -385,7 +385,7 @@ ILInstruction VisitChildren(ILInstruction inst) } } - DisplayClass DetectDisplayClassInitializer(ILVariable v) + DisplayClass? DetectDisplayClassInitializer(ILVariable v) { if (v.StoreInstructions.Count != 1 || !(v.StoreInstructions[0] is StLoc store && store.Parent is Block initializerBlock && initializerBlock.Kind == BlockKind.ObjectInitializer)) return null; @@ -520,7 +520,7 @@ VariableToDeclare AddVariable(DisplayClass result, StObj statement, IField field /// If a value does not match either LdLoc or a LdObj LdLdFlda* LdLoc chain, null is returned. /// The if any of the variables/fields in the chain cannot be propagated, null is returned. /// - ILVariable ResolveVariableToPropagate(ILInstruction value, IType? expectedType = null) + ILVariable? ResolveVariableToPropagate(ILInstruction value, IType? expectedType = null) { ILVariable v; switch (value) @@ -634,7 +634,7 @@ bool IsMonoNestedCaptureScope(ITypeDefinition closureType) /// mcs likes to optimize closures in yield state machines away by moving the captured variables' fields into the state machine type, /// We construct a that spans the whole method body. /// - DisplayClass HandleMonoStateMachine(ILFunction function, ILVariable thisVariable) + DisplayClass? HandleMonoStateMachine(ILFunction function, ILVariable thisVariable) { if (!(function.StateMachineCompiledWithMono && thisVariable.IsThis())) return null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs index e054391517..3261dbb8c4 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs @@ -459,7 +459,7 @@ IType UnwrapExpressionTree(IType delegateType) if (!MatchArgumentList(invocation.Arguments[1], out var arguments)) arguments = new[] { invocation.Arguments[1] }; - ILInstruction Convert() + ILInstruction? Convert() { Func[] toBeConverted = new Func[arguments.Count]; for (int i = 0; i < arguments.Count; i++) @@ -683,7 +683,7 @@ ILInstruction UnpackConstant(ILInstruction inst) return call.Arguments[0]; } - Func[] ConvertCallArguments(IList arguments, IMethod method) + Func[]? ConvertCallArguments(IList arguments, IMethod method) { var converted = new Func[arguments.Count]; Debug.Assert(arguments.Count == method.Parameters.Count); @@ -1359,7 +1359,7 @@ ILInstruction BuildTypeAs() return (null, SpecialType.UnknownType); } - ILInstruction ConvertValue(ILInstruction value, ILInstruction context) + ILInstruction? ConvertValue(ILInstruction value, ILInstruction context) { switch (value) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs index 86ed3d3010..559e107ff9 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/UserDefinedLogicTransform.cs @@ -147,7 +147,7 @@ static bool MatchBitwiseCall(Call call, ILVariable v, string conditionMethodName /// if (call op_True(ldloc lhsVar)) ldloc lhsVar else call op_BitwiseOr(ldloc lhsVar, rhsInst) /// -> user.logic op_BitwiseOr(ldloc lhsVar, rhsInst) /// - public static ILInstruction Transform(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) + public static ILInstruction? Transform(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) { if (!MatchCondition(condition, out var lhsVar, out var conditionMethodName)) return null; @@ -164,7 +164,7 @@ public static ILInstruction Transform(ILInstruction condition, ILInstruction tru return result; } - public static ILInstruction TransformDynamic(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) + public static ILInstruction? TransformDynamic(ILInstruction condition, ILInstruction trueInst, ILInstruction falseInst) { // Check condition: System.Linq.Expressions.ExpressionType unaryOp; diff --git a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs index 9007bde8c6..d35b10b826 100644 --- a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs +++ b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs @@ -211,7 +211,7 @@ static IEnumerable LoadPackageInfos(string depsJsonFileNa } } - public string TryResolveDotNetCoreShared(IAssemblyReference name, out string? runtimePack) + public string? TryResolveDotNetCoreShared(IAssemblyReference name, out string? runtimePack) { if (dotnetBasePath == null) { @@ -286,7 +286,7 @@ string RemoveTrailingVersionInfo() } } - public static string FindDotNetExeDirectory() + public static string? FindDotNetExeDirectory() { string dotnetExeName = (Environment.OSVersion.Platform == PlatformID.Unix) ? "dotnet" : "dotnet.exe"; foreach (var item in Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator)) @@ -312,7 +312,7 @@ public static string FindDotNetExeDirectory() return null; } - static unsafe string GetRealPath(string path, Encoding encoding) + static unsafe string? GetRealPath(string path, Encoding encoding) { var bytes = encoding.GetBytes(path); fixed (byte* input = bytes) diff --git a/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs index 17f203f34e..ba52d003ea 100644 --- a/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs +++ b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs @@ -329,7 +329,7 @@ public double AsNumber { /// Gets this value as a String type. /// /// This value as a String type. - public string AsString { + public string? AsString { get { switch (this.Type) { @@ -354,7 +354,7 @@ public string AsString { /// Gets this value as an JsonObject. /// /// This value as an JsonObject. - public JsonObject AsJsonObject { + public JsonObject? AsJsonObject { get { return this.IsJsonObject ? (JsonObject)this.reference @@ -366,7 +366,7 @@ public JsonObject AsJsonObject { /// Gets this value as an JsonArray. /// /// This value as an JsonArray. - public JsonArray AsJsonArray { + public JsonArray? AsJsonArray { get { return this.IsJsonArray ? (JsonArray)this.reference @@ -397,7 +397,7 @@ public DateTime? AsDateTime { /// Gets this (inner) value as a System.object. /// /// This (inner) value as a System.object. - public object AsObject { + public object? AsObject { get { switch (this.Type) { @@ -808,7 +808,7 @@ public JsonValueDebugView(JsonValue jsonValue) } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public JsonObject ObjectView { + public JsonObject? ObjectView { get { if (this.jsonValue.IsJsonObject) { @@ -822,7 +822,7 @@ public JsonObject ObjectView { } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public JsonArray ArrayView { + public JsonArray? ArrayView { get { if (this.jsonValue.IsJsonArray) { diff --git a/ICSharpCode.Decompiler/NRExtensions.cs b/ICSharpCode.Decompiler/NRExtensions.cs index 58850d2b89..638c3d63f5 100644 --- a/ICSharpCode.Decompiler/NRExtensions.cs +++ b/ICSharpCode.Decompiler/NRExtensions.cs @@ -92,7 +92,7 @@ public override IType VisitTypeDefinition(ITypeDefinition type) } } - internal static string GetDocumentation(this IEntity entity) + internal static string? GetDocumentation(this IEntity entity) { var docProvider = XmlDocLoader.LoadDocumentation(entity.ParentModule.MetadataFile); if (docProvider == null) diff --git a/ICSharpCode.Decompiler/Output/TextTokenWriter.cs b/ICSharpCode.Decompiler/Output/TextTokenWriter.cs index d225feeaa3..eb0a446af8 100644 --- a/ICSharpCode.Decompiler/Output/TextTokenWriter.cs +++ b/ICSharpCode.Decompiler/Output/TextTokenWriter.cs @@ -108,7 +108,7 @@ public override void WriteIdentifier(Identifier identifier) output.Write(name); } - ISymbol GetCurrentMemberReference() + ISymbol? GetCurrentMemberReference() { AstNode node = nodeStack.Peek(); var symbol = node.GetSymbol(); @@ -130,7 +130,7 @@ ISymbol GetCurrentMemberReference() return FilterMember(symbol); } - ISymbol FilterMember(ISymbol symbol) + ISymbol? FilterMember(ISymbol symbol) { if (symbol == null) return null; @@ -141,7 +141,7 @@ ISymbol FilterMember(ISymbol symbol) return symbol; } - object GetCurrentLocalReference() + object? GetCurrentLocalReference() { AstNode node = nodeStack.Peek(); ILVariable variable = node.Annotation()?.Variable; @@ -169,7 +169,7 @@ object GetCurrentLocalReference() return null; } - object GetCurrentLocalDefinition(Identifier id) + object? GetCurrentLocalDefinition(Identifier id) { AstNode node = nodeStack.Peek(); if (node is Identifier && node.Parent != null) @@ -213,7 +213,7 @@ object GetCurrentLocalDefinition(Identifier id) return null; } - ISymbol GetCurrentDefinition() + ISymbol? GetCurrentDefinition() { if (nodeStack == null || nodeStack.Count == 0) return null; diff --git a/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs b/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs index 4c7922b1f7..4eb744def2 100644 --- a/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs @@ -62,7 +62,7 @@ public override bool IsCompileTimeConstant { get { return variable.IsConst; } } - public override object ConstantValue { + public override object? ConstantValue { get { return IsParameter ? null : variable.GetConstantValue(); } } diff --git a/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs b/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs index babf67d830..b5c27eaa43 100644 --- a/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs @@ -123,7 +123,7 @@ public FunctionPointerType(MetadataModule module, public override TypeKind Kind => ((module.TypeSystemOptions & TypeSystemOptions.FunctionPointers) != 0) ? TypeKind.FunctionPointer : TypeKind.Struct; - public override ITypeDefinition GetDefinition() + public override ITypeDefinition? GetDefinition() { if ((module.TypeSystemOptions & TypeSystemOptions.FunctionPointers) != 0) { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs index 66d77a7357..66eedf359b 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs @@ -283,7 +283,7 @@ internal bool HasAttribute(MetadataReader metadata, CustomAttributeHandleCollect return false; } - internal IAttribute GetAttribute(MetadataReader metadata, CustomAttributeHandleCollection customAttributes, KnownAttribute attribute, SymbolKind symbolKind) + internal IAttribute? GetAttribute(MetadataReader metadata, CustomAttributeHandleCollection customAttributes, KnownAttribute attribute, SymbolKind symbolKind) { Debug.Assert(attribute.IsCustomAttribute()); foreach (var h in customAttributes) diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/CustomAttribute.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/CustomAttribute.cs index 9ef6883303..f760cc27c7 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/CustomAttribute.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/CustomAttribute.cs @@ -109,7 +109,7 @@ void DecodeValue() } } - internal static IMember MemberForNamedArgument(IType attributeType, CustomAttributeNamedArgument namedArgument) + internal static IMember? MemberForNamedArgument(IType attributeType, CustomAttributeNamedArgument namedArgument) { switch (namedArgument.Kind) { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecimalConstantHelper.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecimalConstantHelper.cs index effeb11a17..777d440a29 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecimalConstantHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecimalConstantHelper.cs @@ -32,7 +32,7 @@ public static bool IsDecimalConstant(MetadataModule module, CustomAttributeHandl return attributeHandles.HasKnownAttribute(module.metadata, KnownAttribute.DecimalConstant); } - public static object GetDecimalConstantValue(MetadataModule module, CustomAttributeHandleCollection attributeHandles) + public static object? GetDecimalConstantValue(MetadataModule module, CustomAttributeHandleCollection attributeHandles) { var metadata = module.metadata; foreach (var attributeHandle in attributeHandles) diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs index aa89607bfb..7263903422 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs @@ -39,7 +39,7 @@ public DefaultAssemblyReference(string assemblyName) shortName = assemblyName; } - public IModule Resolve(ITypeResolveContext context) + public IModule? Resolve(ITypeResolveContext context) { IModule current = context.CurrentModule; if (current != null && string.Equals(shortName, current.AssemblyName, StringComparison.OrdinalIgnoreCase)) diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs index 16f96c6e56..06b5519a6f 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs @@ -163,7 +163,7 @@ VarianceModifier ITypeParameter.Variance { get { return VarianceModifier.Invariant; } } - IEntity ITypeParameter.Owner { + IEntity? ITypeParameter.Owner { get { return null; } } diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs index 13426414aa..3bb07edfef 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/FakeMember.cs @@ -63,7 +63,7 @@ protected FakeMember(ICompilation compilation) IEnumerable IEntity.GetAttributes() => EmptyList.Instance; bool IEntity.HasAttribute(KnownAttribute attribute) => false; - IAttribute IEntity.GetAttribute(KnownAttribute attribute) => null; + IAttribute? IEntity.GetAttribute(KnownAttribute attribute) => null; public Accessibility Accessibility { get; set; } = Accessibility.Public; @@ -114,7 +114,7 @@ public FakeField(ICompilation compilation) : base(compilation) bool IField.IsVolatile => false; bool IVariable.IsConst => false; - object IVariable.GetConstantValue(bool throwOnInvalidMetadata) => null; + object? IVariable.GetConstantValue(bool throwOnInvalidMetadata) => null; IType IVariable.Type => ReturnType; public override SymbolKind SymbolKind => SymbolKind.Field; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs index ac27c97ec3..56d1321083 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs @@ -84,7 +84,7 @@ public GetClassTypeReference(IModuleReference module, string namespaceName, stri /// public FullTypeName FullTypeName { get { return fullTypeName; } } - internal static IType ResolveInAllAssemblies(ICompilation compilation, in FullTypeName fullTypeName) + internal static IType? ResolveInAllAssemblies(ICompilation compilation, in FullTypeName fullTypeName) { foreach (var asm in compilation.Modules) { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs index 5d2f71bd16..f05b248dca 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs @@ -108,7 +108,7 @@ public IEnumerable ChildNamespaces { get { return GetChildNamespaces().Values; } } - public INamespace GetChildNamespace(string name) + public INamespace? GetChildNamespace(string name) { INamespace ns; if (GetChildNamespaces().TryGetValue(name, out ns)) diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs index 6a35f85687..729d1e5ba6 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs @@ -86,7 +86,7 @@ IEnumerable INamespace.Types { ICompilation ICompilationProvider.Compilation => module.Compilation; - INamespace INamespace.GetChildNamespace(string name) + INamespace? INamespace.GetChildNamespace(string name) { foreach (var ns in ChildNamespaces) { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataParameter.cs index 14bee08dc5..0222e19b9a 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataParameter.cs @@ -156,7 +156,7 @@ public string Name { bool IVariable.IsConst => false; - public object GetConstantValue(bool throwOnInvalidMetadata) + public object? GetConstantValue(bool throwOnInvalidMetadata) { try { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs index 0f8f557341..63b267aa44 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs @@ -59,7 +59,7 @@ protected void AddSubstitution(TypeParameterSubstitution newSubstitution) this.substitution = TypeParameterSubstitution.Compose(newSubstitution, this.substitution); } - internal IMethod WrapAccessor(ref IMethod cachingField, IMethod accessorDefinition) + internal IMethod? WrapAccessor(ref IMethod cachingField, IMethod accessorDefinition) { if (accessorDefinition == null) return null; diff --git a/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs b/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs index 154f063756..b4b82f604a 100644 --- a/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs @@ -109,7 +109,7 @@ public static IEnumerable GetBaseMembers(IMember member, bool includeIm /// /// Finds the member declared in 'derivedType' that has the same signature (could override) 'baseMember'. /// - public static IMember GetDerivedMember(IMember baseMember, ITypeDefinition derivedType) + public static IMember? GetDerivedMember(IMember baseMember, ITypeDefinition derivedType) { if (baseMember == null) throw new ArgumentNullException(nameof(baseMember)); @@ -185,7 +185,7 @@ internal static IEnumerable GetAttributes(ITypeDefinition typeDef) } } - internal static IAttribute GetAttribute(ITypeDefinition typeDef, KnownAttribute attributeType) + internal static IAttribute? GetAttribute(ITypeDefinition typeDef, KnownAttribute attributeType) { foreach (var baseType in typeDef.GetNonInterfaceBaseTypes().Reverse()) { @@ -217,7 +217,7 @@ internal static IEnumerable GetAttributes(IMember member) } while (member.IsOverride && (member = InheritanceHelper.GetBaseMember(member)) != null); } - internal static IAttribute GetAttribute(IMember member, KnownAttribute attributeType) + internal static IAttribute? GetAttribute(IMember member, KnownAttribute attributeType) { HashSet visitedMembers = new HashSet(); do diff --git a/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs b/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs index a7c2881fa9..f8aac8452a 100644 --- a/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs +++ b/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs @@ -192,7 +192,7 @@ string[] GetInternalsVisibleTo() return LazyInit.GetOrSet(ref this.internalsVisibleTo, result); } - static string GetShortName(string fullAssemblyName) + static string? GetShortName(string fullAssemblyName) { if (fullAssemblyName == null) return null; @@ -217,7 +217,7 @@ public IEnumerable TypeDefinitions { } } - public ITypeDefinition GetDefinition(TypeDefinitionHandle handle) + public ITypeDefinition? GetDefinition(TypeDefinitionHandle handle) { if (handle.IsNil) return null; @@ -233,7 +233,7 @@ public ITypeDefinition GetDefinition(TypeDefinitionHandle handle) return LazyInit.GetOrSet(ref typeDefs[row], typeDef); } - public IField GetDefinition(FieldDefinitionHandle handle) + public IField? GetDefinition(FieldDefinitionHandle handle) { if (handle.IsNil) return null; @@ -249,7 +249,7 @@ public IField GetDefinition(FieldDefinitionHandle handle) return LazyInit.GetOrSet(ref fieldDefs[row], field); } - public IMethod GetDefinition(MethodDefinitionHandle handle) + public IMethod? GetDefinition(MethodDefinitionHandle handle) { if (handle.IsNil) return null; @@ -266,7 +266,7 @@ public IMethod GetDefinition(MethodDefinitionHandle handle) return LazyInit.GetOrSet(ref methodDefs[row], method); } - public IProperty GetDefinition(PropertyDefinitionHandle handle) + public IProperty? GetDefinition(PropertyDefinitionHandle handle) { if (handle.IsNil) return null; @@ -283,7 +283,7 @@ public IProperty GetDefinition(PropertyDefinitionHandle handle) return LazyInit.GetOrSet(ref propertyDefs[row], property); } - public IEvent GetDefinition(EventDefinitionHandle handle) + public IEvent? GetDefinition(EventDefinitionHandle handle) { if (handle.IsNil) return null; @@ -308,7 +308,7 @@ void HandleOutOfRange(EntityHandle handle) #region Resolve Module - public IModule ResolveModule(AssemblyReferenceHandle handle) + public IModule? ResolveModule(AssemblyReferenceHandle handle) { if (handle.IsNil) return null; @@ -332,7 +332,7 @@ IModule ResolveModuleUncached(AssemblyReferenceHandle handle) return Compilation.FindModuleByReference(asmRef); } - public IModule ResolveModule(ModuleReferenceHandle handle) + public IModule? ResolveModule(ModuleReferenceHandle handle) { if (handle.IsNil) return null; @@ -348,7 +348,7 @@ public IModule ResolveModule(ModuleReferenceHandle handle) return null; } - public IModule GetDeclaringModule(TypeReferenceHandle handle) + public IModule? GetDeclaringModule(TypeReferenceHandle handle) { if (handle.IsNil) return null; @@ -747,7 +747,7 @@ private void GuessFakeMethodAccessor(IType declaringType, string name, MethodSig /// * May return specialized members, where generics are involved. /// * Other types of handles that don't correspond to TS entities, will return null. /// - public IEntity ResolveEntity(EntityHandle entityHandle, GenericContext context = default) + public IEntity? ResolveEntity(EntityHandle entityHandle, GenericContext context = default) { switch (entityHandle.Kind) { @@ -904,7 +904,7 @@ IType ResolveForwardedType(ExportedType forwarder) } return new UnknownType(typeName); - IModule ResolveModule(ExportedType type) + IModule? ResolveModule(ExportedType type) { switch (type.Implementation.Kind) { diff --git a/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs b/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs index b7309ba738..9608b6c591 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs @@ -442,7 +442,7 @@ static ITypeReference CreateGetClassTypeReference(string assemblyName, string ty return new GetClassTypeReference(assemblyReference, typeName.Substring(0, pos), typeName.Substring(pos + 1), tpc); } - static string SkipAheadAndReadAssemblyName(string reflectionTypeName, int pos) + static string? SkipAheadAndReadAssemblyName(string reflectionTypeName, int pos) { int nestingLevel = 0; while (pos < reflectionTypeName.Length) diff --git a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs index 4eab3d4306..59f1d4b4b8 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs @@ -144,7 +144,7 @@ public static bool IsTupleCompatible(IType type, out int tupleCardinality) /// Construct a tuple type (without element names) from the given underlying type. /// Returns null if the input is not a valid underlying type. /// - public static TupleType FromUnderlyingType(ICompilation compilation, IType type) + public static TupleType? FromUnderlyingType(ICompilation compilation, IType type) { var elementTypes = GetTupleElementTypes(type); if (elementTypes.Length > 0) diff --git a/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs b/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs index 39c2bcad3e..d73b54b29e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs @@ -160,7 +160,7 @@ public IType GetTypeFromReference(SRM.MetadataReader reader, SRM.TypeReferenceHa return type ?? new UnknownType(fullTypeName, IsReferenceType(reader, handle, rawTypeKind)); } - public IType GetTypeFromSerializedName(string name) + public IType? GetTypeFromSerializedName(string name) { if (name == null) { diff --git a/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs b/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs index ca75ab3a7e..c52d62c14c 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs @@ -354,7 +354,7 @@ internal static bool IsKnownType(this TopLevelTypeName typeName, KnownAttribute /// /// Returns null if the type is not a delegate type; or if the invoke method could not be found. /// - public static IMethod GetDelegateInvokeMethod(this IType type) + public static IMethod? GetDelegateInvokeMethod(this IType type) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -461,7 +461,7 @@ public static IType FindType(this ICompilation compilation, FullTypeName fullTyp /// Gets the type definition for the specified unresolved type. /// Returns null if the unresolved type does not belong to this assembly. /// - public static ITypeDefinition GetTypeDefinition(this IModule module, FullTypeName fullTypeName) + public static ITypeDefinition? GetTypeDefinition(this IModule module, FullTypeName fullTypeName) { if (module == null) throw new ArgumentNullException("assembly"); @@ -481,7 +481,7 @@ public static ITypeDefinition GetTypeDefinition(this IModule module, FullTypeNam return typeDef; } - static ITypeDefinition FindNestedType(ITypeDefinition typeDef, string name, int typeParameterCount) + static ITypeDefinition? FindNestedType(ITypeDefinition typeDef, string name, int typeParameterCount) { foreach (var nestedType in typeDef.NestedTypes) { @@ -626,7 +626,7 @@ public static ITypeDefinition GetTypeDefinition(this IModule module, string name #endregion #region ResolveResult - public static ISymbol GetSymbol(this ResolveResult rr) + public static ISymbol? GetSymbol(this ResolveResult rr) { if (rr is LocalResolveResult) { @@ -713,7 +713,7 @@ public static bool IsDirectImportOf(this ITypeDefinition type, IModule module) return false; } - public static IModule FindModuleByReference(this ICompilation compilation, IAssemblyReference assemblyName) + public static IModule? FindModuleByReference(this ICompilation compilation, IAssemblyReference assemblyName) { foreach (var module in compilation.Modules) { @@ -749,7 +749,7 @@ public static IType AsParameterizedType(this ITypeDefinition td) } } - public static INamespace GetNamespaceByFullName(this ICompilation compilation, string name) + public static INamespace? GetNamespaceByFullName(this ICompilation compilation, string name) { if (string.IsNullOrEmpty(name)) return compilation.RootNamespace; diff --git a/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs b/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs index b57516b453..ee940d9d8b 100644 --- a/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs +++ b/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs @@ -34,7 +34,7 @@ public static class CSharpPrimitiveCast /// /// Overflow checking is enabled and an overflow occurred. /// The cast is invalid, e.g. casting a boolean to an integer. - public static object Cast(TypeCode targetType, object input, bool checkForOverflow) + public static object? Cast(TypeCode targetType, object input, bool checkForOverflow) { if (input == null) return null; diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs index e7f83f6385..b54f31f2ec 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs @@ -64,6 +64,6 @@ public override void ActivateItem(IPlatformRoutedEventArgs e) MainWindow.Instance.JumpToReference(analyzedModule.MetadataFile); } - public override IEntity Member => null; + public override IEntity? Member => null; } } diff --git a/ILSpy/App.xaml.cs b/ILSpy/App.xaml.cs index c136891a1a..92c46a1f50 100644 --- a/ILSpy/App.xaml.cs +++ b/ILSpy/App.xaml.cs @@ -122,7 +122,7 @@ private static void SingleInstance_NewInstanceDetected(object sender, NewInstanc #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } - static Assembly ResolvePluginDependencies(AssemblyLoadContext context, AssemblyName assemblyName) + static Assembly? ResolvePluginDependencies(AssemblyLoadContext context, AssemblyName assemblyName) { var rootPath = Path.GetDirectoryName(typeof(App).Assembly.Location); var assemblyFileName = Path.Combine(rootPath, assemblyName.Name + ".dll"); diff --git a/ILSpy/AppEnv/CommandLineTools.cs b/ILSpy/AppEnv/CommandLineTools.cs index 7379db12eb..5f7c14dec2 100644 --- a/ILSpy/AppEnv/CommandLineTools.cs +++ b/ILSpy/AppEnv/CommandLineTools.cs @@ -56,7 +56,7 @@ public static string[] CommandLineToArgumentArray(string commandLine) /// - (2n) + 1 backslashes followed by a quotation mark again produce n backslashes followed by a quotation mark. /// - n backslashes not followed by a quotation mark simply produce n backslashes. /// - public static string ArgumentArrayToCommandLine(params string[] arguments) + public static string? ArgumentArrayToCommandLine(params string[] arguments) { if (arguments == null) return null; diff --git a/ILSpy/Commands/CopyFullyQualifiedNameContextMenuEntry.cs b/ILSpy/Commands/CopyFullyQualifiedNameContextMenuEntry.cs index 47490e37bc..446f434ed2 100644 --- a/ILSpy/Commands/CopyFullyQualifiedNameContextMenuEntry.cs +++ b/ILSpy/Commands/CopyFullyQualifiedNameContextMenuEntry.cs @@ -42,7 +42,7 @@ public void Execute(TextViewContext context) Clipboard.SetText(member.ReflectionName); } - private IMemberTreeNode GetMemberNodeFromContext(TextViewContext context) + private IMemberTreeNode? GetMemberNodeFromContext(TextViewContext context) { return context.SelectedTreeNodes?.Length == 1 ? context.SelectedTreeNodes[0] as IMemberTreeNode : null; } diff --git a/ILSpy/Commands/SaveCodeContextMenuEntry.cs b/ILSpy/Commands/SaveCodeContextMenuEntry.cs index d7e38ada3d..ada78fcba5 100644 --- a/ILSpy/Commands/SaveCodeContextMenuEntry.cs +++ b/ILSpy/Commands/SaveCodeContextMenuEntry.cs @@ -101,7 +101,7 @@ public static void Execute(IReadOnlyList selectedNodes) /// will be used. /// /// The full path of the selected target file, or null if the user canceled. - static string SelectSolutionFile() + static string? SelectSolutionFile() { SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = "Solution.sln"; diff --git a/ILSpy/Commands/ScopeSearchToNamespace.cs b/ILSpy/Commands/ScopeSearchToNamespace.cs index 645f9d425e..83dceb0029 100644 --- a/ILSpy/Commands/ScopeSearchToNamespace.cs +++ b/ILSpy/Commands/ScopeSearchToNamespace.cs @@ -75,7 +75,7 @@ public bool IsVisible(TextViewContext context) return GetNamespace(context) != null; } - string GetNamespace(TextViewContext context) + string? GetNamespace(TextViewContext context) { if (context.Reference?.Reference is IEntity entity) return entity.Namespace; diff --git a/ILSpy/Controls/ExtensionMethods.cs b/ILSpy/Controls/ExtensionMethods.cs index 15e40eb7b9..a0931e3fbb 100644 --- a/ILSpy/Controls/ExtensionMethods.cs +++ b/ILSpy/Controls/ExtensionMethods.cs @@ -60,7 +60,7 @@ public SetValueToExtensionServiceProvider(DependencyObject targetObject, Depende this.targetProperty = property; } - public object GetService(Type serviceType) + public object? GetService(Type serviceType) { if (serviceType == typeof(IProvideValueTarget)) return this; diff --git a/ILSpy/Controls/TreeView/LinesRenderer.cs b/ILSpy/Controls/TreeView/LinesRenderer.cs index ca62d3b313..4508cc0711 100644 --- a/ILSpy/Controls/TreeView/LinesRenderer.cs +++ b/ILSpy/Controls/TreeView/LinesRenderer.cs @@ -32,7 +32,7 @@ static LinesRenderer() static Pen pen; - SharpTreeNodeView NodeView { + SharpTreeNodeView? NodeView { get { return TemplatedParent as SharpTreeNodeView; } } diff --git a/ILSpy/Controls/TreeView/SharpTreeNodeView.cs b/ILSpy/Controls/TreeView/SharpTreeNodeView.cs index a7cca88386..002cc9ba11 100644 --- a/ILSpy/Controls/TreeView/SharpTreeNodeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeNodeView.cs @@ -43,7 +43,7 @@ public Brush TextBackground { set { SetValue(TextBackgroundProperty, value); } } - public SharpTreeNode Node { + public SharpTreeNode? Node { get { return DataContext as SharpTreeNode; } } diff --git a/ILSpy/Controls/TreeView/SharpTreeView.cs b/ILSpy/Controls/TreeView/SharpTreeView.cs index faa7cb2f05..13b8417403 100644 --- a/ILSpy/Controls/TreeView/SharpTreeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeView.cs @@ -420,7 +420,7 @@ public void ScrollIntoView(SharpTreeNode node) base.ScrollIntoView(node); } - object OnFocusItem(object item) + object? OnFocusItem(object item) { FrameworkElement element = this.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement; if (element != null) @@ -531,7 +531,7 @@ class DropTarget public int Index; } - DropTarget GetDropTarget(SharpTreeViewItem item, DragEventArgs e) + DropTarget? GetDropTarget(SharpTreeViewItem item, DragEventArgs e) { var dropTargets = BuildDropTargets(item, e); var y = e.GetPosition(item).Y; diff --git a/ILSpy/Controls/TreeView/SharpTreeViewItem.cs b/ILSpy/Controls/TreeView/SharpTreeViewItem.cs index 5ec32d855f..727f8822d2 100644 --- a/ILSpy/Controls/TreeView/SharpTreeViewItem.cs +++ b/ILSpy/Controls/TreeView/SharpTreeViewItem.cs @@ -34,7 +34,7 @@ static SharpTreeViewItem() new FrameworkPropertyMetadata(typeof(SharpTreeViewItem))); } - public SharpTreeNode Node { + public SharpTreeNode? Node { get { return DataContext as SharpTreeNode; } } diff --git a/ILSpy/Docking/DockLayoutSettings.cs b/ILSpy/Docking/DockLayoutSettings.cs index fc776db795..dc39265009 100644 --- a/ILSpy/Docking/DockLayoutSettings.cs +++ b/ILSpy/Docking/DockLayoutSettings.cs @@ -77,7 +77,7 @@ public DockLayoutSettings(XElement element) } } - public XElement SaveAsXml() + public XElement? SaveAsXml() { try { diff --git a/ILSpy/Languages/CSharpBracketSearcher.cs b/ILSpy/Languages/CSharpBracketSearcher.cs index 28a7a4fd23..9967d4f6b0 100644 --- a/ILSpy/Languages/CSharpBracketSearcher.cs +++ b/ILSpy/Languages/CSharpBracketSearcher.cs @@ -33,7 +33,7 @@ class CSharpBracketSearcher : IBracketSearcher string openingBrackets = "([{"; string closingBrackets = ")]}"; - public BracketSearchResult SearchBracket(IDocument document, int offset) + public BracketSearchResult? SearchBracket(IDocument document, int offset) { if (offset > 0) { diff --git a/ILSpy/Languages/CSharpHighlightingTokenWriter.cs b/ILSpy/Languages/CSharpHighlightingTokenWriter.cs index fe229607a4..c6edcfd4b1 100644 --- a/ILSpy/Languages/CSharpHighlightingTokenWriter.cs +++ b/ILSpy/Languages/CSharpHighlightingTokenWriter.cs @@ -474,7 +474,7 @@ public override void WritePrimitiveValue(object value, Decompiler.CSharp.Syntax. } } - ISymbol GetCurrentDefinition() + ISymbol? GetCurrentDefinition() { if (nodeStack == null || nodeStack.Count == 0) return null; @@ -488,7 +488,7 @@ ISymbol GetCurrentDefinition() return null; } - ISymbol GetCurrentMemberReference() + ISymbol? GetCurrentMemberReference() { if (nodeStack == null || nodeStack.Count == 0) return null; diff --git a/ILSpy/Languages/CSharpLanguage.cs b/ILSpy/Languages/CSharpLanguage.cs index df801511c8..c62222a0b1 100644 --- a/ILSpy/Languages/CSharpLanguage.cs +++ b/ILSpy/Languages/CSharpLanguage.cs @@ -418,7 +418,7 @@ void AddWarningMessage(MetadataFile module, ITextOutput output, string line1, st } } - public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) + public override ProjectId? DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { var module = assembly.GetMetadataFileOrNull(); if (module == null) @@ -702,7 +702,7 @@ static string ToCSharpString(MetadataReader metadata, TypeDefinitionHandle handl } } - public override string GetEntityName(MetadataFile module, EntityHandle handle, bool fullName, bool omitGenerics) + public override string? GetEntityName(MetadataFile module, EntityHandle handle, bool fullName, bool omitGenerics) { MetadataReader metadata = module.Metadata; switch (handle.Kind) diff --git a/ILSpy/Languages/ILLanguage.cs b/ILSpy/Languages/ILLanguage.cs index 22d060b373..29681b982c 100644 --- a/ILSpy/Languages/ILLanguage.cs +++ b/ILSpy/Languages/ILLanguage.cs @@ -163,7 +163,7 @@ public override void DecompileNamespace(string nameSpace, IEnumerable (TypeDefinitionHandle)t.MetadataToken)); } - public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) + public override ProjectId? DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { output.WriteLine("// " + assembly.FileName); output.WriteLine(); @@ -195,7 +195,7 @@ public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput return null; } - public override RichText GetRichTextTooltip(IEntity entity) + public override RichText? GetRichTextTooltip(IEntity entity) { var output = new AvalonEditTextOutput() { IgnoreNewLineAndIndent = true }; var disasm = CreateDisassembler(output, MainWindow.Instance.CreateDecompilationOptions()); diff --git a/ILSpy/Languages/Language.cs b/ILSpy/Languages/Language.cs index 26410fe243..5374a8eec4 100644 --- a/ILSpy/Languages/Language.cs +++ b/ILSpy/Languages/Language.cs @@ -52,7 +52,7 @@ public abstract class Language : ILanguage /// public abstract string FileExtension { get; } - public virtual string ProjectFileExtension { + public virtual string? ProjectFileExtension { get { return null; } } @@ -107,7 +107,7 @@ public virtual void DecompileNamespace(string nameSpace, IEnumerable /// This should produce a string representation of the entity for search to match search strings against. /// - public virtual string GetEntityName(MetadataFile module, EntityHandle handle, bool fullName, bool omitGenerics) + public virtual string? GetEntityName(MetadataFile module, EntityHandle handle, bool fullName, bool omitGenerics) { MetadataReader metadata = module.Metadata; switch (handle.Kind) diff --git a/ILSpy/MainWindow.xaml.cs b/ILSpy/MainWindow.xaml.cs index 21271efeb7..87c9ce1219 100644 --- a/ILSpy/MainWindow.xaml.cs +++ b/ILSpy/MainWindow.xaml.cs @@ -83,7 +83,7 @@ public static MainWindow Instance { get { return instance; } } - public SharpTreeView AssemblyTreeView { + public SharpTreeView? AssemblyTreeView { get { return FindResource("AssemblyTreeView") as SharpTreeView; } @@ -312,7 +312,7 @@ MenuItem GetOrAddParentMenuItem(string menuID, string resourceKey) } } - internal static string GetResourceString(string key) + internal static string? GetResourceString(string key) { if (string.IsNullOrEmpty(key)) { @@ -1109,7 +1109,7 @@ internal void SelectNodes(IEnumerable nodes, bool inNewTabPage, /// /// Retrieves a node using the .ToString() representations of its ancestors. /// - public SharpTreeNode FindNodeByPath(string[] path, bool returnBestMatch) + public SharpTreeNode? FindNodeByPath(string[] path, bool returnBestMatch) { if (path == null) return null; @@ -1135,7 +1135,7 @@ public SharpTreeNode FindNodeByPath(string[] path, bool returnBestMatch) /// /// Gets the .ToString() representation of the node's ancestors. /// - public static string[] GetPathForNode(SharpTreeNode node) + public static string[]? GetPathForNode(SharpTreeNode node) { if (node == null) return null; @@ -1149,7 +1149,7 @@ public static string[] GetPathForNode(SharpTreeNode node) return path.ToArray(); } - public ILSpyTreeNode FindTreeNode(object reference) + public ILSpyTreeNode? FindTreeNode(object reference) { switch (reference) { @@ -1586,7 +1586,7 @@ protected override void OnClosing(CancelEventArgs e) sessionSettings.Save(); } - private string GetAutoLoadedAssemblyNode(SharpTreeNode node) + private string? GetAutoLoadedAssemblyNode(SharpTreeNode node) { if (node == null) return null; diff --git a/ILSpy/Metadata/CoffHeaderTreeNode.cs b/ILSpy/Metadata/CoffHeaderTreeNode.cs index 78eca5bf2f..ab6859024f 100644 --- a/ILSpy/Metadata/CoffHeaderTreeNode.cs +++ b/ILSpy/Metadata/CoffHeaderTreeNode.cs @@ -116,7 +116,7 @@ public CharacteristicsDataTemplateSelector(string detailsFieldName) this.detailsFieldName = detailsFieldName; } - public override DataTemplate SelectTemplate(object item, DependencyObject container) + public override DataTemplate? SelectTemplate(object item, DependencyObject container) { if (((Entry)item).Member == detailsFieldName) return (DataTemplate)MetadataTableViews.Instance["HeaderFlagsDetailsDataGrid"]; diff --git a/ILSpy/Metadata/CorTables/AssemblyRefTableTreeNode.cs b/ILSpy/Metadata/CorTables/AssemblyRefTableTreeNode.cs index d47f49a1a0..3dbdd38a8b 100644 --- a/ILSpy/Metadata/CorTables/AssemblyRefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/AssemblyRefTableTreeNode.cs @@ -89,7 +89,7 @@ struct AssemblyRefEntry [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int PublicKeyOrToken => MetadataTokens.GetHeapOffset(assemblyRef.PublicKeyOrToken); - public string PublicKeyOrTokenTooltip { + public string? PublicKeyOrTokenTooltip { get { if (assemblyRef.PublicKeyOrToken.IsNil) return null; diff --git a/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs b/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs index e6c41e5aae..45155e67e8 100644 --- a/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs @@ -97,7 +97,7 @@ public void OnParentClick() [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Value => MetadataTokens.GetHeapOffset(constant.Value); - public string ValueTooltip { + public string? ValueTooltip { get { return null; } diff --git a/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs b/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs index bae1ceffdd..1249ca69e7 100644 --- a/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs @@ -103,7 +103,7 @@ public void OnConstructorClick() [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Value => MetadataTokens.GetHeapOffset(customAttr.Value); - public string ValueTooltip { + public string? ValueTooltip { get { return null; } diff --git a/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs b/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs index b719f678c5..91ab69defd 100644 --- a/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs @@ -102,7 +102,7 @@ public string ActionTooltip { [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int PermissionSet => MetadataTokens.GetHeapOffset(declSecAttr.PermissionSet); - public string PermissionSetTooltip { + public string? PermissionSetTooltip { get { return null; } diff --git a/ILSpy/Metadata/CorTables/FileTableTreeNode.cs b/ILSpy/Metadata/CorTables/FileTableTreeNode.cs index f48edcb396..896774477f 100644 --- a/ILSpy/Metadata/CorTables/FileTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FileTableTreeNode.cs @@ -90,7 +90,7 @@ struct FileEntry [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int HashValue => MetadataTokens.GetHeapOffset(assemblyFile.HashValue); - public string HashValueTooltip { + public string? HashValueTooltip { get { if (assemblyFile.HashValue.IsNil) return null; diff --git a/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs b/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs index b6f9ac6b47..fe5cb173ca 100644 --- a/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs @@ -122,7 +122,7 @@ public void OnParamListClick() } string paramListTooltip; - public string ParamListTooltip { + public string? ParamListTooltip { get { var param = methodDef.GetParameters().FirstOrDefault(); if (param.IsNil) diff --git a/ILSpy/Metadata/CorTables/ModuleTableTreeNode.cs b/ILSpy/Metadata/CorTables/ModuleTableTreeNode.cs index 490d0ed5ca..1a2b269902 100644 --- a/ILSpy/Metadata/CorTables/ModuleTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ModuleTableTreeNode.cs @@ -83,12 +83,12 @@ struct ModuleEntry [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int GenerationId => MetadataTokens.GetHeapOffset(moduleDef.GenerationId); - public string GenerationIdTooltip => moduleDef.GenerationId.IsNil ? null : metadataFile.Metadata.GetGuid(moduleDef.GenerationId).ToString(); + public string? GenerationIdTooltip => moduleDef.GenerationId.IsNil ? null : metadataFile.Metadata.GetGuid(moduleDef.GenerationId).ToString(); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int BaseGenerationId => MetadataTokens.GetHeapOffset(moduleDef.BaseGenerationId); - public string BaseGenerationIdTooltip => moduleDef.BaseGenerationId.IsNil ? null : metadataFile.Metadata.GetGuid(moduleDef.BaseGenerationId).ToString(); + public string? BaseGenerationIdTooltip => moduleDef.BaseGenerationId.IsNil ? null : metadataFile.Metadata.GetGuid(moduleDef.BaseGenerationId).ToString(); public ModuleEntry(MetadataFile metadataFile, ModuleDefinitionHandle handle) { diff --git a/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs b/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs index 8f9ac73fb9..1ae59f107b 100644 --- a/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs @@ -114,7 +114,7 @@ public void OnBaseTypeClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, typeDef.BaseType, protocol: "metadata")); } - public string BaseTypeTooltip { + public string? BaseTypeTooltip { get { var output = new PlainTextOutput(); var provider = new DisassemblerSignatureTypeProvider(metadataFile, output); @@ -146,7 +146,7 @@ public void OnFieldListClick() } string fieldListTooltip; - public string FieldListTooltip { + public string? FieldListTooltip { get { var field = typeDef.GetFields().FirstOrDefault(); if (field.IsNil) @@ -164,7 +164,7 @@ public void OnMethodListClick() } string methodListTooltip; - public string MethodListTooltip { + public string? MethodListTooltip { get { var method = typeDef.GetMethods().FirstOrDefault(); if (method.IsNil) diff --git a/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs b/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs index f9ef9f3692..9dcbe2f019 100644 --- a/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs @@ -243,7 +243,7 @@ public string ValueTooltip { object rowDetails; - public object RowDetails { + public object? RowDetails { get { if (rowDetails != null) return rowDetails; diff --git a/ILSpy/Metadata/DebugTables/DocumentTableTreeNode.cs b/ILSpy/Metadata/DebugTables/DocumentTableTreeNode.cs index 320fdffffe..c24b6f19f0 100644 --- a/ILSpy/Metadata/DebugTables/DocumentTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/DocumentTableTreeNode.cs @@ -84,7 +84,7 @@ readonly struct DocumentEntry [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int HashAlgorithm => MetadataTokens.GetHeapOffset(document.HashAlgorithm); - public string HashAlgorithmTooltip { + public string? HashAlgorithmTooltip { get { if (document.HashAlgorithm.IsNil) return null; @@ -100,7 +100,7 @@ public string HashAlgorithmTooltip { [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Hash => MetadataTokens.GetHeapOffset(document.Hash); - public string HashTooltip { + public string? HashTooltip { get { if (document.Hash.IsNil) return null; @@ -112,7 +112,7 @@ public string HashTooltip { [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Language => MetadataTokens.GetHeapOffset(document.Language); - public string LanguageTooltip { + public string? LanguageTooltip { get { if (document.Language.IsNil) return null; diff --git a/ILSpy/Metadata/DebugTables/MethodDebugInformationTableTreeNode.cs b/ILSpy/Metadata/DebugTables/MethodDebugInformationTableTreeNode.cs index 80aede7fc0..4059cce6d0 100644 --- a/ILSpy/Metadata/DebugTables/MethodDebugInformationTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/MethodDebugInformationTableTreeNode.cs @@ -86,7 +86,7 @@ public void OnDocumentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, debugInfo.Document, protocol: "metadata")); } - public string DocumentTooltip { + public string? DocumentTooltip { get { if (debugInfo.Document.IsNil) return null; @@ -98,7 +98,7 @@ public string DocumentTooltip { [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int SequencePoints => MetadataTokens.GetHeapOffset(debugInfo.SequencePointsBlob); - public string SequencePointsTooltip { + public string? SequencePointsTooltip { get { if (debugInfo.SequencePointsBlob.IsNil) return null; @@ -119,7 +119,7 @@ public void OnLocalSignatureClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, debugInfo.LocalSignature, protocol: "metadata")); } - public string LocalSignatureTooltip { + public string? LocalSignatureTooltip { get { if (debugInfo.LocalSignature.IsNil) return null; diff --git a/ILSpy/Metadata/GoToTokenCommand.cs b/ILSpy/Metadata/GoToTokenCommand.cs index 1c0caca2b7..9a57de5258 100644 --- a/ILSpy/Metadata/GoToTokenCommand.cs +++ b/ILSpy/Metadata/GoToTokenCommand.cs @@ -90,7 +90,7 @@ public bool IsVisible(TextViewContext context) && GetSelectedCellContent(context.DataGrid, context.MousePosition) != null; } - private string GetSelectedCellContent(DataGrid grid, Point position) + private string? GetSelectedCellContent(DataGrid grid, Point position) { position = grid.PointFromScreen(position); var hit = VisualTreeHelper.HitTest(grid, position); diff --git a/ILSpy/Metadata/MetadataProtocolHandler.cs b/ILSpy/Metadata/MetadataProtocolHandler.cs index c49e300d76..a0008d21e3 100644 --- a/ILSpy/Metadata/MetadataProtocolHandler.cs +++ b/ILSpy/Metadata/MetadataProtocolHandler.cs @@ -29,7 +29,7 @@ namespace ICSharpCode.ILSpy.Metadata [PartCreationPolicy(CreationPolicy.Shared)] class MetadataProtocolHandler : IProtocolHandler { - public ILSpyTreeNode Resolve(string protocol, MetadataFile module, Handle handle, out bool newTabPage) + public ILSpyTreeNode? Resolve(string protocol, MetadataFile module, Handle handle, out bool newTabPage) { newTabPage = true; if (protocol != "metadata") diff --git a/ILSpy/Metadata/MetadataTableTreeNode.cs b/ILSpy/Metadata/MetadataTableTreeNode.cs index 2df51f1c63..18e678804e 100644 --- a/ILSpy/Metadata/MetadataTableTreeNode.cs +++ b/ILSpy/Metadata/MetadataTableTreeNode.cs @@ -66,7 +66,7 @@ private void View_Loaded(object sender, System.Windows.RoutedEventArgs e) this.scrollTarget = default; } - protected static string GenerateTooltip(ref string tooltip, MetadataFile module, EntityHandle handle) + protected static string? GenerateTooltip(ref string tooltip, MetadataFile module, EntityHandle handle) { if (tooltip == null) { diff --git a/ILSpy/Search/SearchPane.xaml.cs b/ILSpy/Search/SearchPane.xaml.cs index a3a7584a2a..8e824a3c60 100644 --- a/ILSpy/Search/SearchPane.xaml.cs +++ b/ILSpy/Search/SearchPane.xaml.cs @@ -435,7 +435,7 @@ SearchRequest Parse(string input) } } - Regex CreateRegex(string s) + Regex? CreateRegex(string s) { try { @@ -492,7 +492,7 @@ await Task.Factory.StartNew(() => { } } - AbstractSearchStrategy GetSearchStrategy(SearchRequest request) + AbstractSearchStrategy? GetSearchStrategy(SearchRequest request) { if (request.Keywords.Length == 0 && request.RegEx == null) return null; diff --git a/ILSpy/TextView/BracketHighlightRenderer.cs b/ILSpy/TextView/BracketHighlightRenderer.cs index 4b958d407a..cf27cd7bd5 100644 --- a/ILSpy/TextView/BracketHighlightRenderer.cs +++ b/ILSpy/TextView/BracketHighlightRenderer.cs @@ -40,7 +40,7 @@ public class DefaultBracketSearcher : IBracketSearcher { public static readonly DefaultBracketSearcher DefaultInstance = new DefaultBracketSearcher(); - public BracketSearchResult SearchBracket(IDocument document, int offset) + public BracketSearchResult? SearchBracket(IDocument document, int offset) { return null; } diff --git a/ILSpy/TextView/ReferenceElementGenerator.cs b/ILSpy/TextView/ReferenceElementGenerator.cs index f1255990a8..ebcfb2774a 100644 --- a/ILSpy/TextView/ReferenceElementGenerator.cs +++ b/ILSpy/TextView/ReferenceElementGenerator.cs @@ -52,7 +52,7 @@ public override int GetFirstInterestedOffset(int startOffset) return segment != null ? segment.StartOffset : -1; } - public override VisualLineElement ConstructElement(int offset) + public override VisualLineElement? ConstructElement(int offset) { if (this.References == null) return null; diff --git a/ILSpy/TextView/UIElementGenerator.cs b/ILSpy/TextView/UIElementGenerator.cs index e0c254e618..0d0f90cba1 100644 --- a/ILSpy/TextView/UIElementGenerator.cs +++ b/ILSpy/TextView/UIElementGenerator.cs @@ -53,7 +53,7 @@ public override int GetFirstInterestedOffset(int startOffset) return -1; } - public override VisualLineElement ConstructElement(int offset) + public override VisualLineElement? ConstructElement(int offset) { if (this.UIElements == null) return null; diff --git a/ILSpy/TreeNodes/AssemblyListTreeNode.cs b/ILSpy/TreeNodes/AssemblyListTreeNode.cs index 9808ddcfd3..3b1bc8bc03 100644 --- a/ILSpy/TreeNodes/AssemblyListTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyListTreeNode.cs @@ -130,7 +130,7 @@ public override void Decompile(Language language, ITextOutput output, Decompilat } #region Find*Node - public ILSpyTreeNode FindResourceNode(Resource resource) + public ILSpyTreeNode? FindResourceNode(Resource resource) { if (resource == null) return null; @@ -169,14 +169,14 @@ public AssemblyTreeNode FindAssemblyNode(IModule module) return FindAssemblyNode(module.MetadataFile); } - public AssemblyTreeNode FindAssemblyNode(MetadataFile module) + public AssemblyTreeNode? FindAssemblyNode(MetadataFile module) { if (module == null) return null; return FindAssemblyNode(module.GetLoadedAssembly()); } - public AssemblyTreeNode FindAssemblyNode(LoadedAssembly asm) + public AssemblyTreeNode? FindAssemblyNode(LoadedAssembly asm) { if (asm == null) return null; @@ -203,7 +203,7 @@ public AssemblyTreeNode FindAssemblyNode(LoadedAssembly asm) } return null; - static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) + static SharpTreeNodeCollection? ExpandAndGetChildren(SharpTreeNode node) { if (node is not PackageFolderTreeNode) return null; @@ -216,7 +216,7 @@ static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) /// Looks up the type node corresponding to the type definition. /// Returns null if no matching node is found. /// - public TypeTreeNode FindTypeNode(ITypeDefinition def) + public TypeTreeNode? FindTypeNode(ITypeDefinition def) { if (def == null) return null; @@ -245,7 +245,7 @@ public TypeTreeNode FindTypeNode(ITypeDefinition def) /// Looks up the method node corresponding to the method definition. /// Returns null if no matching node is found. /// - public ILSpyTreeNode FindMethodNode(IMethod def) + public ILSpyTreeNode? FindMethodNode(IMethod def) { TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) @@ -286,7 +286,7 @@ public ILSpyTreeNode FindMethodNode(IMethod def) /// Looks up the field node corresponding to the field definition. /// Returns null if no matching node is found. /// - public FieldTreeNode FindFieldNode(IField def) + public FieldTreeNode? FindFieldNode(IField def) { TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) @@ -299,7 +299,7 @@ public FieldTreeNode FindFieldNode(IField def) /// Looks up the property node corresponding to the property definition. /// Returns null if no matching node is found. /// - public PropertyTreeNode FindPropertyNode(IProperty def) + public PropertyTreeNode? FindPropertyNode(IProperty def) { TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) @@ -312,7 +312,7 @@ public PropertyTreeNode FindPropertyNode(IProperty def) /// Looks up the event node corresponding to the event definition. /// Returns null if no matching node is found. /// - public EventTreeNode FindEventNode(IEvent def) + public EventTreeNode? FindEventNode(IEvent def) { TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) @@ -325,7 +325,7 @@ public EventTreeNode FindEventNode(IEvent def) /// Looks up the event node corresponding to the namespace definition. /// Returns null if no matching node is found. /// - public NamespaceTreeNode FindNamespaceNode(INamespace def) + public NamespaceTreeNode? FindNamespaceNode(INamespace def) { var module = def.ContributingModules.FirstOrDefault(); if (module == null) diff --git a/ILSpy/TreeNodes/AssemblyTreeNode.cs b/ILSpy/TreeNodes/AssemblyTreeNode.cs index d2f102ef2f..1f4c0b794d 100644 --- a/ILSpy/TreeNodes/AssemblyTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyTreeNode.cs @@ -387,7 +387,7 @@ private static void SetPublicAPI(NamespaceTreeNode ns) /// /// Finds the node for a top-level type. /// - public TypeTreeNode FindTypeNode(ITypeDefinition type) + public TypeTreeNode? FindTypeNode(ITypeDefinition type) { if (type == null) return null; @@ -402,7 +402,7 @@ public TypeTreeNode FindTypeNode(ITypeDefinition type) /// /// Finds the node for a namespace. /// - public NamespaceTreeNode FindNamespaceNode(string namespaceName) + public NamespaceTreeNode? FindNamespaceNode(string namespaceName) { if (string.IsNullOrEmpty(namespaceName)) return null; @@ -730,7 +730,7 @@ public bool IsVisible(TextViewContext context) }); } - internal static AssemblyTreeNode GetAssemblyTreeNode(SharpTreeNode node) + internal static AssemblyTreeNode? GetAssemblyTreeNode(SharpTreeNode node) { while (node != null) { diff --git a/ILSpy/Updates/NotifyOfUpdatesStrategy.cs b/ILSpy/Updates/NotifyOfUpdatesStrategy.cs index 1d5123c261..4bff0a0d84 100644 --- a/ILSpy/Updates/NotifyOfUpdatesStrategy.cs +++ b/ILSpy/Updates/NotifyOfUpdatesStrategy.cs @@ -61,7 +61,7 @@ public static async Task GetLatestVersionAsync() /// Returns the download URL if an update is available. /// Returns null if no update is available, or if no check was performed. /// - public static async Task CheckForUpdatesIfEnabledAsync(ILSpySettings spySettings) + public static async Task CheckForUpdatesIfEnabledAsync(ILSpySettings spySettings) { UpdateSettings s = new UpdateSettings(spySettings); @@ -93,7 +93,7 @@ public static Task CheckForUpdatesAsync(ILSpySettings spySettings) return CheckForUpdateInternal(s); } - static async Task CheckForUpdateInternal(UpdateSettings s) + static async Task CheckForUpdateInternal(UpdateSettings s) { try { From 73a79213b0a8089adce6b820dc46f7866800e242 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 11:20:21 -0400 Subject: [PATCH 09/15] more nullable error cleanups --- .editorconfig | 1 + ICSharpCode.Decompiler/CSharp/CallBuilder.cs | 12 ++--- .../CSharp/RecordDecompiler.cs | 2 +- .../Resolver/MethodGroupResolveResult.cs | 4 +- .../InterpolatedStringExpression.cs | 2 +- .../CSharp/Syntax/Statements/Statement.cs | 4 +- .../CSharp/Syntax/TypeMembers/Accessor.cs | 2 +- .../TypeMembers/EnumMemberDeclaration.cs | 2 +- .../CSharp/Transforms/DeclareVariables.cs | 2 +- .../CSharp/Transforms/FixNameCollisions.cs | 2 +- .../Transforms/IntroduceQueryExpressions.cs | 6 +-- ...ransformFieldAndConstructorInitializers.cs | 2 +- ICSharpCode.Decompiler/DecompilerException.cs | 18 ++++---- .../Disassembler/ReflectionDisassembler.cs | 2 +- .../IL/ControlFlow/AsyncAwaitDecompiler.cs | 44 +++++++++---------- .../IL/ControlFlow/DetectPinnedRegions.cs | 14 +++--- .../Transforms/EarlyExpressionTransforms.cs | 2 +- .../IL/Transforms/IndexRangeTransform.cs | 6 +-- .../Metadata/DotNetCorePathFinder.cs | 4 +- .../TypeSystem/ApplyAttributeTypeVisitor.cs | 2 +- .../TypeSystem/DecompilerTypeSystem.cs | 4 +- .../Implementation/MetadataEvent.cs | 2 +- .../Implementation/MetadataProperty.cs | 2 +- .../TypeSystem/TypeProvider.cs | 2 +- .../TypeSystem/TypeSystemExtensions.cs | 2 +- ICSharpCode.ILSpyX/Abstractions/ILanguage.cs | 2 +- ILSpy.ReadyToRun/ReadyToRunLanguage.cs | 2 +- ILSpy/Analyzers/AnalyzerEntityTreeNode.cs | 4 +- .../TreeNodes/AnalyzedEventTreeNode.cs | 2 +- .../TreeNodes/AnalyzedFieldTreeNode.cs | 2 +- .../TreeNodes/AnalyzedMethodTreeNode.cs | 2 +- .../TreeNodes/AnalyzedPropertyTreeNode.cs | 2 +- .../TreeNodes/AnalyzedTypeTreeNode.cs | 2 +- ILSpy/App.xaml.cs | 11 +++-- ILSpy/AvalonEdit/TextMarkerService.cs | 4 +- ILSpy/Commands/CommandWrapper.cs | 2 +- ILSpy/Commands/DelegateCommand.cs | 4 +- ILSpy/Commands/IProtocolHandler.cs | 2 +- ILSpy/Commands/SimpleCommand.cs | 6 +-- ILSpy/Controls/SearchBox.cs | 2 +- ILSpy/Controls/TreeView/SharpTreeNodeView.cs | 2 +- ILSpy/Controls/TreeView/SharpTreeView.cs | 2 +- .../SharpTreeViewItemAutomationPeer.cs | 14 +++--- ILSpy/Docking/DockWorkspace.cs | 4 +- ILSpy/Docking/PaneCollection.cs | 2 +- ILSpy/LanguageSettings.cs | 4 +- ILSpy/Languages/Language.cs | 2 +- ILSpy/MainWindow.xaml.cs | 10 ++--- ILSpy/Metadata/Helpers.cs | 4 +- ILSpy/Metadata/MetaDataGrid.cs | 4 +- ILSpy/Options/DecompilerSettingsViewModel.cs | 2 +- ILSpy/Options/DisplaySettings.cs | 4 +- ILSpy/Options/MiscSettingsViewModel.cs | 4 +- ILSpy/Search/SearchPane.xaml.cs | 2 +- ILSpy/SessionSettings.cs | 4 +- ILSpy/TextView/BracketHighlightRenderer.cs | 2 +- ILSpy/Themes/WindowStyleManagerBehavior.cs | 6 +-- ILSpy/TreeNodes/AssemblyListTreeNode.cs | 4 +- ILSpy/TreeNodes/ILSpyTreeNode.cs | 4 +- ILSpy/Updates/NotifyOfUpdatesStrategy.cs | 2 +- ILSpy/Updates/UpdateSettings.cs | 4 +- ILSpy/ViewModels/PaneModel.cs | 4 +- ILSpy/ViewModels/ViewModelBase.cs | 4 +- 63 files changed, 144 insertions(+), 144 deletions(-) diff --git a/.editorconfig b/.editorconfig index 7f28f99087..767ae4a998 100644 --- a/.editorconfig +++ b/.editorconfig @@ -153,6 +153,7 @@ dotnet_diagnostic.IDE2003.severity = silent #cleared null error types dotnet_diagnostic.CS8612.severity = error +dotnet_diagnostic.CS8622.severity = error dotnet_diagnostic.CS8714.severity = error dotnet_diagnostic.CS8762.severity = error dotnet_diagnostic.CS8765.severity = error diff --git a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs index 5e2d7c6ee2..4b86a1334d 100644 --- a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs @@ -777,7 +777,7 @@ private enum TokenKind ArgumentWithAlignmentAndFormat, } - private IEnumerable<(TokenKind, string)> TokenizeFormatString(string value) + private IEnumerable<(TokenKind, string?)> TokenizeFormatString(string value) { int pos = -1; @@ -1395,7 +1395,7 @@ private ExpressionWithResolveResult HandleImplicitConversion(IMethod method, Tra } OverloadResolutionErrors IsUnambiguousCall(ExpectedTargetDetails expectedTargetDetails, IMethod method, - ResolveResult target, IType[] typeArguments, ResolveResult[] arguments, + ResolveResult? target, IType[] typeArguments, ResolveResult[] arguments, string[]? argumentNames, int firstOptionalArgumentIndex, out IParameterizedMember? foundMember, out bool bestCandidateIsExpandedForm) { @@ -1676,7 +1676,7 @@ bool IsAppropriateCallTarget(ExpectedTargetDetails expectedTargetDetails, IMembe return false; } - ExpressionWithResolveResult HandleConstructorCall(ExpectedTargetDetails expectedTargetDetails, ResolveResult target, IMethod method, ArgumentList argumentList) + ExpressionWithResolveResult HandleConstructorCall(ExpectedTargetDetails expectedTargetDetails, ResolveResult? target, IMethod method, ArgumentList argumentList) { if (settings.AnonymousTypes && method.DeclaringType.IsAnonymousType()) { @@ -1823,7 +1823,7 @@ internal ExpressionWithResolveResult BuildMethodReference(IMethod method, bool i return expr.Expression.WithRR(new MemberResolveResult(null, method)); } - ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod? invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg) + ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod? invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction? thisArg) { ExpressionBuilder expressionBuilder = this.expressionBuilder; ExpressionWithResolveResult targetExpression; @@ -1850,11 +1850,11 @@ ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod? invo } - (TranslatedExpression target, bool addTypeArguments, string methodName, ResolveResult result) DisambiguateDelegateReference(IMethod method, IMethod invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg) + (TranslatedExpression target, bool addTypeArguments, string? methodName, ResolveResult result) DisambiguateDelegateReference(IMethod method, IMethod invokeMethod, ExpectedTargetDetails expectedTargetDetails, ILInstruction? thisArg) { if (method.IsLocalFunction) { - ILFunction localFunction = expressionBuilder.ResolveLocalFunction(method); + ILFunction? localFunction = expressionBuilder.ResolveLocalFunction(method); Debug.Assert(localFunction != null); return (default, addTypeArguments: true, localFunction.Name, ToMethodGroup(method, localFunction)); } diff --git a/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs b/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs index f1788bb7cc..91d77e1b65 100644 --- a/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs @@ -267,7 +267,7 @@ static List DetectMemberOrder(ITypeDefinition recordTypeDef, Dictionary /// /// Gets the detected primary constructor. Returns null, if there was no primary constructor detected. /// - public IMethod PrimaryConstructor => primaryCtor; + public IMethod? PrimaryConstructor => primaryCtor; public bool IsInheritedRecord => isInheritedRecord; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs index 3dbb5bf7a4..6c5542c94d 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs @@ -79,10 +79,10 @@ public class MethodGroupResolveResult : ResolveResult { readonly IReadOnlyList methodLists; readonly IReadOnlyList typeArguments; - readonly ResolveResult targetResult; + readonly ResolveResult? targetResult; readonly string methodName; - public MethodGroupResolveResult(ResolveResult targetResult, string methodName, + public MethodGroupResolveResult(ResolveResult? targetResult, string methodName, IReadOnlyList methods, IReadOnlyList typeArguments) : base(SpecialType.NoType) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs index 332dc6f3f8..2573c9a5d2 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs @@ -106,7 +106,7 @@ public Expression Expression { public int Alignment { get; } - public string Suffix { get; } + public string? Suffix { get; } public CSharpTokenNode RBraceToken { get { return GetChildByRole(RBrace); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs index 75ecaad58e..92198d5a08 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs @@ -86,12 +86,12 @@ public override void AcceptVisitor(IAstVisitor visitor) visitor.VisitPatternPlaceholder(this, child); } - public override T? AcceptVisitor(IAstVisitor visitor) + public override T AcceptVisitor(IAstVisitor visitor) { return visitor.VisitPatternPlaceholder(this, child); } - public override S? AcceptVisitor(IAstVisitor visitor, T data) + public override S AcceptVisitor(IAstVisitor visitor, T data) { return visitor.VisitPatternPlaceholder(this, child, data); } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs index 890666c8e1..acd6713157 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs @@ -89,7 +89,7 @@ public CSharpTokenNode Keyword { } } - public BlockStatement Body { + public BlockStatement? Body { get { return GetChildByRole(Roles.Body); } set { SetChildByRole(Roles.Body, value); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs index b4f58e628e..cc42720a45 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs @@ -40,7 +40,7 @@ public CSharpTokenNode AssignToken { get { return GetChildByRole(Roles.Assign); } } - public Expression Initializer { + public Expression? Initializer { get { return GetChildByRole(InitializerRole); } set { SetChildByRole(InitializerRole, value); } } diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs index d73ed5ef01..b36e180a58 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs @@ -766,7 +766,7 @@ void UpdateAnnotations(AstNode rootNode) { foreach (var node in rootNode.Descendants) { - ILVariable ilVar; + ILVariable? ilVar; switch (node) { case IdentifierExpression id: diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs index b5edb964d8..db9031008f 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs @@ -50,7 +50,7 @@ public void Run(AstNode rootNode, TransformContext context) if (fieldDecl.Variables.Count != 1) continue; string oldName = fieldDecl.Variables.Single().Name; - ISymbol symbol = fieldDecl.GetSymbol(); + ISymbol? symbol = fieldDecl.GetSymbol(); if (memberNames.Contains(oldName) && ((IField)symbol).Accessibility == Accessibility.Private) { string newName = PickNewName(memberNames, oldName); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs index 457b5331a5..ab6f1c7f0c 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs @@ -80,7 +80,7 @@ bool IsDegenerateQuery(QueryExpression query) void DecompileQueries(AstNode node) { - Expression query = DecompileQuery(node as InvocationExpression); + Expression? query = DecompileQuery(node as InvocationExpression); if (query != null) { if (node.Parent is ExpressionStatement && CanUseDiscardAssignment()) @@ -351,13 +351,13 @@ Expression WrapExpressionInParenthesesIfNecessary(Expression expression, string /// /// Ensure that all ThenBy's are correct, and that the list of ThenBy's is terminated by an 'OrderBy' invocation. /// - bool ValidateThenByChain(InvocationExpression invocation, string expectedParameterName) + bool ValidateThenByChain(InvocationExpression? invocation, string expectedParameterName) { if (invocation == null || invocation.Arguments.Count != 1) return false; if (!(invocation.Target is MemberReferenceExpression mre)) return false; - if (!MatchSimpleLambda(invocation.Arguments.Single(), out ParameterDeclaration parameter, out _)) + if (!MatchSimpleLambda(invocation.Arguments.Single(), out ParameterDeclaration? parameter, out _)) return false; if (parameter.Name != expectedParameterName) return false; diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs index 5ac5dba868..96bafdb26c 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs @@ -184,7 +184,7 @@ void HandleInstanceFieldInitializers(IEnumerable members) if (instanceCtorsNotChainingWithThis.Length > 0) { var ctorMethodDef = instanceCtorsNotChainingWithThis[0].GetSymbol() as IMethod; - ITypeDefinition declaringTypeDefinition = ctorMethodDef?.DeclaringTypeDefinition; + ITypeDefinition? declaringTypeDefinition = ctorMethodDef?.DeclaringTypeDefinition; if (ctorMethodDef != null && declaringTypeDefinition?.IsReferenceType == false && !declaringTypeDefinition.IsRecord) return; diff --git a/ICSharpCode.Decompiler/DecompilerException.cs b/ICSharpCode.Decompiler/DecompilerException.cs index 412a1d395b..63f06f7201 100644 --- a/ICSharpCode.Decompiler/DecompilerException.cs +++ b/ICSharpCode.Decompiler/DecompilerException.cs @@ -36,15 +36,15 @@ namespace ICSharpCode.Decompiler /// public class DecompilerException : Exception, ISerializable { - public string AssemblyName => File.Name; + public string? AssemblyName => File?.Name; - public string FileName => File.FileName; + public string? FileName => File?.FileName; - public IEntity DecompiledEntity { get; } - public IModule Module { get; } - public MetadataFile File { get; } + public IEntity? DecompiledEntity { get; } + public IModule? Module { get; } + public MetadataFile? File { get; } - public DecompilerException(MetadataModule module, IEntity decompiledEntity, + public DecompilerException(MetadataModule module, IEntity? decompiledEntity, Exception innerException, string? message = null) : base(message ?? GetDefaultMessage(decompiledEntity), innerException) { @@ -115,7 +115,7 @@ static string GetStackTrace(Exception exception) for (int i = 0; i < stackTrace.FrameCount; i++) { StackFrame? frame = stackTrace.GetFrame(i); - MethodBase? method = frame.GetMethod(); + MethodBase? method = frame?.GetMethod(); if (method == null) continue; @@ -126,7 +126,7 @@ static string GetStackTrace(Exception exception) Type? declaringType = method.DeclaringType; if (declaringType != null) { - b.Append(declaringType.FullName.Replace('+', '.')); + b.Append(declaringType.FullName?.Replace('+', '.')); b.Append('.'); } b.Append(method.Name); @@ -168,7 +168,7 @@ static string GetStackTrace(Exception exception) b.Append(')'); // source location - if (frame.GetILOffset() >= 0) + if (frame?.GetILOffset() >= 0) { string? filename = null; try diff --git a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs index 9e130ead26..75a3c2877d 100644 --- a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs @@ -1188,7 +1188,7 @@ void WriteConstant(MetadataReader metadata, Constant constant) break; default: var blob = metadata.GetBlobReader(constant.Value); - object value; + object? value; try { value = blob.ReadConstant(constant.TypeCode); diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs index 68459498d3..d8789bd13c 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs @@ -74,29 +74,29 @@ enum AsyncMethodType ILTransformContext context; // These fields are set by MatchTaskCreationPattern() or MatchEnumeratorCreationNewObj() - IType taskType; // return type of the async method; or IAsyncEnumerable{T}/IAsyncEnumerator{T} - IType underlyingReturnType; // return type of the method (only the "T" for Task{T}), for async enumerators this is the type being yielded + IType? taskType; // return type of the async method; or IAsyncEnumerable{T}/IAsyncEnumerator{T} + IType? underlyingReturnType; // return type of the method (only the "T" for Task{T}), for async enumerators this is the type being yielded AsyncMethodType methodType; - ITypeDefinition stateMachineType; - IType builderType; - IField builderField; - IField stateField; + ITypeDefinition? stateMachineType; + IType? builderType; + IField? builderField; + IField? stateField; int initialState; Dictionary fieldToParameterMap = new Dictionary(); Dictionary cachedFieldToParameterMap = new Dictionary(); - IField disposeModeField; // 'disposeMode' field (IAsyncEnumerable/IAsyncEnumerator only) + IField? disposeModeField; // 'disposeMode' field (IAsyncEnumerable/IAsyncEnumerator only) // These fields are set by AnalyzeMoveNext(): - ILFunction moveNextFunction; - ILVariable cachedStateVar; // variable in MoveNext that caches the stateField. - TryCatch mainTryCatch; - Block setResultReturnBlock; // block that is jumped to for return statements - // Note: for async enumerators, a jump to setResultReturnBlock is a 'yield break;' + ILFunction? moveNextFunction; + ILVariable? cachedStateVar; // variable in MoveNext that caches the stateField. + TryCatch? mainTryCatch; + Block? setResultReturnBlock; // block that is jumped to for return statements + // Note: for async enumerators, a jump to setResultReturnBlock is a 'yield break;' int finalState; // final state after the setResultAndExitBlock bool finalStateKnown; - ILVariable resultVar; // the variable that gets returned by the setResultAndExitBlock - Block setResultYieldBlock; // block that is jumped to for 'yield return' statements - ILVariable doFinallyBodies; + ILVariable? resultVar; // the variable that gets returned by the setResultAndExitBlock + Block? setResultYieldBlock; // block that is jumped to for 'yield return' statements + ILVariable? doFinallyBodies; // These fields are set by AnalyzeStateMachine(): int smallestAwaiterVarIndex; @@ -295,15 +295,15 @@ call Start(ldloca V_1, ldloca V_0) } if (startCall.Arguments.Count != 2) return false; - ILInstruction loadBuilderExpr = startCall.Arguments[0]; - if (!startCall.Arguments[1].MatchLdLoca(out ILVariable stateMachineVar)) + ILInstruction? loadBuilderExpr = startCall.Arguments[0]; + if (!startCall.Arguments[1].MatchLdLoca(out ILVariable? stateMachineVar)) return false; stateMachineType = stateMachineVar.Type.GetDefinition(); if (stateMachineType == null) return false; pos--; - if (loadBuilderExpr.MatchLdLocRef(out ILVariable builderVar)) + if (loadBuilderExpr.MatchLdLocRef(out ILVariable? builderVar)) { // Check third-to-last instruction (copy of builder) // stloc builder(ldfld StateMachine::<>t__builder(ldloc stateMachine)) @@ -340,8 +340,8 @@ call Start(ldloca V_1, ldloca V_0) return false; if (!MatchCall(returnValue, "get_Task", out var getTaskArgs) || getTaskArgs.Count != 1) return false; - ILInstruction target; - IField builderField2; + ILInstruction? target; + IField? builderField2; if (builderType.IsReferenceType == true) { if (!getTaskArgs[0].MatchLdFld(out target, out builderField2)) @@ -804,7 +804,7 @@ bool MatchYieldBlock(BlockContainer blockContainer, int pos) return block.Instructions[1].MatchLeave(blockContainer); } - private Block CheckSetResultReturnBlock(BlockContainer blockContainer, int setResultReturnBlockIndex, bool[] blocksAnalyzed) + private Block? CheckSetResultReturnBlock(BlockContainer blockContainer, int setResultReturnBlockIndex, bool[] blocksAnalyzed) { if (setResultReturnBlockIndex >= blockContainer.Blocks.Count) { @@ -1931,7 +1931,7 @@ private void CleanDoFinallyBodies(ILFunction function) context.StepEndGroup(keepIfEmpty: true); } - internal static Block GetBodyEntryPoint(BlockContainer body) + internal static Block? GetBodyEntryPoint(BlockContainer? body) { if (body == null) return null; diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs index 53e5f2c1c5..a20a515fa9 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs @@ -163,7 +163,7 @@ void DetectNullSafeArrayToPointerOrCustomRefPin(BlockContainer container) for (int i = 0; i < container.Blocks.Count; i++) { var block = container.Blocks[i]; - if (IsNullSafeArrayToPointerPattern(block, out ILVariable v, out ILVariable p, out Block targetBlock)) + if (IsNullSafeArrayToPointerPattern(block, out ILVariable? v, out ILVariable? p, out Block? targetBlock)) { context.Step("NullSafeArrayToPointerPattern", block); ILInstruction arrayToPointer = new GetPinnableReference(new LdLoc(v), null); @@ -176,7 +176,7 @@ void DetectNullSafeArrayToPointerOrCustomRefPin(BlockContainer container) ((Branch)block.Instructions.Last()).TargetBlock = targetBlock; modified = true; } - else if (IsCustomRefPinPattern(block, out ILInstruction ldlocMem, out var callGPR, out v, out var stlocPtr, + else if (IsCustomRefPinPattern(block, out ILInstruction? ldlocMem, out var callGPR, out v, out var stlocPtr, out targetBlock, out var nullBlock, out var notNullBlock)) { context.Step("CustomRefPinPattern", block); @@ -432,7 +432,7 @@ bool IsNullSafeArrayToPointerNotNullBlock(Block block, ILVariable v, ILVariable } } condition = condition.UnwrapConv(ConversionKind.Truncate); - if (condition.MatchLdLen(StackType.I, out ILInstruction array)) + if (condition.MatchLdLen(StackType.I, out ILInstruction? array)) { // OK } @@ -451,7 +451,7 @@ bool IsNullSafeArrayToPointerNotNullBlock(Block block, ILVariable v, ILVariable } if (!array.MatchLdLoc(v)) return false; - if (!trueInst.MatchBranch(out Block notNullAndNotEmptyBlock)) + if (!trueInst.MatchBranch(out Block? notNullAndNotEmptyBlock)) return false; if (notNullAndNotEmptyBlock.Parent != block.Parent) return false; @@ -468,7 +468,7 @@ bool IsNullSafeArrayToPointerNotNullAndNotEmptyBlock(Block block, ILVariable v, // } if (block.Instructions.Count != 2) return false; - if (!block.Instructions[0].MatchStLoc(out var p2, out ILInstruction value)) + if (!block.Instructions[0].MatchStLoc(out var p2, out ILInstruction? value)) return false; if (p != p2) { @@ -950,8 +950,8 @@ void HandleStringToPointer(PinnedRegion pinnedRegion) } pinnedRegion.Init = new GetPinnableReference(pinnedRegion.Init, null); - ILVariable otherVar; - ILInstruction otherVarInit; + ILVariable? otherVar; + ILInstruction? otherVarInit; // In optimized builds, the 'nativeVar' may end up being a stack slot, // and only gets assigned to a real variable after the offset adjustment. if (nativeVar.Kind == VariableKind.StackSlot && nativeVar.LoadCount == 1 diff --git a/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs b/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs index f7a9226caf..54458029a8 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/EarlyExpressionTransforms.cs @@ -132,7 +132,7 @@ protected internal override void VisitLdObj(LdObj inst) internal static bool LdObjToLdLoc(LdObj inst, ILTransformContext context) { - if (inst.Target.MatchLdLoca(out ILVariable v) + if (inst.Target.MatchLdLoca(out ILVariable? v) && TypeUtils.IsCompatibleTypeForMemoryAccess(v.Type, inst.Type) && inst.UnalignedPrefix == 0 && !inst.IsVolatile) diff --git a/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs index 5ee75f1679..dd8136a8aa 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs @@ -275,8 +275,8 @@ void TransformIndexing() void TransformSlicing(bool sliceLengthWasMisdetectedAsStartOffset = false) { - ILVariable sliceLengthVar; - ILInstruction sliceLengthVarInit; + ILVariable? sliceLengthVar; + ILInstruction? sliceLengthVarInit; if (sliceLengthWasMisdetectedAsStartOffset) { // Special case: when slicing without a start point, the slice length calculation is mis-detected as the start offset, @@ -303,7 +303,7 @@ void TransformSlicing(bool sliceLengthWasMisdetectedAsStartOffset = false) if (!(sliceLengthVar.IsSingleDefinition && sliceLengthVar.LoadCount == 1)) return; - if (!MatchSliceLength(sliceLengthVarInit, out IndexKind endIndexKind, out ILInstruction endIndexLoad, containerLengthVar, ref containerVar, startOffsetVar)) + if (!MatchSliceLength(sliceLengthVarInit, out IndexKind endIndexKind, out ILInstruction? endIndexLoad, containerLengthVar, ref containerVar, startOffsetVar)) return; if (!CheckContainerLengthVariableUseCount(containerLengthVar, startIndexKind, endIndexKind)) { diff --git a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs index d35b10b826..d98f2fee35 100644 --- a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs +++ b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs @@ -262,7 +262,7 @@ static string GetClosestVersionFolder(string basePath, Version version) return version.ToString(); } - internal static (Version version, DirectoryInfo directory) ConvertToVersion(DirectoryInfo directory) + internal static (Version? version, DirectoryInfo? directory) ConvertToVersion(DirectoryInfo directory) { string RemoveTrailingVersionInfo() { @@ -289,7 +289,7 @@ string RemoveTrailingVersionInfo() public static string? FindDotNetExeDirectory() { string dotnetExeName = (Environment.OSVersion.Platform == PlatformID.Unix) ? "dotnet" : "dotnet.exe"; - foreach (var item in Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator)) + foreach (var item in Environment.GetEnvironmentVariable("PATH")!.Split(Path.PathSeparator)) { try { diff --git a/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs b/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs index 0ebba87ef6..53dd7dea90 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs @@ -48,7 +48,7 @@ public static IType ApplyAttributesToType( bool[]? dynamicAttributeData = null; bool hasNativeIntegersAttribute = (options & TypeSystemOptions.NativeIntegersWithoutAttribute) != 0; bool[]? nativeIntegersAttributeData = null; - string[]? tupleElementNames = null; + string?[]? tupleElementNames = null; Nullability nullability; Nullability[]? nullableAttributeData = null; if ((options & TypeSystemOptions.NullabilityAnnotations) != 0) diff --git a/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs b/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs index 896f9e802d..1c688a03f7 100644 --- a/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs +++ b/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs @@ -245,7 +245,7 @@ private async Task InitializeAsync(MetadataFile mainModule, IAssemblyResolver as // Load referenced assemblies and type-forwarder references. // This is necessary to make .NET Core/PCL binaries work better. var referencedAssemblies = new List(); - var assemblyReferenceQueue = new Queue<(bool IsAssembly, MetadataFile MainModule, object Reference, Task ResolveTask)>(); + var assemblyReferenceQueue = new Queue<(bool IsAssembly, MetadataFile MainModule, object Reference, Task ResolveTask)>(); var comparer = KeyComparer.Create(((bool IsAssembly, MetadataFile MainModule, object Reference) reference) => reference.IsAssembly ? "A:" + ((IAssemblyReference)reference.Reference).FullName : "M:" + reference.Reference); @@ -348,7 +348,7 @@ void AddToQueue(bool isAssembly, MetadataFile mainModule, object reference) { // Immediately start loading the referenced module as we add the entry to the queue. // This allows loading multiple modules in parallel. - Task asm; + Task asm; if (isAssembly) { asm = assemblyResolver.ResolveAsync((IAssemblyReference)reference); diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs index d7f1be94b6..4fe48c5c24 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs @@ -99,7 +99,7 @@ internal static IEnumerable GetInterfaceMembersFromAccessor(IMethod met { if (method == null) return EmptyList.Instance; - return method.ExplicitlyImplementedInterfaceMembers.Select(m => ((IMethod)m).AccessorOwner).Where(m => m != null); + return method.ExplicitlyImplementedInterfaceMembers.Select(m => ((IMethod)m).AccessorOwner).OfType(); } public ITypeDefinition DeclaringTypeDefinition => AnyAccessor?.DeclaringTypeDefinition; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs index 70e24e7356..f9d6d779b9 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs @@ -188,7 +188,7 @@ internal static IEnumerable GetInterfaceMembersFromAccessor(IMethod met { if (method == null) return EmptyList.Instance; - return method.ExplicitlyImplementedInterfaceMembers.Select(m => ((IMethod)m).AccessorOwner).Where(m => m != null); + return method.ExplicitlyImplementedInterfaceMembers.Select(m => ((IMethod)m).AccessorOwner).OfType(); } public ITypeDefinition DeclaringTypeDefinition => AnyAccessor?.DeclaringTypeDefinition; diff --git a/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs b/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs index d73b54b29e..39c2bcad3e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeProvider.cs @@ -160,7 +160,7 @@ public IType GetTypeFromReference(SRM.MetadataReader reader, SRM.TypeReferenceHa return type ?? new UnknownType(fullTypeName, IsReferenceType(reader, handle, rawTypeKind)); } - public IType? GetTypeFromSerializedName(string name) + public IType GetTypeFromSerializedName(string name) { if (name == null) { diff --git a/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs b/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs index c52d62c14c..7e5554e061 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs @@ -83,7 +83,7 @@ public static IEnumerable GetAllBaseTypeDefinitions(this IType if (type == null) throw new ArgumentNullException(nameof(type)); - return type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct(); + return type.GetAllBaseTypes().Select(t => t.GetDefinition()).OfType().Distinct(); } /// diff --git a/ICSharpCode.ILSpyX/Abstractions/ILanguage.cs b/ICSharpCode.ILSpyX/Abstractions/ILanguage.cs index f05c6ded3a..bfc6504e3e 100644 --- a/ICSharpCode.ILSpyX/Abstractions/ILanguage.cs +++ b/ICSharpCode.ILSpyX/Abstractions/ILanguage.cs @@ -27,7 +27,7 @@ public interface ILanguage { bool ShowMember(IEntity member); CodeMappingInfo GetCodeMappingInfo(MetadataFile module, EntityHandle member); - string GetEntityName(MetadataFile module, System.Reflection.Metadata.EntityHandle handle, bool fullName, bool omitGenerics); + string? GetEntityName(MetadataFile module, System.Reflection.Metadata.EntityHandle handle, bool fullName, bool omitGenerics); string GetTooltip(IEntity entity); string TypeToString(IType type, bool includeNamespace); diff --git a/ILSpy.ReadyToRun/ReadyToRunLanguage.cs b/ILSpy.ReadyToRun/ReadyToRunLanguage.cs index b201a66089..b086bd54ce 100644 --- a/ILSpy.ReadyToRun/ReadyToRunLanguage.cs +++ b/ILSpy.ReadyToRun/ReadyToRunLanguage.cs @@ -216,7 +216,7 @@ public override void DecompileMethod(IMethod method, ITextOutput output, Decompi } } - public override RichText GetRichTextTooltip(IEntity entity) + public override RichText? GetRichTextTooltip(IEntity entity) { return Languages.ILLanguage.GetRichTextTooltip(entity); } diff --git a/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs b/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs index 213624ee1a..d0917a9825 100644 --- a/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs +++ b/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs @@ -22,8 +22,8 @@ using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpyX; -using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; using ICSharpCode.ILSpyX.TreeView; +using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; namespace ICSharpCode.ILSpy.Analyzers { @@ -32,7 +32,7 @@ namespace ICSharpCode.ILSpy.Analyzers /// public abstract class AnalyzerEntityTreeNode : AnalyzerTreeNode, IMemberTreeNode { - public abstract IEntity Member { get; } + public abstract IEntity? Member { get; } public override void ActivateItem(IPlatformRoutedEventArgs e) { diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs index e5f88adcb1..463c74c99d 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs @@ -40,7 +40,7 @@ public AnalyzedEventTreeNode(IEvent analyzedEvent, string prefix = "") this.LazyLoading = true; } - public override IEntity Member => analyzedEvent; + public override IEntity? Member => analyzedEvent; public override object Icon => EventTreeNode.GetIcon(analyzedEvent); diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs index 1f2b9b9a3f..b75a8b384e 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs @@ -52,6 +52,6 @@ protected override void LoadChildren() } } - public override IEntity Member => analyzedField; + public override IEntity? Member => analyzedField; } } diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedMethodTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedMethodTreeNode.cs index b7cee8ede4..b4fc0d0443 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedMethodTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedMethodTreeNode.cs @@ -54,6 +54,6 @@ protected override void LoadChildren() } } - public override IEntity Member => analyzedMethod; + public override IEntity? Member => analyzedMethod; } } diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs index d19bc3e730..383f41f26e 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs @@ -62,6 +62,6 @@ protected override void LoadChildren() } } - public override IEntity Member => analyzedProperty; + public override IEntity? Member => analyzedProperty; } } diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedTypeTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedTypeTreeNode.cs index 6836944eb2..09ad9f9504 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedTypeTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedTypeTreeNode.cs @@ -52,6 +52,6 @@ protected override void LoadChildren() } } - public override IEntity Member => analyzedType; + public override IEntity? Member => analyzedType; } } diff --git a/ILSpy/App.xaml.cs b/ILSpy/App.xaml.cs index 92c46a1f50..b1d6e32545 100644 --- a/ILSpy/App.xaml.cs +++ b/ILSpy/App.xaml.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.ComponentModel.Composition.Hosting; using System.Diagnostics; using System.IO; using System.Linq; @@ -34,17 +35,15 @@ using ICSharpCode.ILSpy.Options; using ICSharpCode.ILSpyX.Analyzers; using ICSharpCode.ILSpyX.Settings; +using ICSharpCode.ILSpyX.TreeView; using Medo.Application; using Microsoft.VisualStudio.Composition; -using TomsToolbox.Wpf.Styles; -using ICSharpCode.ILSpyX.TreeView; - using TomsToolbox.Composition; using TomsToolbox.Wpf.Composition; -using System.ComponentModel.Composition.Hosting; +using TomsToolbox.Wpf.Styles; namespace ICSharpCode.ILSpy { @@ -115,7 +114,7 @@ public App() } } - private static void SingleInstance_NewInstanceDetected(object sender, NewInstanceEventArgs e) + private static void SingleInstance_NewInstanceDetected(object? sender, NewInstanceEventArgs e) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed ICSharpCode.ILSpy.MainWindow.Instance.HandleSingleInstanceCommandLineArguments(e.Args); @@ -210,7 +209,7 @@ protected override void OnStartup(StartupEventArgs e) base.OnStartup(e); } - void DotNet40_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) + void DotNet40_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) { // On .NET 4.0, an unobserved exception in a task terminates the process unless we mark it as observed e.SetObserved(); diff --git a/ILSpy/AvalonEdit/TextMarkerService.cs b/ILSpy/AvalonEdit/TextMarkerService.cs index 9a1d1598c9..5abf534f5d 100644 --- a/ILSpy/AvalonEdit/TextMarkerService.cs +++ b/ILSpy/AvalonEdit/TextMarkerService.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.ILSpy.AvalonEdit /// sealed class TextMarkerService : DocumentColorizingTransformer, IBackgroundRenderer, ITextMarkerService { - TextSegmentCollection markers; + TextSegmentCollection? markers; TextView textView; public TextMarkerService(TextView textView) @@ -46,7 +46,7 @@ public TextMarkerService(TextView textView) OnDocumentChanged(null, null); } - void OnDocumentChanged(object sender, EventArgs e) + void OnDocumentChanged(object? sender, EventArgs? e) { if (textView.Document != null) markers = new TextSegmentCollection(textView.Document); diff --git a/ILSpy/Commands/CommandWrapper.cs b/ILSpy/Commands/CommandWrapper.cs index 2cf061b708..15e2d05928 100644 --- a/ILSpy/Commands/CommandWrapper.cs +++ b/ILSpy/Commands/CommandWrapper.cs @@ -39,7 +39,7 @@ public static ICommand Unwrap(ICommand command) return command; } - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { wrappedCommand.CanExecuteChanged += value; } remove { wrappedCommand.CanExecuteChanged -= value; } } diff --git a/ILSpy/Commands/DelegateCommand.cs b/ILSpy/Commands/DelegateCommand.cs index 41996e3270..80345c32da 100644 --- a/ILSpy/Commands/DelegateCommand.cs +++ b/ILSpy/Commands/DelegateCommand.cs @@ -12,7 +12,7 @@ public class DelegateCommand : ICommand private readonly Action action; private readonly Func canExecute; - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } @@ -44,7 +44,7 @@ public class DelegateCommand : ICommand private readonly Action action; private readonly Func canExecute; - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } diff --git a/ILSpy/Commands/IProtocolHandler.cs b/ILSpy/Commands/IProtocolHandler.cs index 53f6e7ef37..dbd6552c42 100644 --- a/ILSpy/Commands/IProtocolHandler.cs +++ b/ILSpy/Commands/IProtocolHandler.cs @@ -25,6 +25,6 @@ namespace ICSharpCode.ILSpy { public interface IProtocolHandler { - ILSpyTreeNode Resolve(string protocol, MetadataFile module, Handle handle, out bool newTabPage); + ILSpyTreeNode? Resolve(string protocol, MetadataFile module, Handle handle, out bool newTabPage); } } diff --git a/ILSpy/Commands/SimpleCommand.cs b/ILSpy/Commands/SimpleCommand.cs index 502d7ea9fe..956ad70ce1 100644 --- a/ILSpy/Commands/SimpleCommand.cs +++ b/ILSpy/Commands/SimpleCommand.cs @@ -24,7 +24,7 @@ namespace ICSharpCode.ILSpy { public abstract class SimpleCommand : ICommand { - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } @@ -41,12 +41,12 @@ public abstract class ToggleableCommand : ICommand, INotifyPropertyChanged { private bool isChecked; - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; void ICommand.Execute(object? parameter) { diff --git a/ILSpy/Controls/SearchBox.cs b/ILSpy/Controls/SearchBox.cs index 4795bbe11b..e7ec45df37 100644 --- a/ILSpy/Controls/SearchBox.cs +++ b/ILSpy/Controls/SearchBox.cs @@ -110,7 +110,7 @@ private void UpdateWatermarkLabel() wl.Visibility = HasText ? Visibility.Hidden : Visibility.Visible; } - void timer_Tick(object sender, EventArgs e) + void timer_Tick(object? sender, EventArgs e) { timer.Stop(); timer = null; diff --git a/ILSpy/Controls/TreeView/SharpTreeNodeView.cs b/ILSpy/Controls/TreeView/SharpTreeNodeView.cs index 002cc9ba11..cecb3cfea6 100644 --- a/ILSpy/Controls/TreeView/SharpTreeNodeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeNodeView.cs @@ -103,7 +103,7 @@ void UpdateDataContext(SharpTreeNode oldNode, SharpTreeNode newNode) } } - void Node_PropertyChanged(object sender, PropertyChangedEventArgs e) + void Node_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsEditing") { diff --git a/ILSpy/Controls/TreeView/SharpTreeView.cs b/ILSpy/Controls/TreeView/SharpTreeView.cs index 13b8417403..845ba297c3 100644 --- a/ILSpy/Controls/TreeView/SharpTreeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeView.cs @@ -171,7 +171,7 @@ void Reload() } } - void flattener_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + void flattener_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { // Deselect nodes that are being hidden, if any remain in the tree if (e.Action == NotifyCollectionChangedAction.Remove && Items.Count > 0) diff --git a/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs b/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs index ca38c4ea46..98bef52e58 100644 --- a/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs +++ b/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs @@ -32,7 +32,7 @@ internal SharpTreeViewItemAutomationPeer(SharpTreeViewItem owner) : base(owner) { SharpTreeViewItem.DataContextChanged += OnDataContextChanged; - SharpTreeNode node = SharpTreeViewItem.DataContext as SharpTreeNode; + SharpTreeNode? node = SharpTreeViewItem.DataContext as SharpTreeNode; if (node == null) return; @@ -61,18 +61,18 @@ public void Expand() public ExpandCollapseState ExpandCollapseState { get { - SharpTreeNode node = SharpTreeViewItem.DataContext as SharpTreeNode; + SharpTreeNode? node = SharpTreeViewItem.DataContext as SharpTreeNode; if (node == null || !node.ShowExpander) return ExpandCollapseState.LeafNode; return node.IsExpanded ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed; } } - private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) + private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName != "IsExpanded") return; - SharpTreeNode node = sender as SharpTreeNode; + SharpTreeNode? node = sender as SharpTreeNode; if (node == null || node.Children.Count == 0) return; bool newValue = node.IsExpanded; @@ -83,12 +83,12 @@ private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) newValue ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed); } - private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) + private void OnDataContextChanged(object? sender, DependencyPropertyChangedEventArgs e) { - SharpTreeNode oldNode = e.OldValue as SharpTreeNode; + SharpTreeNode? oldNode = e.OldValue as SharpTreeNode; if (oldNode != null) oldNode.PropertyChanged -= OnPropertyChanged; - SharpTreeNode newNode = e.NewValue as SharpTreeNode; + SharpTreeNode? newNode = e.NewValue as SharpTreeNode; if (newNode != null) newNode.PropertyChanged += OnPropertyChanged; } diff --git a/ILSpy/Docking/DockWorkspace.cs b/ILSpy/Docking/DockWorkspace.cs index a7b4c71022..59100a4d36 100644 --- a/ILSpy/Docking/DockWorkspace.cs +++ b/ILSpy/Docking/DockWorkspace.cs @@ -52,7 +52,7 @@ private DockWorkspace() MessageBus.Subscribers += (sender, e) => CurrentAssemblyList_Changed(sender, e); } - private void CurrentAssemblyList_Changed(object sender, NotifyCollectionChangedEventArgs e) + private void CurrentAssemblyList_Changed(object? sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems == null) { @@ -163,7 +163,7 @@ public void InitializeLayout(DockingManager manager) } } - void LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e) + void LayoutSerializationCallback(object? sender, LayoutSerializationCallbackEventArgs e) { switch (e.Model) { diff --git a/ILSpy/Docking/PaneCollection.cs b/ILSpy/Docking/PaneCollection.cs index 72b1b851be..a1715d9a44 100644 --- a/ILSpy/Docking/PaneCollection.cs +++ b/ILSpy/Docking/PaneCollection.cs @@ -30,7 +30,7 @@ public class PaneCollection : INotifyCollectionChanged, ICollection { private ObservableCollection observableCollection = new ObservableCollection(); - public event NotifyCollectionChangedEventHandler CollectionChanged; + public event NotifyCollectionChangedEventHandler? CollectionChanged; public PaneCollection() { diff --git a/ILSpy/LanguageSettings.cs b/ILSpy/LanguageSettings.cs index ef7613ccfc..6328a69240 100644 --- a/ILSpy/LanguageSettings.cs +++ b/ILSpy/LanguageSettings.cs @@ -173,9 +173,9 @@ public LanguageVersion LanguageVersion { } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) { if (PropertyChanged != null) { diff --git a/ILSpy/Languages/Language.cs b/ILSpy/Languages/Language.cs index 5374a8eec4..b556c04fff 100644 --- a/ILSpy/Languages/Language.cs +++ b/ILSpy/Languages/Language.cs @@ -364,7 +364,7 @@ public virtual string GetTooltip(IEntity entity) /// Converts a member signature to a string. /// This is used for displaying the tooltip on a member reference. /// - public virtual RichText GetRichTextTooltip(IEntity entity) + public virtual RichText? GetRichTextTooltip(IEntity entity) { return GetTooltip(entity); } diff --git a/ILSpy/MainWindow.xaml.cs b/ILSpy/MainWindow.xaml.cs index 87c9ce1219..b17691b11c 100644 --- a/ILSpy/MainWindow.xaml.cs +++ b/ILSpy/MainWindow.xaml.cs @@ -132,7 +132,7 @@ public MainWindow() this.Loaded += MainWindow_Loaded; } - private void DockWorkspace_ActiveTabPageChanged(object sender, EventArgs e) + private void DockWorkspace_ActiveTabPageChanged(object? sender, EventArgs e) { DockWorkspace dock = DockWorkspace.Instance; @@ -350,7 +350,7 @@ private void InitWindowMenu() ToolsChanged(dock.ToolPanes, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); TabsChanged(dock.TabPages, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - void ToolsChanged(object sender, NotifyCollectionChangedEventArgs e) + void ToolsChanged(object? sender, NotifyCollectionChangedEventArgs e) { int endIndex = windowMenuItem.Items.IndexOf(separatorBeforeDocuments); int startIndex = windowMenuItem.Items.IndexOf(separatorBeforeTools) + 1; @@ -429,7 +429,7 @@ MenuItem CreateMenuItem(ToolPaneModel pane) } } - void TabsChanged(object sender, NotifyCollectionChangedEventArgs e) + void TabsChanged(object? sender, NotifyCollectionChangedEventArgs e) { int endIndex = windowMenuItem.Items.Count; int startIndex = windowMenuItem.Items.IndexOf(separatorBeforeDocuments) + 1; @@ -498,7 +498,7 @@ MenuItem CreateMenuItem(TabPageModel pane) } } - static void TabPageChanged(object sender, PropertyChangedEventArgs e) + static void TabPageChanged(object? sender, PropertyChangedEventArgs e) { var windowMenuItem = Instance.mainMenu.Items.OfType().First(m => (string)m.Tag == nameof(Properties.Resources._Window)); foreach (MenuItem menuItem in windowMenuItem.Items.OfType()) @@ -965,7 +965,7 @@ void ShowAssemblyList(AssemblyList assemblyList) #endif } - void assemblyList_Assemblies_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + void assemblyList_Assemblies_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { diff --git a/ILSpy/Metadata/Helpers.cs b/ILSpy/Metadata/Helpers.cs index aee8137ace..94c733498f 100644 --- a/ILSpy/Metadata/Helpers.cs +++ b/ILSpy/Metadata/Helpers.cs @@ -89,13 +89,13 @@ public static DataGrid PrepareDataGrid(TabPageModel tabPage, ILSpyTreeNode selec return view; } - internal static void View_AutoGeneratedColumns(object sender, EventArgs e) + internal static void View_AutoGeneratedColumns(object? sender, EventArgs e) { ((DataGrid)sender).AutoGeneratedColumns -= View_AutoGeneratedColumns; ((DataGrid)sender).AutoGeneratingColumn -= View_AutoGeneratingColumn; } - internal static void View_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) + internal static void View_AutoGeneratingColumn(object? sender, DataGridAutoGeneratingColumnEventArgs e) { var binding = new Binding(e.PropertyName) { Mode = BindingMode.OneWay }; e.Column = GetColumn(); diff --git a/ILSpy/Metadata/MetaDataGrid.cs b/ILSpy/Metadata/MetaDataGrid.cs index d9328842f4..eaf7f960ca 100644 --- a/ILSpy/Metadata/MetaDataGrid.cs +++ b/ILSpy/Metadata/MetaDataGrid.cs @@ -43,7 +43,7 @@ public MetaDataGrid() this.hoverLogic.MouseHoverStopped += HoverLogic_MouseHoverStopped; } - private void HoverLogic_MouseHoverStopped(object sender, System.Windows.Input.MouseEventArgs e) + private void HoverLogic_MouseHoverStopped(object? sender, System.Windows.Input.MouseEventArgs e) { // Non-popup tooltips get closed as soon as the mouse starts moving again if (toolTip != null) @@ -53,7 +53,7 @@ private void HoverLogic_MouseHoverStopped(object sender, System.Windows.Input.Mo } } - private void HoverLogic_MouseHover(object sender, System.Windows.Input.MouseEventArgs e) + private void HoverLogic_MouseHover(object? sender, System.Windows.Input.MouseEventArgs e) { var position = e.GetPosition(this); var hit = VisualTreeHelper.HitTest(this, position); diff --git a/ILSpy/Options/DecompilerSettingsViewModel.cs b/ILSpy/Options/DecompilerSettingsViewModel.cs index 3a574cca90..af9eeeb103 100644 --- a/ILSpy/Options/DecompilerSettingsViewModel.cs +++ b/ILSpy/Options/DecompilerSettingsViewModel.cs @@ -92,7 +92,7 @@ public bool? AreAllItemsChecked { public DecompilerSettingsItemViewModel[] Settings { get; } - private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void Item_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(DecompilerSettingsItemViewModel.IsEnabled)) { diff --git a/ILSpy/Options/DisplaySettings.cs b/ILSpy/Options/DisplaySettings.cs index f59c31a955..4ab7a05f2a 100644 --- a/ILSpy/Options/DisplaySettings.cs +++ b/ILSpy/Options/DisplaySettings.cs @@ -42,14 +42,14 @@ public DisplaySettings() } #region INotifyPropertyChanged implementation - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } - protected void OnPropertyChanged([CallerMemberName] string propertyName = null) + protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } diff --git a/ILSpy/Options/MiscSettingsViewModel.cs b/ILSpy/Options/MiscSettingsViewModel.cs index de505c3491..727773a452 100644 --- a/ILSpy/Options/MiscSettingsViewModel.cs +++ b/ILSpy/Options/MiscSettingsViewModel.cs @@ -119,14 +119,14 @@ public string AddRemoveShellIntegrationText { #region INotifyPropertyChanged Implementation - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } - protected void OnPropertyChanged([CallerMemberName] string propertyName = null) + protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } diff --git a/ILSpy/Search/SearchPane.xaml.cs b/ILSpy/Search/SearchPane.xaml.cs index 8e824a3c60..028fcb8b84 100644 --- a/ILSpy/Search/SearchPane.xaml.cs +++ b/ILSpy/Search/SearchPane.xaml.cs @@ -203,7 +203,7 @@ void SearchBox_PreviewKeyDown(object sender, KeyEventArgs e) listBox.SelectedIndex = 0; } - void UpdateResults(object sender, EventArgs e) + void UpdateResults(object? sender, EventArgs e) { if (currentSearch == null) return; diff --git a/ILSpy/SessionSettings.cs b/ILSpy/SessionSettings.cs index ad58d121f9..1053603e0c 100644 --- a/ILSpy/SessionSettings.cs +++ b/ILSpy/SessionSettings.cs @@ -69,9 +69,9 @@ public SessionSettings(ILSpySettings spySettings) this.DockLayout = new DockLayoutSettings(doc.Element("DockLayout")); } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - void OnPropertyChanged([CallerMemberName] string propertyName = null) + void OnPropertyChanged([CallerMemberName] string? propertyName = null) { var args = new PropertyChangedEventArgs(propertyName); diff --git a/ILSpy/TextView/BracketHighlightRenderer.cs b/ILSpy/TextView/BracketHighlightRenderer.cs index cf27cd7bd5..0a754510b8 100644 --- a/ILSpy/TextView/BracketHighlightRenderer.cs +++ b/ILSpy/TextView/BracketHighlightRenderer.cs @@ -33,7 +33,7 @@ public interface IBracketSearcher /// Searches for a matching bracket from the given offset to the start of the document. /// /// A BracketSearchResult that contains the positions and lengths of the brackets. Return null if there is nothing to highlight. - BracketSearchResult SearchBracket(IDocument document, int offset); + BracketSearchResult? SearchBracket(IDocument document, int offset); } public class DefaultBracketSearcher : IBracketSearcher diff --git a/ILSpy/Themes/WindowStyleManagerBehavior.cs b/ILSpy/Themes/WindowStyleManagerBehavior.cs index 60e771f1a4..8388be9879 100644 --- a/ILSpy/Themes/WindowStyleManagerBehavior.cs +++ b/ILSpy/Themes/WindowStyleManagerBehavior.cs @@ -65,7 +65,7 @@ protected override void OnDetaching() SettingsService.Instance.DisplaySettings.PropertyChanged -= DisplaySettings_PropertyChanged; } - private void Color_Changed(object sender, EventArgs e) + private void Color_Changed(object? sender, EventArgs e) { ApplyThemeToWindowCaption(); } @@ -83,7 +83,7 @@ private static void ShowRestartNotification() MessageBox.Show(Properties.Resources.SettingsChangeRestartRequired); } - private void DisplaySettings_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void DisplaySettings_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(DisplaySettings.StyleWindowTitleBar)) { @@ -114,7 +114,7 @@ private void ApplyThemeToWindowCaption() } else { - void Initialized(object o, EventArgs eventArgs) + void Initialized(object? o, EventArgs eventArgs) { ApplyThemeToWindowCaption(); window.SourceInitialized -= Initialized; diff --git a/ILSpy/TreeNodes/AssemblyListTreeNode.cs b/ILSpy/TreeNodes/AssemblyListTreeNode.cs index 3b1bc8bc03..5dc676797e 100644 --- a/ILSpy/TreeNodes/AssemblyListTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyListTreeNode.cs @@ -26,8 +26,8 @@ using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; using ICSharpCode.ILSpyX; -using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; using ICSharpCode.ILSpyX.TreeView; +using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; namespace ICSharpCode.ILSpy.TreeNodes { @@ -57,7 +57,7 @@ void BindToObservableCollection(AssemblyList collection) { this.Children.Clear(); this.Children.AddRange(collection.GetAssemblies().Select(a => new AssemblyTreeNode(a))); - collection.CollectionChanged += delegate (object sender, NotifyCollectionChangedEventArgs e) { + collection.CollectionChanged += delegate (object? sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: diff --git a/ILSpy/TreeNodes/ILSpyTreeNode.cs b/ILSpy/TreeNodes/ILSpyTreeNode.cs index e3958a1bb1..9be0705a05 100644 --- a/ILSpy/TreeNodes/ILSpyTreeNode.cs +++ b/ILSpy/TreeNodes/ILSpyTreeNode.cs @@ -29,8 +29,8 @@ using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpy.Util; using ICSharpCode.ILSpyX.Abstractions; -using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; using ICSharpCode.ILSpyX.TreeView; +using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; namespace ICSharpCode.ILSpy.TreeNodes { @@ -128,7 +128,7 @@ void ApplyFilterToChild(ILSpyTreeNode child) } } - protected virtual void LanguageSettings_Changed(object sender, EventArgs e) + protected virtual void LanguageSettings_Changed(object? sender, EventArgs e) { RaisePropertyChanged(nameof(Text)); if (IsVisible) diff --git a/ILSpy/Updates/NotifyOfUpdatesStrategy.cs b/ILSpy/Updates/NotifyOfUpdatesStrategy.cs index 4bff0a0d84..01c6e1ae80 100644 --- a/ILSpy/Updates/NotifyOfUpdatesStrategy.cs +++ b/ILSpy/Updates/NotifyOfUpdatesStrategy.cs @@ -87,7 +87,7 @@ public static async Task GetLatestVersionAsync() } } - public static Task CheckForUpdatesAsync(ILSpySettings spySettings) + public static Task CheckForUpdatesAsync(ILSpySettings spySettings) { UpdateSettings s = new UpdateSettings(spySettings); return CheckForUpdateInternal(s); diff --git a/ILSpy/Updates/UpdateSettings.cs b/ILSpy/Updates/UpdateSettings.cs index 777f23eee1..14022c3233 100644 --- a/ILSpy/Updates/UpdateSettings.cs +++ b/ILSpy/Updates/UpdateSettings.cs @@ -78,9 +78,9 @@ public void Save() ILSpySettings.SaveSettings(updateSettings); } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - void OnPropertyChanged(string propertyName) + void OnPropertyChanged(string? propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/ILSpy/ViewModels/PaneModel.cs b/ILSpy/ViewModels/PaneModel.cs index eef9dca9fa..c8856c7dce 100644 --- a/ILSpy/ViewModels/PaneModel.cs +++ b/ILSpy/ViewModels/PaneModel.cs @@ -39,7 +39,7 @@ public CloseCommandImpl(PaneModel model) this.model.PropertyChanged += Model_PropertyChanged; } - private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void Model_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(model.IsCloseable)) { @@ -47,7 +47,7 @@ private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e) } } - public event EventHandler CanExecuteChanged; + public event EventHandler? CanExecuteChanged; public bool CanExecute(object? parameter) { diff --git a/ILSpy/ViewModels/ViewModelBase.cs b/ILSpy/ViewModels/ViewModelBase.cs index f4517670c3..330c680857 100644 --- a/ILSpy/ViewModels/ViewModelBase.cs +++ b/ILSpy/ViewModels/ViewModelBase.cs @@ -23,9 +23,9 @@ namespace ICSharpCode.ILSpy.ViewModels { public abstract class ViewModelBase : INotifyPropertyChanged { - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) + protected void RaisePropertyChanged([CallerMemberName] string? propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } From 02827835cc70b43adb9d0e08a4896bc56384321f Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 11:56:57 -0400 Subject: [PATCH 10/15] change unfixed to warnings and fixed to errors, changed project settings to match --- .editorconfig | 46 +++++++++++++++++++ .../BamlDecompilerSettings.cs | 4 +- .../ICSharpCode.BamlDecompiler.csproj | 1 + .../ICSharpCode.Decompiler.PowerShell.csproj | 1 + .../WholeProjectDecompiler.cs | 14 +++--- .../Documentation/XmlDocLoader.cs | 14 +++--- .../ICSharpCode.Decompiler.csproj | 1 - .../IL/Transforms/TransformExpressionTrees.cs | 2 +- .../Semantics/OperatorResolveResult.cs | 4 +- .../ICSharpCode.ILSpyCmd.csproj | 2 +- ICSharpCode.ILSpyCmd/ValidationAttributes.cs | 10 ++-- .../Analyzers/AnalyzerHelpers.cs | 2 +- ICSharpCode.ILSpyX/ICSharpCode.ILSpyX.csproj | 3 +- ICSharpCode.ILSpyX/TreeView/TreeTraversal.cs | 4 +- .../ILSpy.BamlDecompiler.Tests.csproj | 1 + ILSpy.BamlDecompiler/BamlResourceEntryNode.cs | 4 +- .../ILSpy.BamlDecompiler.csproj | 1 + ILSpy.ReadyToRun/ILSpy.ReadyToRun.csproj | 1 + ILSpy.ReadyToRun/ReadyToRunOptionPage.xaml.cs | 4 +- ILSpy.Tests/ILSpy.Tests.csproj | 1 + ILSpy/Controls/CustomDialog.cs | 4 +- ILSpy/Docking/DockWorkspace.cs | 2 +- ILSpy/TreeNodes/AssemblyListTreeNode.cs | 4 +- .../ResourceNodes/CursorResourceEntryNode.cs | 2 +- TestPlugin/CustomOptionPage.xaml.cs | 2 +- TestPlugin/MainMenuCommand.cs | 2 +- TestPlugin/TestPlugin.csproj | 1 + 27 files changed, 95 insertions(+), 42 deletions(-) diff --git a/.editorconfig b/.editorconfig index 767ae4a998..538d72491f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -152,12 +152,58 @@ dotnet_diagnostic.MEF006.severity = silent dotnet_diagnostic.IDE2003.severity = silent #cleared null error types +dotnet_diagnostic.CS8597.severity = error +dotnet_diagnostic.CS8605.severity = error +dotnet_diagnostic.CS8606.severity = error +dotnet_diagnostic.CS8607.severity = error +dotnet_diagnostic.CS8608.severity = error +dotnet_diagnostic.CS8609.severity = error +dotnet_diagnostic.CS8610.severity = error +dotnet_diagnostic.CS8611.severity = error dotnet_diagnostic.CS8612.severity = error +dotnet_diagnostic.CS8613.severity = error +dotnet_diagnostic.CS8614.severity = error +dotnet_diagnostic.CS8615.severity = error +dotnet_diagnostic.CS8621.severity = error dotnet_diagnostic.CS8622.severity = error +dotnet_diagnostic.CS8624.severity = error +dotnet_diagnostic.CS8633.severity = error +dotnet_diagnostic.CS8634.severity = error +dotnet_diagnostic.CS8643.severity = error +dotnet_diagnostic.CS8644.severity = error +dotnet_diagnostic.CS8645.severity = error +dotnet_diagnostic.CS8655.severity = error +dotnet_diagnostic.CS8667.severity = error +dotnet_diagnostic.CS8670.severity = error dotnet_diagnostic.CS8714.severity = error dotnet_diagnostic.CS8762.severity = error +dotnet_diagnostic.CS8763.severity = error +dotnet_diagnostic.CS8764.severity = error dotnet_diagnostic.CS8765.severity = error dotnet_diagnostic.CS8766.severity = error dotnet_diagnostic.CS8767.severity = error dotnet_diagnostic.CS8768.severity = error dotnet_diagnostic.CS8769.severity = error +dotnet_diagnostic.CS8770.severity = error +dotnet_diagnostic.CS8773.severity = error +dotnet_diagnostic.CS8774.severity = error +dotnet_diagnostic.CS8775.severity = error +dotnet_diagnostic.CS8776.severity = error +dotnet_diagnostic.CS8775.severity = error +dotnet_diagnostic.CS8777.severity = error + +#nullable error types still not cleaned up +dotnet_diagnostic.CS8600.severity = warning +dotnet_diagnostic.CS8601.severity = warning +dotnet_diagnostic.CS8602.severity = warning +dotnet_diagnostic.CS8603.severity = warning +dotnet_diagnostic.CS8604.severity = warning +dotnet_diagnostic.CS8605.severity = warning +dotnet_diagnostic.CS8615.severity = warning +dotnet_diagnostic.CS8617.severity = warning +dotnet_diagnostic.CS8618.severity = warning +dotnet_diagnostic.CS8619.severity = warning +dotnet_diagnostic.CS8620.severity = warning +dotnet_diagnostic.CS8625.severity = warning +dotnet_diagnostic.CS8629.severity = warning +dotnet_diagnostic.CS8631.severity = warning diff --git a/ICSharpCode.BamlDecompiler/BamlDecompilerSettings.cs b/ICSharpCode.BamlDecompiler/BamlDecompilerSettings.cs index 4f08915607..b8ce8b69ef 100644 --- a/ICSharpCode.BamlDecompiler/BamlDecompilerSettings.cs +++ b/ICSharpCode.BamlDecompiler/BamlDecompilerSettings.cs @@ -37,9 +37,9 @@ public bool ThrowOnAssemblyResolveErrors { } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) { if (PropertyChanged != null) { diff --git a/ICSharpCode.BamlDecompiler/ICSharpCode.BamlDecompiler.csproj b/ICSharpCode.BamlDecompiler/ICSharpCode.BamlDecompiler.csproj index cd022af4bc..9acb0192b9 100644 --- a/ICSharpCode.BamlDecompiler/ICSharpCode.BamlDecompiler.csproj +++ b/ICSharpCode.BamlDecompiler/ICSharpCode.BamlDecompiler.csproj @@ -35,6 +35,7 @@ true true true + enable diff --git a/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj b/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj index f5d58901fe..3c3e0fa1d6 100644 --- a/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj +++ b/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj @@ -6,6 +6,7 @@ true ICSharpCode.Decompiler.PowerShell 8.0 + enable diff --git a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs index b9e619830b..b1e074e0ec 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs @@ -71,7 +71,7 @@ public LanguageVersion LanguageVersion { public AssemblyReferenceClassifier AssemblyReferenceClassifier { get; } - public IDebugInfoProvider DebugInfoProvider { get; } + public IDebugInfoProvider? DebugInfoProvider { get; } /// /// The MSBuild ProjectGuid to use for the new project. @@ -106,9 +106,9 @@ public WholeProjectDecompiler(IAssemblyResolver assemblyResolver) public WholeProjectDecompiler( DecompilerSettings settings, IAssemblyResolver assemblyResolver, - IProjectFileWriter projectWriter, - AssemblyReferenceClassifier assemblyReferenceClassifier, - IDebugInfoProvider debugInfoProvider) + IProjectFileWriter? projectWriter, + AssemblyReferenceClassifier? assemblyReferenceClassifier, + IDebugInfoProvider? debugInfoProvider) : this(settings, Guid.NewGuid(), assemblyResolver, projectWriter, assemblyReferenceClassifier, debugInfoProvider) { } @@ -117,9 +117,9 @@ protected WholeProjectDecompiler( DecompilerSettings settings, Guid projectGuid, IAssemblyResolver assemblyResolver, - IProjectFileWriter projectWriter, - AssemblyReferenceClassifier assemblyReferenceClassifier, - IDebugInfoProvider debugInfoProvider) + IProjectFileWriter? projectWriter, + AssemblyReferenceClassifier? assemblyReferenceClassifier, + IDebugInfoProvider? debugInfoProvider) { Settings = settings ?? throw new ArgumentNullException(nameof(settings)); ProjectGuid = projectGuid; diff --git a/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs index 1a7d16695a..5b5d68f31f 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs @@ -31,8 +31,8 @@ namespace ICSharpCode.Decompiler.Documentation /// public static class XmlDocLoader { - static readonly Lazy mscorlibDocumentation = new Lazy(LoadMscorlibDocumentation); - static readonly ConditionalWeakTable cache = new(); + static readonly Lazy mscorlibDocumentation = new Lazy(LoadMscorlibDocumentation); + static readonly ConditionalWeakTable cache = new(); static XmlDocumentationProvider? LoadMscorlibDocumentation() { @@ -44,11 +44,11 @@ public static class XmlDocLoader return null; } - public static XmlDocumentationProvider MscorlibDocumentation { + public static XmlDocumentationProvider? MscorlibDocumentation { get { return mscorlibDocumentation.Value; } } - public static XmlDocumentationProvider LoadDocumentation(MetadataFile module) + public static XmlDocumentationProvider? LoadDocumentation(MetadataFile module) { if (module == null) throw new ArgumentNullException(nameof(module)); @@ -56,7 +56,7 @@ public static XmlDocumentationProvider LoadDocumentation(MetadataFile module) { if (!cache.TryGetValue(module, out XmlDocumentationProvider? xmlDoc)) { - string xmlDocFile = LookupLocalizedXmlDoc(module.FileName); + string? xmlDocFile = LookupLocalizedXmlDoc(module.FileName); if (xmlDocFile == null) { xmlDocFile = FindXmlDocumentation(Path.GetFileName(module.FileName), module.GetRuntime()); @@ -79,9 +79,9 @@ public static XmlDocumentationProvider LoadDocumentation(MetadataFile module) static readonly string referenceAssembliesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Reference Assemblies\Microsoft\\Framework"); static readonly string frameworkPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"Microsoft.NET\Framework"); - static string FindXmlDocumentation(string assemblyFileName, TargetRuntime runtime) + static string? FindXmlDocumentation(string assemblyFileName, TargetRuntime runtime) { - string fileName; + string? fileName; switch (runtime) { case TargetRuntime.Net_1_0: diff --git a/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj b/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj index 1f9500aa8e..bc037ace59 100644 --- a/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj +++ b/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj @@ -32,7 +32,6 @@ True ICSharpCode.Decompiler.snk 1701;1702;1591;1573 - nullable true embedded diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs index 3261dbb8c4..9600958753 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs @@ -447,7 +447,7 @@ IType UnwrapExpressionTree(IType delegateType) return delegateType; } - (Func?, IType) ConvertArrayIndex(CallInstruction invocation) + (Func?, IType) ConvertArrayIndex(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); diff --git a/ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs b/ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs index cd54d315ec..45f83eb1ea 100644 --- a/ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.Decompiler.Semantics public class OperatorResolveResult : ResolveResult { readonly ExpressionType operatorType; - readonly IMethod userDefinedOperatorMethod; + readonly IMethod? userDefinedOperatorMethod; readonly IList operands; readonly bool isLiftedOperator; @@ -43,7 +43,7 @@ public OperatorResolveResult(IType resultType, ExpressionType operatorType, para this.operands = operands; } - public OperatorResolveResult(IType resultType, ExpressionType operatorType, IMethod userDefinedOperatorMethod, bool isLiftedOperator, IList operands) + public OperatorResolveResult(IType resultType, ExpressionType operatorType, IMethod? userDefinedOperatorMethod, bool isLiftedOperator, IList operands) : base(resultType) { if (operands == null) diff --git a/ICSharpCode.ILSpyCmd/ICSharpCode.ILSpyCmd.csproj b/ICSharpCode.ILSpyCmd/ICSharpCode.ILSpyCmd.csproj index ca25d2eef7..179d463c92 100644 --- a/ICSharpCode.ILSpyCmd/ICSharpCode.ILSpyCmd.csproj +++ b/ICSharpCode.ILSpyCmd/ICSharpCode.ILSpyCmd.csproj @@ -8,7 +8,7 @@ true true true - + enable en-US False False diff --git a/ICSharpCode.ILSpyCmd/ValidationAttributes.cs b/ICSharpCode.ILSpyCmd/ValidationAttributes.cs index 7ddd2ce80b..f9d34db377 100644 --- a/ICSharpCode.ILSpyCmd/ValidationAttributes.cs +++ b/ICSharpCode.ILSpyCmd/ValidationAttributes.cs @@ -14,7 +14,7 @@ public ProjectOptionRequiresOutputDirectoryValidationAttribute() { } - protected override ValidationResult IsValid(object value, ValidationContext context) + protected override ValidationResult? IsValid(object? value, ValidationContext context) { if (value is ILSpyCmdProgram obj) { @@ -30,7 +30,7 @@ protected override ValidationResult IsValid(object value, ValidationContext cont [AttributeUsage(AttributeTargets.Property)] public sealed class FileExistsOrNullAttribute : ValidationAttribute { - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { var path = value as string; if (string.IsNullOrEmpty(path)) @@ -55,7 +55,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali [AttributeUsage(AttributeTargets.Property)] public sealed class FilesExistAttribute : ValidationAttribute { - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { switch (value) { @@ -65,7 +65,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali { foreach (string path in paths) { - ValidationResult result = ValidatePath(path); + ValidationResult? result = ValidatePath(path); if (result != ValidationResult.Success) return result; } @@ -75,7 +75,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali return new ValidationResult($"File '{value}' does not exist!"); } - ValidationResult ValidatePath(string path) + ValidationResult? ValidatePath(string path) { if (!string.IsNullOrWhiteSpace(path)) { diff --git a/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs b/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs index 4c5217ef6a..25b9ebae75 100644 --- a/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs +++ b/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs @@ -54,7 +54,7 @@ public static bool IsPossibleReferenceTo(EntityHandle member, MetadataFile modul switch (customAttribute.Parent.Kind) { case HandleKind.MethodDefinition: - IMethod parent = (IMethod)ts.MainModule.ResolveEntity(customAttribute.Parent); + IMethod? parent = (IMethod?)ts.MainModule.ResolveEntity(customAttribute.Parent); return parent?.AccessorOwner ?? parent; case HandleKind.FieldDefinition: case HandleKind.PropertyDefinition: diff --git a/ICSharpCode.ILSpyX/ICSharpCode.ILSpyX.csproj b/ICSharpCode.ILSpyX/ICSharpCode.ILSpyX.csproj index bcea038e2e..41e03236dc 100644 --- a/ICSharpCode.ILSpyX/ICSharpCode.ILSpyX.csproj +++ b/ICSharpCode.ILSpyX/ICSharpCode.ILSpyX.csproj @@ -4,8 +4,7 @@ net8.0 enable true - nullable - + enable True ..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.snk diff --git a/ICSharpCode.ILSpyX/TreeView/TreeTraversal.cs b/ICSharpCode.ILSpyX/TreeView/TreeTraversal.cs index 25034616d7..e365780eae 100644 --- a/ICSharpCode.ILSpyX/TreeView/TreeTraversal.cs +++ b/ICSharpCode.ILSpyX/TreeView/TreeTraversal.cs @@ -43,7 +43,7 @@ public static IEnumerable PreOrder(T root, Func> recursi /// The root elements of the forest. /// The function that gets the children of an element. /// Iterator that enumerates the tree structure in pre-order. - public static IEnumerable PreOrder(IEnumerable input, Func> recursion) + public static IEnumerable PreOrder(IEnumerable input, Func?> recursion) { Stack> stack = new Stack>(); try @@ -55,7 +55,7 @@ public static IEnumerable PreOrder(IEnumerable input, Func children = recursion(element); + IEnumerable? children = recursion(element); if (children != null) { stack.Push(children.GetEnumerator()); diff --git a/ILSpy.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj b/ILSpy.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj index d92e79c75d..d7c1e6b3eb 100644 --- a/ILSpy.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj +++ b/ILSpy.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj @@ -4,6 +4,7 @@ true true + enable diff --git a/ILSpy.BamlDecompiler/BamlResourceEntryNode.cs b/ILSpy.BamlDecompiler/BamlResourceEntryNode.cs index 788b32ce1c..7a573a4e25 100644 --- a/ILSpy.BamlDecompiler/BamlResourceEntryNode.cs +++ b/ILSpy.BamlDecompiler/BamlResourceEntryNode.cs @@ -33,13 +33,13 @@ namespace ILSpy.BamlDecompiler { public sealed class BamlResourceEntryNode : ResourceEntryNode { - public BamlResourceEntryNode(string key, Func data) : base(key, data) + public BamlResourceEntryNode(string key, Func data) : base(key, data) { } public override bool View(TabPageModel tabPage) { - IHighlightingDefinition highlighting = null; + IHighlightingDefinition? highlighting = null; tabPage.SupportsLanguageSwitching = false; tabPage.ShowTextView(textView => textView.RunWithCancellation( diff --git a/ILSpy.BamlDecompiler/ILSpy.BamlDecompiler.csproj b/ILSpy.BamlDecompiler/ILSpy.BamlDecompiler.csproj index 63950dda4c..7ac2ce92b1 100644 --- a/ILSpy.BamlDecompiler/ILSpy.BamlDecompiler.csproj +++ b/ILSpy.BamlDecompiler/ILSpy.BamlDecompiler.csproj @@ -9,6 +9,7 @@ 6488064 true true + enable diff --git a/ILSpy.ReadyToRun/ILSpy.ReadyToRun.csproj b/ILSpy.ReadyToRun/ILSpy.ReadyToRun.csproj index dfe925ddda..dc007bde06 100644 --- a/ILSpy.ReadyToRun/ILSpy.ReadyToRun.csproj +++ b/ILSpy.ReadyToRun/ILSpy.ReadyToRun.csproj @@ -11,6 +11,7 @@ true false true + enable diff --git a/ILSpy.ReadyToRun/ReadyToRunOptionPage.xaml.cs b/ILSpy.ReadyToRun/ReadyToRunOptionPage.xaml.cs index fbe046ea4a..8b8ae256e1 100644 --- a/ILSpy.ReadyToRun/ReadyToRunOptionPage.xaml.cs +++ b/ILSpy.ReadyToRun/ReadyToRunOptionPage.xaml.cs @@ -114,9 +114,9 @@ public string DisassemblyFormat { } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - protected virtual void OnPropertyChanged(string propertyName) + protected virtual void OnPropertyChanged(string? propertyName) { if (PropertyChanged != null) { diff --git a/ILSpy.Tests/ILSpy.Tests.csproj b/ILSpy.Tests/ILSpy.Tests.csproj index 0f44621f67..2f31cb0008 100644 --- a/ILSpy.Tests/ILSpy.Tests.csproj +++ b/ILSpy.Tests/ILSpy.Tests.csproj @@ -17,6 +17,7 @@ True ..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.snk + diff --git a/ILSpy/Controls/CustomDialog.cs b/ILSpy/Controls/CustomDialog.cs index 994bedffc5..036aff29a0 100644 --- a/ILSpy/Controls/CustomDialog.cs +++ b/ILSpy/Controls/CustomDialog.cs @@ -113,9 +113,9 @@ protected override void OnKeyDown(KeyEventArgs e) } } - void ButtonClick(object sender, EventArgs e) + void ButtonClick(object? sender, EventArgs e) { - result = (int)((Control)sender).Tag; + result = ((int?)(sender as Control)?.Tag) ?? -1; this.Close(); } diff --git a/ILSpy/Docking/DockWorkspace.cs b/ILSpy/Docking/DockWorkspace.cs index 59100a4d36..eb8323adc8 100644 --- a/ILSpy/Docking/DockWorkspace.cs +++ b/ILSpy/Docking/DockWorkspace.cs @@ -82,7 +82,7 @@ private void CurrentAssemblyList_Changed(object? sender, NotifyCollectionChanged } } - private void Documents_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + private void Documents_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { var collection = (PaneCollection)sender; if (e.Action == NotifyCollectionChangedAction.Add) diff --git a/ILSpy/TreeNodes/AssemblyListTreeNode.cs b/ILSpy/TreeNodes/AssemblyListTreeNode.cs index 5dc676797e..9ffe3fdf08 100644 --- a/ILSpy/TreeNodes/AssemblyListTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyListTreeNode.cs @@ -203,7 +203,9 @@ public AssemblyTreeNode FindAssemblyNode(IModule module) } return null; - static SharpTreeNodeCollection? ExpandAndGetChildren(SharpTreeNode node) + + + static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) { if (node is not PackageFolderTreeNode) return null; diff --git a/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs b/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs index 640d373e3e..393b3198d9 100644 --- a/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs @@ -50,7 +50,7 @@ sealed class CursorResourceNodeFactory : IResourceNodeFactory sealed class CursorResourceEntryNode : ResourceEntryNode { - public CursorResourceEntryNode(string key, Func openStream) + public CursorResourceEntryNode(string key, Func openStream) : base(key, openStream) { } diff --git a/TestPlugin/CustomOptionPage.xaml.cs b/TestPlugin/CustomOptionPage.xaml.cs index 9c38af296b..1c16be47fe 100644 --- a/TestPlugin/CustomOptionPage.xaml.cs +++ b/TestPlugin/CustomOptionPage.xaml.cs @@ -86,7 +86,7 @@ public double UselessOption2 { } } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { diff --git a/TestPlugin/MainMenuCommand.cs b/TestPlugin/MainMenuCommand.cs index bb4a041f8c..3832716c24 100644 --- a/TestPlugin/MainMenuCommand.cs +++ b/TestPlugin/MainMenuCommand.cs @@ -21,7 +21,7 @@ namespace TestPlugin [PartCreationPolicy(CreationPolicy.Shared)] public class UnloadAllAssembliesCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { foreach (var loadedAssembly in MainWindow.Instance.CurrentAssemblyList.GetAssemblies()) { diff --git a/TestPlugin/TestPlugin.csproj b/TestPlugin/TestPlugin.csproj index c527fbcaee..fc7d4b5085 100644 --- a/TestPlugin/TestPlugin.csproj +++ b/TestPlugin/TestPlugin.csproj @@ -5,6 +5,7 @@ Test.Plugin true true + enable From eae6e21ee5c434c5ed4837f70dbe5f0013b33712 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 15:56:52 -0400 Subject: [PATCH 11/15] more CS8600 cleanup --- .../Baml/BamlContext.cs | 2 +- ICSharpCode.BamlDecompiler/Baml/BamlNode.cs | 2 +- ICSharpCode.BamlDecompiler/Baml/BamlReader.cs | 2 +- .../Rewrite/ConnectionIdRewritePass.cs | 2 +- ICSharpCode.BamlDecompiler/Xaml/XamlType.cs | 2 +- ICSharpCode.BamlDecompiler/XamlContext.cs | 2 +- .../OutputVisitor/TextWriterTokenWriter.cs | 2 +- .../Util/CSharpPrimitiveCast.cs | 5 ++- ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs | 4 +- ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs | 4 +- ILSpy.ReadyToRun/ReadyToRunDisassembler.cs | 6 +-- ILSpy.ReadyToRun/ReadyToRunLanguage.cs | 10 ++--- ILSpy/AboutPage.cs | 4 +- ILSpy/Analyzers/AnalyzerEntityTreeNode.cs | 2 +- ILSpy/Analyzers/AnalyzerRootNode.cs | 4 +- ILSpy/Analyzers/AnalyzerTreeViewModel.cs | 2 +- ILSpy/App.xaml.cs | 8 ++-- ILSpy/AvalonEdit/TextMarkerService.cs | 4 +- ILSpy/Commands/CommandWrapper.cs | 2 +- ILSpy/Commands/DecompileAllCommand.cs | 2 +- ILSpy/Commands/DecompileCommand.cs | 2 +- ILSpy/Commands/DisassembleAllCommand.cs | 2 +- .../ExtractPackageEntryContextMenuEntry.cs | 4 +- ILSpy/Commands/SaveCodeContextMenuEntry.cs | 9 ++--- ILSpy/Commands/ScopeSearchToNamespace.cs | 2 +- ILSpy/Commands/SelectPdbContextMenuEntry.cs | 2 +- ILSpy/ContextMenuEntry.cs | 24 +++++------ ILSpy/Controls/GridViewColumnAutoSize.cs | 10 ++--- ILSpy/Controls/SearchBox.cs | 2 +- ILSpy/Controls/SortableGridViewColumn.cs | 12 +++--- ILSpy/Controls/TreeView/SharpTreeView.cs | 20 +++++----- .../TreeView/SharpTreeViewTextSearch.cs | 2 +- ILSpy/Controls/ZoomScrollViewer.cs | 4 +- ILSpy/Docking/DockWorkspace.cs | 4 +- ILSpy/ISmartTextOutput.cs | 2 +- ILSpy/Images/Images.cs | 16 ++++---- .../CSharpHighlightingTokenWriter.cs | 8 ++-- ILSpy/Languages/CSharpLanguage.cs | 18 ++++----- ILSpy/Languages/ILLanguage.cs | 14 +++---- ILSpy/Languages/Language.cs | 2 +- ILSpy/MainWindow.xaml.cs | 40 +++++++++---------- .../Metadata/CorTables/EventTableTreeNode.cs | 2 +- .../Metadata/CorTables/FieldTableTreeNode.cs | 2 +- .../Metadata/CorTables/MethodTableTreeNode.cs | 2 +- .../CorTables/PropertyTableTreeNode.cs | 2 +- .../CorTables/TypeDefTableTreeNode.cs | 2 +- .../CustomDebugInformationTableTreeNode.cs | 2 +- ILSpy/Metadata/GoToTokenCommand.cs | 4 +- ILSpy/NavigationState.cs | 2 +- ILSpy/Options/DisplaySettingsPanel.xaml.cs | 4 +- ILSpy/Options/OptionsDialog.xaml.cs | 4 +- ILSpy/Search/SearchPane.xaml.cs | 10 ++--- ILSpy/SessionSettings.cs | 12 +++--- ILSpy/TaskHelper.cs | 2 +- ILSpy/TextView/AvalonEditTextOutput.cs | 2 +- ILSpy/TextView/DecompilerTextView.cs | 6 +-- ILSpy/TextView/DocumentationUIBuilder.cs | 6 +-- ILSpy/TextView/FoldingCommands.cs | 6 +-- ILSpy/TreeNodes/AssemblyListTreeNode.cs | 16 ++++---- ILSpy/TreeNodes/AssemblyTreeNode.cs | 8 ++-- .../ResourceNodes/ResourceTreeNode.cs | 6 +-- .../ResourceNodes/ResourcesFileTreeNode.cs | 8 ++-- .../ResourceNodes/XamlResourceNode.cs | 2 +- ILSpy/TreeNodes/ThreadingSupport.cs | 2 +- ILSpy/Updates/NotifyOfUpdatesStrategy.cs | 2 +- TestPlugin/CustomLanguage.cs | 2 +- TestPlugin/CustomOptionPage.xaml.cs | 2 +- 67 files changed, 195 insertions(+), 193 deletions(-) diff --git a/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs b/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs index 21a2e733fc..a310a23801 100644 --- a/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs +++ b/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs @@ -116,7 +116,7 @@ public static BamlContext ConstructContext(IDecompilerTypeSystem typeSystem, Bam private IModule FindMatchingReference(AssemblyNameReference name) { - IModule bestMatch = null; + IModule? bestMatch = null; foreach (var module in TypeSystem.ReferencedModules) { if (module.AssemblyName == name.Name) diff --git a/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs b/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs index c8049a668a..89062e1296 100644 --- a/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs +++ b/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs @@ -111,7 +111,7 @@ public static BamlNode Parse(BamlDocument document, CancellationToken token) { Debug.Assert(document.Count > 0 && document[0].Type == BamlRecordType.DocumentStart); - BamlBlockNode current = null; + BamlBlockNode? current = null; var stack = new Stack(); for (int i = 0; i < document.Count; i++) diff --git a/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs b/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs index bed8f934a0..5137c2fcec 100644 --- a/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs +++ b/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs @@ -91,7 +91,7 @@ public static BamlDocument ReadDocument(Stream str, CancellationToken token) long pos = str.Position; var type = (BamlRecordType)reader.ReadByte(); - BamlRecord rec = null; + BamlRecord? rec = null; switch (type) { case BamlRecordType.AssemblyInfo: diff --git a/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs b/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs index 496080af18..4c7a518fcb 100644 --- a/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs +++ b/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs @@ -127,7 +127,7 @@ void DecompileConnections(XamlContext ctx, List<(LongSet, FieldAssignment)> fiel return; var connect = connectorInterface.GetMethods(m => m.Name == "Connect").SingleOrDefault(); - IMethod connectMethod = null; + IMethod? connectMethod = null; MethodDefinition connectMetadataEntry = default; var module = ctx.TypeSystem.MainModule.MetadataFile; diff --git a/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs b/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs index f2f9075729..709e18c043 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs @@ -62,7 +62,7 @@ public void ResolveNamespace(XElement elem, XamlContext ctx) // Since XmlnsProperty records are inside the element, // the namespace is resolved after processing the element body. - string xmlNs = null; + string? xmlNs = null; if (elem.Annotation() != null) xmlNs = elem.Annotation().LookupXmlns(FullAssemblyName, TypeNamespace); if (xmlNs == null) diff --git a/ICSharpCode.BamlDecompiler/XamlContext.cs b/ICSharpCode.BamlDecompiler/XamlContext.cs index bd24cbeaf5..4558b13b3a 100644 --- a/ICSharpCode.BamlDecompiler/XamlContext.cs +++ b/ICSharpCode.BamlDecompiler/XamlContext.cs @@ -143,7 +143,7 @@ public XamlProperty ResolveProperty(ushort id) XamlType type; string name; - IMember member; + IMember? member; if (id > 0x7fff) { diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs index 477ba3a6f2..1862be0801 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs @@ -499,7 +499,7 @@ public static string ConvertString(string str) StringBuilder sb = new StringBuilder(); foreach (char ch in str) { - string s = ch == '"' ? "\\\"" : ConvertChar(ch); + string? s = ch == '"' ? "\\\"" : ConvertChar(ch); if (s != null) sb.Append(s); else diff --git a/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs b/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs index ee940d9d8b..015251fe9b 100644 --- a/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs +++ b/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs @@ -17,6 +17,7 @@ // DEALINGS IN THE SOFTWARE. using System; +using System.Diagnostics.CodeAnalysis; namespace ICSharpCode.Decompiler.Util { @@ -34,7 +35,9 @@ public static class CSharpPrimitiveCast /// /// Overflow checking is enabled and an overflow occurred. /// The cast is invalid, e.g. casting a boolean to an integer. - public static object? Cast(TypeCode targetType, object input, bool checkForOverflow) + //[return: MaybeNull] + //[return: NotNullIfNotNull(nameof(input))] + public static object Cast(TypeCode targetType, [MaybeNull] object input, bool checkForOverflow) { if (input == null) return null; diff --git a/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs b/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs index 57e08d5e38..8cc359925c 100644 --- a/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs +++ b/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs @@ -122,7 +122,7 @@ public ILSpyCmdProgram(IHostEnvironment env) private async Task OnExecuteAsync(CommandLineApplication app) { - Task updateCheckTask = null; + Task? updateCheckTask = null; if (!DisableUpdateCheck) { updateCheckTask = DotNetToolUpdateChecker.CheckForPackageUpdateAsync("ilspycmd"); @@ -214,7 +214,7 @@ int PerformPerFileAction(string fileName) } else if (CreateDebugInfoFlag) { - string pdbFileName = null; + string? pdbFileName = null; if (outputDirectory != null) { string outputName = Path.GetFileNameWithoutExtension(fileName); diff --git a/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs b/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs index 970618e8ef..3a94ffcae7 100644 --- a/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs +++ b/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs @@ -205,11 +205,11 @@ string NormalizeLine(string line) return line.Trim(); } - Stream LoadBaml(Resource res, string name) + Stream? LoadBaml(Resource res, string name) { if (res.ResourceType != ResourceType.Embedded) return null; - Stream s = res.TryOpenStream(); + Stream? s = res.TryOpenStream(); if (s == null) return null; s.Position = 0; diff --git a/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs b/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs index 0b7d0ee6c9..6cd03c5582 100644 --- a/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs +++ b/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs @@ -67,14 +67,14 @@ public void Disassemble(PEFile currentFile, int bitness, ulong address, bool sho } } - Dictionary unwindInfo = null; + Dictionary? unwindInfo = null; if (ReadyToRunOptions.GetIsShowUnwindInfo(null) && bitness == 64) { unwindInfo = WriteUnwindInfo(); } bool isShowDebugInfo = ReadyToRunOptions.GetIsShowDebugInfo(null); - DebugInfoHelper debugInfo = null; + DebugInfoHelper? debugInfo = null; if (isShowDebugInfo) { debugInfo = WriteDebugInfo(); @@ -98,7 +98,7 @@ public void Disassemble(PEFile currentFile, int bitness, ulong address, bool sho } string disassemblyFormat = ReadyToRunOptions.GetDisassemblyFormat(null); - Formatter formatter = null; + Formatter? formatter = null; if (disassemblyFormat.Equals(ReadyToRunOptions.intel)) { formatter = new NasmFormatter(); diff --git a/ILSpy.ReadyToRun/ReadyToRunLanguage.cs b/ILSpy.ReadyToRun/ReadyToRunLanguage.cs index b086bd54ce..a963dee76b 100644 --- a/ILSpy.ReadyToRun/ReadyToRunLanguage.cs +++ b/ILSpy.ReadyToRun/ReadyToRunLanguage.cs @@ -114,7 +114,7 @@ public override void WriteCommentLine(ITextOutput output, string comment) public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { - PEFile module = assembly.GetMetadataFileAsync().GetAwaiter().GetResult() as PEFile; + PEFile? module = assembly.GetMetadataFileAsync().GetAwaiter().GetResult() as PEFile; ReadyToRunReaderCacheEntry cacheEntry = GetReader(assembly, module); if (cacheEntry.readyToRunReader == null) { @@ -137,7 +137,7 @@ public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options) { - PEFile module = method.ParentModule.MetadataFile as PEFile; + PEFile? module = method.ParentModule.MetadataFile as PEFile; ReadyToRunReaderCacheEntry cacheEntry = GetReader(module.GetLoadedAssembly(), module); if (cacheEntry.readyToRunReader == null) { @@ -158,7 +158,7 @@ public override void DecompileMethod(IMethod method, ITextOutput output, Decompi } if (cacheEntry.methodMap == null) { - IEnumerable readyToRunMethods = null; + IEnumerable? readyToRunMethods = null; if (cacheEntry.compositeReadyToRunReader == null) { readyToRunMethods = reader.Methods; @@ -192,8 +192,8 @@ public override void DecompileMethod(IMethod method, ITextOutput output, Decompi #endif foreach (RuntimeFunction runtimeFunction in readyToRunMethod.RuntimeFunctions) { - PEFile file = null; - ReadyToRunReader disassemblingReader = null; + PEFile? file = null; + ReadyToRunReader? disassemblingReader = null; if (cacheEntry.compositeReadyToRunReader == null) { disassemblingReader = reader; diff --git a/ILSpy/AboutPage.cs b/ILSpy/AboutPage.cs index 0fbaa89ba1..f9f969edab 100644 --- a/ILSpy/AboutPage.cs +++ b/ILSpy/AboutPage.cs @@ -90,11 +90,11 @@ public static void Display(DecompilerTextView textView) plugin.Write(output); output.WriteLine(); output.Address = new Uri("resource://AboutPage"); - using (Stream s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), Resources.ILSpyAboutPageTxt)) + using (Stream? s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), Resources.ILSpyAboutPageTxt)) { using (StreamReader r = new StreamReader(s)) { - string line; + string? line; while ((line = r.ReadLine()) != null) { output.WriteLine(line); diff --git a/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs b/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs index d0917a9825..3dfab8c060 100644 --- a/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs +++ b/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs @@ -54,7 +54,7 @@ public override bool HandleAssemblyListChanged(ICollection remov } this.Children.RemoveAll( delegate (SharpTreeNode n) { - AnalyzerTreeNode an = n as AnalyzerTreeNode; + AnalyzerTreeNode? an = n as AnalyzerTreeNode; return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies); }); return true; diff --git a/ILSpy/Analyzers/AnalyzerRootNode.cs b/ILSpy/Analyzers/AnalyzerRootNode.cs index 17709687f9..c47fbe27cc 100644 --- a/ILSpy/Analyzers/AnalyzerRootNode.cs +++ b/ILSpy/Analyzers/AnalyzerRootNode.cs @@ -15,7 +15,7 @@ public AnalyzerRootNode() MessageBus.Subscribers += (sender, e) => CurrentAssemblyList_Changed(sender, e); } - void CurrentAssemblyList_Changed(object sender, NotifyCollectionChangedEventArgs e) + void CurrentAssemblyList_Changed(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { @@ -34,7 +34,7 @@ public override bool HandleAssemblyListChanged(ICollection remov { this.Children.RemoveAll( delegate (SharpTreeNode n) { - AnalyzerTreeNode an = n as AnalyzerTreeNode; + AnalyzerTreeNode? an = n as AnalyzerTreeNode; return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies); }); return true; diff --git a/ILSpy/Analyzers/AnalyzerTreeViewModel.cs b/ILSpy/Analyzers/AnalyzerTreeViewModel.cs index fc7def7558..a9034f59bb 100644 --- a/ILSpy/Analyzers/AnalyzerTreeViewModel.cs +++ b/ILSpy/Analyzers/AnalyzerTreeViewModel.cs @@ -73,7 +73,7 @@ void AddOrSelect(AnalyzerTreeNode node) { Show(); - AnalyzerTreeNode target = default; + AnalyzerTreeNode? target = default; if (node is AnalyzerEntityTreeNode { Member: { } member }) { diff --git a/ILSpy/App.xaml.cs b/ILSpy/App.xaml.cs index b1d6e32545..fa45bd234c 100644 --- a/ILSpy/App.xaml.cs +++ b/ILSpy/App.xaml.cs @@ -224,7 +224,7 @@ static void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExce static void ShowErrorBox(object sender, UnhandledExceptionEventArgs e) { - Exception ex = e.ExceptionObject as Exception; + Exception? ex = e.ExceptionObject as Exception; if (ex != null) { UnhandledException(ex); @@ -237,13 +237,13 @@ static void ShowErrorBox(object sender, UnhandledExceptionEventArgs e) internal static void UnhandledException(Exception exception) { Debug.WriteLine(exception.ToString()); - for (Exception ex = exception; ex != null; ex = ex.InnerException) + for (Exception? ex = exception; ex != null; ex = ex.InnerException) { - ReflectionTypeLoadException rtle = ex as ReflectionTypeLoadException; + ReflectionTypeLoadException? rtle = ex as ReflectionTypeLoadException; if (rtle != null && rtle.LoaderExceptions.Length > 0) { exception = rtle.LoaderExceptions[0]; - Debug.WriteLine(exception.ToString()); + Debug.WriteLine(exception?.ToString()); break; } } diff --git a/ILSpy/AvalonEdit/TextMarkerService.cs b/ILSpy/AvalonEdit/TextMarkerService.cs index 5abf534f5d..ae5e0dc861 100644 --- a/ILSpy/AvalonEdit/TextMarkerService.cs +++ b/ILSpy/AvalonEdit/TextMarkerService.cs @@ -102,7 +102,7 @@ public void Remove(ITextMarker marker) { if (marker == null) throw new ArgumentNullException(nameof(marker)); - TextMarker m = marker as TextMarker; + TextMarker? m = marker as TextMarker; if (markers != null && markers.Remove(m)) { Redraw(m); @@ -131,7 +131,7 @@ protected override void ColorizeLine(DocumentLine line) int lineEnd = lineStart + line.Length; foreach (TextMarker marker in markers.FindOverlappingSegments(lineStart, line.Length)) { - Brush foregroundBrush = null; + Brush? foregroundBrush = null; if (marker.ForegroundColor != null) { foregroundBrush = new SolidColorBrush(marker.ForegroundColor.Value); diff --git a/ILSpy/Commands/CommandWrapper.cs b/ILSpy/Commands/CommandWrapper.cs index 15e2d05928..30bd37599d 100644 --- a/ILSpy/Commands/CommandWrapper.cs +++ b/ILSpy/Commands/CommandWrapper.cs @@ -32,7 +32,7 @@ public CommandWrapper(ICommand wrappedCommand) public static ICommand Unwrap(ICommand command) { - CommandWrapper w = command as CommandWrapper; + CommandWrapper? w = command as CommandWrapper; if (w != null) return w.wrappedCommand; else diff --git a/ILSpy/Commands/DecompileAllCommand.cs b/ILSpy/Commands/DecompileAllCommand.cs index 84d53a41f2..b866937600 100644 --- a/ILSpy/Commands/DecompileAllCommand.cs +++ b/ILSpy/Commands/DecompileAllCommand.cs @@ -55,7 +55,7 @@ public override void Execute(object? parameter) if (!asm.HasLoadError) { Stopwatch w = Stopwatch.StartNew(); - Exception exception = null; + Exception? exception = null; using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) { try diff --git a/ILSpy/Commands/DecompileCommand.cs b/ILSpy/Commands/DecompileCommand.cs index 0a7d1a3857..07ce981fb3 100644 --- a/ILSpy/Commands/DecompileCommand.cs +++ b/ILSpy/Commands/DecompileCommand.cs @@ -56,7 +56,7 @@ bool IsValidReference(object reference) public void Execute(TextViewContext context) { - IEntity selection = null; + IEntity? selection = null; if (context.SelectedTreeNodes?[0] is IMemberTreeNode node) { selection = node.Member; diff --git a/ILSpy/Commands/DisassembleAllCommand.cs b/ILSpy/Commands/DisassembleAllCommand.cs index 42f1089e2a..8907dba99c 100644 --- a/ILSpy/Commands/DisassembleAllCommand.cs +++ b/ILSpy/Commands/DisassembleAllCommand.cs @@ -50,7 +50,7 @@ public override void Execute(object? parameter) if (!asm.HasLoadError) { Stopwatch w = Stopwatch.StartNew(); - Exception exception = null; + Exception? exception = null; using (var writer = new System.IO.StreamWriter("c:\\temp\\disassembled\\" + asm.Text.Replace("(", "").Replace(")", "").Replace(' ', '_') + ".il")) { try diff --git a/ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs b/ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs index 3f22fa1cdc..8dfc5aae62 100644 --- a/ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs +++ b/ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs @@ -57,7 +57,7 @@ public void Execute(TextViewContext context) return; string fileName = dlg.FileName; - string outputFolderOrFileName = fileName; + string? outputFolderOrFileName = fileName; if (selectedNodes.Length > 1) outputFolderOrFileName = Path.GetDirectoryName(outputFolderOrFileName); @@ -89,7 +89,7 @@ public void Execute(TextViewContext context) void SaveEntry(ITextOutput output, PackageEntry entry, string targetFileName) { output.Write(entry.Name + ": "); - using Stream stream = entry.TryOpenStream(); + using Stream? stream = entry.TryOpenStream(); if (stream == null) { output.WriteLine("Could not open stream!"); diff --git a/ILSpy/Commands/SaveCodeContextMenuEntry.cs b/ILSpy/Commands/SaveCodeContextMenuEntry.cs index ada78fcba5..d68ad1c7fa 100644 --- a/ILSpy/Commands/SaveCodeContextMenuEntry.cs +++ b/ILSpy/Commands/SaveCodeContextMenuEntry.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Windows; @@ -26,13 +27,11 @@ using ICSharpCode.ILSpy.Options; using ICSharpCode.ILSpy.Properties; using ICSharpCode.ILSpy.TreeNodes; +using ICSharpCode.ILSpy.Util; using ICSharpCode.ILSpy.ViewModels; - -using Microsoft.Win32; using ICSharpCode.ILSpyX.TreeView; -using System.ComponentModel.Composition; -using ICSharpCode.ILSpy.Util; +using Microsoft.Win32; namespace ICSharpCode.ILSpy.TextView { @@ -112,7 +111,7 @@ public static void Execute(IReadOnlyList selectedNodes) return null; } - string selectedPath = Path.GetDirectoryName(dlg.FileName); + string? selectedPath = Path.GetDirectoryName(dlg.FileName); bool directoryNotEmpty; try { diff --git a/ILSpy/Commands/ScopeSearchToNamespace.cs b/ILSpy/Commands/ScopeSearchToNamespace.cs index 83dceb0029..b75c2d140f 100644 --- a/ILSpy/Commands/ScopeSearchToNamespace.cs +++ b/ILSpy/Commands/ScopeSearchToNamespace.cs @@ -41,7 +41,7 @@ public ScopeSearchToNamespace(SearchPaneModel searchPane) public void Execute(TextViewContext context) { string ns = GetNamespace(context); - string searchTerm = searchPane.SearchTerm; + string? searchTerm = searchPane.SearchTerm; string[] args = CommandLineTools.CommandLineToArgumentArray(searchTerm); bool replaced = false; for (int i = 0; i < args.Length; i++) diff --git a/ILSpy/Commands/SelectPdbContextMenuEntry.cs b/ILSpy/Commands/SelectPdbContextMenuEntry.cs index 061ff7e6b0..46fa62625f 100644 --- a/ILSpy/Commands/SelectPdbContextMenuEntry.cs +++ b/ILSpy/Commands/SelectPdbContextMenuEntry.cs @@ -48,7 +48,7 @@ public async void Execute(TextViewContext context) await assembly.LoadDebugInfo(dlg.FileName); } - var node = (AssemblyTreeNode)MainWindow.Instance.FindNodeByPath(new[] { assembly.FileName }, true); + var node = (AssemblyTreeNode?)MainWindow.Instance.FindNodeByPath(new[] { assembly.FileName }, true); node.UpdateToolTip(); MainWindow.Instance.SelectNode(node); MainWindow.Instance.RefreshDecompiledView(); diff --git a/ILSpy/ContextMenuEntry.cs b/ILSpy/ContextMenuEntry.cs index fcbdb1bae9..27c7c1b24b 100644 --- a/ILSpy/ContextMenuEntry.cs +++ b/ILSpy/ContextMenuEntry.cs @@ -26,9 +26,9 @@ using System.Windows.Media; using ICSharpCode.AvalonEdit; +using ICSharpCode.ILSpy.Controls.TreeView; using ICSharpCode.ILSpy.TextView; using ICSharpCode.ILSpyX.Search; -using ICSharpCode.ILSpy.Controls.TreeView; using ICSharpCode.ILSpyX.TreeView; using TomsToolbox.Composition; @@ -48,37 +48,37 @@ public class TextViewContext /// Returns the selected nodes in the tree view. /// Returns null, if context menu does not belong to a tree view. /// - public SharpTreeNode[] SelectedTreeNodes { get; private set; } + public SharpTreeNode[]? SelectedTreeNodes { get; private set; } /// /// Returns the tree view the context menu is assigned to. /// Returns null, if context menu is not assigned to a tree view. /// - public SharpTreeView TreeView { get; private set; } + public SharpTreeView? TreeView { get; private set; } /// /// Returns the text view the context menu is assigned to. /// Returns null, if context menu is not assigned to a text view. /// - public DecompilerTextView TextView { get; private set; } + public DecompilerTextView? TextView { get; private set; } /// /// Returns the list box the context menu is assigned to. /// Returns null, if context menu is not assigned to a list box. /// - public ListBox ListBox { get; private set; } + public ListBox? ListBox { get; private set; } /// /// Returns the data grid the context menu is assigned to. /// Returns null, if context menu is not assigned to a data grid. /// - public DataGrid DataGrid { get; private set; } + public DataGrid? DataGrid { get; private set; } /// /// Returns the reference the mouse cursor is currently hovering above. /// Returns null, if there was no reference found. /// - public ReferenceSegment Reference { get; private set; } + public ReferenceSegment? Reference { get; private set; } /// /// Returns the position in TextView the mouse cursor is currently hovering above. @@ -88,9 +88,9 @@ public class TextViewContext public Point MousePosition { get; private set; } - public static TextViewContext Create(SharpTreeView treeView = null, DecompilerTextView textView = null, ListBox listBox = null, DataGrid dataGrid = null) + public static TextViewContext Create(SharpTreeView? treeView = null, DecompilerTextView? textView = null, ListBox? listBox = null, DataGrid? dataGrid = null) { - ReferenceSegment reference; + ReferenceSegment? reference; if (textView != null) reference = textView.GetReferenceSegmentAtMousePosition(); else if (listBox?.SelectedItem is SearchResult result) @@ -115,7 +115,7 @@ public static TextViewContext Create(SharpTreeView treeView = null, DecompilerTe TextView = textView, Reference = reference, Position = position, - MousePosition = ((Visual)textView ?? treeView ?? (Visual)listBox ?? dataGrid).PointToScreen(Mouse.GetPosition((IInputElement)textView ?? treeView ?? (IInputElement)listBox ?? dataGrid)) + MousePosition = ((Visual?)textView ?? treeView ?? (Visual?)listBox ?? dataGrid).PointToScreen(Mouse.GetPosition((IInputElement?)textView ?? treeView ?? (IInputElement?)listBox ?? dataGrid)) }; } } @@ -291,7 +291,7 @@ bool ShowContextMenu(TextViewContext context, out ContextMenu menu) { menu = new ContextMenu(); var menuGroups = new Dictionary[]>(); - IExport[] topLevelGroup = null; + IExport[]? topLevelGroup = null; foreach (var group in entries.OrderBy(c => c.Metadata.Order).GroupBy(c => c.Metadata.ParentMenuID)) { if (group.Key == null) @@ -313,7 +313,7 @@ void BuildMenu(IExport[] menuGroup bool needSeparatorForCategory = parent.Count > 0; foreach (var entryPair in category) { - IContextMenuEntry entry = entryPair.Value; + IContextMenuEntry? entry = entryPair.Value; if (entry.IsVisible(context)) { if (needSeparatorForCategory) diff --git a/ILSpy/Controls/GridViewColumnAutoSize.cs b/ILSpy/Controls/GridViewColumnAutoSize.cs index 5c833b1cfd..0d8f6edf38 100644 --- a/ILSpy/Controls/GridViewColumnAutoSize.cs +++ b/ILSpy/Controls/GridViewColumnAutoSize.cs @@ -52,25 +52,25 @@ public static void SetAutoWidth(DependencyObject obj, string value) static void AutoWidthPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { - ListView grid = sender as ListView; + ListView? grid = sender as ListView; if (grid == null) return; grid.SizeChanged += delegate (object listView, SizeChangedEventArgs e) { - ListView lv = listView as ListView; + ListView? lv = listView as ListView; if (lv == null) return; - GridView v = lv.View as GridView; + GridView? v = lv.View as GridView; if (v == null) return; CalculateSizes(v, GetAutoWidth(lv), e.NewSize.Width); }; - GridView view = grid.View as GridView; + GridView? view = grid.View as GridView; if (view == null) return; CalculateSizes(view, args.NewValue as string, grid.ActualWidth); } - static void CalculateSizes(GridView view, string sizeValue, double fullWidth) + static void CalculateSizes(GridView view, string? sizeValue, double fullWidth) { string[] sizes = (sizeValue ?? "").Split(';'); diff --git a/ILSpy/Controls/SearchBox.cs b/ILSpy/Controls/SearchBox.cs index e7ec45df37..f07dc24c12 100644 --- a/ILSpy/Controls/SearchBox.cs +++ b/ILSpy/Controls/SearchBox.cs @@ -137,7 +137,7 @@ public override void OnApplyTemplate() { base.OnApplyTemplate(); - Border iconBorder = GetTemplateChild("PART_IconBorder") as Border; + Border? iconBorder = GetTemplateChild("PART_IconBorder") as Border; if (iconBorder != null) { iconBorder.MouseLeftButtonUp += IconBorder_MouseLeftButtonUp; diff --git a/ILSpy/Controls/SortableGridViewColumn.cs b/ILSpy/Controls/SortableGridViewColumn.cs index 336f5442c8..7fe23d447c 100644 --- a/ILSpy/Controls/SortableGridViewColumn.cs +++ b/ILSpy/Controls/SortableGridViewColumn.cs @@ -73,7 +73,7 @@ public static void SetSortDirection(ListView listView, ColumnSortDirection value static void OnSortDirectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { - ListView grid = sender as ListView; + ListView? grid = sender as ListView; if (grid != null) { SortableGridViewColumn col = GetCurrentSortColumn(grid); @@ -101,7 +101,7 @@ public static void SetCurrentSortColumn(ListView listView, SortableGridViewColum static void OnCurrentSortColumnChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { - ListView grid = sender as ListView; + ListView? grid = sender as ListView; if (grid != null) { SortableGridViewColumn oldColumn = (SortableGridViewColumn)args.OldValue; @@ -134,7 +134,7 @@ public static void SetSortMode(ListView listView, ListViewSortMode value) static void OnSortModeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { - ListView grid = sender as ListView; + ListView? grid = sender as ListView; if (grid != null) { if ((ListViewSortMode)args.NewValue != ListViewSortMode.None) @@ -146,8 +146,8 @@ static void OnSortModeChanged(DependencyObject sender, DependencyPropertyChanged static void GridViewColumnHeaderClickHandler(object sender, RoutedEventArgs e) { - ListView grid = sender as ListView; - GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader; + ListView? grid = sender as ListView; + GridViewColumnHeader? headerClicked = e.OriginalSource as GridViewColumnHeader; if (grid != null && headerClicked != null && headerClicked.Role != GridViewColumnHeaderRole.Padding) { if (headerClicked.Column == GetCurrentSortColumn(grid)) @@ -188,7 +188,7 @@ static void Sort(ListView grid) string sortBy = column.SortBy; if (sortBy == null) { - Binding binding = column.DisplayMemberBinding as Binding; + Binding? binding = column.DisplayMemberBinding as Binding; if (binding != null && binding.Path != null) { sortBy = binding.Path.Path; diff --git a/ILSpy/Controls/TreeView/SharpTreeView.cs b/ILSpy/Controls/TreeView/SharpTreeView.cs index 845ba297c3..e8a76208cc 100644 --- a/ILSpy/Controls/TreeView/SharpTreeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeView.cs @@ -176,8 +176,8 @@ void flattener_CollectionChanged(object? sender, NotifyCollectionChangedEventArg // Deselect nodes that are being hidden, if any remain in the tree if (e.Action == NotifyCollectionChangedAction.Remove && Items.Count > 0) { - List selectedOldItems = null; - foreach (SharpTreeNode node in e.OldItems) + List? selectedOldItems = null; + foreach (SharpTreeNode node in e.OldItems!) { if (node.IsSelected) { @@ -194,7 +194,7 @@ void flattener_CollectionChanged(object? sender, NotifyCollectionChangedEventArg } } - void UpdateFocusedNode(List newSelection, int topSelectedIndex) + void UpdateFocusedNode(List? newSelection, int topSelectedIndex) { if (updatesLocked) return; @@ -222,7 +222,7 @@ protected override bool IsItemItsOwnContainerOverride(object item) protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { base.PrepareContainerForItemOverride(element, item); - SharpTreeViewItem container = element as SharpTreeViewItem; + SharpTreeViewItem? container = element as SharpTreeViewItem; container.ParentTreeView = this; // Make sure that the line renderer takes into account the new bound data if (container.NodeView != null) @@ -244,7 +244,7 @@ internal void HandleExpanding(SharpTreeNode node) SharpTreeNode lastVisibleChild = node; while (true) { - SharpTreeNode tmp = lastVisibleChild.Children.LastOrDefault(c => c.IsVisible); + SharpTreeNode? tmp = lastVisibleChild.Children.LastOrDefault(c => c.IsVisible); if (tmp != null) { lastVisibleChild = tmp; @@ -269,7 +269,7 @@ internal void HandleExpanding(SharpTreeNode node) protected override void OnKeyDown(KeyEventArgs e) { - SharpTreeViewItem container = e.OriginalSource as SharpTreeViewItem; + SharpTreeViewItem? container = e.OriginalSource as SharpTreeViewItem; switch (e.Key) { case Key.Left: @@ -422,7 +422,7 @@ public void ScrollIntoView(SharpTreeNode node) object? OnFocusItem(object item) { - FrameworkElement element = this.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement; + FrameworkElement? element = this.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement; if (element != null) { element.Focus(); @@ -606,7 +606,7 @@ List BuildDropTargets(SharpTreeViewItem item, DragEventArgs e) void TryAddDropTarget(List targets, SharpTreeViewItem item, DropPlace place, DragEventArgs e) { - SharpTreeNode node; + SharpTreeNode? node; int index; GetNodeAndIndex(item, place, out node, out index); @@ -627,7 +627,7 @@ void TryAddDropTarget(List targets, SharpTreeViewItem item, DropPlac } } - void GetNodeAndIndex(SharpTreeViewItem item, DropPlace place, out SharpTreeNode node, out int index) + void GetNodeAndIndex(SharpTreeViewItem item, DropPlace place, out SharpTreeNode? node, out int index) { node = null; index = 0; @@ -697,7 +697,7 @@ void ShowPreview(SharpTreeViewItem item, DropPlace place) insertMarker.Margin = new Thickness(p.X, p.Y, 0, 0); - SharpTreeNodeView secondNodeView = null; + SharpTreeNodeView? secondNodeView = null; var index = flattener.IndexOf(item.Node); if (place == DropPlace.Before) diff --git a/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs b/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs index 731744c149..5b14ebc6f7 100644 --- a/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs +++ b/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs @@ -116,7 +116,7 @@ int IndexOfMatch(string needle, int startIndex, bool tryBackward, out bool charW var item = (SharpTreeNode)treeView.Items[i]; if (item != null && item.Text != null) { - string text = item.Text.ToString(); + string text = item.Text.ToString() ?? ""; if (text.StartsWith(needle, comparisonType)) { charWasUsed = true; diff --git a/ILSpy/Controls/ZoomScrollViewer.cs b/ILSpy/Controls/ZoomScrollViewer.cs index 21e258963b..a6373fcc41 100644 --- a/ILSpy/Controls/ZoomScrollViewer.cs +++ b/ILSpy/Controls/ZoomScrollViewer.cs @@ -103,7 +103,7 @@ public bool ComputedZoomButtonCollapsed { static void CalculateZoomButtonCollapsed(DependencyObject d, DependencyPropertyChangedEventArgs e) { - ZoomScrollViewer z = d as ZoomScrollViewer; + ZoomScrollViewer? z = d as ZoomScrollViewer; if (z != null) z.ComputedZoomButtonCollapsed = (z.AlwaysShowZoomButtons == false) && (z.CurrentZoom == 1.0); } @@ -117,7 +117,7 @@ protected override void OnPreviewMouseWheel(MouseWheelEventArgs e) newZoom = Math.Max(this.MinimumZoom, Math.Min(this.MaximumZoom, newZoom)); // adjust scroll position so that mouse stays over the same virtual coordinate - ContentPresenter presenter = Template.FindName("PART_Presenter", this) as ContentPresenter; + ContentPresenter? presenter = Template.FindName("PART_Presenter", this) as ContentPresenter; Vector relMousePos; if (presenter != null) { diff --git a/ILSpy/Docking/DockWorkspace.cs b/ILSpy/Docking/DockWorkspace.cs index eb8323adc8..adc8497a74 100644 --- a/ILSpy/Docking/DockWorkspace.cs +++ b/ILSpy/Docking/DockWorkspace.cs @@ -84,7 +84,7 @@ private void CurrentAssemblyList_Changed(object? sender, NotifyCollectionChanged private void Documents_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - var collection = (PaneCollection)sender; + var collection = (PaneCollection?)sender; if (e.Action == NotifyCollectionChangedAction.Add) { ActiveTabPage = e.NewItems?[0] as TabPageModel; @@ -246,7 +246,7 @@ LayoutAnchorablePane GetContainer() { var anchorable = layout.Descendents().OfType().FirstOrDefault(x => x.Content is T) ?? layout.Hidden.First(x => x.Content is T); - return (LayoutAnchorablePane)previousContainerProperty.GetValue(anchorable) ?? (LayoutAnchorablePane)anchorable.Parent; + return (LayoutAnchorablePane?)previousContainerProperty.GetValue(anchorable) ?? (LayoutAnchorablePane)anchorable.Parent; } } diff --git a/ILSpy/ISmartTextOutput.cs b/ILSpy/ISmartTextOutput.cs index 1cee54e592..3bb46afe3d 100644 --- a/ILSpy/ISmartTextOutput.cs +++ b/ILSpy/ISmartTextOutput.cs @@ -52,7 +52,7 @@ public static class SmartTextOutputExtensions /// /// Creates a button. /// - public static void AddButton(this ISmartTextOutput output, ImageSource icon, string text, RoutedEventHandler click) + public static void AddButton(this ISmartTextOutput output, ImageSource? icon, string text, RoutedEventHandler click) { output.AddUIElement( delegate { diff --git a/ILSpy/Images/Images.cs b/ILSpy/Images/Images.cs index 49dfde0fd6..d605e4be7c 100644 --- a/ILSpy/Images/Images.cs +++ b/ILSpy/Images/Images.cs @@ -150,12 +150,12 @@ static BitmapImage LoadImage(object part, string icon) return image; } - public static Drawing LoadDrawingGroup(object part, string icon) + public static Drawing LoadDrawingGroup(object? part, string icon) { return (Drawing)Application.LoadComponent(GetUri(part, icon + ".xaml", absolute: false)); } - private static Uri GetUri(object part, string icon, bool absolute = true) + private static Uri GetUri(object? part, string icon, bool absolute = true) { Uri uri; var assembly = part?.GetType().Assembly; @@ -212,15 +212,15 @@ public static ImageSource GetIcon(MemberIcon icon, AccessOverlayIcon overlay, bo return memberIconCache.GetIcon(icon, overlay, isStatic); } - private static ImageSource GetIcon(string baseImage, string overlay = null, bool isStatic = false) + private static ImageSource GetIcon(string baseImage, string? overlay = null, bool isStatic = false) { ImageSource baseImageSource = Load(baseImage); - ImageSource overlayImageSource = overlay != null ? Load(overlay) : null; + ImageSource? overlayImageSource = overlay != null ? Load(overlay) : null; return CreateOverlayImage(baseImageSource, overlayImageSource, isStatic); } - private static ImageSource CreateOverlayImage(ImageSource baseImage, ImageSource overlay, bool isStatic) + private static ImageSource CreateOverlayImage(ImageSource baseImage, ImageSource? overlay, bool isStatic) { var group = new DrawingGroup(); @@ -391,16 +391,16 @@ public ImageSource GetIcon(T icon, AccessOverlayIcon overlay, bool isStatic) private ImageSource BuildMemberIcon(T icon, AccessOverlayIcon overlay, bool isStatic) { ImageSource baseImage = GetBaseImage(icon); - ImageSource overlayImage = GetOverlayImage(overlay); + ImageSource? overlayImage = GetOverlayImage(overlay); return CreateOverlayImage(baseImage, overlayImage, isStatic); } protected abstract ImageSource GetBaseImage(T icon); - private static ImageSource GetOverlayImage(AccessOverlayIcon overlay) + private static ImageSource? GetOverlayImage(AccessOverlayIcon overlay) { - ImageSource overlayImage; + ImageSource? overlayImage; switch (overlay) { case AccessOverlayIcon.Public: diff --git a/ILSpy/Languages/CSharpHighlightingTokenWriter.cs b/ILSpy/Languages/CSharpHighlightingTokenWriter.cs index c6edcfd4b1..4128dd4862 100644 --- a/ILSpy/Languages/CSharpHighlightingTokenWriter.cs +++ b/ILSpy/Languages/CSharpHighlightingTokenWriter.cs @@ -122,7 +122,7 @@ public CSharpHighlightingTokenWriter(TokenWriter decoratedWriter, ISmartTextOutp public override void WriteKeyword(Role role, string keyword) { - HighlightingColor color = null; + HighlightingColor? color = null; switch (keyword) { case "namespace": @@ -299,7 +299,7 @@ public override void WriteKeyword(Role role, string keyword) public override void WritePrimitiveType(string type) { - HighlightingColor color = null; + HighlightingColor? color = null; switch (type) { case "new": @@ -348,7 +348,7 @@ public override void WritePrimitiveType(string type) public override void WriteIdentifier(Identifier identifier) { - HighlightingColor color = null; + HighlightingColor? color = null; if (identifier.Parent?.GetResolveResult() is ILVariableResolveResult rr) { if (rr.Variable.Kind == VariableKind.Parameter) @@ -454,7 +454,7 @@ void ApplyTypeColor(IType type, ref HighlightingColor color) public override void WritePrimitiveValue(object value, Decompiler.CSharp.Syntax.LiteralFormat format) { - HighlightingColor color = null; + HighlightingColor? color = null; if (value is null) { color = valueKeywordColor; diff --git a/ILSpy/Languages/CSharpLanguage.cs b/ILSpy/Languages/CSharpLanguage.cs index c62222a0b1..4ec839456f 100644 --- a/ILSpy/Languages/CSharpLanguage.cs +++ b/ILSpy/Languages/CSharpLanguage.cs @@ -95,7 +95,7 @@ public override string ProjectFileExtension { get { return ".csproj"; } } - IReadOnlyList versions; + IReadOnlyList? versions; public override IReadOnlyList LanguageVersions { get { @@ -151,7 +151,7 @@ void WriteCode(ITextOutput output, DecompilerSettings settings, SyntaxTree synta public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options) { - MetadataFile assembly = method.ParentModule.MetadataFile; + MetadataFile? assembly = method.ParentModule.MetadataFile; CSharpDecompiler decompiler = CreateDecompiler(assembly, options); AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output); @@ -182,7 +182,7 @@ public SelectCtorTransform(IMethod ctor) public void Run(AstNode rootNode, TransformContext context) { - ConstructorDeclaration ctorDecl = null; + ConstructorDeclaration? ctorDecl = null; foreach (var node in rootNode.Children) { switch (node) @@ -247,7 +247,7 @@ public void Run(AstNode rootNode, TransformContext context) public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options) { - MetadataFile assembly = property.ParentModule.MetadataFile; + MetadataFile? assembly = property.ParentModule.MetadataFile; CSharpDecompiler decompiler = CreateDecompiler(assembly, options); AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output); @@ -258,7 +258,7 @@ public override void DecompileProperty(IProperty property, ITextOutput output, D public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options) { - MetadataFile assembly = field.ParentModule.MetadataFile; + MetadataFile? assembly = field.ParentModule.MetadataFile; CSharpDecompiler decompiler = CreateDecompiler(assembly, options); AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output); @@ -348,7 +348,7 @@ public override void DecompileEvent(IEvent @event, ITextOutput output, Decompila public override void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options) { - MetadataFile assembly = type.ParentModule.MetadataFile; + MetadataFile? assembly = type.ParentModule.MetadataFile; CSharpDecompiler decompiler = CreateDecompiler(assembly, options); AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output); @@ -380,8 +380,8 @@ void AddReferenceAssemblyWarningMessage(MetadataFile module, ITextOutput output) AddWarningMessage(module, output, line1); } - void AddWarningMessage(MetadataFile module, ITextOutput output, string line1, string line2 = null, - string buttonText = null, System.Windows.Media.ImageSource buttonImage = null, RoutedEventHandler buttonClickHandler = null) + void AddWarningMessage(MetadataFile module, ITextOutput output, string line1, string? line2 = null, + string? buttonText = null, System.Windows.Media.ImageSource? buttonImage = null, RoutedEventHandler? buttonClickHandler = null) { if (output is ISmartTextOutput fancyOutput) { @@ -775,7 +775,7 @@ static string ToCSharpString(MetadataReader metadata, TypeDefinitionHandle handl public override bool ShowMember(IEntity member) { - MetadataFile assembly = member.ParentModule.MetadataFile; + MetadataFile? assembly = member.ParentModule?.MetadataFile; return showAllMembers || !CSharpDecompiler.MemberIsHidden(assembly, member.MetadataToken, SettingsService.Instance.DecompilerSettings); } diff --git a/ILSpy/Languages/ILLanguage.cs b/ILSpy/Languages/ILLanguage.cs index 29681b982c..01d0324954 100644 --- a/ILSpy/Languages/ILLanguage.cs +++ b/ILSpy/Languages/ILLanguage.cs @@ -73,7 +73,7 @@ protected virtual ReflectionDisassembler CreateDisassembler(ITextOutput output, public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options) { var dis = CreateDisassembler(output, options); - MetadataFile module = method.ParentModule.MetadataFile; + MetadataFile? module = method.ParentModule?.MetadataFile; dis.AssemblyResolver = module.GetAssemblyResolver(); dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DisassembleMethod(module, (MethodDefinitionHandle)method.MetadataToken); @@ -82,7 +82,7 @@ public override void DecompileMethod(IMethod method, ITextOutput output, Decompi public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options) { var dis = CreateDisassembler(output, options); - MetadataFile module = field.ParentModule.MetadataFile; + MetadataFile? module = field.ParentModule?.MetadataFile; dis.AssemblyResolver = module.GetAssemblyResolver(); dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DisassembleField(module, (FieldDefinitionHandle)field.MetadataToken); @@ -91,7 +91,7 @@ public override void DecompileField(IField field, ITextOutput output, Decompilat public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options) { var dis = CreateDisassembler(output, options); - MetadataFile module = property.ParentModule.MetadataFile; + MetadataFile? module = property.ParentModule?.MetadataFile; dis.AssemblyResolver = module.GetAssemblyResolver(); dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DisassembleProperty(module, (PropertyDefinitionHandle)property.MetadataToken); @@ -117,7 +117,7 @@ public override void DecompileProperty(IProperty property, ITextOutput output, D public override void DecompileEvent(IEvent ev, ITextOutput output, DecompilationOptions options) { var dis = CreateDisassembler(output, options); - MetadataFile module = ev.ParentModule.MetadataFile; + MetadataFile? module = ev.ParentModule?.MetadataFile; dis.AssemblyResolver = module.GetAssemblyResolver(); dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DisassembleEvent(module, (EventDefinitionHandle)ev.MetadataToken); @@ -148,7 +148,7 @@ public override void DecompileEvent(IEvent ev, ITextOutput output, Decompilation public override void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options) { var dis = CreateDisassembler(output, options); - MetadataFile module = type.ParentModule.MetadataFile; + MetadataFile? module = type.ParentModule?.MetadataFile; dis.AssemblyResolver = module.GetAssemblyResolver(); dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DisassembleType(module, (TypeDefinitionHandle)type.MetadataToken); @@ -157,7 +157,7 @@ public override void DecompileType(ITypeDefinition type, ITextOutput output, Dec public override void DecompileNamespace(string nameSpace, IEnumerable types, ITextOutput output, DecompilationOptions options) { var dis = CreateDisassembler(output, options); - MetadataFile module = types.FirstOrDefault()?.ParentModule.MetadataFile; + MetadataFile? module = types.FirstOrDefault()?.ParentModule?.MetadataFile; dis.AssemblyResolver = module.GetAssemblyResolver(); dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DisassembleNamespace(nameSpace, module, types.Select(t => (TypeDefinitionHandle)t.MetadataToken)); @@ -199,7 +199,7 @@ public override void DecompileNamespace(string nameSpace, IEnumerable(ex => { }); - NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName); + NamespaceTreeNode? nsNode = asmNode.FindNamespaceNode(namespaceName); if (nsNode != null) { found = true; @@ -686,7 +686,7 @@ async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSp } else { - IEntity mr = await Task.Run(() => FindEntityInRelevantAssemblies(navigateTo, relevantAssemblies)); + IEntity? mr = await Task.Run(() => FindEntityInRelevantAssemblies(navigateTo, relevantAssemblies)); // Make sure we wait for assemblies being loaded... // BeginInvoke in LoadedAssembly.LookupReferencedAssemblyInternal await Dispatcher.InvokeAsync(delegate { }, DispatcherPriority.Normal); @@ -710,7 +710,7 @@ async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSp { // NavigateTo == null and an assembly was given on the command-line: // Select the newly loaded assembly - AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(relevantAssemblies[0]); + AssemblyTreeNode? asmNode = assemblyListTreeNode.FindAssemblyNode(relevantAssemblies[0]); if (asmNode != null && AssemblyTreeView.SelectedItem == initialSelection) { SelectNode(asmNode); @@ -718,7 +718,7 @@ async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSp } else if (spySettings != null) { - SharpTreeNode node = null; + SharpTreeNode? node = null; if (activeTreeViewPath?.Length > 0) { foreach (var asm in CurrentAssemblyList.GetAssemblies()) @@ -772,7 +772,7 @@ async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSp : new SimpleCompilation((PEFile)module, MinimalCorlib.Instance); return memberRef == null ? typeRef.Resolve(new SimpleTypeResolveContext(compilation)) as ITypeDefinition - : (IEntity)memberRef.Resolve(new SimpleTypeResolveContext(compilation)); + : (IEntity?)memberRef.Resolve(new SimpleTypeResolveContext(compilation)); } } return null; @@ -875,7 +875,7 @@ static bool FormatExceptions(App.ExceptionData[] exceptions, ITextOutput output) public async Task ShowMessageIfUpdatesAvailableAsync(ILSpySettings spySettings, bool forceCheck = false) { - string downloadUrl; + string? downloadUrl; if (forceCheck) { downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(spySettings); @@ -903,12 +903,12 @@ async void downloadOrCheckUpdateButtonClick(object sender, RoutedEventArgs e) else { updatePanel.Visibility = Visibility.Collapsed; - string downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(ILSpySettings.Load()); + string? downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(ILSpySettings.Load()); AdjustUpdateUIAfterCheck(downloadUrl, true); } } - void AdjustUpdateUIAfterCheck(string downloadUrl, bool displayMessage) + void AdjustUpdateUIAfterCheck(string? downloadUrl, bool displayMessage) { updateAvailableDownloadUrl = downloadUrl; updatePanel.Visibility = displayMessage ? Visibility.Visible : Visibility.Collapsed; @@ -1113,8 +1113,8 @@ internal void SelectNodes(IEnumerable nodes, bool inNewTabPage, { if (path == null) return null; - SharpTreeNode node = AssemblyTreeView.Root; - SharpTreeNode bestMatch = node; + SharpTreeNode? node = AssemblyTreeView.Root; + SharpTreeNode? bestMatch = node; foreach (var element in path) { if (node == null) @@ -1237,7 +1237,7 @@ public Task JumpToReferenceAsync(object reference, bool inNewTabPage) } break; default: - ILSpyTreeNode treeNode = FindTreeNode(reference); + ILSpyTreeNode? treeNode = FindTreeNode(reference); if (treeNode != null) SelectNode(treeNode, inNewTabPage); break; @@ -1301,9 +1301,9 @@ public void OpenFiles(string[] fileNames, bool focusNode = true) LoadAssemblies(fileNames, focusNode: focusNode); } - void LoadAssemblies(IEnumerable fileNames, List loadedAssemblies = null, bool focusNode = true) + void LoadAssemblies(IEnumerable fileNames, List? loadedAssemblies = null, bool focusNode = true) { - SharpTreeNode lastNode = null; + SharpTreeNode? lastNode = null; foreach (string file in fileNames) { var asm = assemblyList.OpenAssembly(file); @@ -1367,7 +1367,7 @@ protected override void OnContextMenuClosing(ContextMenuEventArgs e) void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e) { - DecompilerTextViewState state = null; + DecompilerTextViewState? state = null; if (refreshInProgress || changingActiveTab) { state = DockWorkspace.Instance.ActiveTabPage.GetState() as DecompilerTextViewState; @@ -1385,7 +1385,7 @@ void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e) Task decompilationTask; bool ignoreDecompilationRequests; - void DecompileSelectedNodes(DecompilerTextViewState newState = null, bool recordHistory = true) + void DecompileSelectedNodes(DecompilerTextViewState? newState = null, bool recordHistory = true) { if (ignoreDecompilationRequests) return; @@ -1406,7 +1406,7 @@ void DecompileSelectedNodes(DecompilerTextViewState newState = null, bool record if (AssemblyTreeView.SelectedItems.Count == 1) { - ILSpyTreeNode node = AssemblyTreeView.SelectedItem as ILSpyTreeNode; + ILSpyTreeNode? node = AssemblyTreeView.SelectedItem as ILSpyTreeNode; if (node != null && node.View(DockWorkspace.Instance.ActiveTabPage)) return; } @@ -1533,11 +1533,11 @@ internal void NavigateTo(RequestNavigateEventArgs e, bool recordHistory = true, Title = e.Uri.AbsolutePath, EnableHyperlinks = true }; - using (Stream s = typeof(App).Assembly.GetManifestResourceStream(typeof(App), e.Uri.AbsolutePath)) + using (Stream? s = typeof(App).Assembly.GetManifestResourceStream(typeof(App), e.Uri.AbsolutePath)) { using (StreamReader r = new StreamReader(s)) { - string line; + string? line; while ((line = r.ReadLine()) != null) { output.Write(line); diff --git a/ILSpy/Metadata/CorTables/EventTableTreeNode.cs b/ILSpy/Metadata/CorTables/EventTableTreeNode.cs index 7e3c95ca58..20f7003d3d 100644 --- a/ILSpy/Metadata/CorTables/EventTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/EventTableTreeNode.cs @@ -92,7 +92,7 @@ struct EventDefEntry : IMemberTreeNode public string Name => metadataFile.Metadata.GetString(eventDef.Name); - IEntity IMemberTreeNode.Member { + IEntity? IMemberTreeNode.Member { get { return ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); } diff --git a/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs b/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs index c8e8e310d1..c200cba3c8 100644 --- a/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs @@ -95,7 +95,7 @@ struct FieldDefEntry : IMemberTreeNode public string NameTooltip => $"{MetadataTokens.GetHeapOffset(fieldDef.Name):X} \"{Name}\""; - IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); + IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(fieldDef.Signature); diff --git a/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs b/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs index fe5cb173ca..f92db4da8c 100644 --- a/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs @@ -131,7 +131,7 @@ public string? ParamListTooltip { } } - IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); + IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); public MethodDefEntry(MetadataFile metadataFile, MethodDefinitionHandle handle) { diff --git a/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs b/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs index 05ff38b715..fe1d1eb72c 100644 --- a/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs @@ -92,7 +92,7 @@ struct PropertyDefEntry : IMemberTreeNode public string NameTooltip => $"{MetadataTokens.GetHeapOffset(propertyDef.Name):X} \"{Name}\""; - IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle); + IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(propertyDef.Signature); diff --git a/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs b/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs index 1ae59f107b..cdcb575555 100644 --- a/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs @@ -173,7 +173,7 @@ public string? MethodListTooltip { } } - IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle); + IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle); public TypeDefEntry(MetadataFile metadataFile, TypeDefinitionHandle handle) { diff --git a/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs b/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs index 9dcbe2f019..8715c2f0e9 100644 --- a/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs @@ -47,7 +47,7 @@ public override bool View(ViewModels.TabPageModel tabPage) view.RowDetailsTemplateSelector = new CustomDebugInformationDetailsTemplateSelector(); var list = new List(); - CustomDebugInformationEntry scrollTargetEntry = default; + CustomDebugInformationEntry? scrollTargetEntry = default; foreach (var row in metadataFile.Metadata.CustomDebugInformation) { diff --git a/ILSpy/Metadata/GoToTokenCommand.cs b/ILSpy/Metadata/GoToTokenCommand.cs index 9a57de5258..51b3ab038e 100644 --- a/ILSpy/Metadata/GoToTokenCommand.cs +++ b/ILSpy/Metadata/GoToTokenCommand.cs @@ -51,7 +51,7 @@ public bool IsVisible(TextViewContext context) return context.DataGrid?.Name == "MetadataView" && GetSelectedToken(context.DataGrid, out _) != null; } - private int? GetSelectedToken(DataGrid grid, out MetadataFile module) + private int? GetSelectedToken(DataGrid grid, out MetadataFile? module) { module = null; if (grid == null) @@ -75,7 +75,7 @@ class CopyCommand : IContextMenuEntry { public void Execute(TextViewContext context) { - string content = GetSelectedCellContent(context.DataGrid, context.MousePosition); + string? content = GetSelectedCellContent(context.DataGrid, context.MousePosition); Clipboard.SetText(content); } diff --git a/ILSpy/NavigationState.cs b/ILSpy/NavigationState.cs index e30ee7f639..1d72b66b75 100644 --- a/ILSpy/NavigationState.cs +++ b/ILSpy/NavigationState.cs @@ -38,7 +38,7 @@ public class NavigationState : IEquatable public NavigationState(TabPageModel tabPage, ViewState viewState) { this.TabPage = tabPage; - this.treeNodes = new HashSet((IEnumerable)viewState.DecompiledNodes ?? Array.Empty()); + this.treeNodes = new HashSet((IEnumerable?)viewState.DecompiledNodes ?? Array.Empty()); ViewState = viewState; } diff --git a/ILSpy/Options/DisplaySettingsPanel.xaml.cs b/ILSpy/Options/DisplaySettingsPanel.xaml.cs index 9645dacc7d..7101665c7d 100644 --- a/ILSpy/Options/DisplaySettingsPanel.xaml.cs +++ b/ILSpy/Options/DisplaySettingsPanel.xaml.cs @@ -99,11 +99,11 @@ orderby ff.Source select ff).ToArray(); } - public static DisplaySettings LoadDisplaySettings(ILSpySettings settings, SessionSettings sessionSettings = null) + public static DisplaySettings LoadDisplaySettings(ILSpySettings settings, SessionSettings? sessionSettings = null) { XElement e = settings["DisplaySettings"]; var s = new DisplaySettings(); - s.SelectedFont = new FontFamily((string)e.Attribute("Font") ?? "Consolas"); + s.SelectedFont = new FontFamily((string?)e.Attribute("Font") ?? "Consolas"); s.SelectedFontSize = (double?)e.Attribute("FontSize") ?? 10.0 * 4 / 3; s.ShowLineNumbers = (bool?)e.Attribute("ShowLineNumbers") ?? false; s.ShowMetadataTokens = (bool?)e.Attribute("ShowMetadataTokens") ?? false; diff --git a/ILSpy/Options/OptionsDialog.xaml.cs b/ILSpy/Options/OptionsDialog.xaml.cs index c9226fdefd..184dc9b1c4 100644 --- a/ILSpy/Options/OptionsDialog.xaml.cs +++ b/ILSpy/Options/OptionsDialog.xaml.cs @@ -63,7 +63,7 @@ public OptionsDialog() tabControl.Items.Add(tabItem); - IOptionPage page = optionPage.Value as IOptionPage; + IOptionPage? page = optionPage.Value as IOptionPage; if (page != null) page.Load(settings); } @@ -75,7 +75,7 @@ void OKButton_Click(object sender, RoutedEventArgs e) delegate (XElement root) { foreach (var optionPage in optionPages) { - IOptionPage page = optionPage.Value as IOptionPage; + IOptionPage? page = optionPage.Value as IOptionPage; if (page != null) page.Save(root); } diff --git a/ILSpy/Search/SearchPane.xaml.cs b/ILSpy/Search/SearchPane.xaml.cs index 028fcb8b84..c9ae399304 100644 --- a/ILSpy/Search/SearchPane.xaml.cs +++ b/ILSpy/Search/SearchPane.xaml.cs @@ -53,7 +53,7 @@ public partial class SearchPane { const int MAX_RESULTS = 1000; const int MAX_REFRESH_TIME_MS = 10; // More means quicker forward of data, fewer means better responsibility - RunningSearch currentSearch; + RunningSearch? currentSearch; bool runSearchOnNextShow; IComparer resultsComparer; @@ -231,7 +231,7 @@ void UpdateResults(object? sender, EventArgs e) currentSearch.Cancel(); } - async void StartSearch(string searchTerm) + async void StartSearch(string? searchTerm) { if (currentSearch != null) { @@ -245,7 +245,7 @@ async void StartSearch(string searchTerm) SearchResult.ComparerByName; Results.Clear(); - RunningSearch startedSearch = null; + RunningSearch? startedSearch = null; if (!string.IsNullOrEmpty(searchTerm)) { @@ -299,7 +299,7 @@ SearchRequest Parse(string input) SearchRequest request = new(); List keywords = new(); - Regex regex = null; + Regex? regex = null; request.Mode = searchMode; foreach (string part in parts) @@ -325,7 +325,7 @@ SearchRequest Parse(string input) prefixLength = part.IndexOf(':', 0, prefixLength); delimiterLength = 1; } - string prefix; + string? prefix; if (prefixLength <= 0) { prefix = null; diff --git a/ILSpy/SessionSettings.cs b/ILSpy/SessionSettings.cs index 1053603e0c..74aaaa1775 100644 --- a/ILSpy/SessionSettings.cs +++ b/ILSpy/SessionSettings.cs @@ -44,7 +44,7 @@ public SessionSettings(ILSpySettings spySettings) { XElement doc = spySettings["SessionSettings"]; - XElement filterSettings = doc.Element("FilterSettings"); + XElement? filterSettings = doc.Element("FilterSettings"); if (filterSettings == null) filterSettings = new XElement("FilterSettings"); @@ -52,7 +52,7 @@ public SessionSettings(ILSpySettings spySettings) this.ActiveAssemblyList = (string)doc.Element("ActiveAssemblyList"); - XElement activeTreeViewPath = doc.Element("ActiveTreeViewPath"); + XElement? activeTreeViewPath = doc.Element("ActiveTreeViewPath"); if (activeTreeViewPath != null) { this.ActiveTreeViewPath = activeTreeViewPath.Elements().Select(e => Unescape((string)e)).ToArray(); @@ -63,7 +63,7 @@ public SessionSettings(ILSpySettings spySettings) this.WindowBounds = FromString((string)doc.Element("WindowBounds"), DefaultWindowBounds); this.SelectedSearchMode = FromString((string)doc.Element("SelectedSearchMode"), SearchMode.TypeAndMember); this.Theme = FromString((string)doc.Element(nameof(Theme)), ThemeManager.Current.DefaultTheme); - string currentCulture = (string)doc.Element(nameof(CurrentCulture)); + string? currentCulture = (string)doc.Element(nameof(CurrentCulture)); this.CurrentCulture = string.IsNullOrEmpty(currentCulture) ? null : currentCulture; this.DockLayout = new DockLayoutSettings(doc.Element("DockLayout")); @@ -108,7 +108,7 @@ public string CurrentCulture { } } - public string ActiveAssemblyList { + public string? ActiveAssemblyList { get => activeAssemblyList; set { if (value != null && value != activeAssemblyList) @@ -166,7 +166,7 @@ public void Save() } static Regex regex = new Regex("\\\\x(?[0-9A-f]{4})"); - private string activeAssemblyList; + private string? activeAssemblyList; static string Escape(string p) { @@ -186,7 +186,7 @@ static string Unescape(string p) return regex.Replace(p, m => ((char)int.Parse(m.Groups["num"].Value, NumberStyles.HexNumber)).ToString()); } - static T FromString(string s, T defaultValue) + static T FromString(string? s, T defaultValue) { if (s == null) return defaultValue; diff --git a/ILSpy/TaskHelper.cs b/ILSpy/TaskHelper.cs index e26eaf0627..21bfd56e47 100644 --- a/ILSpy/TaskHelper.cs +++ b/ILSpy/TaskHelper.cs @@ -174,7 +174,7 @@ public static Task Catch(this Task task, Action action) return task.ContinueWith(t => { if (t.IsFaulted) { - Exception ex = t.Exception; + Exception? ex = t.Exception; while (ex is AggregateException) ex = ex.InnerException; if (ex is TException) diff --git a/ILSpy/TextView/AvalonEditTextOutput.cs b/ILSpy/TextView/AvalonEditTextOutput.cs index da62890a0f..6517a1783c 100644 --- a/ILSpy/TextView/AvalonEditTextOutput.cs +++ b/ILSpy/TextView/AvalonEditTextOutput.cs @@ -40,7 +40,7 @@ namespace ICSharpCode.ILSpy.TextView /// public sealed class ReferenceSegment : TextSegment { - public object Reference; + public object? Reference; public bool IsLocal; public bool IsDefinition; } diff --git a/ILSpy/TextView/DecompilerTextView.cs b/ILSpy/TextView/DecompilerTextView.cs index 1124a73e5e..f500fd3743 100644 --- a/ILSpy/TextView/DecompilerTextView.cs +++ b/ILSpy/TextView/DecompilerTextView.cs @@ -392,7 +392,7 @@ void ToolTipClosed(object? sender, EventArgs e) { if (segment.Reference is ICSharpCode.Decompiler.Disassembler.OpCodeInfo code) { - XmlDocumentationProvider docProvider = XmlDocLoader.MscorlibDocumentation; + XmlDocumentationProvider? docProvider = XmlDocLoader.MscorlibDocumentation; DocumentationUIBuilder renderer = new DocumentationUIBuilder(new CSharpAmbience(), SettingsService.Instance.SessionSettings.LanguageSettings.Language.SyntaxHighlighting); renderer.AddSignatureBlock($"{code.Name} (0x{code.Code:x})"); if (docProvider != null) @@ -425,7 +425,7 @@ void ToolTipClosed(object? sender, EventArgs e) Handle handle = unresolvedEntity.Handle; if (!handle.IsEntityHandle()) return null; - IEntity resolved = typeSystem.MainModule.ResolveEntity((EntityHandle)handle); + IEntity? resolved = typeSystem.MainModule.ResolveEntity((EntityHandle)handle); if (resolved == null) return null; var document = CreateTooltipForEntity(resolved); @@ -445,7 +445,7 @@ void ToolTipClosed(object? sender, EventArgs e) { Language currentLanguage = SettingsService.Instance.SessionSettings.LanguageSettings.Language; DocumentationUIBuilder renderer = new DocumentationUIBuilder(new CSharpAmbience(), currentLanguage.SyntaxHighlighting); - RichText richText = currentLanguage.GetRichTextTooltip(resolved); + RichText? richText = currentLanguage.GetRichTextTooltip(resolved); if (richText == null) { return null; diff --git a/ILSpy/TextView/DocumentationUIBuilder.cs b/ILSpy/TextView/DocumentationUIBuilder.cs index e8527c858c..d6d6550210 100644 --- a/ILSpy/TextView/DocumentationUIBuilder.cs +++ b/ILSpy/TextView/DocumentationUIBuilder.cs @@ -128,7 +128,7 @@ public void AddSignatureBlock(string signature, RichTextModel highlighting = nul AddBlock(block); } - public void AddXmlDocumentation(string xmlDocumentation, IEntity declaringEntity, Func resolver) + public void AddXmlDocumentation(string xmlDocumentation, IEntity? declaringEntity, Func? resolver) { if (xmlDocumentation == null) return; @@ -375,7 +375,7 @@ void AddPreliminary(IEnumerable children) void AddSee(XmlDocumentationElement element) { - IEntity referencedEntity = element.ReferencedEntity; + IEntity? referencedEntity = element.ReferencedEntity; if (referencedEntity != null) { if (element.Children.Any()) @@ -397,7 +397,7 @@ void AddSee(XmlDocumentationElement element) } else if (element.GetAttribute("href") != null) { - Uri uri; + Uri? uri; if (Uri.TryCreate(element.GetAttribute("href"), UriKind.Absolute, out uri)) { if (element.Children.Any()) diff --git a/ILSpy/TextView/FoldingCommands.cs b/ILSpy/TextView/FoldingCommands.cs index c061c543e7..4fceb11766 100644 --- a/ILSpy/TextView/FoldingCommands.cs +++ b/ILSpy/TextView/FoldingCommands.cs @@ -43,7 +43,7 @@ public void Execute(TextViewContext context) { if (null == context.TextView) return; - FoldingManager foldingManager = context.TextView.FoldingManager; + FoldingManager? foldingManager = context.TextView.FoldingManager; if (null == foldingManager) return; bool doFold = true; @@ -82,7 +82,7 @@ public void Execute(TextViewContext context) if (null == textView) return; var editor = textView.textEditor; - FoldingManager foldingManager = context.TextView.FoldingManager; + FoldingManager? foldingManager = context.TextView.FoldingManager; if (null == foldingManager) return; // TODO: or use Caret if position is not given? @@ -91,7 +91,7 @@ public void Execute(TextViewContext context) return; TextViewPosition pos = posBox.Value; // look for folding on this line: - FoldingSection folding = foldingManager.GetNextFolding(editor.Document.GetOffset(pos.Line, 1)); + FoldingSection? folding = foldingManager.GetNextFolding(editor.Document.GetOffset(pos.Line, 1)); if (folding == null || editor.Document.GetLineByOffset(folding.StartOffset).LineNumber != pos.Line) { // no folding found on current line: find innermost folding containing the mouse position diff --git a/ILSpy/TreeNodes/AssemblyListTreeNode.cs b/ILSpy/TreeNodes/AssemblyListTreeNode.cs index 9ffe3fdf08..218771aa76 100644 --- a/ILSpy/TreeNodes/AssemblyListTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyListTreeNode.cs @@ -98,7 +98,7 @@ public override bool CanDrop(IPlatformDragEventArgs e, int index) public override void Drop(IPlatformDragEventArgs e, int index) { - string[] files = e.Data.GetData(AssemblyTreeNode.DataFormat) as string[]; + string[]? files = e.Data.GetData(AssemblyTreeNode.DataFormat) as string[]; if (files == null) files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files != null) @@ -225,7 +225,7 @@ static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) var declaringType = def.DeclaringTypeDefinition; if (declaringType != null) { - TypeTreeNode decl = FindTypeNode(declaringType); + TypeTreeNode? decl = FindTypeNode(declaringType); if (decl != null) { decl.EnsureLazyChildren(); @@ -249,12 +249,12 @@ static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) /// public ILSpyTreeNode? FindMethodNode(IMethod def) { - TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); + TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) return null; // method might be an accessor, must look for parent node - ILSpyTreeNode parentNode = typeNode; - MethodTreeNode methodNode; + ILSpyTreeNode? parentNode = typeNode; + MethodTreeNode? methodNode; parentNode.EnsureLazyChildren(); switch (def.AccessorOwner) { @@ -290,7 +290,7 @@ static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) /// public FieldTreeNode? FindFieldNode(IField def) { - TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); + TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) return null; typeNode.EnsureLazyChildren(); @@ -303,7 +303,7 @@ static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) /// public PropertyTreeNode? FindPropertyNode(IProperty def) { - TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); + TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) return null; typeNode.EnsureLazyChildren(); @@ -316,7 +316,7 @@ static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) /// public EventTreeNode? FindEventNode(IEvent def) { - TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); + TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) return null; typeNode.EnsureLazyChildren(); diff --git a/ILSpy/TreeNodes/AssemblyTreeNode.cs b/ILSpy/TreeNodes/AssemblyTreeNode.cs index 1f4c0b794d..fb108dfaab 100644 --- a/ILSpy/TreeNodes/AssemblyTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyTreeNode.cs @@ -248,7 +248,7 @@ void LoadChildrenForPEFile(MetadataFile module) typeSystem = LoadedAssembly.GetTypeSystemOrNull(); var assembly = (MetadataModule)typeSystem.MainModule; this.Children.Add(new MetadataTreeNode(module, Resources.Metadata)); - Decompiler.DebugInfo.IDebugInfoProvider debugInfo = LoadedAssembly.GetDebugInfoOrNull(); + Decompiler.DebugInfo.IDebugInfoProvider? debugInfo = LoadedAssembly.GetDebugInfoOrNull(); if (debugInfo is PortableDebugInfoProvider ppdb && ppdb.GetMetadataReader() is System.Reflection.Metadata.MetadataReader reader) { @@ -280,7 +280,7 @@ void LoadChildrenForPEFile(MetadataFile module) NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace) { - if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode ns)) + if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode? ns)) { if (useNestedStructure) { @@ -346,7 +346,7 @@ void LoadChildrenForWebCilFile(WebCilFile module) NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace) { - if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode ns)) + if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode? ns)) { if (useNestedStructure) { @@ -392,7 +392,7 @@ private static void SetPublicAPI(NamespaceTreeNode ns) if (type == null) return null; EnsureLazyChildren(); - TypeTreeNode node; + TypeTreeNode? node; if (typeDict.TryGetValue((TypeDefinitionHandle)type.MetadataToken, out node)) return node; else diff --git a/ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs b/ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs index 69502149fd..04dccc7b99 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs @@ -71,7 +71,7 @@ public override void Decompile(Language language, ITextOutput output, Decompilat var sizeInBytesText = sizeInBytes == null ? "" : ", " + sizeInBytes + " bytes"; language.WriteCommentLine(output, $"{Resource.Name} ({Resource.ResourceType}, {Resource.Attributes}{sizeInBytesText})"); - ISmartTextOutput smartOutput = output as ISmartTextOutput; + ISmartTextOutput? smartOutput = output as ISmartTextOutput; if (smartOutput != null) { smartOutput.AddButton(Images.Save, Resources.Save, delegate { Save(Docking.DockWorkspace.Instance.ActiveTabPage); }); @@ -81,7 +81,7 @@ public override void Decompile(Language language, ITextOutput output, Decompilat public override bool View(TabPageModel tabPage) { - Stream s = Resource.TryOpenStream(); + Stream? s = Resource.TryOpenStream(); if (s != null && s.Length < DecompilerTextView.DefaultOutputLengthLimit) { s.Position = 0; @@ -107,7 +107,7 @@ public override bool View(TabPageModel tabPage) public override bool Save(TabPageModel tabPage) { - Stream s = Resource.TryOpenStream(); + Stream? s = Resource.TryOpenStream(); if (s == null) return false; SaveFileDialog dlg = new SaveFileDialog(); diff --git a/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs b/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs index eb3ab6e17c..0b1ce8d851 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs @@ -71,7 +71,7 @@ public ResourcesFileTreeNode(Resource er) protected override void LoadChildren() { - Stream s = Resource.TryOpenStream(); + Stream? s = Resource.TryOpenStream(); if (s == null) return; s.Position = 0; @@ -128,7 +128,7 @@ private void ProcessResourceEntry(KeyValuePair entry) public override bool Save(TabPageModel tabPage) { - Stream s = Resource.TryOpenStream(); + Stream? s = Resource.TryOpenStream(); if (s == null) return false; SaveFileDialog dlg = new SaveFileDialog(); @@ -179,7 +179,7 @@ public override void Decompile(Language language, ITextOutput output, Decompilat var textView = (DecompilerTextView)Docking.DockWorkspace.Instance.ActiveTabPage.Content; if (stringTableEntries.Count != 0) { - ISmartTextOutput smartOutput = output as ISmartTextOutput; + ISmartTextOutput? smartOutput = output as ISmartTextOutput; if (null != smartOutput) { smartOutput.AddUIElement( @@ -193,7 +193,7 @@ public override void Decompile(Language language, ITextOutput output, Decompilat } if (otherEntries.Count != 0) { - ISmartTextOutput smartOutput = output as ISmartTextOutput; + ISmartTextOutput? smartOutput = output as ISmartTextOutput; if (null != smartOutput) { smartOutput.AddUIElement( diff --git a/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs b/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs index a582b43b57..cd2b796b87 100644 --- a/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs @@ -54,7 +54,7 @@ public XamlResourceEntryNode(string key, Func openStream) : base(key, o public override bool View(TabPageModel tabPage) { AvalonEditTextOutput output = new AvalonEditTextOutput(); - IHighlightingDefinition highlighting = null; + IHighlightingDefinition? highlighting = null; tabPage.ShowTextView(textView => textView.RunWithCancellation( token => Task.Factory.StartNew( diff --git a/ILSpy/TreeNodes/ThreadingSupport.cs b/ILSpy/TreeNodes/ThreadingSupport.cs index ce1d875154..a1d66245a4 100644 --- a/ILSpy/TreeNodes/ThreadingSupport.cs +++ b/ILSpy/TreeNodes/ThreadingSupport.cs @@ -67,7 +67,7 @@ public void LoadChildren(SharpTreeNode node, Func> thisTask = null; + Task>? thisTask = null; thisTask = new Task>( delegate { List result = new List(); diff --git a/ILSpy/Updates/NotifyOfUpdatesStrategy.cs b/ILSpy/Updates/NotifyOfUpdatesStrategy.cs index 01c6e1ae80..d025657841 100644 --- a/ILSpy/Updates/NotifyOfUpdatesStrategy.cs +++ b/ILSpy/Updates/NotifyOfUpdatesStrategy.cs @@ -46,7 +46,7 @@ public static async Task GetLatestVersionAsync() var bands = doc.Root.Elements("band"); var currentBand = bands.FirstOrDefault(b => (string)b.Attribute("id") == band) ?? bands.First(); Version version = new Version((string)currentBand.Element("latestVersion")); - string url = (string)currentBand.Element("downloadUrl"); + string? url = (string)currentBand.Element("downloadUrl"); if (!(url.StartsWith("http://", StringComparison.Ordinal) || url.StartsWith("https://", StringComparison.Ordinal))) url = null; // don't accept non-urls diff --git a/TestPlugin/CustomLanguage.cs b/TestPlugin/CustomLanguage.cs index 7e38fdffef..bfd2ac285a 100644 --- a/TestPlugin/CustomLanguage.cs +++ b/TestPlugin/CustomLanguage.cs @@ -41,7 +41,7 @@ public override void DecompileMethod(IMethod method, ITextOutput output, Decompi var methodBody = module.GetMethodBody(methodDef.RelativeVirtualAddress); output.WriteLine("Size of method: {0} bytes", methodBody.GetCodeSize()); - ISmartTextOutput smartOutput = output as ISmartTextOutput; + ISmartTextOutput? smartOutput = output as ISmartTextOutput; if (smartOutput != null) { // when writing to the text view (but not when writing to a file), we can even add UI elements such as buttons: diff --git a/TestPlugin/CustomOptionPage.xaml.cs b/TestPlugin/CustomOptionPage.xaml.cs index 1c16be47fe..b4d6079172 100644 --- a/TestPlugin/CustomOptionPage.xaml.cs +++ b/TestPlugin/CustomOptionPage.xaml.cs @@ -50,7 +50,7 @@ public void Save(XElement root) // Replace the existing section in the settings file, or add a new section, // if required. - XElement existingElement = root.Element(ns + "CustomOptions"); + XElement? existingElement = root.Element(ns + "CustomOptions"); if (existingElement != null) existingElement.ReplaceWith(section); else From b652648db30330527954b87bb5282a9f698d5da2 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 16:30:39 -0400 Subject: [PATCH 12/15] more nullability updates focus CS8619 --- ICSharpCode.BamlDecompiler/Baml/BamlContext.cs | 4 ++-- ICSharpCode.Decompiler/CSharp/CallBuilder.cs | 4 ++-- .../CSharp/Resolver/MemberLookup.cs | 2 +- .../CSharp/StatementBuilder.cs | 6 +++--- ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs | 2 +- .../CSharp/Syntax/TypeSystemAstBuilder.cs | 2 +- .../DebugInfo/IDebugInfoProvider.cs | 4 ++-- .../Disassembler/ReflectionDisassembler.cs | 18 +++++++++--------- .../IL/ControlFlow/AwaitInCatchTransform.cs | 2 +- .../IL/Transforms/SwitchOnStringTransform.cs | 10 +++++----- .../IL/Transforms/TransformExpressionTrees.cs | 4 ++-- 11 files changed, 29 insertions(+), 29 deletions(-) diff --git a/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs b/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs index a310a23801..797db27ccc 100644 --- a/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs +++ b/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs @@ -37,7 +37,7 @@ internal class BamlContext public IDecompilerTypeSystem TypeSystem { get; } public KnownThings KnownThings { get; } - Dictionary assemblyMap = new Dictionary(); + Dictionary assemblyMap = new Dictionary(); public Dictionary AssemblyIdMap { get; } public Dictionary AttributeIdMap { get; } @@ -88,7 +88,7 @@ public static BamlContext ConstructContext(IDecompilerTypeSystem typeSystem, Bam return ctx; } - public (string FullAssemblyName, IModule Assembly) ResolveAssembly(ushort id) + public (string? FullAssemblyName, IModule? Assembly) ResolveAssembly(ushort id) { id &= 0xfff; if (!assemblyMap.TryGetValue(id, out var assembly)) diff --git a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs index 4b86a1334d..15f5c8705d 100644 --- a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs @@ -711,7 +711,7 @@ private bool TryGetStringInterpolationTokens(ArgumentList argumentList, [NotNull return false; tokens = new List<(TokenKind Kind, int Index, int Alignment, string? Format)>(); int i = 0; - format = (string)crr.ConstantValue; + format = (string?)crr.ConstantValue; foreach (var (kind, data) in TokenizeFormatString(format)) { int index; @@ -1827,7 +1827,7 @@ ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod? invo { ExpressionBuilder expressionBuilder = this.expressionBuilder; ExpressionWithResolveResult targetExpression; - (TranslatedExpression target, bool addTypeArguments, string methodName, ResolveResult result) = DisambiguateDelegateReference(method, invokeMethod, expectedTargetDetails, thisArg); + (TranslatedExpression target, bool addTypeArguments, string? methodName, ResolveResult result) = DisambiguateDelegateReference(method, invokeMethod, expectedTargetDetails, thisArg); if (target.Expression != null) { var mre = new MemberReferenceExpression(target, methodName); diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs index d08f85522b..b0a8f4ee83 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs @@ -189,7 +189,7 @@ public IEnumerable GetAccessibleMembers(ResolveResult targetResolveResu { var nestedTypes = type.GetNestedTypes(options: GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions); // GetDefinition() might return null if some IType has a strange implementation of GetNestedTypes. - entities.AddRange(nestedTypes.Select(t => t.GetDefinition()).Where(td => td != null)); + entities.AddRange(nestedTypes.Select(t => t.GetDefinition()).OfType()); } foreach (var entityGroup in entities.GroupBy(e => e.Name)) diff --git a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs index e335af2198..e648d584ad 100644 --- a/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/StatementBuilder.cs @@ -152,7 +152,7 @@ protected internal override TranslatedStatement VisitIfInstruction(IfInstruction return new IfElseStatement(condition, trueStatement, falseStatement).WithILInstruction(inst); } - internal IEnumerable CreateTypedCaseLabel(long i, IType type, List<(string Key, int Value)>? map = null) + internal IEnumerable CreateTypedCaseLabel(long i, IType type, List<(string? Key, int Value)>? map = null) { object value; // unpack nullable type, if necessary: @@ -204,7 +204,7 @@ protected internal override TranslatedStatement VisitSwitchInstruction(SwitchIns return TranslateSwitch(null, inst).WithILInstruction(inst); } - SwitchStatement TranslateSwitch(BlockContainer switchContainer, SwitchInstruction inst) + SwitchStatement TranslateSwitch(BlockContainer? switchContainer, SwitchInstruction inst) { var oldBreakTarget = breakTarget; breakTarget = switchContainer; // 'break' within a switch would only leave the switch @@ -385,7 +385,7 @@ protected internal override TranslatedStatement VisitBranch(Branch inst) } /// Target container that a 'break;' statement would break out of - BlockContainer breakTarget; + BlockContainer? breakTarget; /// Dictionary from BlockContainer to label name for 'goto of_container'; readonly Dictionary endContainerLabels = new Dictionary(); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs index 60d0791a60..eae240691d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs @@ -29,7 +29,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { public static class Roles { - public static readonly Role Root = AstNode.RootRole; + public static readonly Role Root = AstNode.RootRole; // some pre defined constants for common roles public static readonly Role Identifier = new Role("Identifier", Syntax.Identifier.Null); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs index 3b5320f862..8eeda41577 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs @@ -1291,7 +1291,7 @@ Expression ConvertEnumValue(IType type, long val) } return new CastExpression(ConvertType(type), new PrimitiveExpression(CSharpPrimitiveCast.Cast(enumBaseTypeCode, val, false))); - (long value, IField field) PrepareConstant(IField field) + (long value, IField? field) PrepareConstant(IField field) { if (!field.IsConst) return (-1, null); diff --git a/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs b/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs index 04de5d8d72..0e233d7754 100644 --- a/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs +++ b/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs @@ -20,8 +20,8 @@ public Variable(int index, string name) public struct PdbExtraTypeInfo { - public string[] TupleElementNames; - public bool[] DynamicFlags; + public string?[]? TupleElementNames; + public bool[]? DynamicFlags; } public interface IDebugInfoProvider diff --git a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs index 75a3c2877d..9bec3d1268 100644 --- a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs @@ -475,7 +475,7 @@ void WriteSecurityDeclarations(MetadataFile module, DeclarativeSecurityAttribute } } - class SecurityDeclarationDecoder : ICustomAttributeTypeProvider<(PrimitiveTypeCode, string)> + class SecurityDeclarationDecoder : ICustomAttributeTypeProvider<(PrimitiveTypeCode, string?)> { readonly ITextOutput output; readonly IAssemblyResolver resolver; @@ -488,32 +488,32 @@ public SecurityDeclarationDecoder(ITextOutput output, IAssemblyResolver resolver this.module = module; } - public (PrimitiveTypeCode, string) GetPrimitiveType(PrimitiveTypeCode typeCode) + public (PrimitiveTypeCode, string?) GetPrimitiveType(PrimitiveTypeCode typeCode) { return (typeCode, null); } - public (PrimitiveTypeCode, string) GetSystemType() + public (PrimitiveTypeCode, string?) GetSystemType() { return (0, "type"); } - public (PrimitiveTypeCode, string) GetSZArrayType((PrimitiveTypeCode, string) elementType) + public (PrimitiveTypeCode, string?) GetSZArrayType((PrimitiveTypeCode, string?) elementType) { return (elementType.Item1, (elementType.Item2 ?? PrimitiveTypeCodeToString(elementType.Item1)) + "[]"); } - public (PrimitiveTypeCode, string) GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) + public (PrimitiveTypeCode, string?) GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { throw new NotImplementedException(); } - public (PrimitiveTypeCode, string) GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) + public (PrimitiveTypeCode, string?) GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { throw new NotImplementedException(); } - public (PrimitiveTypeCode, string) GetTypeFromSerializedName(string name) + public (PrimitiveTypeCode, string?) GetTypeFromSerializedName(string name) { if (resolver == null) throw new EnumUnderlyingTypeResolveException(); @@ -525,12 +525,12 @@ public SecurityDeclarationDecoder(ITextOutput output, IAssemblyResolver resolver return (0, name); } - public PrimitiveTypeCode GetUnderlyingEnumType((PrimitiveTypeCode, string) type) + public PrimitiveTypeCode GetUnderlyingEnumType((PrimitiveTypeCode, string?) type) { return type.Item1; } - public bool IsSystemType((PrimitiveTypeCode, string) type) + public bool IsSystemType((PrimitiveTypeCode, string?) type) { return "type" == type.Item2; } diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs index 031f0ff730..569ccede8c 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs @@ -420,7 +420,7 @@ bool ParseIfJumpTable(int id, Block jumpTableEntryBlock, ILVariable identifierVa // => // throw(ldloc result.Handler.Variable) internal static bool MatchExceptionCaptureBlock(ILTransformContext context, Block block, - ref ILVariable? objectVariable, out StLoc? typedExceptionVariableStore, out Block? captureBlock, out Block? throwBlock) + [NotNullWhen(true)] ref ILVariable? objectVariable, [NotNullWhen(true)] out StLoc? typedExceptionVariableStore, [NotNullWhen(true)] out Block? captureBlock, [NotNullWhen(true)] out Block? throwBlock) { bool DerivesFromException(IType t) => t.GetAllBaseTypes().Any(ty => ty.IsKnownType(KnownTypeCode.Exception)); diff --git a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs index 4ac25bfc05..419ea000f4 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnStringTransform.cs @@ -422,8 +422,8 @@ bool SimplifyCSharp1CascadingIfStatements(InstructionCollection i return false; switchValueVar = switchValueVarCopy; int conditionOffset = 1; - Block currentCaseBlock = isInternedBlock; - var values = new List<(string, ILInstruction)>(); + Block? currentCaseBlock = isInternedBlock; + var values = new List<(string?, ILInstruction)>(); if (!switchValueVarCopy.IsSingleDefinition) return false; @@ -440,9 +440,9 @@ bool SimplifyCSharp1CascadingIfStatements(InstructionCollection i break; if (!left.MatchLdLoc(switchValueVar)) break; - if (!right.MatchLdStr(out string value)) + if (!right.MatchLdStr(out string? value)) break; - if (!(caseBlockJump.MatchBranch(out var caseBlock) || caseBlockJump.MatchLeave((BlockContainer)currentCaseBlock.Parent))) + if (!(caseBlockJump.MatchBranch(out var caseBlock) || caseBlockJump.MatchLeave((BlockContainer?)currentCaseBlock.Parent))) break; if (!currentCaseBlock.Instructions[conditionOffset + 1].MatchBranch(out currentCaseBlock)) break; @@ -705,7 +705,7 @@ bool MatchLegacySwitchOnStringWithDict(InstructionCollection inst return true; } - bool FixCasesWithoutValue(List sections, List<(string, int)> stringValues) + bool FixCasesWithoutValue(List sections, List<(string?, int)> stringValues) { bool HasLabel(SwitchSection section) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs index 9600958753..3a7e3f1e8c 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformExpressionTrees.cs @@ -398,7 +398,7 @@ ILFunction ApplyChangesToILFunction() { if (function.Kind == ILFunctionKind.ExpressionTree) { - function.DelegateType = UnwrapExpressionTree(function.DelegateType); + function.DelegateType = UnwrapExpressionTree(function.DelegateType!); function.Kind = ILFunctionKind.Delegate; } return function; @@ -536,7 +536,7 @@ IType UnwrapExpressionTree(IType delegateType) } } - (Func, IType) ConvertBind(CallInstruction invocation) + (Func?, IType) ConvertBind(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); From 0430c3b519e9c45f15dad85f7b98dd5c695f52f1 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 17:55:29 -0400 Subject: [PATCH 13/15] focus on CS8625, convert to error --- .editorconfig | 32 +++++++++---------- ICSharpCode.BamlDecompiler/BamlElement.cs | 10 +++--- .../Blocks/ConstructorParametersHandler.cs | 2 +- .../Handlers/Blocks/DocumentHandler.cs | 2 +- .../Handlers/Blocks/ElementHandler.cs | 2 +- .../Handlers/Blocks/KeyElementStartHandler.cs | 2 +- .../Handlers/Blocks/PropertyArrayHandler.cs | 2 +- .../Handlers/Blocks/PropertyComplexHandler.cs | 2 +- .../Blocks/PropertyDictionaryHandler.cs | 2 +- .../Handlers/Blocks/PropertyListHandler.cs | 2 +- .../Handlers/Records/AssemblyInfoHandler.cs | 2 +- .../Handlers/Records/AttributeInfoHandler.cs | 2 +- .../Handlers/Records/ConnectionIdHandler.cs | 2 +- .../ConstructorParameterTypeHandler.cs | 2 +- .../Records/ContentPropertyHandler.cs | 2 +- .../Handlers/Records/DefAttributeHandler.cs | 2 +- .../Records/DefAttributeKeyStringHandler.cs | 2 +- .../Records/DefAttributeKeyTypeHandler.cs | 2 +- .../Records/DeferableContentStartHandler.cs | 2 +- .../Records/LineNumberAndPositionHandler.cs | 2 +- .../Handlers/Records/LinePositionHandler.cs | 2 +- .../Handlers/Records/LiteralContentHandler.cs | 2 +- .../Records/OptimizedStaticResourceHandler.cs | 2 +- .../Handlers/Records/PIMappingHandler.cs | 2 +- .../PresentationOptionsAttributeHandler.cs | 2 +- .../Handlers/Records/PropertyCustomHandler.cs | 2 +- .../Handlers/Records/PropertyHandler.cs | 2 +- .../Records/PropertyTypeReferenceHandler.cs | 5 ++- .../Records/PropertyWithExtensionHandler.cs | 2 +- .../PropertyWithStaticResourceIdHandler.cs | 6 ++-- .../Records/StaticResourceIdHandler.cs | 6 ++-- .../Records/StaticResourceStartHandler.cs | 2 +- .../Handlers/Records/TextHandler.cs | 4 +-- .../Handlers/Records/TypeInfoHandler.cs | 4 +-- .../Handlers/Records/XmlnsPropertyHandler.cs | 2 +- ICSharpCode.BamlDecompiler/IHandlers.cs | 2 +- .../Rewrite/ConnectionIdRewritePass.cs | 2 +- .../Xaml/NamespaceMap.cs | 6 ++-- .../Xaml/XamlProperty.cs | 2 +- .../Xaml/XamlResourceKey.cs | 6 ++-- ICSharpCode.BamlDecompiler/Xaml/XamlType.cs | 4 +-- ICSharpCode.BamlDecompiler/XamlContext.cs | 9 +++--- ICSharpCode.BamlDecompiler/XmlnsDictionary.cs | 5 ++- .../GetDecompiledProjectCmdlet.cs | 2 +- .../Semantics/OverloadResolutionTests.cs | 2 +- .../CSharp/OutputVisitor/ITokenWriter.cs | 4 +-- .../InsertMissingTokensDecorator.cs | 2 +- .../InsertRequiredSpacesDecorator.cs | 2 +- .../OutputVisitor/InsertSpecialsDecorator.cs | 4 +-- .../OutputVisitor/TextWriterTokenWriter.cs | 2 +- .../CSharp/Resolver/AwaitResolveResult.cs | 8 ++--- .../CSharp/Resolver/CSharpConversions.cs | 8 ++--- .../CSharp/Resolver/CSharpResolver.cs | 6 ++-- .../CSharp/Resolver/LambdaResolveResult.cs | 4 +-- .../CSharp/Resolver/MemberLookup.cs | 8 ++--- .../Resolver/MethodGroupResolveResult.cs | 6 ++-- .../CSharp/Resolver/OverloadResolution.cs | 8 ++--- .../CSharp/Resolver/TypeInference.cs | 10 +++--- .../CSharp/SequencePointBuilder.cs | 2 +- .../CSharp/Syntax/CSharpTokenNode.cs | 2 +- .../Syntax/Expressions/IndexerExpression.cs | 2 +- .../CSharp/Syntax/PatternMatching/Match.cs | 8 ++--- ICSharpCode.Decompiler/CSharp/Syntax/Role.cs | 6 ++-- .../Transforms/ContextTrackingVisitor.cs | 6 ++-- .../CSharp/Transforms/DeclareVariables.cs | 2 +- .../Transforms/NormalizeBlockStatements.cs | 2 +- .../Transforms/PatternStatementTransform.cs | 2 +- .../CSharp/Transforms/PrettifyAssignments.cs | 2 +- .../ReplaceMethodCallsWithOperators.cs | 2 +- ...ransformFieldAndConstructorInitializers.cs | 4 +-- .../DebugInfo/ImportScopeInfo.cs | 2 +- .../Disassembler/MethodBodyDisassembler.cs | 2 +- .../Disassembler/OpCodeInfo.cs | 2 +- .../Disassembler/ReflectionDisassembler.cs | 10 +++--- .../FlowAnalysis/ControlFlowNode.cs | 8 ++--- .../ReachingDefinitionsVisitor.cs | 2 +- .../IL/ControlFlow/DetectPinnedRegions.cs | 2 +- .../IL/ControlFlow/SwitchAnalysis.cs | 2 +- .../IL/ControlFlow/SwitchDetection.cs | 8 ++--- .../IL/ControlFlow/YieldReturnDecompiler.cs | 14 ++++---- .../IL/Instructions/DeconstructInstruction.cs | 2 +- .../IL/Transforms/DeconstructionTransform.cs | 2 +- .../IL/Transforms/ILInlining.cs | 6 ++-- .../IL/Transforms/LockTransform.cs | 2 +- .../IL/Transforms/NullableLiftingTransform.cs | 2 +- .../IL/Transforms/ReduceNestingTransform.cs | 8 ++--- .../Transforms/TransformArrayInitializers.cs | 2 +- .../IL/Transforms/TransformAssignment.cs | 4 +-- .../Transforms/TransformDisplayClassUsage.cs | 14 ++++---- .../Metadata/LightJson/JsonValue.cs | 18 +++++------ .../Output/TextTokenWriter.cs | 2 +- ICSharpCode.Decompiler/SRMExtensions.cs | 4 +-- .../Semantics/InvocationResolveResult.cs | 2 +- .../TypeSystem/ApplyAttributeTypeVisitor.cs | 8 ++--- .../TypeSystem/FullTypeName.cs | 2 +- .../Implementation/GetMembersHelper.cs | 6 ++-- .../Implementation/MetadataNamespace.cs | 2 +- .../TypeSystem/Implementation/UnknownType.cs | 2 +- .../TypeSystem/TupleType.cs | 14 ++++---- .../Util/ResXResourceWriter.cs | 14 ++++---- ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs | 2 +- ILSpy.ReadyToRun/ReadyToRunDisassembler.cs | 16 +++++----- ILSpy.ReadyToRun/ReadyToRunLanguage.cs | 8 ++--- ILSpy.ReadyToRun/ReadyToRunOptions.cs | 18 +++++------ ILSpy/Commands/ShowCFGContextMenuEntry.cs | 2 +- ILSpy/Controls/SearchBox.cs | 2 +- ILSpy/Controls/TreeView/SharpTreeView.cs | 2 +- .../TreeView/SharpTreeViewTextSearch.cs | 2 +- ILSpy/DecompilationOptions.cs | 2 +- ILSpy/Docking/DockWorkspace.cs | 10 +++--- ILSpy/Docking/PaneCollection.cs | 2 +- ILSpy/Images/Images.cs | 4 +-- ILSpy/LanguageSettings.cs | 6 ++-- .../CSharpHighlightingTokenWriter.cs | 8 ++--- ILSpy/Languages/CSharpILMixedLanguage.cs | 4 +-- ILSpy/MainWindow.xaml.cs | 6 ++-- .../CorTables/ClassLayoutTableTreeNode.cs | 4 +-- .../CorTables/ConstantTableTreeNode.cs | 4 +-- .../CorTables/CustomAttributeTableTreeNode.cs | 8 ++--- .../CorTables/DeclSecurityTableTreeNode.cs | 4 +-- .../CorTables/EventMapTableTreeNode.cs | 8 ++--- .../Metadata/CorTables/EventTableTreeNode.cs | 4 +-- .../CorTables/ExportedTypeTableTreeNode.cs | 4 +-- .../CorTables/FieldLayoutTableTreeNode.cs | 4 +-- .../CorTables/FieldMarshalTableTreeNode.cs | 4 +-- .../CorTables/FieldRVATableTreeNode.cs | 4 +-- .../Metadata/CorTables/FieldTableTreeNode.cs | 4 +-- .../GenericParamConstraintTableTreeNode.cs | 8 ++--- .../CorTables/GenericParamTableTreeNode.cs | 4 +-- .../CorTables/ImplMapTableTreeNode.cs | 8 ++--- .../CorTables/InterfaceImplTableTreeNode.cs | 8 ++--- .../ManifestResourceTableTreeNode.cs | 4 +-- .../CorTables/MemberRefTableTreeNode.cs | 8 ++--- .../CorTables/MethodImplTableTreeNode.cs | 12 +++---- .../CorTables/MethodSemanticsTableTreeNode.cs | 8 ++--- .../CorTables/MethodSpecTableTreeNode.cs | 4 +-- .../Metadata/CorTables/MethodTableTreeNode.cs | 6 ++-- .../CorTables/NestedClassTableTreeNode.cs | 8 ++--- .../CorTables/PropertyMapTableTreeNode.cs | 8 ++--- .../CorTables/PropertyTableTreeNode.cs | 4 +-- ILSpy/Metadata/CorTables/PtrTableTreeNode.cs | 4 +-- .../CorTables/StandAloneSigTableTreeNode.cs | 4 +-- .../CorTables/TypeDefTableTreeNode.cs | 4 +-- .../CorTables/TypeRefTableTreeNode.cs | 4 +-- .../DebugTables/LocalScopeTableTreeNode.cs | 4 +-- .../StateMachineMethodTableTreeNode.cs | 8 ++--- ILSpy/Metadata/FlagsTooltip.xaml.cs | 10 +++--- ILSpy/Metadata/MetadataTableTreeNode.cs | 2 +- ILSpy/Metadata/MetadataTreeNode.cs | 4 +-- ILSpy/Options/MiscSettingsPanel.xaml.cs | 2 +- ILSpy/TaskHelper.cs | 6 ++-- ILSpy/TextView/BracketHighlightRenderer.cs | 4 +-- ILSpy/TextView/DocumentationUIBuilder.cs | 4 +-- ILSpy/TextView/UIElementGenerator.cs | 4 +-- ILSpy/TreeNodes/AssemblyTreeNode.cs | 6 ++-- ILSpy/TreeNodes/PackageFolderTreeNode.cs | 2 +- ILSpy/TreeNodes/ThreadingSupport.cs | 2 +- .../ManageAssemblyListsViewModel.cs | 6 ++-- 158 files changed, 378 insertions(+), 381 deletions(-) diff --git a/.editorconfig b/.editorconfig index 538d72491f..6c1c8d12e4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -151,9 +151,14 @@ dotnet_diagnostic.MEF006.severity = silent dotnet_diagnostic.IDE2003.severity = silent -#cleared null error types +#nullability diagnostics dotnet_diagnostic.CS8597.severity = error -dotnet_diagnostic.CS8605.severity = error +dotnet_diagnostic.CS8600.severity = warning +dotnet_diagnostic.CS8601.severity = warning +dotnet_diagnostic.CS8602.severity = warning +dotnet_diagnostic.CS8603.severity = warning +dotnet_diagnostic.CS8604.severity = warning +dotnet_diagnostic.CS8605.severity = warning dotnet_diagnostic.CS8606.severity = error dotnet_diagnostic.CS8607.severity = error dotnet_diagnostic.CS8608.severity = error @@ -164,9 +169,16 @@ dotnet_diagnostic.CS8612.severity = error dotnet_diagnostic.CS8613.severity = error dotnet_diagnostic.CS8614.severity = error dotnet_diagnostic.CS8615.severity = error +dotnet_diagnostic.CS8617.severity = warning +dotnet_diagnostic.CS8618.severity = warning +dotnet_diagnostic.CS8619.severity = warning +dotnet_diagnostic.CS8620.severity = warning dotnet_diagnostic.CS8621.severity = error dotnet_diagnostic.CS8622.severity = error dotnet_diagnostic.CS8624.severity = error +dotnet_diagnostic.CS8625.severity = error +dotnet_diagnostic.CS8629.severity = warning +dotnet_diagnostic.CS8631.severity = warning dotnet_diagnostic.CS8633.severity = error dotnet_diagnostic.CS8634.severity = error dotnet_diagnostic.CS8643.severity = error @@ -193,17 +205,5 @@ dotnet_diagnostic.CS8775.severity = error dotnet_diagnostic.CS8777.severity = error #nullable error types still not cleaned up -dotnet_diagnostic.CS8600.severity = warning -dotnet_diagnostic.CS8601.severity = warning -dotnet_diagnostic.CS8602.severity = warning -dotnet_diagnostic.CS8603.severity = warning -dotnet_diagnostic.CS8604.severity = warning -dotnet_diagnostic.CS8605.severity = warning -dotnet_diagnostic.CS8615.severity = warning -dotnet_diagnostic.CS8617.severity = warning -dotnet_diagnostic.CS8618.severity = warning -dotnet_diagnostic.CS8619.severity = warning -dotnet_diagnostic.CS8620.severity = warning -dotnet_diagnostic.CS8625.severity = warning -dotnet_diagnostic.CS8629.severity = warning -dotnet_diagnostic.CS8631.severity = warning + + diff --git a/ICSharpCode.BamlDecompiler/BamlElement.cs b/ICSharpCode.BamlDecompiler/BamlElement.cs index 0e546a4748..7e2553b8cd 100644 --- a/ICSharpCode.BamlDecompiler/BamlElement.cs +++ b/ICSharpCode.BamlDecompiler/BamlElement.cs @@ -41,13 +41,13 @@ internal readonly struct XamlNode String = value; } - public readonly XElement Element; - public readonly string String; + public readonly XElement? Element; + public readonly string? String; public static implicit operator XamlNode(XElement value) => new XamlNode(value); public static implicit operator XamlNode(string value) => new XamlNode(value); - public static implicit operator XElement(XamlNode node) => node.Element; - public static implicit operator string(XamlNode node) => node.String; + public static implicit operator XElement?(XamlNode node) => node.Element; + public static implicit operator string?(XamlNode node) => node.String; } internal class BamlElement @@ -55,7 +55,7 @@ internal class BamlElement public BamlNode Node { get; } public XamlNode Xaml { get; set; } - public BamlElement Parent { get; set; } + public BamlElement? Parent { get; set; } public IList Children { get; } public BamlElement(BamlNode node) diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/ConstructorParametersHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/ConstructorParametersHandler.cs index 844c825286..e204ab042d 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/ConstructorParametersHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/ConstructorParametersHandler.cs @@ -30,7 +30,7 @@ internal class ConstructorParametersStartHandler : IHandler { public BamlRecordType Type => BamlRecordType.ConstructorParametersStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var doc = new BamlElement(node); doc.Xaml = new XElement(ctx.GetPseudoName("Ctor")); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/DocumentHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/DocumentHandler.cs index 8f543271fc..347b61d6fe 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/DocumentHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/DocumentHandler.cs @@ -30,7 +30,7 @@ internal class DocumentHandler : IHandler { public BamlRecordType Type => BamlRecordType.DocumentStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var doc = new BamlElement(node); doc.Xaml = new XElement(ctx.GetPseudoName("Document")); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/ElementHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/ElementHandler.cs index 351fbd3884..49b8c31570 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/ElementHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/ElementHandler.cs @@ -31,7 +31,7 @@ internal class ElementHandler : IHandler { public BamlRecordType Type => BamlRecordType.ElementStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (ElementStartRecord)((BamlBlockNode)node).Header; var doc = new BamlElement(node); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/KeyElementStartHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/KeyElementStartHandler.cs index 366b8d93a5..80acd5df01 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/KeyElementStartHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/KeyElementStartHandler.cs @@ -31,7 +31,7 @@ internal class KeyElementStartHandler : ElementHandler, IHandler, IDeferHandler { BamlRecordType IHandler.Type => BamlRecordType.KeyElementStart; - BamlElement IHandler.Translate(XamlContext ctx, BamlNode node, BamlElement parent) + BamlElement? IHandler.Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { XamlResourceKey.Create(node); return null; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs index c4b20965f5..b92fc9d8f2 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs @@ -30,7 +30,7 @@ internal class PropertyArrayHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyArrayStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyArrayStartRecord)((BamlBlockNode)node).Header; var doc = new BamlElement(node); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyComplexHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyComplexHandler.cs index e20ae0155b..4560e8193b 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyComplexHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyComplexHandler.cs @@ -30,7 +30,7 @@ internal class PropertyComplexHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyComplexStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyComplexStartRecord)((BamlBlockNode)node).Header; var doc = new BamlElement(node); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyDictionaryHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyDictionaryHandler.cs index 15a2626803..0849784753 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyDictionaryHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyDictionaryHandler.cs @@ -30,7 +30,7 @@ internal class PropertyDictionaryHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyDictionaryStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyDictionaryStartRecord)((BamlBlockNode)node).Header; var doc = new BamlElement(node); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyListHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyListHandler.cs index a7041d9cff..2f934399e4 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyListHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyListHandler.cs @@ -30,7 +30,7 @@ internal class PropertyListHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyListStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyListStartRecord)((BamlBlockNode)node).Header; var doc = new BamlElement(node); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/AssemblyInfoHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/AssemblyInfoHandler.cs index 24c0dfe650..9ea3037bf5 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/AssemblyInfoHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/AssemblyInfoHandler.cs @@ -28,6 +28,6 @@ internal class AssemblyInfoHandler : IHandler { public BamlRecordType Type => BamlRecordType.AssemblyInfo; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) => null; + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) => null; } } \ No newline at end of file diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/AttributeInfoHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/AttributeInfoHandler.cs index bcada05719..690833c10d 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/AttributeInfoHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/AttributeInfoHandler.cs @@ -28,6 +28,6 @@ internal class AttributeInfoHandler : IHandler { public BamlRecordType Type => BamlRecordType.AttributeInfo; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) => null; + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) => null; } } \ No newline at end of file diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/ConnectionIdHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/ConnectionIdHandler.cs index a0b9f9bb1e..320f3f1494 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/ConnectionIdHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/ConnectionIdHandler.cs @@ -28,7 +28,7 @@ internal class ConnectionIdHandler : IHandler { public BamlRecordType Type => BamlRecordType.ConnectionId; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (ConnectionIdRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/ConstructorParameterTypeHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/ConstructorParameterTypeHandler.cs index a6ba8047ee..cf0449e2c9 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/ConstructorParameterTypeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/ConstructorParameterTypeHandler.cs @@ -31,7 +31,7 @@ internal class ConstructorParameterTypeHandler : IHandler { public BamlRecordType Type => BamlRecordType.ConstructorParameterType; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (ConstructorParameterTypeRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/ContentPropertyHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/ContentPropertyHandler.cs index 3f95e62dec..7d53382c87 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/ContentPropertyHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/ContentPropertyHandler.cs @@ -28,7 +28,7 @@ internal class ContentPropertyHandler : IHandler { public BamlRecordType Type => BamlRecordType.ContentProperty; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (ContentPropertyRecord)((BamlRecordNode)node).Record; // TODO: What to do here? diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeHandler.cs index f8ac9786e9..01adead25b 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeHandler.cs @@ -30,7 +30,7 @@ internal class DefAttributeHandler : IHandler { public BamlRecordType Type => BamlRecordType.DefAttribute; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (DefAttributeRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyStringHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyStringHandler.cs index c8df693492..2ce607fa0c 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyStringHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyStringHandler.cs @@ -31,7 +31,7 @@ internal class DefAttributeStringHandler : IHandler, IDeferHandler { public BamlRecordType Type => BamlRecordType.DefAttributeKeyString; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { XamlResourceKey.Create(node); return null; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyTypeHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyTypeHandler.cs index 82a2d82a0a..e0689ff56b 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyTypeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyTypeHandler.cs @@ -31,7 +31,7 @@ internal class DefAttributeTypeHandler : IHandler, IDeferHandler { public BamlRecordType Type => BamlRecordType.DefAttributeKeyType; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { XamlResourceKey.Create(node); return null; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/DeferableContentStartHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/DeferableContentStartHandler.cs index 65385bf1c9..1799017135 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DeferableContentStartHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DeferableContentStartHandler.cs @@ -30,7 +30,7 @@ internal class DeferableContentStartHandler : IHandler { public BamlRecordType Type => BamlRecordType.DeferableContentStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (DeferableContentStartRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/LineNumberAndPositionHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/LineNumberAndPositionHandler.cs index 6398b2f3e4..c797738055 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/LineNumberAndPositionHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/LineNumberAndPositionHandler.cs @@ -28,6 +28,6 @@ internal class LineNumberAndPositionHandler : IHandler { public BamlRecordType Type => BamlRecordType.LineNumberAndPosition; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) => null; + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) => null; } } \ No newline at end of file diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/LinePositionHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/LinePositionHandler.cs index feb1c36aa0..16e439df46 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/LinePositionHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/LinePositionHandler.cs @@ -28,6 +28,6 @@ internal class LinePositionHandler : IHandler { public BamlRecordType Type => BamlRecordType.LinePosition; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) => null; + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) => null; } } \ No newline at end of file diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/LiteralContentHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/LiteralContentHandler.cs index f53b3fd5f4..f8b7ef25d9 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/LiteralContentHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/LiteralContentHandler.cs @@ -30,7 +30,7 @@ internal class LiteralContentHandler : IHandler { public BamlRecordType Type => BamlRecordType.LiteralContent; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (LiteralContentRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/OptimizedStaticResourceHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/OptimizedStaticResourceHandler.cs index 520392349f..15976101bb 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/OptimizedStaticResourceHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/OptimizedStaticResourceHandler.cs @@ -31,7 +31,7 @@ internal class OptimizedStaticResourceHandler : IHandler, IDeferHandler { public BamlRecordType Type => BamlRecordType.OptimizedStaticResource; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (OptimizedStaticResourceRecord)((BamlRecordNode)node).Record; var key = XamlResourceKey.FindKeyInSiblings(node); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/PIMappingHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/PIMappingHandler.cs index e32ba8a4ed..f68bf73f42 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PIMappingHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PIMappingHandler.cs @@ -28,6 +28,6 @@ internal class PIMappingHandler : IHandler { public BamlRecordType Type => BamlRecordType.PIMapping; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) => null; + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) => null; } } \ No newline at end of file diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/PresentationOptionsAttributeHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/PresentationOptionsAttributeHandler.cs index f4d13ebdb5..0a584a6141 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PresentationOptionsAttributeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PresentationOptionsAttributeHandler.cs @@ -30,7 +30,7 @@ internal class PresentationOptionsAttributeHandler : IHandler { public BamlRecordType Type => BamlRecordType.PresentationOptionsAttribute; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PresentationOptionsAttributeRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyCustomHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyCustomHandler.cs index c62f2fa4aa..0b01a57603 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyCustomHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyCustomHandler.cs @@ -179,7 +179,7 @@ private bool NeedsFullName(XamlProperty property, XamlContext ctx, XElement elem return property.IsAttachedTo(type); } - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyCustomRecord)((BamlRecordNode)node).Record; var serTypeId = ((short)record.SerializerTypeId & 0xfff); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyHandler.cs index e50002cebb..49e24a617c 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyHandler.cs @@ -31,7 +31,7 @@ internal class PropertyHandler : IHandler { public virtual BamlRecordType Type => BamlRecordType.Property; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyTypeReferenceHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyTypeReferenceHandler.cs index 9405d210d3..5e24ae7c2f 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyTypeReferenceHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyTypeReferenceHandler.cs @@ -22,10 +22,9 @@ THE SOFTWARE. using System.Xml.Linq; -using ICSharpCode.Decompiler.TypeSystem; - using ICSharpCode.BamlDecompiler.Baml; using ICSharpCode.BamlDecompiler.Xaml; +using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.BamlDecompiler.Handlers { @@ -33,7 +32,7 @@ internal class PropertyTypeReferenceHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyTypeReference; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyTypeReferenceRecord)((BamlRecordNode)node).Record; var attr = ctx.ResolveProperty(record.AttributeId); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithExtensionHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithExtensionHandler.cs index 034b6aac6b..5515e05309 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithExtensionHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithExtensionHandler.cs @@ -31,7 +31,7 @@ internal class PropertyWithExtensionHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyWithExtension; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyWithExtensionRecord)((BamlRecordNode)node).Record; var extTypeId = ((short)record.Flags & 0xfff); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs index a701316e97..3a2bbd7566 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs @@ -32,7 +32,7 @@ internal class PropertyWithStaticResourceIdHandler : IHandler { public BamlRecordType Type => BamlRecordType.PropertyWithStaticResourceId; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (PropertyWithStaticResourceIdRecord)((BamlRecordNode)node).Record; var doc = new BamlElement(node); @@ -43,8 +43,8 @@ public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) doc.Xaml.Element.AddAnnotation(elemAttr); parent.Xaml.Element.Add(doc.Xaml.Element); - BamlNode found = node; - XamlResourceKey key; + BamlNode? found = node; + XamlResourceKey? key; do { key = XamlResourceKey.FindKeyInAncestors(found.Parent, out found); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceIdHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceIdHandler.cs index b0f62432c8..f5cbca3192 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceIdHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceIdHandler.cs @@ -27,12 +27,12 @@ class StaticResourceIdHandler : IHandler { public BamlRecordType Type => BamlRecordType.StaticResourceId; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (StaticResourceIdRecord)((BamlRecordNode)node).Record; - BamlNode found = node; - XamlResourceKey key; + BamlNode? found = node; + XamlResourceKey? key; do { key = XamlResourceKey.FindKeyInAncestors(found.Parent, out found); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceStartHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceStartHandler.cs index 37857e14e5..08fd3f7f8d 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceStartHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceStartHandler.cs @@ -29,7 +29,7 @@ class StaticResourceStartHandler : IHandler, IDeferHandler { public BamlRecordType Type => BamlRecordType.StaticResourceStart; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (StaticResourceStartRecord)((BamlBlockNode)node).Record; var key = XamlResourceKey.FindKeyInSiblings(node); diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/TextHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/TextHandler.cs index fc41caf5e1..93ccce0a9e 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/TextHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/TextHandler.cs @@ -28,7 +28,7 @@ internal class TextHandler : IHandler { public BamlRecordType Type => BamlRecordType.Text; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (TextRecord)((BamlRecordNode)node).Record; @@ -42,7 +42,7 @@ internal class TextWithIdHandler : IHandler { public BamlRecordType Type => BamlRecordType.TextWithId; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (TextWithIdRecord)((BamlRecordNode)node).Record; diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/TypeInfoHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/TypeInfoHandler.cs index 583c680d53..2e929ccfa5 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/TypeInfoHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/TypeInfoHandler.cs @@ -28,13 +28,13 @@ internal class TypeInfoHandler : IHandler { public BamlRecordType Type => BamlRecordType.TypeInfo; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) => null; + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) => null; } internal class TypeSerializerInfoHandler : IHandler { public BamlRecordType Type => BamlRecordType.TypeSerializerInfo; - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) => null; + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) => null; } } \ No newline at end of file diff --git a/ICSharpCode.BamlDecompiler/Handlers/Records/XmlnsPropertyHandler.cs b/ICSharpCode.BamlDecompiler/Handlers/Records/XmlnsPropertyHandler.cs index 399dd7d4d2..1c5d5c48dc 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/XmlnsPropertyHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/XmlnsPropertyHandler.cs @@ -52,7 +52,7 @@ IEnumerable ResolveCLRNamespaces(IModule assembly, string ns) } } - public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) + public BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent) { var record = (XmlnsPropertyRecord)((BamlRecordNode)node).Record; foreach (var asmId in record.AssemblyIds) diff --git a/ICSharpCode.BamlDecompiler/IHandlers.cs b/ICSharpCode.BamlDecompiler/IHandlers.cs index c373f0bf26..067a9e1736 100644 --- a/ICSharpCode.BamlDecompiler/IHandlers.cs +++ b/ICSharpCode.BamlDecompiler/IHandlers.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler internal interface IHandler { BamlRecordType Type { get; } - BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent); + BamlElement? Translate(XamlContext ctx, BamlNode node, BamlElement? parent); } internal interface IDeferHandler diff --git a/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs b/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs index 4c7a518fcb..8a22800337 100644 --- a/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs +++ b/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs @@ -250,7 +250,7 @@ FieldAssignment FindField(ILInstruction inst) } } - bool MatchFieldAssignment(ILInstruction inst, [NotNullWhen(true)] out FieldAssignment field) + bool MatchFieldAssignment(ILInstruction inst, [NotNullWhen(true)] out FieldAssignment? field) { field = null; if (!inst.MatchStFld(out _, out var fld, out var value) || !value.MatchCastClass(out var arg, out _) diff --git a/ICSharpCode.BamlDecompiler/Xaml/NamespaceMap.cs b/ICSharpCode.BamlDecompiler/Xaml/NamespaceMap.cs index 6523c2be70..19cc97234d 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/NamespaceMap.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/NamespaceMap.cs @@ -29,17 +29,17 @@ namespace ICSharpCode.BamlDecompiler.Xaml { internal class NamespaceMap { - public string XmlnsPrefix { get; set; } + public string? XmlnsPrefix { get; set; } public string FullAssemblyName { get; set; } public string XMLNamespace { get; set; } - public string CLRNamespace { get; set; } + public string? CLRNamespace { get; set; } public NamespaceMap(string prefix, string fullAssemblyName, string xmlNs) : this(prefix, fullAssemblyName, xmlNs, null) { } - public NamespaceMap(string prefix, string fullAssemblyName, string xmlNs, string clrNs) + public NamespaceMap(string? prefix, string fullAssemblyName, string xmlNs, string? clrNs) { XmlnsPrefix = prefix; FullAssemblyName = fullAssemblyName; diff --git a/ICSharpCode.BamlDecompiler/Xaml/XamlProperty.cs b/ICSharpCode.BamlDecompiler/Xaml/XamlProperty.cs index 6372f2a0cf..097f2f558f 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/XamlProperty.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/XamlProperty.cs @@ -82,7 +82,7 @@ public bool IsAttachedTo(XamlType type) return true; } - public XName ToXName(XamlContext ctx, XElement parent, bool isFullName = true) + public XName ToXName(XamlContext ctx, XElement? parent, bool isFullName = true) { var typeName = DeclaringType.ToXName(ctx); XName name; diff --git a/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs b/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs index 7e642fd05b..ba9cb583f0 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs @@ -78,7 +78,7 @@ internal class XamlResourceKey public BamlElement KeyElement { get; set; } public IList StaticResources { get; } - public static XamlResourceKey FindKeyInSiblings(BamlNode node) + public static XamlResourceKey? FindKeyInSiblings(BamlNode node) { var children = node.Parent.Children; var index = children.IndexOf(node); @@ -90,9 +90,9 @@ public static XamlResourceKey FindKeyInSiblings(BamlNode node) return null; } - public static XamlResourceKey FindKeyInAncestors(BamlNode node) => FindKeyInAncestors(node, out var found); + public static XamlResourceKey? FindKeyInAncestors(BamlNode node) => FindKeyInAncestors(node, out var found); - public static XamlResourceKey FindKeyInAncestors(BamlNode node, out BamlNode found) + public static XamlResourceKey? FindKeyInAncestors(BamlNode node, out BamlNode? found) { BamlNode n = node; do diff --git a/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs b/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs index 709e18c043..ca7dd21340 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs @@ -37,7 +37,7 @@ internal class XamlType public string TypeNamespace { get; } public string TypeName { get; } - public XNamespace Namespace { get; private set; } + public XNamespace? Namespace { get; private set; } public IType ResolvedType { get; set; } public XamlType(IModule assembly, string fullAssemblyName, string ns, string name) @@ -45,7 +45,7 @@ public XamlType(IModule assembly, string fullAssemblyName, string ns, string nam { } - public XamlType(IModule assembly, string fullAssemblyName, string ns, string name, XNamespace xmlns) + public XamlType(IModule assembly, string fullAssemblyName, string ns, string name, XNamespace? xmlns) { Assembly = assembly; FullAssemblyName = fullAssemblyName; diff --git a/ICSharpCode.BamlDecompiler/XamlContext.cs b/ICSharpCode.BamlDecompiler/XamlContext.cs index 4558b13b3a..a0f56f96a6 100644 --- a/ICSharpCode.BamlDecompiler/XamlContext.cs +++ b/ICSharpCode.BamlDecompiler/XamlContext.cs @@ -27,10 +27,9 @@ THE SOFTWARE. using System.Threading; using System.Xml.Linq; -using ICSharpCode.Decompiler.TypeSystem; - using ICSharpCode.BamlDecompiler.Baml; using ICSharpCode.BamlDecompiler.Xaml; +using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.BamlDecompiler { @@ -207,8 +206,8 @@ public string TryGetXmlNamespace(IModule assembly, string typeNamespace) continue; var xmlNs = attr.FixedArguments[0].Value as string; var typeNs = attr.FixedArguments[1].Value as string; - Debug.Assert((object)xmlNs != null && (object)typeNs != null); - if ((object)xmlNs == null || (object)typeNs == null) + Debug.Assert((object?)xmlNs != null && (object?)typeNs != null); + if ((object?)xmlNs == null || (object?)typeNs == null) continue; if (typeNamespace == typeNs) @@ -221,7 +220,7 @@ public string TryGetXmlNamespace(IModule assembly, string typeNamespace) return possibleXmlNs.FirstOrDefault(); } - public XName GetKnownNamespace(string name, string xmlNamespace, XElement context = null) + public XName GetKnownNamespace(string name, string xmlNamespace, XElement? context = null) { var xNs = GetXmlNamespace(xmlNamespace); XName xName; diff --git a/ICSharpCode.BamlDecompiler/XmlnsDictionary.cs b/ICSharpCode.BamlDecompiler/XmlnsDictionary.cs index 74f7f7f0db..ba4c1be60b 100644 --- a/ICSharpCode.BamlDecompiler/XmlnsDictionary.cs +++ b/ICSharpCode.BamlDecompiler/XmlnsDictionary.cs @@ -22,11 +22,10 @@ THE SOFTWARE. using System.Collections.Generic; +using ICSharpCode.BamlDecompiler.Xaml; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; -using ICSharpCode.BamlDecompiler.Xaml; - namespace ICSharpCode.BamlDecompiler { internal class XmlnsScope : List @@ -58,7 +57,7 @@ internal class XmlnsDictionary public XmlnsDictionary() => CurrentScope = null; - public XmlnsScope CurrentScope { get; set; } + public XmlnsScope? CurrentScope { get; set; } public void PushScope(BamlElement element) => CurrentScope = new XmlnsScope(CurrentScope, element); diff --git a/ICSharpCode.Decompiler.PowerShell/GetDecompiledProjectCmdlet.cs b/ICSharpCode.Decompiler.PowerShell/GetDecompiledProjectCmdlet.cs index e94175e80a..7f395e166b 100644 --- a/ICSharpCode.Decompiler.PowerShell/GetDecompiledProjectCmdlet.cs +++ b/ICSharpCode.Decompiler.PowerShell/GetDecompiledProjectCmdlet.cs @@ -25,7 +25,7 @@ public class GetDecompiledProjectCmdlet : PSCmdlet, IProgress /// Writes a primitive/literal value /// - public abstract void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None); + public abstract void WritePrimitiveValue(object? value, LiteralFormat format = LiteralFormat.None); public abstract void WritePrimitiveType(string type); @@ -129,7 +129,7 @@ public override void WriteToken(Role role, string token) decoratedWriter.WriteToken(role, token); } - public override void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None) + public override void WritePrimitiveValue(object? value, LiteralFormat format = LiteralFormat.None) { decoratedWriter.WritePrimitiveValue(value, format); } diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs index d115f75727..55c49cb69a 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs @@ -138,7 +138,7 @@ public override void WriteIdentifier(Identifier identifier) base.WriteIdentifier(identifier); } - public override void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None) + public override void WritePrimitiveValue(object? value, LiteralFormat format = LiteralFormat.None) { Expression? node = nodes.Peek().LastOrDefault() as Expression; var startLocation = locationProvider.Location; diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs index 6da12dd60e..70b90901b0 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs @@ -148,7 +148,7 @@ public override void WritePreProcessorDirective(PreProcessorDirectiveType type, lastWritten = LastWritten.Whitespace; } - public override void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None) + public override void WritePrimitiveValue(object? value, LiteralFormat format = LiteralFormat.None) { if (lastWritten == LastWritten.KeywordOrIdentifier) { diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs index b4d0051434..de9850ec8a 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs @@ -82,7 +82,7 @@ public override void NewLine() /// /// Writes all specials from start to end (exclusive). Does not touch the positionStack. /// - void WriteSpecials(AstNode start, AstNode end) + void WriteSpecials(AstNode start, AstNode? end) { for (AstNode? pos = start; pos != end; pos = pos.NextSibling) { @@ -118,7 +118,7 @@ void WriteSpecialsUpToRole(Role role) WriteSpecialsUpToRole(role, null); } - void WriteSpecialsUpToRole(Role role, AstNode nextNode) + void WriteSpecialsUpToRole(Role role, AstNode? nextNode) { if (positionStack.Count == 0) { diff --git a/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs index 1862be0801..4c2bbf8a61 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs @@ -233,7 +233,7 @@ public static string PrintPrimitiveValue(object value) return writer.ToString(); } - public override void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None) + public override void WritePrimitiveValue(object? value, LiteralFormat format = LiteralFormat.None) { if (value == null) { diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs index 71ea5810cb..156fa14f35 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs @@ -42,20 +42,20 @@ public class AwaitResolveResult : ResolveResult /// /// Property representing the IsCompleted property on the awaiter type. Can be null if the awaiter type or the property was not found, or when awaiting a dynamic expression. /// - public readonly IProperty IsCompletedProperty; + public readonly IProperty? IsCompletedProperty; /// /// Method representing the OnCompleted method on the awaiter type. Can be null if the awaiter type or the method was not found, or when awaiting a dynamic expression. /// This can also refer to an UnsafeOnCompleted method, if the awaiter type implements System.Runtime.CompilerServices.ICriticalNotifyCompletion. /// - public readonly IMethod OnCompletedMethod; + public readonly IMethod? OnCompletedMethod; /// /// Method representing the GetResult method on the awaiter type. Can be null if the awaiter type or the method was not found, or when awaiting a dynamic expression. /// - public readonly IMethod GetResultMethod; + public readonly IMethod? GetResultMethod; - public AwaitResolveResult(IType resultType, ResolveResult getAwaiterInvocation, IType awaiterType, IProperty isCompletedProperty, IMethod onCompletedMethod, IMethod getResultMethod) + public AwaitResolveResult(IType resultType, ResolveResult getAwaiterInvocation, IType awaiterType, IProperty? isCompletedProperty, IMethod? onCompletedMethod, IMethod? getResultMethod) : base(resultType) { if (awaiterType == null) diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs index 9cfe6918de..af1612277b 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs @@ -792,7 +792,7 @@ bool UnboxingConversion(IType fromType, IType toType) #endregion #region Implicit Constant-Expression Conversion - bool ImplicitConstantExpressionConversion(ResolveResult rr, IType toType) + bool ImplicitConstantExpressionConversion(ResolveResult? rr, IType toType) { if (rr == null || !rr.IsCompileTimeConstant) return false; @@ -983,7 +983,7 @@ Conversion SelectOperator(IType mostSpecificSource, IType mostSpecificTarget, IL return Conversion.UserDefinedConversion(selected[0].Method, isLifted: selected[0].IsLifted, isImplicit: isImplicit, isAmbiguous: true, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target)); } - Conversion UserDefinedImplicitConversion(ResolveResult fromResult, IType fromType, IType toType) + Conversion UserDefinedImplicitConversion(ResolveResult? fromResult, IType fromType, IType toType) { // C# 4.0 spec §6.4.4 User-defined implicit conversions var operators = GetApplicableConversionOperators(fromResult, fromType, toType, false); @@ -1025,7 +1025,7 @@ Conversion UserDefinedImplicitConversion(ResolveResult fromResult, IType fromTyp } } - Conversion UserDefinedExplicitConversion(ResolveResult fromResult, IType fromType, IType toType) + Conversion UserDefinedExplicitConversion(ResolveResult? fromResult, IType fromType, IType toType) { // C# 4.0 spec §6.4.5 User-defined explicit conversions var operators = GetApplicableConversionOperators(fromResult, fromType, toType, true); @@ -1112,7 +1112,7 @@ static IType UnderlyingTypeForConversion(IType type) return NullableType.GetUnderlyingType(type); } - List GetApplicableConversionOperators(ResolveResult fromResult, IType fromType, IType toType, bool isExplicit) + List GetApplicableConversionOperators(ResolveResult? fromResult, IType fromType, IType toType, bool isExplicit) { // Find the candidate operators: Predicate opFilter; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs index 431cbdae06..a7197e22d0 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs @@ -1712,7 +1712,7 @@ public bool IsVariableReferenceWithSameType(ResolveResult rr, string identifier, return null; } - ResolveResult? LookInUsingScopeNamespace(ResolvedUsingScope usingScope, INamespace n, string identifier, IReadOnlyList typeArguments, bool parameterizeResultType) + ResolveResult? LookInUsingScopeNamespace(ResolvedUsingScope? usingScope, INamespace n, string identifier, IReadOnlyList typeArguments, bool parameterizeResultType) { if (n == null) return null; @@ -2222,7 +2222,7 @@ where m.IsExtensionMethod #region ResolveInvocation - IList AddArgumentNamesIfNecessary(ResolveResult[] arguments, string[] argumentNames) + IList AddArgumentNamesIfNecessary(ResolveResult[] arguments, string[]? argumentNames) { if (argumentNames == null) { @@ -2239,7 +2239,7 @@ IList AddArgumentNamesIfNecessary(ResolveResult[] arguments, stri } } - private ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[] argumentNames, bool allowOptionalParameters) + private ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[]? argumentNames, bool allowOptionalParameters) { // C# 4.0 spec: §7.6.5 diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs index 7006952714..ca362f0859 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs @@ -65,7 +65,7 @@ protected LambdaResolveResult() : base(SpecialType.NoType) /// This method determines the return type inferred from the lambda body, which is used as part of C# type inference. /// Use the property to retrieve the actual return type as determined by the target delegate type. /// - public abstract IType GetInferredReturnType(IType[] parameterTypes); + public abstract IType GetInferredReturnType(IType[]? parameterTypes); /// /// Gets the list of parameters. @@ -138,7 +138,7 @@ public DecompiledLambdaResolveResult(IL.ILFunction function, public override ResolveResult Body { get; } - public override IType GetInferredReturnType(IType[] parameterTypes) + public override IType GetInferredReturnType(IType[]? parameterTypes) { // We don't know how to compute which type would be inferred if // given other parameter types. diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs index b0a8f4ee83..6f85d18208 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs @@ -259,18 +259,18 @@ sealed class LookupGroup public readonly IType DeclaringType; // When a nested type is hidden, it is simply removed from the list. - public List NestedTypes; + public List? NestedTypes; // When members are hidden, they are merely marked as hidden. // We still need to store the hidden methods so that the 'override' processing can // find them, so that it won't introduce the override as a new method. - public readonly List Methods; + public readonly List? Methods; public bool MethodsAreHidden; - public IMember NonMethod; + public IMember? NonMethod; public bool NonMethodIsHidden; - public LookupGroup(IType declaringType, List nestedTypes, List methods, IMember nonMethod) + public LookupGroup(IType declaringType, List? nestedTypes, List? methods, IMember? nonMethod) { this.DeclaringType = declaringType; this.NestedTypes = nestedTypes; diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs index 6c5542c94d..05d1363192 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs @@ -83,7 +83,7 @@ public class MethodGroupResolveResult : ResolveResult readonly string methodName; public MethodGroupResolveResult(ResolveResult? targetResult, string methodName, - IReadOnlyList methods, IReadOnlyList typeArguments) + IReadOnlyList methods, IReadOnlyList? typeArguments) : base(SpecialType.NoType) { if (methods == null) @@ -143,10 +143,10 @@ public IReadOnlyList TypeArguments { /// List of extension methods, used to avoid re-calculating it in ResolveInvocation() when it was already /// calculated by ResolveMemberAccess(). /// - internal List> extensionMethods; + internal List>? extensionMethods; // the resolver is used to fetch extension methods on demand - internal CSharpResolver resolver; + internal CSharpResolver? resolver; /// /// Gets all candidate extension methods. diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs index 311b66b671..d0f6231525 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs @@ -130,7 +130,7 @@ public void AddError(OverloadResolutionErrors newError) readonly CSharpConversions conversions; //List candidates = new List(); Candidate bestCandidate; - Candidate bestCandidateAmbiguousWith; + Candidate? bestCandidateAmbiguousWith; IType[] explicitlyGivenTypeArguments; bool bestCandidateWasValidated; OverloadResolutionErrors bestCandidateValidationResult; @@ -994,7 +994,7 @@ public IList GetArgumentsWithConversionsAndNames() return GetArgumentsWithConversions(null, GetBestCandidateWithSubstitutedTypeArguments()); } - IList GetArgumentsWithConversions(ResolveResult targetResolveResult, IParameterizedMember bestCandidateForNamedArguments) + IList GetArgumentsWithConversions(ResolveResult? targetResolveResult, IParameterizedMember? bestCandidateForNamedArguments) { var conversions = this.ArgumentConversions; ResolveResult[] args = new ResolveResult[arguments.Length]; @@ -1072,9 +1072,9 @@ TypeParameterSubstitution GetSubstitution(Candidate candidate) /// /// If not null, use this instead of the ReturnType of the member as the type of the created resolve result. /// - public CSharpInvocationResolveResult CreateResolveResult(ResolveResult targetResolveResult, IList? initializerStatements = null, IType? returnTypeOverride = null) + public CSharpInvocationResolveResult CreateResolveResult(ResolveResult? targetResolveResult, IList? initializerStatements = null, IType? returnTypeOverride = null) { - IParameterizedMember member = GetBestCandidateWithSubstitutedTypeArguments(); + IParameterizedMember? member = GetBestCandidateWithSubstitutedTypeArguments(); if (member == null) throw new InvalidOperationException(); diff --git a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs index 3942c2d1e4..bfd664dd3f 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs @@ -94,11 +94,11 @@ TypeInference CreateNestedInstance() } #endregion - TP[] typeParameters; - IType[] parameterTypes; - ResolveResult[] arguments; - bool[,] dependencyMatrix; - IReadOnlyList classTypeArguments; + TP[]? typeParameters; + IType[]? parameterTypes; + ResolveResult[]? arguments; + bool[,]? dependencyMatrix; + IReadOnlyList? classTypeArguments; #region InferTypeArguments (main function) /// diff --git a/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs b/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs index 61186bb496..707b4f7150 100644 --- a/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs @@ -76,7 +76,7 @@ struct StatePerSequencePoint /// /// The function containing this sequence point. /// - internal ILFunction Function; + internal ILFunction? Function; public StatePerSequencePoint(AstNode primaryNode) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs index 114ae9cb0c..4a8eb2fc93 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs @@ -100,7 +100,7 @@ public override TextLocation EndLocation { } } - public CSharpTokenNode(TextLocation location, TokenRole role) + public CSharpTokenNode(TextLocation location, TokenRole? role) { this.startLocation = location; if (role != null) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs index 43c5311d8a..26f95c3061 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs @@ -54,7 +54,7 @@ public IndexerExpression() { } - public IndexerExpression(Expression target, IEnumerable? arguments) + public IndexerExpression(Expression? target, IEnumerable? arguments) { AddChild(target, Roles.TargetExpression); if (arguments != null) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs index 70a4dbc973..3c08979cc9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs @@ -27,7 +27,7 @@ public struct Match { // TODO: maybe we should add an implicit Match->bool conversion? (implicit operator bool(Match m) { return m != null; }) - List> results; + List>? results; public bool Success { get { return results != null; } @@ -36,7 +36,7 @@ public bool Success { internal static Match CreateNew() { Match m; - m.results = new List>(); + m.results = new List>(); return m; } @@ -88,7 +88,7 @@ public void Add(string groupName, INode node) { if (groupName != null && node != null) { - results.Add(new KeyValuePair(groupName, node)); + results.Add(new KeyValuePair(groupName, node)); } } @@ -96,7 +96,7 @@ internal void AddNull(string groupName) { if (groupName != null) { - results.Add(new KeyValuePair(groupName, null)); + results.Add(new KeyValuePair(groupName, null)); } } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/Role.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Role.cs index 2411a26524..4c755579a3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Role.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Role.cs @@ -69,7 +69,7 @@ public static Role GetByIndex(uint index) public class Role : Role where T : class? { readonly string name; // helps with debugging the AST - readonly T nullObject; + readonly T? nullObject; /// /// Gets the null object used when there's no node with this role. @@ -79,7 +79,7 @@ public class Role : Role where T : class? /// Roles used for non-collections should always have a null object, so that no AST property returns null. /// However, if a role used for collections only, it may leave out the null object. /// - public T NullObject { + public T? NullObject { get { return nullObject; } } @@ -97,7 +97,7 @@ public Role(string name) this.nullObject = null!; } - public Role(string name, T nullObject) + public Role(string name, T? nullObject) { this.name = name ?? throw new ArgumentNullException(nameof(name)); this.nullObject = nullObject; diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs b/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs index 5f60b62f78..3346c39148 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs @@ -28,8 +28,8 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms /// public abstract class ContextTrackingVisitor : DepthFirstAstVisitor { - protected ITypeDefinition currentTypeDefinition; - protected IMethod currentMethod; + protected ITypeDefinition? currentTypeDefinition; + protected IMethod? currentMethod; protected void Initialize(TransformContext context) { @@ -45,7 +45,7 @@ protected void Uninitialize() public override TResult VisitTypeDeclaration(TypeDeclaration typeDeclaration) { - ITypeDefinition oldType = currentTypeDefinition; + ITypeDefinition? oldType = currentTypeDefinition; try { currentTypeDefinition = typeDeclaration.GetSymbol() as ITypeDefinition; diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs index b36e180a58..30fbeae6c0 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs @@ -139,7 +139,7 @@ public VariableToDeclare(ILVariable variable, InsertionPoint insertionPoint, Ide } readonly Dictionary variableDict = new Dictionary(); - TransformContext context; + TransformContext? context; public void Run(AstNode rootNode, TransformContext context) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/NormalizeBlockStatements.cs b/ICSharpCode.Decompiler/CSharp/Transforms/NormalizeBlockStatements.cs index 80d177a12e..8371d06016 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/NormalizeBlockStatements.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/NormalizeBlockStatements.cs @@ -12,7 +12,7 @@ class NormalizeBlockStatements : DepthFirstAstVisitor, IAstTransform { TransformContext context; bool hasNamespace; - NamespaceDeclaration singleNamespaceDeclaration; + NamespaceDeclaration? singleNamespaceDeclaration; public override void VisitSyntaxTree(SyntaxTree syntaxTree) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs index 5424ececc0..72fcb5be97 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/PatternStatementTransform.cs @@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms public sealed class PatternStatementTransform : ContextTrackingVisitor, IAstTransform { readonly DeclareVariables declareVariables = new DeclareVariables(); - TransformContext context; + TransformContext? context; public void Run(AstNode rootNode, TransformContext context) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs index ff1ed9e3ee..649407a0e8 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs @@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms /// class PrettifyAssignments : DepthFirstAstVisitor, IAstTransform { - TransformContext context; + TransformContext? context; public override void VisitAssignmentExpression(AssignmentExpression assignment) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs b/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs index c1181a5621..028acf8d03 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs @@ -41,7 +41,7 @@ public class ReplaceMethodCallsWithOperators : DepthFirstAstVisitor, IAstTransfo MemberName = "TypeHandle" }; - TransformContext context; + TransformContext? context; public override void VisitInvocationExpression(InvocationExpression invocationExpression) { diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs index 96bafdb26c..326551ddfb 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/TransformFieldAndConstructorInitializers.cs @@ -37,8 +37,8 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms /// public class TransformFieldAndConstructorInitializers : DepthFirstAstVisitor, IAstTransform { - TransformContext context; - Dictionary fieldToVariableMap; + TransformContext? context; + Dictionary? fieldToVariableMap; public void Run(AstNode node, TransformContext context) { diff --git a/ICSharpCode.Decompiler/DebugInfo/ImportScopeInfo.cs b/ICSharpCode.Decompiler/DebugInfo/ImportScopeInfo.cs index c6625350df..cd10e158c4 100644 --- a/ICSharpCode.Decompiler/DebugInfo/ImportScopeInfo.cs +++ b/ICSharpCode.Decompiler/DebugInfo/ImportScopeInfo.cs @@ -23,7 +23,7 @@ namespace ICSharpCode.Decompiler.DebugInfo { class ImportScopeInfo { - public readonly ImportScopeInfo Parent; + public readonly ImportScopeInfo? Parent; public ImportScopeHandle Handle; public readonly HashSet Imports = new HashSet(); diff --git a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs index fbbd5e6dd2..e89afa56a4 100644 --- a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs @@ -68,7 +68,7 @@ public class MethodBodyDisassembler /// public IDebugInfoProvider DebugInfo { get; set; } - IList sequencePoints; + IList? sequencePoints; int nextSequencePointIndex; // cache info diff --git a/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs b/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs index a1748d7808..8c2228f377 100644 --- a/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs +++ b/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs @@ -31,7 +31,7 @@ public struct OpCodeInfo : IEquatable public readonly ILOpCode Code; public readonly string Name; - string encodedName; + string? encodedName; public OpCodeInfo(ILOpCode code, string name) { diff --git a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs index 9bec3d1268..7d083b4067 100644 --- a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs @@ -1912,16 +1912,16 @@ void WriteEnum(T enumValue, EnumNameCollection enumNames) where T : struct } - sealed class EnumNameCollection : IEnumerable> where T : struct + sealed class EnumNameCollection : IEnumerable> where T : struct { - List> names = new List>(); + List> names = new List>(); - public void Add(T flag, string name) + public void Add(T flag, string? name) { - this.names.Add(new KeyValuePair(Convert.ToInt64(flag), name)); + this.names.Add(new KeyValuePair(Convert.ToInt64(flag), name)); } - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { return names.GetEnumerator(); } diff --git a/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs b/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs index 713fd360f0..4dd360de53 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs @@ -38,7 +38,7 @@ public class ControlFlowNode /// /// User data. /// - public object UserData; + public object? UserData; /// /// Visited flag, used in various algorithms. @@ -62,13 +62,13 @@ public bool IsReachable { /// Gets the immediate dominator (the parent in the dominator tree). /// Null if dominance has not been calculated; or if the node is unreachable. /// - public ControlFlowNode ImmediateDominator { get; internal set; } + public ControlFlowNode? ImmediateDominator { get; internal set; } /// /// List of children in the dominator tree. /// Null if dominance has not been calculated; or if the node is unreachable. /// - public List DominatorTreeChildren { get; internal set; } + public List? DominatorTreeChildren { get; internal set; } /// /// List of incoming control flow edges. @@ -120,7 +120,7 @@ bool Visit(ControlFlowNode node) public bool Dominates(ControlFlowNode node) { // TODO: this can be made O(1) by numbering the dominator tree - ControlFlowNode tmp = node; + ControlFlowNode? tmp = node; while (tmp != null) { if (tmp == this) diff --git a/ICSharpCode.Decompiler/FlowAnalysis/ReachingDefinitionsVisitor.cs b/ICSharpCode.Decompiler/FlowAnalysis/ReachingDefinitionsVisitor.cs index 0f57fab078..1aba19e7a0 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/ReachingDefinitionsVisitor.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/ReachingDefinitionsVisitor.cs @@ -331,7 +331,7 @@ static List[] FindAllStoresByVariable(ILFunction scope, BitSet ac for (int vi = 0; vi < storesByVar.Length; vi++) { if (activeVariables[vi]) - storesByVar[vi] = new List { null }; + storesByVar[vi] = new List { null }; } foreach (var inst in scope.Descendants) { diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs index a20a515fa9..defe7bd6fc 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs @@ -57,7 +57,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// public class DetectPinnedRegions : IILTransform { - ILTransformContext context; + ILTransformContext? context; public void Run(ILFunction function, ILTransformContext context) { diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs index 42c0f668df..d319b975b2 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs @@ -24,7 +24,7 @@ class SwitchAnalysis /// The variable that is used to represent the switch expression. /// null while analyzing the first block. /// - ILVariable switchVar; + ILVariable? switchVar; /// /// The variable to be used as the argument of the switch instruction. diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs index 2f00105162..e973c5b4d1 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs @@ -38,10 +38,10 @@ public class SwitchDetection : IILTransform { private readonly SwitchAnalysis analysis = new SwitchAnalysis(); - private ILTransformContext context; - private BlockContainer currentContainer; - private ControlFlowGraph controlFlowGraph; - private LoopContext loopContext; + private ILTransformContext? context; + private BlockContainer? currentContainer; + private ControlFlowGraph? controlFlowGraph; + private LoopContext? loopContext; /// /// When detecting a switch, it is important to distinguish Branch instructions which will diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs index a018bfe283..f243084440 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs @@ -73,15 +73,15 @@ public class YieldReturnDecompiler : IILTransform /// The field in the compiler-generated class holding the current state of the state machine /// Set in AnalyzeCtor() for MS, MatchEnumeratorCreationPattern() or AnalyzeMoveNext() for Mono - IField stateField; + IField? stateField; /// The backing field of the 'Current' property in the compiler-generated class /// Set in AnalyzeCurrentProperty() - IField currentField; + IField? currentField; /// The disposing field of the compiler-generated enumerator class. /// Set in ConstructExceptionTable() for assembly compiled with Mono - IField disposingField; + IField? disposingField; /// Maps the fields of the compiler-generated class to the original parameters. /// Set in MatchEnumeratorCreationPattern() and ResolveIEnumerableIEnumeratorFieldMapping() @@ -90,7 +90,7 @@ public class YieldReturnDecompiler : IILTransform /// This dictionary stores the information extracted from the Dispose() method: /// for each "Finally Method", it stores the set of states for which the method is being called. /// Set in ConstructExceptionTable() - Dictionary finallyMethodToStateRange; + Dictionary? finallyMethodToStateRange; /// /// For each finally method, stores the target state when entering the finally block, @@ -106,17 +106,17 @@ public class YieldReturnDecompiler : IILTransform /// /// Local bool variable in MoveNext() that signifies whether to skip finally bodies. /// - ILVariable skipFinallyBodies; + ILVariable? skipFinallyBodies; /// /// Local bool variable in MoveNext() that signifies whether to execute finally bodies. /// - ILVariable doFinallyBodies; + ILVariable? doFinallyBodies; /// /// Set of variables might hold copies of the generated state field. /// - HashSet cachedStateVars; + HashSet? cachedStateVars; #region Run() method public void Run(ILFunction function, ILTransformContext context) diff --git a/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs b/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs index 055b91bc6f..28fb6e3949 100644 --- a/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs +++ b/ICSharpCode.Decompiler/IL/Instructions/DeconstructInstruction.cs @@ -211,7 +211,7 @@ internal static bool IsConversionStLoc(ILInstruction inst, [NotNullWhen(true)] o return input.MatchLdLoc(out inputVariable) || input.MatchLdLoca(out inputVariable); } - internal static bool IsAssignment(ILInstruction inst, ICompilation typeSystem, [NotNullWhen(true)] out IType? expectedType, [NotNullWhen(true)] out ILInstruction? value) + internal static bool IsAssignment(ILInstruction inst, ICompilation? typeSystem, [NotNullWhen(true)] out IType? expectedType, [NotNullWhen(true)] out ILInstruction? value) { expectedType = null; value = null; diff --git a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs index 78181b4a7a..9e7836ed8b 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// class DeconstructionTransform : IStatementTransform { - StatementTransformContext context; + StatementTransformContext? context; readonly Dictionary deconstructionResultsLookup = new Dictionary(); ILVariable[]? deconstructionResults; ILVariable? tupleVariable; diff --git a/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs b/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs index bc4ccdf3bc..bfcc4afec7 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs @@ -741,10 +741,10 @@ internal enum FindResultType internal readonly struct FindResult { public readonly FindResultType Type; - public readonly ILInstruction LoadInst; // ldloc or ldloca instruction that loads the variable to be inlined - public readonly ILInstruction CallArgument; // argument of call that needs to be promoted to a named argument + public readonly ILInstruction? LoadInst; // ldloc or ldloca instruction that loads the variable to be inlined + public readonly ILInstruction? CallArgument; // argument of call that needs to be promoted to a named argument - private FindResult(FindResultType type, ILInstruction loadInst, ILInstruction callArg) + private FindResult(FindResultType type, ILInstruction? loadInst, ILInstruction? callArg) { this.Type = type; this.LoadInst = loadInst; diff --git a/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs index 2d3d54ac50..07a691282e 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/LockTransform.cs @@ -294,7 +294,7 @@ bool TransformLockRoslyn(Block block, int i) return true; } - bool MatchExitBlock(Block entryPoint, ILVariable flag, ILVariable obj) + bool MatchExitBlock(Block entryPoint, ILVariable? flag, ILVariable obj) { if (entryPoint.Instructions.Count != 2 || entryPoint.IncomingEdgeCount != 1) return false; diff --git a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs index d721e08c99..bf4d456915 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/NullableLiftingTransform.cs @@ -42,7 +42,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms struct NullableLiftingTransform { readonly ILTransformContext context; - List nullableVars; + List? nullableVars; public NullableLiftingTransform(ILTransformContext context) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs index d0a88b74c0..b870bc10df 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs @@ -54,7 +54,7 @@ public void Run(ILFunction function, ILTransformContext context) } } - private void Visit(BlockContainer container, Block continueTarget) + private void Visit(BlockContainer container, Block? continueTarget) { switch (container.Kind) { @@ -84,7 +84,7 @@ private void Visit(BlockContainer container, Block continueTarget) /// /// Marks the target block of continue statements. /// The instruction following the end point of the block. Can only be null if the end point is unreachable. - private void Visit(Block block, Block continueTarget, ILInstruction? nextInstruction = null) + private void Visit(Block block, Block? continueTarget, ILInstruction? nextInstruction = null) { Debug.Assert(block.HasFlag(InstructionFlags.EndPointUnreachable) || nextInstruction != null); @@ -174,7 +174,7 @@ private void VisitContainers(ILInstruction inst, Block continueTarget) /// For an if statement with an unreachable end point and no else block, /// inverts to match IL order of the first statement of each branch /// - private void ImproveILOrdering(Block block, IfInstruction ifInst, Block continueTarget) + private void ImproveILOrdering(Block block, IfInstruction ifInst, Block? continueTarget) { if (!block.HasFlag(InstructionFlags.EndPointUnreachable) || !ifInst.TrueInst.HasFlag(InstructionFlags.EndPointUnreachable) @@ -368,7 +368,7 @@ private bool ReduceSwitchNesting(Block parentBlock, BlockContainer switchContain /// /// Checks if an exit is a duplicable keyword exit (return; break; continue;) /// - private bool CanDuplicateExit(ILInstruction exit, Block continueTarget, out ILInstruction keywordExit) + private bool CanDuplicateExit(ILInstruction exit, Block? continueTarget, out ILInstruction keywordExit) { keywordExit = exit; if (exit != null && exit.MatchBranch(continueTarget)) diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs index 665d64cd4b..26dd639d62 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformArrayInitializers.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// public class TransformArrayInitializers : IStatementTransform { - StatementTransformContext context; + StatementTransformContext? context; void IStatementTransform.Run(Block block, int pos, StatementTransformContext context) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs index 4dd4c33996..75bbd4671e 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformAssignment.cs @@ -545,7 +545,7 @@ bool TransformInlineAssignmentLocal(Block block, int pos) return true; } - internal static bool IsImplicitTruncation(ILInstruction value, IType type, ICompilation compilation, bool allowNullableValue = false) + internal static bool IsImplicitTruncation(ILInstruction value, IType type, ICompilation? compilation, bool allowNullableValue = false) { return CheckImplicitTruncation(value, type, compilation, allowNullableValue) != ImplicitTruncationResult.ValuePreserved; } @@ -571,7 +571,7 @@ internal enum ImplicitTruncationResult : byte /// Gets whether 'stobj type(..., value)' would evaluate to a different value than 'value' /// due to implicit truncation. /// - internal static ImplicitTruncationResult CheckImplicitTruncation(ILInstruction value, IType type, ICompilation compilation, bool allowNullableValue = false) + internal static ImplicitTruncationResult CheckImplicitTruncation(ILInstruction value, IType type, ICompilation? compilation, bool allowNullableValue = false) { if (!type.IsSmallIntegerType()) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs index 74bdd9c52c..086f27c73e 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs @@ -52,7 +52,7 @@ class VariableToDeclare { private readonly DisplayClass container; private readonly IField field; - private ILVariable declaredVariable; + private ILVariable? declaredVariable; public string Name => field.Name; @@ -70,7 +70,7 @@ public VariableToDeclare(DisplayClass container, IField field, ILVariable? decla Debug.Assert(declaredVariable == null || declaredVariable.StateMachineField == field); } - public void Propagate(ILVariable variable) + public void Propagate(ILVariable? variable) { this.declaredVariable = variable; this.CanPropagate = variable != null; @@ -94,8 +94,8 @@ class DisplayClass public readonly ILVariable Variable; public readonly ITypeDefinition Type; public readonly Dictionary VariablesToDeclare; - public BlockContainer CaptureScope; - public ILInstruction Initializer; + public BlockContainer? CaptureScope; + public ILInstruction? Initializer; public DisplayClass(ILVariable variable, ITypeDefinition type) { @@ -105,8 +105,8 @@ public DisplayClass(ILVariable variable, ITypeDefinition type) } } - ILTransformContext context; - ITypeResolveContext decompilationContext; + ILTransformContext? context; + ITypeResolveContext? decompilationContext; readonly Dictionary displayClasses = new Dictionary(); readonly Dictionary displayClassCopyMap = new Dictionary(); @@ -502,7 +502,7 @@ static ILOpCode DecodeOpCodeSkipNop(ref BlobReader reader) return code; } - VariableToDeclare AddVariable(DisplayClass result, StObj statement, IField field) + VariableToDeclare AddVariable(DisplayClass result, StObj? statement, IField field) { VariableToDeclare variable = new VariableToDeclare(result, field); if (statement != null) diff --git a/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs index ba52d003ea..4fb65c9555 100644 --- a/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs +++ b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs @@ -24,7 +24,7 @@ internal struct JsonValue public static readonly JsonValue Null = new JsonValue(JsonValueType.Null, default(double), null); private readonly JsonValueType type; - private readonly object reference; + private readonly object? reference; private readonly double value; /// @@ -139,7 +139,7 @@ public JsonValue(JsonArray value) /// The internal value reference of the JsonValue. /// This value is used when the Json type is String, JsonObject, or JsonArray. /// - private JsonValue(JsonValueType type, double value, object reference) + private JsonValue(JsonValueType type, double value, object? reference) { this.type = type; this.value = value; @@ -357,7 +357,7 @@ public string? AsString { public JsonObject? AsJsonObject { get { return this.IsJsonObject - ? (JsonObject)this.reference + ? (JsonObject?)this.reference : null; } } @@ -369,7 +369,7 @@ public JsonObject? AsJsonObject { public JsonArray? AsJsonArray { get { return this.IsJsonArray - ? (JsonArray)this.reference + ? (JsonArray?)this.reference : null; } } @@ -382,7 +382,7 @@ public DateTime? AsDateTime { get { DateTime value; - if (this.IsString && DateTime.TryParse((string)this.reference, out value)) + if (this.IsString && DateTime.TryParse((string?)this.reference, out value)) { return value; } @@ -427,7 +427,7 @@ public JsonValue this[string key] { get { if (this.IsJsonObject) { - return ((JsonObject)this.reference)[key]; + return ((JsonObject?)this.reference)[key]; } else { @@ -438,7 +438,7 @@ public JsonValue this[string key] { set { if (this.IsJsonObject) { - ((JsonObject)this.reference)[key] = value; + ((JsonObject?)this.reference)[key] = value; } else { @@ -458,7 +458,7 @@ public JsonValue this[int index] { get { if (this.IsJsonArray) { - return ((JsonArray)this.reference)[index]; + return ((JsonArray?)this.reference)[index]; } else { @@ -469,7 +469,7 @@ public JsonValue this[int index] { set { if (this.IsJsonArray) { - ((JsonArray)this.reference)[index] = value; + ((JsonArray?)this.reference)[index] = value; } else { diff --git a/ICSharpCode.Decompiler/Output/TextTokenWriter.cs b/ICSharpCode.Decompiler/Output/TextTokenWriter.cs index eb0a446af8..fbb14dc560 100644 --- a/ICSharpCode.Decompiler/Output/TextTokenWriter.cs +++ b/ICSharpCode.Decompiler/Output/TextTokenWriter.cs @@ -363,7 +363,7 @@ public override void WritePreProcessorDirective(PreProcessorDirectiveType type, output.WriteLine(); } - public override void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None) + public override void WritePrimitiveValue(object? value, LiteralFormat format = LiteralFormat.None) { new TextWriterTokenWriter(new TextOutputWriter(output)).WritePrimitiveValue(value, format); } diff --git a/ICSharpCode.Decompiler/SRMExtensions.cs b/ICSharpCode.Decompiler/SRMExtensions.cs index 1b4a82aa63..6b12228cbf 100644 --- a/ICSharpCode.Decompiler/SRMExtensions.cs +++ b/ICSharpCode.Decompiler/SRMExtensions.cs @@ -628,7 +628,7 @@ internal static bool IsKnownAttribute(this SRM.CustomAttribute attr, MetadataRea #endregion public static unsafe BlobReader GetInitialValue(this FieldDefinition field, MetadataFile pefile, - ICompilation typeSystem) + ICompilation? typeSystem) { if (!field.HasFlag(FieldAttributes.HasFieldRVA)) return default; @@ -647,7 +647,7 @@ public static unsafe BlobReader GetInitialValue(this FieldDefinition field, Meta sealed class FieldValueSizeDecoder : ISignatureTypeProvider { - readonly MetadataModule module; + readonly MetadataModule? module; readonly int pointerSize; public FieldValueSizeDecoder(ICompilation? typeSystem = null) diff --git a/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs b/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs index 551f92605e..69ebb8cd7d 100644 --- a/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs @@ -42,7 +42,7 @@ public class InvocationResolveResult : MemberResolveResult /// public readonly IList InitializerStatements; - public InvocationResolveResult(ResolveResult targetResult, IParameterizedMember member, + public InvocationResolveResult(ResolveResult? targetResult, IParameterizedMember member, IList? arguments = null, IList? initializerStatements = null, IType? returnTypeOverride = null) diff --git a/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs b/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs index 53dd7dea90..971ea22636 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs @@ -175,11 +175,11 @@ public static IType ApplyAttributesToType(IType inputType, ICompilation compilat readonly bool hasDynamicAttribute; readonly bool[] dynamicAttributeData; readonly bool hasNativeIntegersAttribute; - readonly bool[] nativeIntegersAttributeData; + readonly bool[]? nativeIntegersAttributeData; readonly TypeSystemOptions options; readonly string[] tupleElementNames; readonly Nullability defaultNullability; - readonly Nullability[] nullableAttributeData; + readonly Nullability[]? nullableAttributeData; int dynamicTypeIndex = 0; int tupleTypeIndex = 0; int nullabilityTypeIndex = 0; @@ -187,9 +187,9 @@ public static IType ApplyAttributesToType(IType inputType, ICompilation compilat private ApplyAttributeTypeVisitor(ICompilation compilation, bool hasDynamicAttribute, bool[] dynamicAttributeData, - bool hasNativeIntegersAttribute, bool[] nativeIntegersAttributeData, + bool hasNativeIntegersAttribute, bool[]? nativeIntegersAttributeData, TypeSystemOptions options, string[] tupleElementNames, - Nullability defaultNullability, Nullability[] nullableAttributeData) + Nullability defaultNullability, Nullability[]? nullableAttributeData) { this.compilation = compilation ?? throw new ArgumentNullException(nameof(compilation)); this.hasDynamicAttribute = hasDynamicAttribute; diff --git a/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs b/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs index 74701a6ed9..fec605b9db 100644 --- a/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs +++ b/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs @@ -52,7 +52,7 @@ public NestedTypeName(string name, int additionalTypeParameterCount) } readonly TopLevelTypeName topLevelType; - readonly NestedTypeName[] nestedTypes; + readonly NestedTypeName[]? nestedTypes; FullTypeName(TopLevelTypeName topLevelTypeName, NestedTypeName[] nestedTypes) { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs index 285403b712..a4cea68c64 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs @@ -41,7 +41,7 @@ public static IEnumerable GetNestedTypes(IType type, Predicate GetNestedTypes(IType type, IReadOnlyList nestedTypeArguments, Predicate filter, GetMemberOptions options) + public static IEnumerable GetNestedTypes(IType type, IReadOnlyList? nestedTypeArguments, Predicate filter, GetMemberOptions options) { if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) { @@ -53,9 +53,9 @@ public static IEnumerable GetNestedTypes(IType type, IReadOnlyList } } - static IEnumerable GetNestedTypesImpl(IType outerType, IReadOnlyList nestedTypeArguments, Predicate filter, GetMemberOptions options) + static IEnumerable GetNestedTypesImpl(IType outerType, IReadOnlyList? nestedTypeArguments, Predicate? filter, GetMemberOptions options) { - ITypeDefinition outerTypeDef = outerType.GetDefinition(); + ITypeDefinition? outerTypeDef = outerType.GetDefinition(); if (outerTypeDef == null) yield break; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs index 729d1e5ba6..9a2271358a 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs @@ -34,7 +34,7 @@ sealed class MetadataNamespace : INamespace public string FullName { get; } public string Name { get; } - public MetadataNamespace(MetadataModule module, INamespace parent, string fullName, NamespaceDefinition ns) + public MetadataNamespace(MetadataModule module, INamespace? parent, string fullName, NamespaceDefinition ns) { Debug.Assert(module != null); Debug.Assert(fullName != null); diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs index 88e0b57a6b..c3c74d80fd 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs @@ -38,7 +38,7 @@ public class UnknownType : AbstractType, ITypeDefinitionOrUnknown, ITypeReferenc /// Namespace name, if known. Can be null if unknown. /// Name of the type, must not be null. /// Type parameter count, zero if unknown. - public UnknownType(string namespaceName, string name, int typeParameterCount = 0, bool? isReferenceType = null) + public UnknownType(string? namespaceName, string name, int typeParameterCount = 0, bool? isReferenceType = null) { if (name == null) throw new ArgumentNullException(nameof(name)); diff --git a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs index 59f1d4b4b8..0ddee615d7 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs @@ -53,10 +53,10 @@ public sealed class TupleType : AbstractType, ICompilationProvider /// /// Gets the names of the tuple elements. /// - public ImmutableArray ElementNames { get; } + public ImmutableArray ElementNames { get; } public TupleType(ICompilation compilation, ImmutableArray elementTypes, - ImmutableArray elementNames = default(ImmutableArray), + ImmutableArray elementNames = default(ImmutableArray), IModule? valueTupleAssembly = null) { this.Compilation = compilation; @@ -64,7 +64,7 @@ public TupleType(ICompilation compilation, ImmutableArray elementTypes, this.ElementTypes = elementTypes; if (elementNames.IsDefault) { - this.ElementNames = Enumerable.Repeat(null, elementTypes.Length).ToImmutableArray(); + this.ElementNames = Enumerable.Repeat(null, elementTypes.Length).ToImmutableArray(); } else { @@ -73,7 +73,7 @@ public TupleType(ICompilation compilation, ImmutableArray elementTypes, } } - static ParameterizedType CreateUnderlyingType(ICompilation compilation, ImmutableArray elementTypes, IModule valueTupleAssembly) + static ParameterizedType CreateUnderlyingType(ICompilation compilation, ImmutableArray elementTypes, IModule? valueTupleAssembly) { int remainder = (elementTypes.Length - 1) % (RestPosition - 1) + 1; Debug.Assert(remainder >= 1 && remainder < RestPosition); @@ -92,7 +92,7 @@ static ParameterizedType CreateUnderlyingType(ICompilation compilation, Immutabl return type; } - private static IType FindValueTupleType(ICompilation compilation, IModule valueTupleAssembly, int tpc) + private static IType FindValueTupleType(ICompilation compilation, IModule? valueTupleAssembly, int tpc) { var typeName = new TopLevelTypeName("System", "ValueTuple", tpc); if (valueTupleAssembly != null) @@ -236,7 +236,7 @@ public override int GetHashCode() unchecked { int hash = UnderlyingType.GetHashCode(); - foreach (string name in ElementNames) + foreach (string? name in ElementNames) { hash *= 31; hash += name != null ? name.GetHashCode() : 0; @@ -387,7 +387,7 @@ public class TupleTypeReference : ITypeReference /// public ImmutableArray ElementNames { get; } - public IModuleReference ValueTupleAssembly { get; } + public IModuleReference? ValueTupleAssembly { get; } public TupleTypeReference(ImmutableArray elementTypes) { diff --git a/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs b/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs index 7d18ef5517..d8795da635 100644 --- a/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs +++ b/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs @@ -45,12 +45,12 @@ namespace ICSharpCode.Decompiler.Util #endif class ResXResourceWriter : IDisposable { - private string filename; - private Stream stream; - private TextWriter textwriter; - private XmlTextWriter writer; + private string? filename; + private Stream? stream; + private TextWriter? textwriter; + private XmlTextWriter? writer; private bool written; - private string base_path; + private string? base_path; public static readonly string BinSerializedObjectMimeType = "application/x-microsoft.net.object.binary.base64"; public static readonly string ByteArraySerializedObjectMimeType = "application/x-microsoft.net.object.bytearray.base64"; @@ -131,7 +131,7 @@ void WriteNiceBase64(byte[] value, int offset, int length) writer.WriteString(base64); } - void WriteBytes(string name, string type, byte[] value, int offset, int length, string comment) + void WriteBytes(string name, string? type, byte[] value, int offset, int length, string comment) { writer.WriteStartElement("data"); writer.WriteAttributeString("name", name); @@ -165,7 +165,7 @@ void WriteBytes(string name, string type, byte[] value, int offset, int length, writer.WriteEndElement(); } - void WriteString(string name, string value, string type, string comment) + void WriteString(string name, string value, string? type, string comment) { writer.WriteStartElement("data"); writer.WriteAttributeString("name", name); diff --git a/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs b/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs index 8cc359925c..605e5bd94e 100644 --- a/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs +++ b/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs @@ -317,7 +317,7 @@ ProjectId DecompileAsProject(string assemblyFileName, string projectFileName) return decompiler.DecompileProject(module, Path.GetDirectoryName(projectFileName), projectFileWriter); } - int Decompile(string assemblyFileName, TextWriter output, string typeName = null) + int Decompile(string assemblyFileName, TextWriter output, string? typeName = null) { CSharpDecompiler decompiler = GetDecompiler(assemblyFileName); diff --git a/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs b/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs index 6cd03c5582..564922d1b6 100644 --- a/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs +++ b/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs @@ -171,10 +171,10 @@ public void Disassemble(PEFile currentFile, int bitness, ulong address, bool sho output.WriteLine(); } - private void DecorateGCInfo(Instruction instr, ulong baseInstrIP, BaseGcInfo gcInfo) + private void DecorateGCInfo(Instruction instr, ulong baseInstrIP, BaseGcInfo? gcInfo) { ulong codeOffset = instr.IP - baseInstrIP; - if (gcInfo != null && gcInfo.Transitions != null && gcInfo.Transitions.TryGetValue((int)codeOffset, out List transitionsForOffset)) + if (gcInfo != null && gcInfo.Transitions != null && gcInfo.Transitions.TryGetValue((int)codeOffset, out List? transitionsForOffset)) { // this value comes from a manual count of the spaces used for each instruction in Disassemble() string indent = new string(' ', 36); @@ -192,17 +192,17 @@ private void WriteCommentLine(string comment) private class NativeVarInfoRecord { - public ulong codeOffset; - public bool isStart; - public bool isRegRelative; - public string register; + public required ulong codeOffset; + public required bool isStart; + public required bool isRegRelative; + public required string register; public int registerOffset; - public Variable variable; + public required Variable variable; } private class DebugInfoHelper { - public List records; + public List? records; public int i; public Dictionary>> registerRelativeVariables; public Dictionary> registerVariables; diff --git a/ILSpy.ReadyToRun/ReadyToRunLanguage.cs b/ILSpy.ReadyToRun/ReadyToRunLanguage.cs index a963dee76b..75cbeba082 100644 --- a/ILSpy.ReadyToRun/ReadyToRunLanguage.cs +++ b/ILSpy.ReadyToRun/ReadyToRunLanguage.cs @@ -307,10 +307,10 @@ public IlSpyAssemblyMetadata(PEFile module) : base(module.Reader) private class ReadyToRunReaderCacheEntry { - public ReadyToRunReader readyToRunReader; - public ReadyToRunReader compositeReadyToRunReader; - public string failureReason; - public Dictionary methodMap; + public ReadyToRunReader? readyToRunReader; + public ReadyToRunReader? compositeReadyToRunReader; + public string? failureReason; + public Dictionary? methodMap; } } } diff --git a/ILSpy.ReadyToRun/ReadyToRunOptions.cs b/ILSpy.ReadyToRun/ReadyToRunOptions.cs index 365d1dd9a3..5e65b574a5 100644 --- a/ILSpy.ReadyToRun/ReadyToRunOptions.cs +++ b/ILSpy.ReadyToRun/ReadyToRunOptions.cs @@ -31,14 +31,14 @@ internal class ReadyToRunOptions internal static string gas = "AT & T"; internal static string[] disassemblyFormats = new string[] { intel, gas }; - public static string GetDisassemblyFormat(ILSpySettings settings) + public static string GetDisassemblyFormat(ILSpySettings? settings) { if (settings == null) { settings = ILSpySettings.Load(); } XElement e = settings[ns + "ReadyToRunOptions"]; - XAttribute a = e.Attribute("DisassemblyFormat"); + XAttribute? a = e.Attribute("DisassemblyFormat"); if (a == null) { return ReadyToRunOptions.intel; @@ -49,14 +49,14 @@ public static string GetDisassemblyFormat(ILSpySettings settings) } } - public static bool GetIsShowUnwindInfo(ILSpySettings settings) + public static bool GetIsShowUnwindInfo(ILSpySettings? settings) { if (settings == null) { settings = ILSpySettings.Load(); } XElement e = settings[ns + "ReadyToRunOptions"]; - XAttribute a = e.Attribute("IsShowUnwindInfo"); + XAttribute? a = e.Attribute("IsShowUnwindInfo"); if (a == null) { @@ -68,14 +68,14 @@ public static bool GetIsShowUnwindInfo(ILSpySettings settings) } } - public static bool GetIsShowDebugInfo(ILSpySettings settings) + public static bool GetIsShowDebugInfo(ILSpySettings? settings) { if (settings == null) { settings = ILSpySettings.Load(); } XElement e = settings[ns + "ReadyToRunOptions"]; - XAttribute a = e.Attribute("IsShowDebugInfo"); + XAttribute? a = e.Attribute("IsShowDebugInfo"); if (a == null) { @@ -87,14 +87,14 @@ public static bool GetIsShowDebugInfo(ILSpySettings settings) } } - public static bool GetIsShowGCInfo(ILSpySettings settings) + public static bool GetIsShowGCInfo(ILSpySettings? settings) { if (settings == null) { settings = ILSpySettings.Load(); } XElement e = settings[ns + "ReadyToRunOptions"]; - XAttribute a = e.Attribute("IsShowGCInfo"); + XAttribute? a = e.Attribute("IsShowGCInfo"); if (a == null) { @@ -113,7 +113,7 @@ public static void SetDisassemblyOptions(XElement root, string disassemblyFormat section.SetAttributeValue("IsShowUnwindInfo", isShowUnwindInfo); section.SetAttributeValue("IsShowDebugInfo", isShowDebugInfo); section.SetAttributeValue("IsShowGCInfo", isShowGCInfo); - XElement existingElement = root.Element(ns + "ReadyToRunOptions"); + XElement? existingElement = root.Element(ns + "ReadyToRunOptions"); if (existingElement != null) { existingElement.ReplaceWith(section); diff --git a/ILSpy/Commands/ShowCFGContextMenuEntry.cs b/ILSpy/Commands/ShowCFGContextMenuEntry.cs index b4e8be003e..9ff313da7f 100644 --- a/ILSpy/Commands/ShowCFGContextMenuEntry.cs +++ b/ILSpy/Commands/ShowCFGContextMenuEntry.cs @@ -39,7 +39,7 @@ public bool IsVisible(TextViewContext context) return context.Reference?.Reference is BlockContainer; } - internal static GraphVizGraph ExportGraph(IReadOnlyList nodes, Func labelFunc = null) + internal static GraphVizGraph ExportGraph(IReadOnlyList nodes, Func? labelFunc = null) { if (labelFunc == null) { diff --git a/ILSpy/Controls/SearchBox.cs b/ILSpy/Controls/SearchBox.cs index f07dc24c12..5c701652be 100644 --- a/ILSpy/Controls/SearchBox.cs +++ b/ILSpy/Controls/SearchBox.cs @@ -84,7 +84,7 @@ private void IconBorder_MouseLeftButtonUp(object obj, MouseButtonEventArgs e) #region Overrides - DispatcherTimer timer; + DispatcherTimer? timer; protected override void OnTextChanged(TextChangedEventArgs e) { diff --git a/ILSpy/Controls/TreeView/SharpTreeView.cs b/ILSpy/Controls/TreeView/SharpTreeView.cs index e8a76208cc..7ca7537596 100644 --- a/ILSpy/Controls/TreeView/SharpTreeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeView.cs @@ -655,7 +655,7 @@ void GetNodeAndIndex(SharpTreeViewItem item, DropPlace place, out SharpTreeNode? } } - SharpTreeNodeView previewNodeView; + SharpTreeNodeView? previewNodeView; InsertMarker insertMarker; DropPlace previewPlace; diff --git a/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs b/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs index 5b14ebc6f7..19532e66f4 100644 --- a/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs +++ b/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs @@ -36,7 +36,7 @@ public partial class SharpTreeViewTextSearch : DependencyObject typeof(SharpTreeViewTextSearch), typeof(SharpTreeViewTextSearch), new FrameworkPropertyMetadata(null)); static readonly DependencyProperty TextSearchInstanceProperty = TextSearchInstancePropertyKey.DependencyProperty; - DispatcherTimer timer; + DispatcherTimer? timer; bool isActive; int lastMatchIndex; diff --git a/ILSpy/DecompilationOptions.cs b/ILSpy/DecompilationOptions.cs index e5d480c3e0..f070267328 100644 --- a/ILSpy/DecompilationOptions.cs +++ b/ILSpy/DecompilationOptions.cs @@ -83,7 +83,7 @@ public class DecompilationOptions internal int StepLimit = int.MaxValue; internal bool IsDebug = false; - public DecompilationOptions(LanguageVersion version, DecompilerSettings settings, DisplaySettings displaySettings) + public DecompilationOptions(LanguageVersion? version, DecompilerSettings settings, DisplaySettings displaySettings) { if (!Enum.TryParse(version?.Version, out Decompiler.CSharp.LanguageVersion languageVersion)) languageVersion = Decompiler.CSharp.LanguageVersion.Latest; diff --git a/ILSpy/Docking/DockWorkspace.cs b/ILSpy/Docking/DockWorkspace.cs index adc8497a74..f3de5959fb 100644 --- a/ILSpy/Docking/DockWorkspace.cs +++ b/ILSpy/Docking/DockWorkspace.cs @@ -120,8 +120,8 @@ public void Remove(PaneModel model) tool.IsVisible = false; } - private TabPageModel activeTabPage = null; - public TabPageModel ActiveTabPage { + private TabPageModel? activeTabPage = null; + public TabPageModel? ActiveTabPage { get { return activeTabPage; } @@ -131,7 +131,7 @@ public TabPageModel ActiveTabPage { return; } - var state = value.GetState(); + var state = value?.GetState(); if (state != null) { if (state.DecompiledNodes != null) @@ -193,7 +193,7 @@ public Task RunWithCancellation(Func> taskCreat return ActiveTabPage.ShowTextViewAsync(textView => textView.RunWithCancellation(taskCreation)); } - internal void ShowNodes(AvalonEditTextOutput output, TreeNodes.ILSpyTreeNode[] nodes, IHighlightingDefinition highlighting) + internal void ShowNodes(AvalonEditTextOutput output, TreeNodes.ILSpyTreeNode[]? nodes, IHighlightingDefinition highlighting) { ActiveTabPage.ShowTextView(textView => textView.ShowNodes(output, nodes, highlighting)); } @@ -266,6 +266,6 @@ public void AfterInsertDocument(LayoutRoot layout, LayoutDocument anchorableShow } // Dummy property to make the XAML designer happy, the model is provided by the AvalonDock PaneStyleSelectors, not by the DockWorkspace, but the designer assumes the data context in the PaneStyleSelectors is the DockWorkspace. - public PaneModel Model { get; } = null; + public PaneModel? Model { get; } = null; } } diff --git a/ILSpy/Docking/PaneCollection.cs b/ILSpy/Docking/PaneCollection.cs index a1715d9a44..0afa5f316c 100644 --- a/ILSpy/Docking/PaneCollection.cs +++ b/ILSpy/Docking/PaneCollection.cs @@ -37,7 +37,7 @@ public PaneCollection() observableCollection.CollectionChanged += (sender, e) => CollectionChanged?.Invoke(this, e); } - public void Add(T item = null) + public void Add(T? item = null) { item ??= new T(); diff --git a/ILSpy/Images/Images.cs b/ILSpy/Images/Images.cs index d605e4be7c..4f24c3d0c9 100644 --- a/ILSpy/Images/Images.cs +++ b/ILSpy/Images/Images.cs @@ -122,7 +122,7 @@ static ImageSource Load(string icon) public static readonly ImageSource FieldReference = GetIcon("Field", "ReferenceOverlay"); public static readonly ImageSource ExportedType = GetIcon("ShowPublicOnly", "ExportOverlay"); - public static ImageSource Load(object part, string icon) + public static ImageSource Load(object? part, string icon) { if (icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) return LoadImage(part, icon); @@ -139,7 +139,7 @@ public static ImageSource Load(object part, string icon) return LoadImage(part, icon + ".png"); } - static BitmapImage LoadImage(object part, string icon) + static BitmapImage LoadImage(object? part, string icon) { Uri uri = GetUri(part, icon); BitmapImage image = new BitmapImage(uri); diff --git a/ILSpy/LanguageSettings.cs b/ILSpy/LanguageSettings.cs index 6328a69240..c4a6da66df 100644 --- a/ILSpy/LanguageSettings.cs +++ b/ILSpy/LanguageSettings.cs @@ -38,7 +38,7 @@ public class LanguageSettings : INotifyPropertyChanged /// the user first select C# 10, then switches to IL, then switches back to C#. After that we must be /// able to restore the original selection (i.e., C# 10). /// - private readonly Dictionary languageVersionHistory = new Dictionary(); + private readonly Dictionary languageVersionHistory = new Dictionary(); public LanguageSettings(XElement element) { @@ -149,7 +149,7 @@ public Language Language { } } - LanguageVersion languageVersion; + LanguageVersion? languageVersion; /// /// Gets/Sets the current language version. @@ -158,7 +158,7 @@ public Language Language { /// While this isn't related to filtering, having it as part of the FilterSettings /// makes it easy to pass it down into all tree nodes. /// - public LanguageVersion LanguageVersion { + public LanguageVersion? LanguageVersion { get { return languageVersion; } set { if (languageVersion != value) diff --git a/ILSpy/Languages/CSharpHighlightingTokenWriter.cs b/ILSpy/Languages/CSharpHighlightingTokenWriter.cs index 4128dd4862..dfddf721ed 100644 --- a/ILSpy/Languages/CSharpHighlightingTokenWriter.cs +++ b/ILSpy/Languages/CSharpHighlightingTokenWriter.cs @@ -73,7 +73,7 @@ class CSharpHighlightingTokenWriter : DecoratingTokenWriter public RichTextModel HighlightingModel { get; } = new RichTextModel(); - public CSharpHighlightingTokenWriter(TokenWriter decoratedWriter, ISmartTextOutput textOutput = null, ILocatable locatable = null) + public CSharpHighlightingTokenWriter(TokenWriter decoratedWriter, ISmartTextOutput? textOutput = null, ILocatable? locatable = null) : base(decoratedWriter) { var highlighting = HighlightingManager.Instance.GetDefinition("C#"); @@ -452,7 +452,7 @@ void ApplyTypeColor(IType type, ref HighlightingColor color) } } - public override void WritePrimitiveValue(object value, Decompiler.CSharp.Syntax.LiteralFormat format) + public override void WritePrimitiveValue(object? value, Decompiler.CSharp.Syntax.LiteralFormat format) { HighlightingColor? color = null; if (value is null) @@ -529,8 +529,8 @@ public override void EndNode(AstNode node) readonly Stack colorStack = new Stack(); HighlightingColor currentColor = new HighlightingColor(); int currentColorBegin = -1; - readonly ILocatable locatable; - readonly ISmartTextOutput textOutput; + readonly ILocatable? locatable; + readonly ISmartTextOutput? textOutput; private void BeginSpan(HighlightingColor highlightingColor) { diff --git a/ILSpy/Languages/CSharpILMixedLanguage.cs b/ILSpy/Languages/CSharpILMixedLanguage.cs index 4f7ca57cc3..ebed5d1c6c 100644 --- a/ILSpy/Languages/CSharpILMixedLanguage.cs +++ b/ILSpy/Languages/CSharpILMixedLanguage.cs @@ -83,9 +83,9 @@ class MixedMethodBodyDisassembler : MethodBodyDisassembler { readonly DecompilationOptions options; // list sorted by IL offset - IList sequencePoints; + IList? sequencePoints; // lines of raw c# source code - string[] codeLines; + string[]? codeLines; public MixedMethodBodyDisassembler(ITextOutput output, DecompilationOptions options) : base(output, options.CancellationToken) diff --git a/ILSpy/MainWindow.xaml.cs b/ILSpy/MainWindow.xaml.cs index dbd5816013..cdd8cb429e 100644 --- a/ILSpy/MainWindow.xaml.cs +++ b/ILSpy/MainWindow.xaml.cs @@ -632,7 +632,7 @@ bool HandleCommandLineArguments(CommandLineArguments args) /// Called on startup or when passed arguments via WndProc from a second instance. /// In the format case, spySettings is non-null; in the latter it is null. /// - void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args, ILSpySettings spySettings = null) + void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args, ILSpySettings? spySettings = null) { var sessionSettings = SettingsService.Instance.SessionSettings; @@ -648,7 +648,7 @@ void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args, ILSpySet } } - async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSpySettings spySettings, List relevantAssemblies) + async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSpySettings? spySettings, List relevantAssemblies) { var initialSelection = AssemblyTreeView.SelectedItem; if (navigateTo != null) @@ -1448,7 +1448,7 @@ public void RefreshDecompiledView() public Language CurrentLanguage => SettingsService.Instance.SessionSettings.LanguageSettings.Language; - public LanguageVersion CurrentLanguageVersion => SettingsService.Instance.SessionSettings.LanguageSettings.LanguageVersion; + public LanguageVersion? CurrentLanguageVersion => SettingsService.Instance.SessionSettings.LanguageSettings.LanguageVersion; public event SelectionChangedEventHandler SelectionChanged; diff --git a/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs b/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs index f36164b16e..3dc8eeee06 100644 --- a/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs @@ -100,8 +100,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference("metadata", classLayout.Parent)); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, classLayout.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, classLayout.Parent); [ColumnInfo("X4", Kind = ColumnKind.Other)] public ushort PackingSize => classLayout.PackingSize; diff --git a/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs b/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs index 45155e67e8..4ca9f575a7 100644 --- a/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs @@ -91,8 +91,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, constant.Parent, protocol: "metadata")); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, constant.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, constant.Parent); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Value => MetadataTokens.GetHeapOffset(constant.Value); diff --git a/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs b/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs index 1249ca69e7..a687035add 100644 --- a/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs @@ -86,8 +86,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, customAttr.Parent, protocol: "metadata")); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, customAttr.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, customAttr.Parent); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Constructor => MetadataTokens.GetToken(customAttr.Constructor); @@ -97,8 +97,8 @@ public void OnConstructorClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, customAttr.Constructor, protocol: "metadata")); } - string constructorTooltip; - public string ConstructorTooltip => GenerateTooltip(ref constructorTooltip, metadataFile, customAttr.Constructor); + string? constructorTooltip; + public string? ConstructorTooltip => GenerateTooltip(ref constructorTooltip, metadataFile, customAttr.Constructor); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Value => MetadataTokens.GetHeapOffset(customAttr.Value); diff --git a/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs b/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs index 91ab69defd..cc297a2fd8 100644 --- a/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs @@ -87,8 +87,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, declSecAttr.Parent, protocol: "metadata")); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, declSecAttr.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, declSecAttr.Parent); [ColumnInfo("X8", Kind = ColumnKind.Other)] public DeclarativeSecurityAction Action => declSecAttr.Action; diff --git a/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs b/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs index 44ea708f1f..ee7c4359ff 100644 --- a/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs @@ -98,8 +98,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, eventMap.Parent, protocol: "metadata")); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, eventMap.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, eventMap.Parent); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int EventList => MetadataTokens.GetToken(eventMap.EventList); @@ -109,8 +109,8 @@ public void OnEventListClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, eventMap.EventList, protocol: "metadata")); } - string eventListTooltip; - public string EventListTooltip => GenerateTooltip(ref eventListTooltip, metadataFile, eventMap.EventList); + string? eventListTooltip; + public string? EventListTooltip => GenerateTooltip(ref eventListTooltip, metadataFile, eventMap.EventList); public EventMapEntry(MetadataFile metadataFile, ReadOnlySpan ptr, int row) { diff --git a/ILSpy/Metadata/CorTables/EventTableTreeNode.cs b/ILSpy/Metadata/CorTables/EventTableTreeNode.cs index 20f7003d3d..484346d91d 100644 --- a/ILSpy/Metadata/CorTables/EventTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/EventTableTreeNode.cs @@ -106,8 +106,8 @@ public void OnTypeClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, eventDef.Type, protocol: "metadata")); } - string typeTooltip; - public string TypeTooltip => GenerateTooltip(ref typeTooltip, metadataFile, eventDef.Type); + string? typeTooltip; + public string? TypeTooltip => GenerateTooltip(ref typeTooltip, metadataFile, eventDef.Type); public EventDefEntry(MetadataFile metadataFile, EventDefinitionHandle handle) { diff --git a/ILSpy/Metadata/CorTables/ExportedTypeTableTreeNode.cs b/ILSpy/Metadata/CorTables/ExportedTypeTableTreeNode.cs index dc88622c64..e66d16d223 100644 --- a/ILSpy/Metadata/CorTables/ExportedTypeTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ExportedTypeTableTreeNode.cs @@ -110,8 +110,8 @@ public void OnImplementationClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, type.Implementation, protocol: "metadata")); } - string implementationTooltip; - public string ImplementationTooltip => GenerateTooltip(ref implementationTooltip, metadataFile, type.Implementation); + string? implementationTooltip; + public string? ImplementationTooltip => GenerateTooltip(ref implementationTooltip, metadataFile, type.Implementation); public ExportedTypeEntry(MetadataFile metadataFile, ExportedTypeHandle handle, ExportedType type) { diff --git a/ILSpy/Metadata/CorTables/FieldLayoutTableTreeNode.cs b/ILSpy/Metadata/CorTables/FieldLayoutTableTreeNode.cs index ba014ccc09..117db920d1 100644 --- a/ILSpy/Metadata/CorTables/FieldLayoutTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldLayoutTableTreeNode.cs @@ -99,8 +99,8 @@ public void OnFieldClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, fieldLayout.Field, protocol: "metadata")); } - string fieldTooltip; - public string FieldTooltip => GenerateTooltip(ref fieldTooltip, metadataFile, fieldLayout.Field); + string? fieldTooltip; + public string? FieldTooltip => GenerateTooltip(ref fieldTooltip, metadataFile, fieldLayout.Field); [ColumnInfo("X8", Kind = ColumnKind.Other)] public int FieldOffset => fieldLayout.Offset; diff --git a/ILSpy/Metadata/CorTables/FieldMarshalTableTreeNode.cs b/ILSpy/Metadata/CorTables/FieldMarshalTableTreeNode.cs index 7bb2c1da21..5edae567c1 100644 --- a/ILSpy/Metadata/CorTables/FieldMarshalTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldMarshalTableTreeNode.cs @@ -98,8 +98,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, fieldMarshal.Parent, protocol: "metadata")); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, fieldMarshal.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, fieldMarshal.Parent); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int NativeType => MetadataTokens.GetHeapOffset(fieldMarshal.NativeType); diff --git a/ILSpy/Metadata/CorTables/FieldRVATableTreeNode.cs b/ILSpy/Metadata/CorTables/FieldRVATableTreeNode.cs index f95f21a296..02f26f6192 100644 --- a/ILSpy/Metadata/CorTables/FieldRVATableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldRVATableTreeNode.cs @@ -102,8 +102,8 @@ public void OnFieldClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, fieldRVA.Field, protocol: "metadata")); } - string fieldTooltip; - public string FieldTooltip => GenerateTooltip(ref fieldTooltip, metadataFile, fieldRVA.Field); + string? fieldTooltip; + public string? FieldTooltip => GenerateTooltip(ref fieldTooltip, metadataFile, fieldRVA.Field); [ColumnInfo("X8", Kind = ColumnKind.Other)] public int FieldOffset => fieldRVA.Offset; diff --git a/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs b/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs index c200cba3c8..7d2b5f2ddc 100644 --- a/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs @@ -100,8 +100,8 @@ struct FieldDefEntry : IMemberTreeNode [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(fieldDef.Signature); - string signatureTooltip; - public string SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); + string? signatureTooltip; + public string? SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); public FieldDefEntry(MetadataFile metadataFile, FieldDefinitionHandle handle) { diff --git a/ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs b/ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs index d7af52a198..91bd5ef97d 100644 --- a/ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs @@ -87,9 +87,9 @@ public void OnOwnerClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, genericParamConstraint.Parameter, protocol: "metadata")); } - string ownerTooltip; + string? ownerTooltip; - public string OwnerTooltip { + public string? OwnerTooltip { get { if (ownerTooltip == null) { @@ -111,8 +111,8 @@ public void OnTypeClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, genericParamConstraint.Type, protocol: "metadata")); } - string typeTooltip; - public string TypeTooltip => GenerateTooltip(ref typeTooltip, metadataFile, genericParamConstraint.Type); + string? typeTooltip; + public string? TypeTooltip => GenerateTooltip(ref typeTooltip, metadataFile, genericParamConstraint.Type); public GenericParamConstraintEntry(MetadataFile metadataFile, GenericParameterConstraintHandle handle) { diff --git a/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs b/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs index 1ebc8f1065..cfdbfaecb8 100644 --- a/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs @@ -95,8 +95,8 @@ public void OnOwnerClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, genericParam.Parent, protocol: "metadata")); } - string ownerTooltip; - public string OwnerTooltip => GenerateTooltip(ref ownerTooltip, metadataFile, genericParam.Parent); + string? ownerTooltip; + public string? OwnerTooltip => GenerateTooltip(ref ownerTooltip, metadataFile, genericParam.Parent); public string Name => metadataFile.Metadata.GetString(genericParam.Name); diff --git a/ILSpy/Metadata/CorTables/ImplMapTableTreeNode.cs b/ILSpy/Metadata/CorTables/ImplMapTableTreeNode.cs index e47456fb58..c8d4c0f911 100644 --- a/ILSpy/Metadata/CorTables/ImplMapTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ImplMapTableTreeNode.cs @@ -116,8 +116,8 @@ public void OnMemberForwardedClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, implMap.MemberForwarded, protocol: "metadata")); } - string memberForwardedTooltip; - public string MemberForwardedTooltip => GenerateTooltip(ref memberForwardedTooltip, metadataFile, implMap.MemberForwarded); + string? memberForwardedTooltip; + public string? MemberForwardedTooltip => GenerateTooltip(ref memberForwardedTooltip, metadataFile, implMap.MemberForwarded); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int ImportScope => MetadataTokens.GetToken(implMap.ImportScope); @@ -127,8 +127,8 @@ public void OnImportScopeClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, implMap.ImportScope, protocol: "metadata")); } - string importScopeTooltip; - public string ImportScopeTooltip => GenerateTooltip(ref importScopeTooltip, metadataFile, implMap.ImportScope); + string? importScopeTooltip; + public string? ImportScopeTooltip => GenerateTooltip(ref importScopeTooltip, metadataFile, implMap.ImportScope); public string ImportName => metadataFile.Metadata.GetString(implMap.ImportName); diff --git a/ILSpy/Metadata/CorTables/InterfaceImplTableTreeNode.cs b/ILSpy/Metadata/CorTables/InterfaceImplTableTreeNode.cs index 72e2a6d8b0..5068aead00 100644 --- a/ILSpy/Metadata/CorTables/InterfaceImplTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/InterfaceImplTableTreeNode.cs @@ -99,8 +99,8 @@ public void OnClassClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, interfaceImpl.Class, protocol: "metadata")); } - string classTooltip; - public string ClassTooltip => GenerateTooltip(ref classTooltip, metadataFile, interfaceImpl.Class); + string? classTooltip; + public string? ClassTooltip => GenerateTooltip(ref classTooltip, metadataFile, interfaceImpl.Class); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Interface => MetadataTokens.GetToken(interfaceImpl.Interface); @@ -110,8 +110,8 @@ public void OnInterfaceClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, interfaceImpl.Interface, protocol: "metadata")); } - string interfaceTooltip; - public string InterfaceTooltip => GenerateTooltip(ref interfaceTooltip, metadataFile, interfaceImpl.Interface); + string? interfaceTooltip; + public string? InterfaceTooltip => GenerateTooltip(ref interfaceTooltip, metadataFile, interfaceImpl.Interface); public InterfaceImplEntry(MetadataFile metadataFile, ReadOnlySpan ptr, int row) { diff --git a/ILSpy/Metadata/CorTables/ManifestResourceTableTreeNode.cs b/ILSpy/Metadata/CorTables/ManifestResourceTableTreeNode.cs index fca47ac3dd..a0fd9dc080 100644 --- a/ILSpy/Metadata/CorTables/ManifestResourceTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ManifestResourceTableTreeNode.cs @@ -96,8 +96,8 @@ public void OnImplementationClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, manifestResource.Implementation, protocol: "metadata")); } - string implementationTooltip; - public string ImplementationTooltip => GenerateTooltip(ref implementationTooltip, metadataFile, manifestResource.Implementation); + string? implementationTooltip; + public string? ImplementationTooltip => GenerateTooltip(ref implementationTooltip, metadataFile, manifestResource.Implementation); public ManifestResourceEntry(MetadataFile metadataFile, ManifestResourceHandle handle) { diff --git a/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs b/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs index fc2d018655..c084df6bc0 100644 --- a/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs @@ -86,8 +86,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, memberRef.Parent, protocol: "metadata")); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, memberRef.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, memberRef.Parent); public string Name => metadataFile.Metadata.GetString(memberRef.Name); @@ -96,8 +96,8 @@ public void OnParentClick() [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(memberRef.Signature); - string signatureTooltip; - public string SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); + string? signatureTooltip; + public string? SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); public MemberRefEntry(MetadataFile metadataFile, MemberReferenceHandle handle) { diff --git a/ILSpy/Metadata/CorTables/MethodImplTableTreeNode.cs b/ILSpy/Metadata/CorTables/MethodImplTableTreeNode.cs index 2edd46feb1..0573fbbb98 100644 --- a/ILSpy/Metadata/CorTables/MethodImplTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodImplTableTreeNode.cs @@ -85,8 +85,8 @@ public void OnMethodDeclarationClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, methodImpl.MethodDeclaration, protocol: "metadata")); } - string methodDeclarationTooltip; - public string MethodDeclarationTooltip => GenerateTooltip(ref methodDeclarationTooltip, metadataFile, methodImpl.MethodDeclaration); + string? methodDeclarationTooltip; + public string? MethodDeclarationTooltip => GenerateTooltip(ref methodDeclarationTooltip, metadataFile, methodImpl.MethodDeclaration); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int MethodBody => MetadataTokens.GetToken(methodImpl.MethodBody); @@ -96,8 +96,8 @@ public void OnMethodBodyClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, methodImpl.MethodBody, protocol: "metadata")); } - string methodBodyTooltip; - public string MethodBodyTooltip => GenerateTooltip(ref methodBodyTooltip, metadataFile, methodImpl.MethodBody); + string? methodBodyTooltip; + public string? MethodBodyTooltip => GenerateTooltip(ref methodBodyTooltip, metadataFile, methodImpl.MethodBody); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Type => MetadataTokens.GetToken(methodImpl.Type); @@ -107,8 +107,8 @@ public void OnTypeClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, methodImpl.Type, protocol: "metadata")); } - string typeTooltip; - public string TypeTooltip => GenerateTooltip(ref typeTooltip, metadataFile, methodImpl.Type); + string? typeTooltip; + public string? TypeTooltip => GenerateTooltip(ref typeTooltip, metadataFile, methodImpl.Type); public MethodImplEntry(MetadataFile metadataFile, MethodImplementationHandle handle) { diff --git a/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs b/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs index 62f22c8a9c..0878e7d763 100644 --- a/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs @@ -93,8 +93,8 @@ public void OnMethodClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, method, protocol: "metadata")); } - string methodTooltip; - public string MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, method); + string? methodTooltip; + public string? MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, method); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Association => MetadataTokens.GetToken(association); @@ -104,8 +104,8 @@ public void OnAssociationClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, association, protocol: "metadata")); } - string associationTooltip; - public string AssociationTooltip => GenerateTooltip(ref associationTooltip, metadataFile, association); + string? associationTooltip; + public string? AssociationTooltip => GenerateTooltip(ref associationTooltip, metadataFile, association); public MethodSemanticsEntry(MetadataFile metadataFile, Handle handle, MethodSemanticsAttributes semantics, MethodDefinitionHandle method, EntityHandle association) { diff --git a/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs b/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs index 7e8acf6f55..e77d7fb1e3 100644 --- a/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs @@ -88,8 +88,8 @@ public void OnMethodClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, methodSpec.Method, protocol: "metadata")); } - string methodTooltip; - public string MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, methodSpec.Method); + string? methodTooltip; + public string? MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, methodSpec.Method); [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(methodSpec.Signature); diff --git a/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs b/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs index f92db4da8c..4d75665266 100644 --- a/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs @@ -109,9 +109,9 @@ struct MethodDefEntry : IMemberTreeNode [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(methodDef.Signature); - string signatureTooltip; + string? signatureTooltip; - public string SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); + public string? SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int ParamList => MetadataTokens.GetToken(methodDef.GetParameters().FirstOrDefault()); @@ -121,7 +121,7 @@ public void OnParamListClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, methodDef.GetParameters().FirstOrDefault(), protocol: "metadata")); } - string paramListTooltip; + string? paramListTooltip; public string? ParamListTooltip { get { var param = methodDef.GetParameters().FirstOrDefault(); diff --git a/ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs b/ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs index 02fcd52335..ecbf99b37d 100644 --- a/ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs @@ -98,8 +98,8 @@ public void OnNestedClassClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, nestedClass.Nested, protocol: "metadata")); } - string nestedClassTooltip; - public string NestedClassTooltip => GenerateTooltip(ref nestedClassTooltip, metadataFile, nestedClass.Nested); + string? nestedClassTooltip; + public string? NestedClassTooltip => GenerateTooltip(ref nestedClassTooltip, metadataFile, nestedClass.Nested); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int EnclosingClass => MetadataTokens.GetToken(nestedClass.Enclosing); @@ -109,8 +109,8 @@ public void OnEnclosingClassClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, nestedClass.Enclosing, protocol: "metadata")); } - string enclosingClassTooltip; - public string EnclosingClassTooltip => GenerateTooltip(ref enclosingClassTooltip, metadataFile, nestedClass.Enclosing); + string? enclosingClassTooltip; + public string? EnclosingClassTooltip => GenerateTooltip(ref enclosingClassTooltip, metadataFile, nestedClass.Enclosing); public NestedClassEntry(MetadataFile metadataFile, ReadOnlySpan ptr, int row) { diff --git a/ILSpy/Metadata/CorTables/PropertyMapTableTreeNode.cs b/ILSpy/Metadata/CorTables/PropertyMapTableTreeNode.cs index 7bbfcf09b9..4addf69bcf 100644 --- a/ILSpy/Metadata/CorTables/PropertyMapTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/PropertyMapTableTreeNode.cs @@ -98,8 +98,8 @@ public void OnParentClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, propertyMap.Parent, protocol: "metadata")); } - string parentTooltip; - public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, propertyMap.Parent); + string? parentTooltip; + public string? ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, propertyMap.Parent); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int PropertyList => MetadataTokens.GetToken(propertyMap.PropertyList); @@ -109,8 +109,8 @@ public void OnPropertyListClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, propertyMap.PropertyList, protocol: "metadata")); } - string propertyListTooltip; - public string PropertyListTooltip => GenerateTooltip(ref propertyListTooltip, metadataFile, propertyMap.PropertyList); + string? propertyListTooltip; + public string? PropertyListTooltip => GenerateTooltip(ref propertyListTooltip, metadataFile, propertyMap.PropertyList); public PropertyMapEntry(MetadataFile metadataFile, ReadOnlySpan ptr, int row) { diff --git a/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs b/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs index fe1d1eb72c..4c799241ca 100644 --- a/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs @@ -97,8 +97,8 @@ struct PropertyDefEntry : IMemberTreeNode [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(propertyDef.Signature); - string signatureTooltip; - public string SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); + string? signatureTooltip; + public string? SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); public PropertyDefEntry(MetadataFile metadataFile, PropertyDefinitionHandle handle) { diff --git a/ILSpy/Metadata/CorTables/PtrTableTreeNode.cs b/ILSpy/Metadata/CorTables/PtrTableTreeNode.cs index 245507368d..53a3a3d702 100644 --- a/ILSpy/Metadata/CorTables/PtrTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/PtrTableTreeNode.cs @@ -115,8 +115,8 @@ public void OnHandleClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, handlePtr.Handle, protocol: "metadata")); } - string handleTooltip; - public string HandleTooltip => GenerateTooltip(ref handleTooltip, metadataFile, handlePtr.Handle); + string? handleTooltip; + public string? HandleTooltip => GenerateTooltip(ref handleTooltip, metadataFile, handlePtr.Handle); public PtrEntry(MetadataFile metadataFile, TableIndex kind, TableIndex handleKind, int handleDefSize, ReadOnlySpan ptr, int row) { diff --git a/ILSpy/Metadata/CorTables/StandAloneSigTableTreeNode.cs b/ILSpy/Metadata/CorTables/StandAloneSigTableTreeNode.cs index 24c5cf163b..8b5b78b1a9 100644 --- a/ILSpy/Metadata/CorTables/StandAloneSigTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/StandAloneSigTableTreeNode.cs @@ -80,8 +80,8 @@ struct StandAloneSigEntry [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int Signature => MetadataTokens.GetHeapOffset(standaloneSig.Signature); - string signatureTooltip; - public string SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); + string? signatureTooltip; + public string? SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle); public StandAloneSigEntry(MetadataFile metadataFile, StandaloneSignatureHandle handle) { diff --git a/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs b/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs index cdcb575555..f36940c476 100644 --- a/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs @@ -145,7 +145,7 @@ public void OnFieldListClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, typeDef.GetFields().FirstOrDefault(), protocol: "metadata")); } - string fieldListTooltip; + string? fieldListTooltip; public string? FieldListTooltip { get { var field = typeDef.GetFields().FirstOrDefault(); @@ -163,7 +163,7 @@ public void OnMethodListClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, typeDef.GetMethods().FirstOrDefault(), protocol: "metadata")); } - string methodListTooltip; + string? methodListTooltip; public string? MethodListTooltip { get { var method = typeDef.GetMethods().FirstOrDefault(); diff --git a/ILSpy/Metadata/CorTables/TypeRefTableTreeNode.cs b/ILSpy/Metadata/CorTables/TypeRefTableTreeNode.cs index aeaead6087..cff75d02d4 100644 --- a/ILSpy/Metadata/CorTables/TypeRefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/TypeRefTableTreeNode.cs @@ -86,8 +86,8 @@ public void OnResolutionScopeClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, typeRef.ResolutionScope, protocol: "metadata")); } - string resolutionScopeTooltip; - public string ResolutionScopeTooltip => GenerateTooltip(ref resolutionScopeTooltip, metadataFile, typeRef.ResolutionScope); + string? resolutionScopeTooltip; + public string? ResolutionScopeTooltip => GenerateTooltip(ref resolutionScopeTooltip, metadataFile, typeRef.ResolutionScope); public string NameTooltip => $"{MetadataTokens.GetHeapOffset(typeRef.Name):X} \"{Name}\""; diff --git a/ILSpy/Metadata/DebugTables/LocalScopeTableTreeNode.cs b/ILSpy/Metadata/DebugTables/LocalScopeTableTreeNode.cs index 8b0f1e888b..d2f6b0b636 100644 --- a/ILSpy/Metadata/DebugTables/LocalScopeTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/LocalScopeTableTreeNode.cs @@ -84,8 +84,8 @@ public void OnMethodClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, localScope.Method, protocol: "metadata")); } - string methodTooltip; - public string MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, localScope.Method); + string? methodTooltip; + public string? MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, localScope.Method); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int ImportScope => MetadataTokens.GetToken(localScope.ImportScope); diff --git a/ILSpy/Metadata/DebugTables/StateMachineMethodTableTreeNode.cs b/ILSpy/Metadata/DebugTables/StateMachineMethodTableTreeNode.cs index 9341cad78f..d9efe7ff62 100644 --- a/ILSpy/Metadata/DebugTables/StateMachineMethodTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/StateMachineMethodTableTreeNode.cs @@ -86,8 +86,8 @@ public void OnMoveNextMethodClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, moveNextMethod, protocol: "metadata")); } - string moveNextMethodTooltip; - public string MoveNextMethodTooltip => GenerateTooltip(ref moveNextMethodTooltip, metadataFile, moveNextMethod); + string? moveNextMethodTooltip; + public string? MoveNextMethodTooltip => GenerateTooltip(ref moveNextMethodTooltip, metadataFile, moveNextMethod); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int KickoffMethod => MetadataTokens.GetToken(kickoffMethod); @@ -97,8 +97,8 @@ public void OnKickofMethodClick() MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, kickoffMethod, protocol: "metadata")); } - string kickoffMethodTooltip; - public string KickoffMethodTooltip => GenerateTooltip(ref kickoffMethodTooltip, metadataFile, kickoffMethod); + string? kickoffMethodTooltip; + public string? KickoffMethodTooltip => GenerateTooltip(ref kickoffMethodTooltip, metadataFile, kickoffMethod); public StateMachineMethodEntry(MetadataFile metadataFile, ref BlobReader reader, int row) { diff --git a/ILSpy/Metadata/FlagsTooltip.xaml.cs b/ILSpy/Metadata/FlagsTooltip.xaml.cs index 8e670fca3a..c66128a387 100644 --- a/ILSpy/Metadata/FlagsTooltip.xaml.cs +++ b/ILSpy/Metadata/FlagsTooltip.xaml.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.ILSpy.Metadata /// public partial class FlagsTooltip : IEnumerable { - public FlagsTooltip(int value = 0, Type flagsType = null) + public FlagsTooltip(int value = 0, Type? flagsType = null) { InitializeComponent(); } @@ -94,7 +94,7 @@ public Flag(string name, int value, bool isSelected) public abstract class FlagGroup { - public static MultipleChoiceGroup CreateMultipleChoiceGroup(Type flagsType, string header = null, int mask = -1, int selectedValue = 0, bool includeAll = true) + public static MultipleChoiceGroup CreateMultipleChoiceGroup(Type flagsType, string? header = null, int mask = -1, int selectedValue = 0, bool includeAll = true) { MultipleChoiceGroup group = new MultipleChoiceGroup(GetFlags(flagsType, mask, selectedValue, includeAll ? "" : null)); group.Header = header; @@ -102,7 +102,7 @@ public static MultipleChoiceGroup CreateMultipleChoiceGroup(Type flagsType, stri return group; } - public static SingleChoiceGroup CreateSingleChoiceGroup(Type flagsType, string header = null, int mask = -1, int selectedValue = 0, Flag defaultFlag = default, bool includeAny = true) + public static SingleChoiceGroup CreateSingleChoiceGroup(Type flagsType, string? header = null, int mask = -1, int selectedValue = 0, Flag defaultFlag = default, bool includeAny = true) { var group = new SingleChoiceGroup(GetFlags(flagsType, mask, selectedValue, includeAny ? "" : null)); group.Header = header; @@ -114,7 +114,7 @@ public static SingleChoiceGroup CreateSingleChoiceGroup(Type flagsType, string h return group; } - public static IEnumerable GetFlags(Type flagsType, int mask = -1, int selectedValues = 0, string neutralItem = null) + public static IEnumerable GetFlags(Type flagsType, int mask = -1, int selectedValues = 0, string? neutralItem = null) { if (neutralItem != null) yield return new Flag(neutralItem, -1, false); @@ -130,7 +130,7 @@ public static IEnumerable GetFlags(Type flagsType, int mask = -1, int sele } } - public string Header { get; set; } + public string? Header { get; set; } public IList Flags { get; protected set; } } diff --git a/ILSpy/Metadata/MetadataTableTreeNode.cs b/ILSpy/Metadata/MetadataTableTreeNode.cs index 18e678804e..bbee36ce24 100644 --- a/ILSpy/Metadata/MetadataTableTreeNode.cs +++ b/ILSpy/Metadata/MetadataTableTreeNode.cs @@ -66,7 +66,7 @@ private void View_Loaded(object sender, System.Windows.RoutedEventArgs e) this.scrollTarget = default; } - protected static string? GenerateTooltip(ref string tooltip, MetadataFile module, EntityHandle handle) + protected static string? GenerateTooltip(ref string? tooltip, MetadataFile module, EntityHandle handle) { if (tooltip == null) { diff --git a/ILSpy/Metadata/MetadataTreeNode.cs b/ILSpy/Metadata/MetadataTreeNode.cs index 50f739868c..e475ba69b0 100644 --- a/ILSpy/Metadata/MetadataTreeNode.cs +++ b/ILSpy/Metadata/MetadataTreeNode.cs @@ -120,9 +120,9 @@ class Entry public object Value { get; } public string Meaning { get; } - public IList RowDetails { get; } + public IList? RowDetails { get; } - public Entry(int offset, object value, int size, string member, string meaning, IList rowDetails = null) + public Entry(int offset, object value, int size, string member, string meaning, IList? rowDetails = null) { this.Member = member; this.Offset = offset; diff --git a/ILSpy/Options/MiscSettingsPanel.xaml.cs b/ILSpy/Options/MiscSettingsPanel.xaml.cs index ac98981ddb..d72778b40e 100644 --- a/ILSpy/Options/MiscSettingsPanel.xaml.cs +++ b/ILSpy/Options/MiscSettingsPanel.xaml.cs @@ -41,7 +41,7 @@ public void Load(ILSpySettings settings) this.DataContext = LoadMiscSettings(settings); } - static MiscSettingsViewModel currentMiscSettings; + static MiscSettingsViewModel? currentMiscSettings; public static MiscSettingsViewModel CurrentMiscSettings { get { diff --git a/ILSpy/TaskHelper.cs b/ILSpy/TaskHelper.cs index 21bfd56e47..630d1d7d2f 100644 --- a/ILSpy/TaskHelper.cs +++ b/ILSpy/TaskHelper.cs @@ -26,7 +26,7 @@ namespace ICSharpCode.ILSpy { public static class TaskHelper { - public static readonly Task CompletedTask = FromResult(null); + public static readonly Task CompletedTask = FromResult(null); public static Task FromResult(T result) { @@ -73,7 +73,7 @@ public static void SetFromTask(this TaskCompletionSource tcs, Task task /// /// Sets the result of the TaskCompletionSource based on the result of the finished task. /// - public static void SetFromTask(this TaskCompletionSource tcs, Task task) + public static void SetFromTask(this TaskCompletionSource tcs, Task task) { switch (task.Status) { @@ -84,7 +84,7 @@ public static void SetFromTask(this TaskCompletionSource tcs, Task task) tcs.SetCanceled(); break; case TaskStatus.Faulted: - tcs.SetException(task.Exception.InnerExceptions); + tcs.SetException(task.Exception!.InnerExceptions); //the exceptuion must be set if we are faulted sow we igonre nullability warning break; default: throw new InvalidOperationException("The input task must have already finished"); diff --git a/ILSpy/TextView/BracketHighlightRenderer.cs b/ILSpy/TextView/BracketHighlightRenderer.cs index 0a754510b8..2336bca8c6 100644 --- a/ILSpy/TextView/BracketHighlightRenderer.cs +++ b/ILSpy/TextView/BracketHighlightRenderer.cs @@ -71,12 +71,12 @@ public BracketSearchResult(int openingBracketOffset, int openingBracketLength, public class BracketHighlightRenderer : IBackgroundRenderer { - BracketSearchResult result; + BracketSearchResult? result; Pen borderPen; Brush backgroundBrush; ICSharpCode.AvalonEdit.Rendering.TextView textView; - public void SetHighlight(BracketSearchResult result) + public void SetHighlight(BracketSearchResult? result) { if (this.result != result) { diff --git a/ILSpy/TextView/DocumentationUIBuilder.cs b/ILSpy/TextView/DocumentationUIBuilder.cs index d6d6550210..1e0cd1e8dc 100644 --- a/ILSpy/TextView/DocumentationUIBuilder.cs +++ b/ILSpy/TextView/DocumentationUIBuilder.cs @@ -50,7 +50,7 @@ public class DocumentationUIBuilder readonly IHighlightingDefinition highlightingDefinition; readonly FlowDocument document; BlockCollection blockCollection; - InlineCollection inlineCollection; + InlineCollection? inlineCollection; public DocumentationUIBuilder(IAmbience ambience, IHighlightingDefinition highlightingDefinition) { @@ -107,7 +107,7 @@ public void AddCodeBlock(string textContent, bool keepLargeMargin = false) AddBlock(block); } - public void AddSignatureBlock(string signature, RichTextModel highlighting = null) + public void AddSignatureBlock(string signature, RichTextModel? highlighting = null) { var document = new TextDocument(signature); var richText = highlighting ?? DocumentPrinter.ConvertTextDocumentToRichText(document, new DocumentHighlighter(document, highlightingDefinition)).ToRichTextModel(); diff --git a/ILSpy/TextView/UIElementGenerator.cs b/ILSpy/TextView/UIElementGenerator.cs index 0d0f90cba1..26a763fd52 100644 --- a/ILSpy/TextView/UIElementGenerator.cs +++ b/ILSpy/TextView/UIElementGenerator.cs @@ -24,7 +24,7 @@ namespace ICSharpCode.ILSpy.TextView { - using Pair = KeyValuePair>; + using Pair = KeyValuePair?>; /// /// Embeds UIElements in the text output. @@ -36,7 +36,7 @@ sealed class UIElementGenerator : VisualLineElementGenerator, IComparer /// We store this as a sorted list of (offset, Lazy<UIElement>) pairs. /// The "Lazy" part is used to create UIElements on demand (and thus on the UI thread, not on the decompiler thread). /// - public List UIElements; + public List? UIElements; public override int GetFirstInterestedOffset(int startOffset) { diff --git a/ILSpy/TreeNodes/AssemblyTreeNode.cs b/ILSpy/TreeNodes/AssemblyTreeNode.cs index fb108dfaab..c0540530e7 100644 --- a/ILSpy/TreeNodes/AssemblyTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyTreeNode.cs @@ -61,7 +61,7 @@ public AssemblyTreeNode(LoadedAssembly assembly) : this(assembly, null) { } - internal AssemblyTreeNode(LoadedAssembly assembly, PackageEntry packageEntry) + internal AssemblyTreeNode(LoadedAssembly assembly, PackageEntry? packageEntry) { this.LoadedAssembly = assembly ?? throw new ArgumentNullException(nameof(assembly)); this.LazyLoading = true; @@ -79,7 +79,7 @@ public AssemblyList AssemblyList { /// If this assembly was loaded from a bundle; this property returns the bundle entry that the /// assembly was loaded from. /// - public PackageEntry PackageEntry { get; } + public PackageEntry? PackageEntry { get; } public override bool IsAutoLoaded { get { @@ -124,7 +124,7 @@ public override object Icon { } } - TextBlock tooltip; + TextBlock? tooltip; public override object ToolTip { get { diff --git a/ILSpy/TreeNodes/PackageFolderTreeNode.cs b/ILSpy/TreeNodes/PackageFolderTreeNode.cs index 9fc528b3f1..b6f7432884 100644 --- a/ILSpy/TreeNodes/PackageFolderTreeNode.cs +++ b/ILSpy/TreeNodes/PackageFolderTreeNode.cs @@ -33,7 +33,7 @@ sealed class PackageFolderTreeNode : ILSpyTreeNode { readonly PackageFolder folder; - public PackageFolderTreeNode(PackageFolder folder, string text = null) + public PackageFolderTreeNode(PackageFolder folder, string? text = null) { this.folder = folder; this.Text = text ?? folder.Name; diff --git a/ILSpy/TreeNodes/ThreadingSupport.cs b/ILSpy/TreeNodes/ThreadingSupport.cs index a1d66245a4..c42c7cba70 100644 --- a/ILSpy/TreeNodes/ThreadingSupport.cs +++ b/ILSpy/TreeNodes/ThreadingSupport.cs @@ -40,7 +40,7 @@ class ThreadingSupport { readonly Stopwatch stopwatch = new Stopwatch(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - Task> loadChildrenTask; + Task>? loadChildrenTask; public bool IsRunning { get { return loadChildrenTask != null && !loadChildrenTask.IsCompleted; } diff --git a/ILSpy/ViewModels/ManageAssemblyListsViewModel.cs b/ILSpy/ViewModels/ManageAssemblyListsViewModel.cs index ec039552f3..4b88b4dbeb 100644 --- a/ILSpy/ViewModels/ManageAssemblyListsViewModel.cs +++ b/ILSpy/ViewModels/ManageAssemblyListsViewModel.cs @@ -101,9 +101,9 @@ IEnumerable ResolvePreconfiguredAssemblyLists() public List PreconfiguredAssemblyLists { get; } - private string selectedAssemblyList; + private string? selectedAssemblyList; - public string SelectedAssemblyList { + public string? SelectedAssemblyList { get => selectedAssemblyList; set { if (selectedAssemblyList != value) @@ -283,7 +283,7 @@ public class PreconfiguredAssemblyList public string Name { get; } public string Path { get; } - public PreconfiguredAssemblyList(string name, string path = null) + public PreconfiguredAssemblyList(string name, string? path = null) { this.Name = name; this.Path = path; From 6312e594a7fbf0d1a68f6f0c67ea8d7dac65c05d Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 18:27:28 -0400 Subject: [PATCH 14/15] fix build errors from merge --- ILSpy/App.xaml.cs | 8 ++-- ILSpy/AssemblyTree/AssemblyTreeModel.cs | 52 +++++++++++----------- ILSpy/ContextMenuEntry.cs | 2 +- ILSpy/Docking/DockWorkspace.cs | 2 +- ILSpy/MainWindow.xaml.cs | 1 - ILSpy/Options/DisplaySettingsPanel.xaml.cs | 4 +- ILSpy/Options/OptionsDialog.xaml.cs | 2 +- ILSpy/SessionSettings.cs | 6 +-- ILSpy/Views/DebugSteps.xaml.cs | 4 +- 9 files changed, 38 insertions(+), 43 deletions(-) diff --git a/ILSpy/App.xaml.cs b/ILSpy/App.xaml.cs index a5027f08ec..5494bd85d7 100644 --- a/ILSpy/App.xaml.cs +++ b/ILSpy/App.xaml.cs @@ -18,13 +18,14 @@ using System; using System.Collections.Generic; -using System.ComponentModel.Composition.Hosting; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Documents; @@ -33,8 +34,8 @@ using ICSharpCode.ILSpy.AppEnv; using ICSharpCode.ILSpy.AssemblyTree; +using ICSharpCode.ILSpy.Themes; using ICSharpCode.ILSpyX.Analyzers; -using ICSharpCode.ILSpyX.Settings; using ICSharpCode.ILSpyX.TreeView; using Medo.Application; @@ -43,9 +44,6 @@ using TomsToolbox.Composition; using TomsToolbox.Wpf.Composition; -using ICSharpCode.ILSpy.Themes; -using System.Globalization; -using System.Threading; using TomsToolbox.Wpf.Styles; namespace ICSharpCode.ILSpy diff --git a/ILSpy/AssemblyTree/AssemblyTreeModel.cs b/ILSpy/AssemblyTree/AssemblyTreeModel.cs index 1c6903a552..2e3f1a5d4a 100644 --- a/ILSpy/AssemblyTree/AssemblyTreeModel.cs +++ b/ILSpy/AssemblyTree/AssemblyTreeModel.cs @@ -16,40 +16,38 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System.Collections.Generic; using System; +using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; using System.ComponentModel.Composition; using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Text; using System.Threading.Tasks; +using System.Windows; using System.Windows.Input; +using System.Windows.Navigation; using System.Windows.Threading; +using ICSharpCode.Decompiler; +using ICSharpCode.Decompiler.Documentation; +using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; +using ICSharpCode.Decompiler.TypeSystem.Implementation; +using ICSharpCode.ILSpy.AppEnv; using ICSharpCode.ILSpy.Docking; using ICSharpCode.ILSpy.Properties; +using ICSharpCode.ILSpy.Search; using ICSharpCode.ILSpy.TextView; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpy.ViewModels; using ICSharpCode.ILSpyX; using ICSharpCode.ILSpyX.Settings; using ICSharpCode.ILSpyX.TreeView; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Linq; -using ICSharpCode.Decompiler.Metadata; - -using System.Reflection.Metadata.Ecma335; -using System.Windows; -using ICSharpCode.Decompiler.Documentation; -using ICSharpCode.Decompiler.TypeSystem.Implementation; -using System.Reflection.Metadata; -using System.Text; -using System.Windows.Navigation; - -using ICSharpCode.ILSpy.AppEnv; -using ICSharpCode.ILSpy.Search; -using ICSharpCode.Decompiler; using TomsToolbox.Essentials; using TomsToolbox.Wpf; @@ -121,8 +119,8 @@ public SharpTreeNode Root { set => SetProperty(ref root, value); } - private SharpTreeNode selectedItem; - public SharpTreeNode SelectedItem { + private SharpTreeNode? selectedItem; + public SharpTreeNode? SelectedItem { get => selectedItem; set => SetProperty(ref selectedItem, value); } @@ -145,7 +143,7 @@ public bool HandleCommandLineArguments(CommandLineArguments args) /// Called on startup or when passed arguments via WndProc from a second instance. /// In the format case, spySettings is non-null; in the latter it is null. /// - public void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args, ISettingsProvider spySettings = null) + public void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args, ISettingsProvider? spySettings = null) { var sessionSettings = SettingsService.Instance.SessionSettings; @@ -432,7 +430,7 @@ void ShowAssemblyList(AssemblyList assemblyList) #endif } - void assemblyList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + void assemblyList_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { @@ -595,7 +593,7 @@ public ILSpyTreeNode FindTreeNode(object reference) } } - private void JumpToReference(object sender, NavigateToReferenceEventArgs e) + private void JumpToReference(object? sender, NavigateToReferenceEventArgs e) { JumpToReferenceAsync(e.Reference, e.InNewTabPage).HandleExceptions(); } @@ -655,11 +653,11 @@ private Task JumpToReferenceAsync(object reference, bool inNewTabPage = false) #endregion - public void LoadAssemblies(IEnumerable fileNames, List loadedAssemblies = null, bool focusNode = true) + public void LoadAssemblies(IEnumerable fileNames, List? loadedAssemblies = null, bool focusNode = true) { using (Keyboard.FocusedElement.PreserveFocus(!focusNode)) { - AssemblyTreeNode lastNode = null; + AssemblyTreeNode? lastNode = null; foreach (string file in fileNames) { @@ -717,7 +715,7 @@ void TreeView_SelectionChanged() return; - void ContextMenuClosed(object sender, EventArgs e) + void ContextMenuClosed(object? sender, EventArgs e) { ContextMenuProvider.ContextMenuClosed -= ContextMenuClosed; @@ -730,7 +728,7 @@ void ContextMenuClosed(object sender, EventArgs e) } } - private void DecompileSelectedNodes(DecompilerTextViewState newState = null) + private void DecompileSelectedNodes(DecompilerTextViewState? newState = null) { var activeTabPage = DockWorkspace.Instance.ActiveTabPage; @@ -882,7 +880,7 @@ public void SortAssemblyList() private class AssemblyComparer : IComparer { public static readonly AssemblyComparer Instance = new(); - int IComparer.Compare(LoadedAssembly x, LoadedAssembly y) + int IComparer.Compare(LoadedAssembly? x, LoadedAssembly? y) { return string.Compare(x?.ShortName, y?.ShortName, StringComparison.CurrentCulture); } diff --git a/ILSpy/ContextMenuEntry.cs b/ILSpy/ContextMenuEntry.cs index f4a96d1877..ce581f6e26 100644 --- a/ILSpy/ContextMenuEntry.cs +++ b/ILSpy/ContextMenuEntry.cs @@ -90,7 +90,7 @@ public class TextViewContext /// public DependencyObject OriginalSource { get; private set; } - public static TextViewContext Create(ContextMenuEventArgs eventArgs, SharpTreeView?? treeView = null, DecompilerTextView textView = null, ListBox? listBox = null, DataGrid? dataGrid = null) + public static TextViewContext Create(ContextMenuEventArgs eventArgs, SharpTreeView? treeView = null, DecompilerTextView? textView = null, ListBox? listBox = null, DataGrid? dataGrid = null) { ReferenceSegment? reference; diff --git a/ILSpy/Docking/DockWorkspace.cs b/ILSpy/Docking/DockWorkspace.cs index 2b1765b3d2..7a7251d1ef 100644 --- a/ILSpy/Docking/DockWorkspace.cs +++ b/ILSpy/Docking/DockWorkspace.cs @@ -110,7 +110,7 @@ private void TabPages_CollectionChanged(object? sender, NotifyCollectionChangedE } } - public void AddTabPage(TabPageModel tabPage = null) + public void AddTabPage(TabPageModel? tabPage = null) { tabPages.Add(tabPage ?? new TabPageModel()); } diff --git a/ILSpy/MainWindow.xaml.cs b/ILSpy/MainWindow.xaml.cs index f3668f6f05..eb0b2288f1 100644 --- a/ILSpy/MainWindow.xaml.cs +++ b/ILSpy/MainWindow.xaml.cs @@ -29,7 +29,6 @@ using AvalonDock.Layout.Serialization; using ICSharpCode.ILSpy.AssemblyTree; -using ICSharpCode.ILSpy.Docking; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpy.Updates; using ICSharpCode.ILSpyX.FileLoaders; diff --git a/ILSpy/Options/DisplaySettingsPanel.xaml.cs b/ILSpy/Options/DisplaySettingsPanel.xaml.cs index 3b51a16ba3..66c965b2ab 100644 --- a/ILSpy/Options/DisplaySettingsPanel.xaml.cs +++ b/ILSpy/Options/DisplaySettingsPanel.xaml.cs @@ -69,7 +69,7 @@ private static void OnPaste(object sender, DataObjectPastingEventArgs e) public sealed class FontSizeConverter : ValueConverter { - protected override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + protected override object Convert(object value, Type? targetType, object? parameter, System.Globalization.CultureInfo? culture) { if (value is double d) { @@ -79,7 +79,7 @@ protected override object Convert(object value, Type targetType, object paramete return DependencyProperty.UnsetValue; } - protected override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + protected override object ConvertBack(object value, Type? targetType, object? parameter, System.Globalization.CultureInfo? culture) { if (value is not string s) return DependencyProperty.UnsetValue; diff --git a/ILSpy/Options/OptionsDialog.xaml.cs b/ILSpy/Options/OptionsDialog.xaml.cs index 7834881758..79323e5b81 100644 --- a/ILSpy/Options/OptionsDialog.xaml.cs +++ b/ILSpy/Options/OptionsDialog.xaml.cs @@ -69,7 +69,7 @@ public ShowOptionsCommand(AssemblyTreeModel assemblyTreeModel) this.assemblyTreeModel = assemblyTreeModel; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { OptionsDialog dlg = new() { Owner = MainWindow.Instance, diff --git a/ILSpy/SessionSettings.cs b/ILSpy/SessionSettings.cs index ddd9f78269..e76544b193 100644 --- a/ILSpy/SessionSettings.cs +++ b/ILSpy/SessionSettings.cs @@ -180,14 +180,14 @@ static string ToString(T obj) return c.ConvertToInvariantString(obj); } - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - private void OnPropertyChanged([CallerMemberName] string propertyName = null) + private void OnPropertyChanged([CallerMemberName] string? propertyName = null) { PropertyChanged?.Invoke(this, new(propertyName)); } - private bool SetProperty(ref T field, T value, [CallerMemberName] string propertyName = null) + private bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null) { if (EqualityComparer.Default.Equals(field, value)) return false; diff --git a/ILSpy/Views/DebugSteps.xaml.cs b/ILSpy/Views/DebugSteps.xaml.cs index b7336a43bc..42cb93f959 100644 --- a/ILSpy/Views/DebugSteps.xaml.cs +++ b/ILSpy/Views/DebugSteps.xaml.cs @@ -52,7 +52,7 @@ private void WritingOptions_PropertyChanged(object? sender, System.ComponentMode DecompileAsync(lastSelectedStep); } - private void SelectionChanged(object sender, EventArgs e) + private void SelectionChanged(object? sender, EventArgs e) { Dispatcher.Invoke(() => { tree.ItemsSource = null; @@ -60,7 +60,7 @@ private void SelectionChanged(object sender, EventArgs e) }); } - private void Settings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + private void Settings_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { #if DEBUG if (sender is not LanguageSettings) From b63837e4660e04aa6baabe1a96c3391f48402280 Mon Sep 17 00:00:00 2001 From: apmoskevitz Date: Mon, 23 Sep 2024 18:53:15 -0400 Subject: [PATCH 15/15] fixed conversions tests failing by adding a polyfill for the frameworks that do not have the nullability attributes --- .../Util/CSharpPrimitiveCast.cs | 38 ++++++++++++++++++- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs b/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs index 015251fe9b..f39ee44048 100644 --- a/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs +++ b/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs @@ -35,8 +35,10 @@ public static class CSharpPrimitiveCast /// /// Overflow checking is enabled and an overflow occurred. /// The cast is invalid, e.g. casting a boolean to an integer. - //[return: MaybeNull] - //[return: NotNullIfNotNull(nameof(input))] + /// + + [return: MaybeNull] + [return: NotNullIfNotNull("input")] public static object Cast(TypeCode targetType, [MaybeNull] object input, bool checkForOverflow) { if (input == null) @@ -772,3 +774,35 @@ static object CSharpPrimitiveCastUnchecked(TypeCode targetType, object input) } } } +#if (!NETSTANDARD2_0_OR_GREATER && !NETCORE) || MCS +namespace System.Diagnostics.CodeAnalysis +{ + /// Specifies that the output will be non-null if the named parameter is non-null. + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] + internal sealed class NotNullIfNotNullAttribute : Attribute + { + /// Initializes the attribute with the associated parameter name. + /// + /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. + /// + public NotNullIfNotNullAttribute(string parameterName) + { + ParameterName = parameterName; + } + private string _parameterName; + /// Gets the associated parameter name. + public string ParameterName { + get { + return _parameterName; + } + private set { + _parameterName = value; + } + } + } + + /// Specifies that an output may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] + internal sealed class MaybeNullAttribute : Attribute { } +} +#endif \ No newline at end of file