diff --git a/.editorconfig b/.editorconfig index 1ea262ade..6c1c8d12e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -147,3 +147,63 @@ dotnet_naming_rule.private_fields_rule.symbols = private_fields_symbols # MEF006: No importing constructor dotnet_diagnostic.MEF006.severity = silent + + +dotnet_diagnostic.IDE2003.severity = silent + +#nullability diagnostics +dotnet_diagnostic.CS8597.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 +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.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 +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 + + diff --git a/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs b/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs index 21a2e733f..797db27cc 100644 --- a/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs +++ b/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs @@ -37,7 +37,7 @@ namespace ICSharpCode.BamlDecompiler.Baml 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 @@ namespace ICSharpCode.BamlDecompiler.Baml 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)) @@ -116,7 +116,7 @@ namespace ICSharpCode.BamlDecompiler.Baml 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 c8049a668..89062e129 100644 --- a/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs +++ b/ICSharpCode.BamlDecompiler/Baml/BamlNode.cs @@ -111,7 +111,7 @@ namespace ICSharpCode.BamlDecompiler.Baml { 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 bed8f934a..5137c2fce 100644 --- a/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs +++ b/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs @@ -91,7 +91,7 @@ namespace ICSharpCode.BamlDecompiler.Baml 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/BamlDecompilerSettings.cs b/ICSharpCode.BamlDecompiler/BamlDecompilerSettings.cs index 4f0891560..b8ce8b69e 100644 --- a/ICSharpCode.BamlDecompiler/BamlDecompilerSettings.cs +++ b/ICSharpCode.BamlDecompiler/BamlDecompilerSettings.cs @@ -37,9 +37,9 @@ namespace ICSharpCode.BamlDecompiler } } - 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/BamlElement.cs b/ICSharpCode.BamlDecompiler/BamlElement.cs index 0e546a474..7e2553b8c 100644 --- a/ICSharpCode.BamlDecompiler/BamlElement.cs +++ b/ICSharpCode.BamlDecompiler/BamlElement.cs @@ -41,13 +41,13 @@ namespace ICSharpCode.BamlDecompiler 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 @@ namespace ICSharpCode.BamlDecompiler 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 844c82528..e204ab042 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/ConstructorParametersHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/ConstructorParametersHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 8f543271f..347b61d6f 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/DocumentHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/DocumentHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 351fbd388..49b8c3157 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/ElementHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/ElementHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 366b8d93a..80acd5df0 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/KeyElementStartHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/KeyElementStartHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 c4b20965f..b92fc9d8f 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 e20ae0155..4560e8193 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyComplexHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyComplexHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 15a262680..084978475 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyDictionaryHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyDictionaryHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 a7041d9cf..2f934399e 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyListHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyListHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 24c0dfe65..9ea3037bf 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/AssemblyInfoHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/AssemblyInfoHandler.cs @@ -28,6 +28,6 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 bcada0571..690833c10 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/AttributeInfoHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/AttributeInfoHandler.cs @@ -28,6 +28,6 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 a0b9f9bb1..320f3f149 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/ConnectionIdHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/ConnectionIdHandler.cs @@ -28,7 +28,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 a6ba8047e..cf0449e2c 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/ConstructorParameterTypeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/ConstructorParameterTypeHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 3f95e62de..7d53382c8 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/ContentPropertyHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/ContentPropertyHandler.cs @@ -28,7 +28,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 f8ac9786e..01adead25 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 c8df69349..2ce607fa0 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyStringHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyStringHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 82a2d82a0..e0689ff56 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyTypeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DefAttributeKeyTypeHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 65385bf1c..179901713 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/DeferableContentStartHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/DeferableContentStartHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 6398b2f3e..c79773805 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/LineNumberAndPositionHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/LineNumberAndPositionHandler.cs @@ -28,6 +28,6 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 feb1c36aa..16e439df4 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/LinePositionHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/LinePositionHandler.cs @@ -28,6 +28,6 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 f53b3fd5f..f8b7ef25d 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/LiteralContentHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/LiteralContentHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 520392349..15976101b 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/OptimizedStaticResourceHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/OptimizedStaticResourceHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 e32ba8a4e..f68bf73f4 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PIMappingHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PIMappingHandler.cs @@ -28,6 +28,6 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 f4d13ebdb..0a584a614 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PresentationOptionsAttributeHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PresentationOptionsAttributeHandler.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 c62f2fa4a..0b01a5760 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyCustomHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyCustomHandler.cs @@ -179,7 +179,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers 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 e50002ceb..49e24a617 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 9405d210d..5e24ae7c2 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyTypeReferenceHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyTypeReferenceHandler.cs @@ -22,10 +22,9 @@ 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 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 034b6aac6..5515e0530 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithExtensionHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithExtensionHandler.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 a701316e9..3a2bbd756 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs @@ -32,7 +32,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 @@ namespace ICSharpCode.BamlDecompiler.Handlers 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 b0f62432c..f5cbca319 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceIdHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceIdHandler.cs @@ -27,12 +27,12 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 37857e14e..08fd3f7f8 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceStartHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/StaticResourceStartHandler.cs @@ -29,7 +29,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 fc41caf5e..93ccce0a9 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/TextHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/TextHandler.cs @@ -28,7 +28,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 583c680d5..2e929ccfa 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/TypeInfoHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/TypeInfoHandler.cs @@ -28,13 +28,13 @@ namespace ICSharpCode.BamlDecompiler.Handlers { 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 399dd7d4d..1c5d5c48d 100644 --- a/ICSharpCode.BamlDecompiler/Handlers/Records/XmlnsPropertyHandler.cs +++ b/ICSharpCode.BamlDecompiler/Handlers/Records/XmlnsPropertyHandler.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.BamlDecompiler.Handlers } } - 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/ICSharpCode.BamlDecompiler.csproj b/ICSharpCode.BamlDecompiler/ICSharpCode.BamlDecompiler.csproj index cd022af4b..9acb0192b 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.BamlDecompiler/IHandlers.cs b/ICSharpCode.BamlDecompiler/IHandlers.cs index c373f0bf2..067a9e173 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 104f6343b..8a2280033 100644 --- a/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs +++ b/ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs @@ -22,15 +22,16 @@ using System.Linq; 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 @@ -126,7 +127,7 @@ namespace ICSharpCode.BamlDecompiler.Rewrite 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; @@ -249,7 +250,7 @@ namespace ICSharpCode.BamlDecompiler.Rewrite } } - 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 @@ namespace ICSharpCode.BamlDecompiler.Rewrite // 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 @@ namespace ICSharpCode.BamlDecompiler.Rewrite 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.BamlDecompiler/Xaml/NamespaceMap.cs b/ICSharpCode.BamlDecompiler/Xaml/NamespaceMap.cs index 6523c2be7..19cc97234 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 6372f2a0c..097f2f558 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/XamlProperty.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/XamlProperty.cs @@ -82,7 +82,7 @@ namespace ICSharpCode.BamlDecompiler.Xaml 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 7e642fd05..ba9cb583f 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/XamlResourceKey.cs @@ -78,7 +78,7 @@ namespace ICSharpCode.BamlDecompiler.Xaml 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 @@ namespace ICSharpCode.BamlDecompiler.Xaml 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 f2f907572..ca7dd2134 100644 --- a/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs +++ b/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs @@ -37,7 +37,7 @@ namespace ICSharpCode.BamlDecompiler.Xaml 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 @@ namespace ICSharpCode.BamlDecompiler.Xaml { } - 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; @@ -62,7 +62,7 @@ namespace ICSharpCode.BamlDecompiler.Xaml // 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 bd24cbeaf..a0f56f96a 100644 --- a/ICSharpCode.BamlDecompiler/XamlContext.cs +++ b/ICSharpCode.BamlDecompiler/XamlContext.cs @@ -27,10 +27,9 @@ using System.Reflection.Metadata; 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 { @@ -143,7 +142,7 @@ namespace ICSharpCode.BamlDecompiler XamlType type; string name; - IMember member; + IMember? member; if (id > 0x7fff) { @@ -207,8 +206,8 @@ namespace ICSharpCode.BamlDecompiler 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 @@ namespace ICSharpCode.BamlDecompiler 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 74f7f7f0d..ba4c1be60 100644 --- a/ICSharpCode.BamlDecompiler/XmlnsDictionary.cs +++ b/ICSharpCode.BamlDecompiler/XmlnsDictionary.cs @@ -22,11 +22,10 @@ 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 @@ namespace ICSharpCode.BamlDecompiler 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 e94175e80..7f395e166 100644 --- a/ICSharpCode.Decompiler.PowerShell/GetDecompiledProjectCmdlet.cs +++ b/ICSharpCode.Decompiler.PowerShell/GetDecompiledProjectCmdlet.cs @@ -25,7 +25,7 @@ namespace ICSharpCode.Decompiler.PowerShell readonly object syncObject = new object(); int completed; string fileName; - ProgressRecord progress; + ProgressRecord? progress; public void Report(DecompilationProgress value) { diff --git a/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj b/ICSharpCode.Decompiler.PowerShell/ICSharpCode.Decompiler.PowerShell.csproj index f5d58901f..3c3e0fa1d 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.Tests/Semantics/OverloadResolutionTests.cs b/ICSharpCode.Decompiler.Tests/Semantics/OverloadResolutionTests.cs index cabe83281..c36ba760a 100644 --- a/ICSharpCode.Decompiler.Tests/Semantics/OverloadResolutionTests.cs +++ b/ICSharpCode.Decompiler.Tests/Semantics/OverloadResolutionTests.cs @@ -258,7 +258,7 @@ namespace ICSharpCode.Decompiler.Tests.Semantics get { throw new NotImplementedException(); } } - public override IType GetInferredReturnType(IType[] parameterTypes) + public override IType GetInferredReturnType(IType[]? parameterTypes) { return inferredReturnType; } diff --git a/ICSharpCode.Decompiler/CSharp/Annotations.cs b/ICSharpCode.Decompiler/CSharp/Annotations.cs index 30f221db1..935963454 100644 --- a/ICSharpCode.Decompiler/CSharp/Annotations.cs +++ b/ICSharpCode.Decompiler/CSharp/Annotations.cs @@ -134,7 +134,7 @@ namespace ICSharpCode.Decompiler.CSharp /// 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 @@ namespace ICSharpCode.Decompiler.CSharp /// 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 @@ namespace ICSharpCode.Decompiler.CSharp /// 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 @@ namespace ICSharpCode.Decompiler.CSharp /// 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 520619787..7fd38be1a 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 @@ namespace ICSharpCode.Decompiler.CSharp 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); @@ -540,7 +541,7 @@ namespace ICSharpCode.Decompiler.CSharp return typeSystemAstBuilder; } - IDocumentationProvider CreateDefaultDocumentationProvider() + IDocumentationProvider? CreateDefaultDocumentationProvider() { try { @@ -631,8 +632,8 @@ namespace ICSharpCode.Decompiler.CSharp 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 +1028,7 @@ namespace ICSharpCode.Decompiler.CSharp } bool first = true; - ITypeDefinition parentTypeDef = null; + ITypeDefinition? parentTypeDef = null; foreach (var entity in definitions) { @@ -1095,7 +1096,7 @@ namespace ICSharpCode.Decompiler.CSharp return syntaxTree; } - ITypeDefinition FindCommonDeclaringTypeDefinition(ITypeDefinition a, ITypeDefinition b) + ITypeDefinition? FindCommonDeclaringTypeDefinition(ITypeDefinition a, ITypeDefinition b) { if (a == null || b == null) return null; @@ -1212,7 +1213,7 @@ namespace ICSharpCode.Decompiler.CSharp /// 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(); @@ -1315,7 +1316,7 @@ namespace ICSharpCode.Decompiler.CSharp 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); @@ -1324,7 +1325,7 @@ namespace ICSharpCode.Decompiler.CSharp 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) { @@ -1566,7 +1567,7 @@ namespace ICSharpCode.Decompiler.CSharp { 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); @@ -1779,7 +1780,7 @@ namespace ICSharpCode.Decompiler.CSharp ); 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); @@ -1799,7 +1800,8 @@ namespace ICSharpCode.Decompiler.CSharp 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)) @@ -1916,7 +1918,7 @@ namespace ICSharpCode.Decompiler.CSharp 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) @@ -1956,7 +1958,7 @@ namespace ICSharpCode.Decompiler.CSharp 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); @@ -2016,11 +2018,11 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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; - 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 56f420e07..15f5c8705 100644 --- a/ICSharpCode.Decompiler/CSharp/CallBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/CallBuilder.cs @@ -20,6 +20,7 @@ using System; 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp { for (int i = 0; i < Arguments.Length; i++) { - string inferredName; + string? inferredName; switch (Arguments[i].Expression) { case IdentifierExpression identifier: @@ -188,13 +189,13 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp var expectedTargetDetails = new ExpectedTargetDetails { CallOpCode = callOpCode }; - ILFunction localFunction = null; + ILFunction? localFunction = null; if (method.IsLocalFunction) { localFunction = expressionBuilder.ResolveLocalFunction(method); @@ -523,7 +525,7 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp argument = new TranslatedExpression(element, arrayCreationRR.InitializerElements.First()); } - if (tokens.Count == 0) + if (tokens == null || tokens.Count == 0) { return default; } @@ -655,7 +657,7 @@ namespace ICSharpCode.Decompiler.CSharp } 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 @@ namespace ICSharpCode.Decompiler.CSharp ); } - 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; @@ -707,9 +709,9 @@ namespace ICSharpCode.Decompiler.CSharp 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; + format = (string?)crr.ConstantValue; foreach (var (kind, data) in TokenizeFormatString(format)) { int index; @@ -775,7 +777,7 @@ namespace ICSharpCode.Decompiler.CSharp ArgumentWithAlignmentAndFormat, } - private IEnumerable<(TokenKind, string)> TokenizeFormatString(string value) + private IEnumerable<(TokenKind, string?)> TokenizeFormatString(string value) { int pos = -1; @@ -867,14 +869,14 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp } 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 @@ namespace ICSharpCode.Decompiler.CSharp // initialize requireTarget flag bool requireTarget; - ResolveResult targetResolveResult; + ResolveResult? targetResolveResult; if ((allowedTransforms & CallTransformation.RequireTarget) != 0) { if (settings.AlwaysQualifyMemberReferences || expressionBuilder.HidesVariableWithName(method.Name)) @@ -1393,9 +1395,9 @@ namespace ICSharpCode.Decompiler.CSharp } OverloadResolutionErrors IsUnambiguousCall(ExpectedTargetDetails expectedTargetDetails, IMethod method, - ResolveResult target, IType[] typeArguments, ResolveResult[] arguments, - string[] argumentNames, int firstOptionalArgumentIndex, - out IParameterizedMember foundMember, out bool bestCandidateIsExpandedForm) + ResolveResult? target, IType[] typeArguments, ResolveResult[] arguments, + string[]? argumentNames, int firstOptionalArgumentIndex, + out IParameterizedMember? foundMember, out bool bestCandidateIsExpandedForm) { foundMember = null; bestCandidateIsExpandedForm = false; @@ -1504,7 +1506,7 @@ namespace ICSharpCode.Decompiler.CSharp } 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 @@ namespace ICSharpCode.Decompiler.CSharp } 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)) @@ -1572,7 +1574,7 @@ namespace ICSharpCode.Decompiler.CSharp arguments.Remove(value); } - IMember foundMember; + IMember? foundMember; while (!IsUnambiguousAccess(expectedTargetDetails, targetResolveResult, method, arguments, argumentNames, out foundMember)) { if (!argumentsCasted) @@ -1674,7 +1676,7 @@ namespace ICSharpCode.Decompiler.CSharp 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()) { @@ -1715,7 +1717,7 @@ namespace ICSharpCode.Decompiler.CSharp 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), @@ -1821,11 +1823,11 @@ namespace ICSharpCode.Decompiler.CSharp 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; - (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); @@ -1848,11 +1850,11 @@ namespace ICSharpCode.Decompiler.CSharp } - (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)); } @@ -1932,7 +1934,7 @@ namespace ICSharpCode.Decompiler.CSharp 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; @@ -1981,7 +1983,7 @@ namespace ICSharpCode.Decompiler.CSharp 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 0f629f38e..f187b3c43 100644 --- a/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs @@ -153,7 +153,7 @@ namespace ICSharpCode.Decompiler.CSharp } } - public TranslatedExpression Translate(ILInstruction inst, IType typeHint = null) + public TranslatedExpression Translate(ILInstruction inst, IType? typeHint = null) { Debug.Assert(inst != null); cancellationToken.ThrowIfCancellationRequested(); @@ -265,7 +265,7 @@ namespace ICSharpCode.Decompiler.CSharp } } - internal ILFunction ResolveLocalFunction(IMethod method) + internal ILFunction? ResolveLocalFunction(IMethod method) { Debug.Assert(method.IsLocalFunction); method = (IMethod)((IMethod)method.MemberDefinition).ReducedFrom.MemberDefinition; @@ -289,7 +289,7 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp { Expression expr; IType constantType; - object constantValue; + object? constantValue; if (type.IsReferenceType == true || type.IsKnownType(KnownTypeCode.NullableOfT)) { expr = new NullReferenceExpression(); @@ -960,7 +960,7 @@ namespace ICSharpCode.Decompiler.CSharp .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 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp ); 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); @@ -2535,7 +2535,7 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ -2544,7 +2544,8 @@ namespace ICSharpCode.Decompiler.CSharp 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) { @@ -2612,7 +2613,7 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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. @@ -2987,7 +2988,7 @@ namespace ICSharpCode.Decompiler.CSharp 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); @@ -3393,7 +3394,7 @@ namespace ICSharpCode.Decompiler.CSharp 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)) { @@ -3544,7 +3545,7 @@ namespace ICSharpCode.Decompiler.CSharp { 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!"); @@ -3563,11 +3564,11 @@ namespace ICSharpCode.Decompiler.CSharp 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) { @@ -3602,7 +3603,7 @@ namespace ICSharpCode.Decompiler.CSharp } } ArraySpecifier[] additionalSpecifiers; - AstType typeExpression; + AstType? typeExpression; if (settings.AnonymousTypes && type.ContainsAnonymousType()) { typeExpression = null; @@ -3916,7 +3917,8 @@ namespace ICSharpCode.Decompiler.CSharp { TranslatedExpression value; IType type; - if (inst.Value is StringToInt strToInt) + var strToInt = inst.Value as StringToInt; + if (strToInt != null) { value = Translate(strToInt.Argument) .ConvertTo( @@ -4023,7 +4025,7 @@ namespace ICSharpCode.Decompiler.CSharp protected internal override TranslatedExpression VisitAwait(Await inst, TranslationContext context) { - IType expectedType = null; + IType? expectedType = null; if (inst.GetAwaiterMethod != null) { if (inst.GetAwaiterMethod.IsStatic) @@ -4533,7 +4535,7 @@ namespace ICSharpCode.Decompiler.CSharp { if (subPattern.HasDesignator) { - if (!conversionMapping.TryGetValue(subPattern.Variable, out ILVariable value)) + if (!conversionMapping.TryGetValue(subPattern.Variable, out ILVariable? value)) { value = subPattern.Variable; } @@ -4638,7 +4640,7 @@ namespace ICSharpCode.Decompiler.CSharp 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/CSharpAmbience.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs index beac7989c..97e92e15b 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs @@ -58,7 +58,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 96d591dab..be451afa2 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs @@ -92,7 +92,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor /// /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor /// /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor /// /// 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) @@ -200,7 +200,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor NewLine(); return; } - BlockStatement block = embeddedStatement as BlockStatement; + BlockStatement? block = embeddedStatement as BlockStatement; if (block != null) { WriteBlock(block, policy.StatementBraceStyle); @@ -672,7 +672,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor { // "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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor if (typeDeclaration.ClassType == ClassType.Enum) { bool first = true; - AstNode last = null; + AstNode? last = null; foreach (var member in typeDeclaration.Members) { if (first) @@ -1947,7 +1947,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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) { @@ -2340,7 +2340,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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/GenericGrammarAmbiguityVisitor.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs index e7f372f96..b56c4f6de 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/GenericGrammarAmbiguityVisitor.cs @@ -53,7 +53,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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/ITokenWriter.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs index 9c8aa787e..539748931 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs @@ -46,7 +46,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor /// /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 8b637218d..55c49cb69 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertMissingTokensDecorator.cs @@ -105,20 +105,20 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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; } @@ -138,9 +138,9 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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; + Expression? node = nodes.Peek().LastOrDefault() as Expression; var startLocation = locationProvider.Location; base.WritePrimitiveValue(value, format); if (node is PrimitiveExpression) @@ -155,7 +155,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 2fb3a4546..e99715fec 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertParenthesesVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertParenthesesVisitor.cs @@ -218,7 +218,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor } // 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor } } // 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor // 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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/OutputVisitor/InsertRequiredSpacesDecorator.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs index 6da12dd60..70b90901b 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs @@ -148,7 +148,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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 61901cc9c..de9850ec8 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/InsertSpecialsDecorator.cs @@ -82,9 +82,9 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor /// /// 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) + for (AstNode? pos = start; pos != end; pos = pos.NextSibling) { if (pos.Role == Roles.Comment) { @@ -118,14 +118,14 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor WriteSpecialsUpToRole(role, null); } - void WriteSpecialsUpToRole(Role role, AstNode nextNode) + void WriteSpecialsUpToRole(Role role, AstNode? nextNode) { if (positionStack.Count == 0) { 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 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor { 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/OutputVisitor/TextWriterTokenWriter.cs b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs index e305cb98e..4c2bbf8a6 100644 --- a/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs +++ b/ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs @@ -233,7 +233,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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) { @@ -437,7 +437,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor /// 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) { @@ -499,7 +499,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor 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/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs index ee0029dc9..fc169285e 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/ProjectFileWriterSdkStyle.cs @@ -272,7 +272,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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 66279bbd3..ff8a2ecef 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetFramework.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler /// /// 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. @@ -79,7 +79,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler /// 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/TargetServices.cs b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs index adbf96fc4..b36a043ad 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/TargetServices.cs @@ -66,15 +66,15 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler break; } - string targetFrameworkIdentifier = null; - string targetFrameworkProfile = null; + string? targetFrameworkIdentifier = null; + string? targetFrameworkProfile = null; string targetFramework = module.DetectTargetFrameworkId(); if (!string.IsNullOrEmpty(targetFramework)) { 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 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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); } @@ -245,7 +245,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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 f8b687b73..b1e074e0e 100644 --- a/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs +++ b/ICSharpCode.Decompiler/CSharp/ProjectDecompiler/WholeProjectDecompiler.cs @@ -71,7 +71,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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; @@ -325,7 +325,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler { 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 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler { 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)); @@ -488,7 +488,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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) @@ -636,7 +636,7 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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 @@ namespace ICSharpCode.Decompiler.CSharp.ProjectDecompiler 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 1ddc179b3..91d77e1b6 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp } } - IMethod DetectPrimaryConstructor() + IMethod? DetectPrimaryConstructor() { if (recordTypeDef.IsRecord) { @@ -266,7 +267,7 @@ namespace ICSharpCode.Decompiler.CSharp /// /// 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; @@ -373,7 +374,7 @@ namespace ICSharpCode.Decompiler.CSharp && 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 @@ namespace ICSharpCode.Decompiler.CSharp { 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp { 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 @@ namespace ICSharpCode.Decompiler.CSharp } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp } } - Block DecompileBody(IMethod method) + Block? DecompileBody(IMethod method) { if (method == null || method.MetadataToken.IsNil) return null; diff --git a/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs b/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs index d304ad3fe..e181d9805 100644 --- a/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs +++ b/ICSharpCode.Decompiler/CSharp/RequiredNamespaceCollector.cs @@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.CSharp 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()); @@ -56,7 +56,7 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ namespace ICSharpCode.Decompiler.CSharp 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/AwaitResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs index 71ea5810c..156fa14f3 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs @@ -42,20 +42,20 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// /// 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 51ea71144..af1612277 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs @@ -56,7 +56,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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)); @@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver this.ToType = toType; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return (obj is TypePair) && Equals((TypePair)obj); } @@ -182,7 +182,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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); @@ -523,10 +523,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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) @@ -554,9 +554,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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; + ParameterizedType? pt = interfaceType as ParameterizedType; if (pt != null) { switch (pt.GetDefinition()?.KnownTypeCode) @@ -600,13 +600,13 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver bool IdentityOrVarianceConversion(IType s, IType t, int subtypeCheckNestingDepth) { - ITypeDefinition def = s.GetDefinition(); + ITypeDefinition? def = s.GetDefinition(); if (def != null) { 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 @@ -697,11 +697,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } 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; - 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 @@ -792,7 +792,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver #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; @@ -811,7 +811,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } else if (fromTypeCode == TypeCode.Int32) { - object cv = rr.ConstantValue; + object? cv = rr.ConstantValue; if (cv == null) return false; int val = (int)cv; @@ -938,9 +938,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver && (StandardImplicitConversion(a, b).IsValid || StandardImplicitConversion(b, a).IsValid); } - IType FindMostEncompassedType(IEnumerable candidates) + IType? FindMostEncompassedType(IEnumerable candidates) { - IType best = null; + IType? best = null; foreach (var current in candidates) { if (best == null || IsEncompassedBy(current, best)) @@ -951,9 +951,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver return best; } - IType FindMostEncompassingType(IEnumerable candidates) + IType? FindMostEncompassingType(IEnumerable candidates) { - IType best = null; + IType? best = null; foreach (var current in candidates) { if (best == null || IsEncompassedBy(best, current)) @@ -983,7 +983,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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; @@ -1179,7 +1179,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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) @@ -1482,9 +1482,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// /// 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; + 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 b6fa7c0e3..b6771041e 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpInvocationResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpInvocationResolveResult.cs @@ -57,9 +57,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 14ab787ba..a7197e22d 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs @@ -20,6 +20,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using ICSharpCode.Decompiler.CSharp.Syntax; @@ -154,7 +155,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver return WithContext(context.WithCurrentMember(member)); } - ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember member) + ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember? member) { return WithCurrentMember(member); } @@ -188,12 +189,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// /// Sets the current type definition. /// - public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition typeDefinition) + public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition? typeDefinition) { if (this.CurrentTypeDefinition == typeDefinition) return this; - TypeDefinitionCache newTypeDefinitionCache; + TypeDefinitionCache? newTypeDefinitionCache; if (typeDefinition != null) newTypeDefinitionCache = new TypeDefinitionCache(typeDefinition); else @@ -203,7 +204,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver checkForOverflow, isWithinLambdaExpression, newTypeDefinitionCache, localVariableStack, objectInitializerStack); } - ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition typeDefinition) + ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition? typeDefinition) { return WithCurrentTypeDefinition(typeDefinition); } @@ -344,7 +345,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 +358,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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) @@ -505,7 +506,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } else if (expression.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) { - object val; + object? val; try { val = m.Invoke(this, expression.ConstantValue); @@ -564,7 +565,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver #endregion #region GetOverloadableOperatorName - static string GetOverloadableOperatorName(UnaryOperatorType op) + static string? GetOverloadableOperatorName(UnaryOperatorType op) { switch (op) { @@ -922,7 +923,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } else if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) { - object val; + object? val; try { val = m.Invoke(this, lhs.ConstantValue, rhs.ConstantValue); @@ -979,9 +980,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver #endregion #region Enum helper methods - IType GetEnumUnderlyingType(IType enumType) + IType? GetEnumUnderlyingType(IType enumType) { - ITypeDefinition def = enumType.GetDefinition(); + ITypeDefinition? def = enumType.GetDefinition(); return def != null ? def.EnumUnderlyingType : SpecialType.UnknownType; } @@ -1202,7 +1203,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver #endregion #region GetOverloadableOperatorName - static string GetOverloadableOperatorName(BinaryOperatorType op) + static string? GetOverloadableOperatorName(BinaryOperatorType op) { switch (op) { @@ -1490,7 +1491,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } } // 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 +1505,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } // 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 +1518,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 +1598,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } } - 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)) { @@ -1608,12 +1609,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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) { @@ -1650,7 +1651,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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; @@ -1680,10 +1681,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // 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); + ITypeDefinition? def = importedNamespace.GetTypeDefinition(identifier, typeArguments.Count); if (def != null) { IType resultType; @@ -1711,7 +1712,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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; @@ -1719,7 +1720,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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)) @@ -1728,7 +1729,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } } // 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; @@ -1780,7 +1781,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver ResolveResult ResolveExternAlias(string alias) { - INamespace ns = compilation.GetNamespaceForExternAlias(alias); + INamespace? ns = compilation.GetNamespaceForExternAlias(alias); if (ns != null) return new NamespaceResolveResult(ns); else @@ -1794,7 +1795,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // 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 +1839,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } else { - MethodGroupResolveResult mgrr = result as MethodGroupResolveResult; + MethodGroupResolveResult? mgrr = result as MethodGroupResolveResult; if (mgrr != null) { Debug.Assert(mgrr.extensionMethods == null); @@ -1853,11 +1854,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver { 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) @@ -1914,7 +1915,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 +1959,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 +1971,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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; @@ -1984,13 +1985,13 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ -2030,7 +2031,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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 +2060,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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>(); @@ -2072,7 +2073,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver continue; if (!lookup.IsAccessible(method, false)) continue; - IType[] inferredTypes; + IType[]? inferredTypes; if (typeArguments != null && typeArguments.Count > 0) { if (method.TypeParameters.Count != typeArguments.Count) @@ -2117,7 +2118,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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)); @@ -2127,7 +2128,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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) @@ -2221,7 +2222,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver #region ResolveInvocation - IList AddArgumentNamesIfNecessary(ResolveResult[] arguments, string[] argumentNames) + IList AddArgumentNamesIfNecessary(ResolveResult[] arguments, string[]? argumentNames) { if (argumentNames == null) { @@ -2238,7 +2239,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } } - 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 @@ -2248,7 +2249,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } 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 +2293,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 +2331,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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 +2371,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } // 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 +2395,19 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 +2430,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 +2451,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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 +2534,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// /// /// 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) { @@ -2813,9 +2814,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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) @@ -2875,7 +2876,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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 +2905,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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 +2945,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 caf46c8ff..0b8d2d085 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/DynamicInvocationResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/DynamicInvocationResolveResult.cs @@ -72,7 +72,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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/LambdaResolveResult.cs b/ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs index 700695271..ca362f085 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs @@ -65,7 +65,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 65a276942..6f85d1820 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs @@ -79,7 +79,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver { 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) @@ -189,21 +189,21 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver { 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)) { - List lookupGroups = new List(); + List? lookupGroups = new List(); 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) { @@ -243,7 +243,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver { foreach (IType type in lookupGroup.NestedTypes) { - ITypeDefinition typeDef = type.GetDefinition(); + ITypeDefinition? typeDef = type.GetDefinition(); if (typeDef != null) yield return typeDef; } @@ -259,18 +259,18 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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; @@ -310,8 +310,8 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver { 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver if (!IsAccessible(member, allowProtectedAccess)) continue; - IParameterizedMember method; + IParameterizedMember? method; if (treatAllParameterizedMembersAsMethods) method = member as IParameterizedMember; else @@ -691,7 +691,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // 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 @@ -753,7 +753,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver { 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 d08108c22..05d136319 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs @@ -79,11 +79,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver { readonly IReadOnlyList methodLists; readonly IReadOnlyList typeArguments; - readonly ResolveResult targetResult; + readonly ResolveResult? targetResult; readonly string methodName; - public MethodGroupResolveResult(ResolveResult targetResult, string methodName, - IReadOnlyList methods, IReadOnlyList typeArguments) + public MethodGroupResolveResult(ResolveResult? targetResult, string methodName, + IReadOnlyList methods, IReadOnlyList? typeArguments) : base(SpecialType.NoType) { if (methods == null) @@ -143,10 +143,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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. @@ -229,12 +229,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 bfeb1bbd2..d0f623152 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs @@ -78,7 +78,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // (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; @@ -130,13 +130,13 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver readonly CSharpConversions conversions; //List candidates = new List(); Candidate bestCandidate; - Candidate bestCandidateAmbiguousWith; + Candidate? bestCandidateAmbiguousWith; IType[] explicitlyGivenTypeArguments; bool bestCandidateWasValidated; 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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)); @@ -582,7 +582,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } if (typeParameter.HasDefaultConstructorConstraint) { - ITypeDefinition def = typeArgument.GetDefinition(); + ITypeDefinition? def = typeArgument.GetDefinition(); if (def != null && def.IsAbstract) return false; var ctors = typeArgument.GetConstructors( @@ -791,8 +791,8 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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); @@ -891,7 +891,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver #endregion #region Output Properties - public IParameterizedMember BestCandidate { + public IParameterizedMember? BestCandidate { get { return bestCandidate != null ? bestCandidate.Member : null; } } @@ -919,7 +919,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); } } - public IParameterizedMember BestCandidateAmbiguousWith { + public IParameterizedMember? BestCandidateAmbiguousWith { get { return bestCandidateAmbiguousWith != null ? bestCandidateAmbiguousWith.Member : null; } } @@ -958,7 +958,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// /// parameterIndex = GetArgumentToParameterMap()[argumentIndex] /// - public IReadOnlyList GetArgumentToParameterMap() + public IReadOnlyList? GetArgumentToParameterMap() { if (bestCandidate != null) return bestCandidate.ArgumentToParameterMap; @@ -994,7 +994,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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]; @@ -1037,11 +1037,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver return args; } - public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments() + 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,9 +1072,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// /// 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 1c02d9da6..bfd664dd3 100644 --- a/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs +++ b/ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs @@ -94,11 +94,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } #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) /// @@ -113,7 +113,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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) @@ -698,7 +698,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } } - TP GetTPForType(IType v) + TP? GetTPForType(IType v) { if (v is NullabilityAnnotatedTypeParameter natp) { @@ -743,17 +743,17 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver } // 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 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // 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) @@ -1109,7 +1109,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver // 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 6bf75e350..707b4f715 100644 --- a/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs @@ -76,7 +76,7 @@ namespace ICSharpCode.Decompiler.CSharp /// /// The function containing this sequence point. /// - internal ILFunction Function; + internal ILFunction? Function; public StatePerSequencePoint(AstNode primaryNode) { @@ -547,7 +547,7 @@ namespace ICSharpCode.Decompiler.CSharp } - 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 4dfc5f658..e648d584a 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; @@ -151,7 +152,7 @@ namespace ICSharpCode.Decompiler.CSharp 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: @@ -203,7 +204,7 @@ namespace ICSharpCode.Decompiler.CSharp 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 @@ -212,7 +213,8 @@ namespace ICSharpCode.Decompiler.CSharp 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( @@ -243,7 +245,7 @@ namespace ICSharpCode.Decompiler.CSharp 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) @@ -327,7 +329,7 @@ namespace ICSharpCode.Decompiler.CSharp } 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()); @@ -346,7 +348,7 @@ namespace ICSharpCode.Decompiler.CSharp 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()); @@ -383,7 +385,7 @@ namespace ICSharpCode.Decompiler.CSharp } /// 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(); @@ -410,7 +412,7 @@ namespace ICSharpCode.Decompiler.CSharp 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)) @@ -622,7 +624,7 @@ namespace ICSharpCode.Decompiler.CSharp } } - Statement TransformToForeach(UsingInstruction inst, Expression resource) + Statement? TransformToForeach(UsingInstruction inst, Expression resource) { if (!settings.ForEachStatement) { @@ -731,7 +733,7 @@ namespace ICSharpCode.Decompiler.CSharp break; } - VariableDesignation designation = null; + VariableDesignation? designation = null; // Handle the required foreach-variable transformation: switch (transformation) @@ -875,7 +877,7 @@ namespace ICSharpCode.Decompiler.CSharp 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)) { @@ -898,7 +900,7 @@ namespace ICSharpCode.Decompiler.CSharp /// 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 +980,7 @@ namespace ICSharpCode.Decompiler.CSharp /// 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; @@ -1260,8 +1262,8 @@ namespace ICSharpCode.Decompiler.CSharp Statement ConvertLoop(BlockContainer container) { - ILInstruction condition; - Block loopBody; + ILInstruction? condition; + Block? loopBody; BlockStatement blockStatement; continueCount = 0; breakTarget = container; @@ -1425,7 +1427,7 @@ namespace ICSharpCode.Decompiler.CSharp 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); @@ -1479,7 +1481,7 @@ namespace ICSharpCode.Decompiler.CSharp 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)) { @@ -1499,7 +1501,7 @@ namespace ICSharpCode.Decompiler.CSharp 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 b11edf399..02383e97c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs @@ -202,7 +202,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax get { return parent; } } - public Role Role { + public Role? Role { get { return Role.GetByIndex(flags & roleIndexMask); } @@ -340,7 +340,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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/AstNodeCollection.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs index e61079c71..bccffa798 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs @@ -49,7 +49,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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++; @@ -149,7 +149,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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) @@ -177,8 +177,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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. @@ -200,9 +200,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax return node.GetHashCode() ^ role.GetHashCode(); } - public override bool Equals(object obj) + 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; @@ -214,7 +214,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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/AstType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs index a8b8da53a..74c0434e9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/AstType.cs @@ -56,12 +56,12 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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); } @@ -133,7 +133,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 fbe31464d..b3a45155b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpModifierToken.cs @@ -49,14 +49,14 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - 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; + 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 6bbf8a546..4a8eb2fc9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/CSharpTokenNode.cs @@ -64,7 +64,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; } @@ -100,14 +100,14 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - public CSharpTokenNode(TextLocation location, TokenRole role) + public CSharpTokenNode(TextLocation location, TokenRole? role) { this.startLocation = location; if (role != null) 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,9 +132,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 c042a2ca9..8914430f9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/ComposedType.cs @@ -144,9 +144,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + ComposedType? o = other as ComposedType; return o != null && this.HasNullableSpecifier == o.HasNullableSpecifier && this.PointerRank == o.PointerRank @@ -156,7 +156,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax && 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) @@ -201,7 +201,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; @@ -287,13 +287,13 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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/DepthFirstAstVisitor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs index 2016b429c..2a4317d4d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/DepthFirstAstVisitor.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { 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 @@ -713,9 +713,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// public abstract class DepthFirstAstVisitor : IAstVisitor { - protected virtual T VisitChildren(AstNode node) + 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 @@ -726,7 +726,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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. @@ -1396,9 +1396,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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/DocumentationReference.cs b/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs index 893f015fc..2293f8c70 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/DocumentationReference.cs @@ -109,9 +109,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 633073b36..03ea04f44 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousMethodExpression.cs @@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public AnonymousMethodExpression(BlockStatement body, IEnumerable parameters = null) + public AnonymousMethodExpression(BlockStatement body, IEnumerable? parameters = null) { if (parameters != null) { @@ -109,9 +109,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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/AnonymousTypeCreateExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousTypeCreateExpression.cs index e74e2e1af..381276031 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousTypeCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AnonymousTypeCreateExpression.cs @@ -81,7 +81,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 e4314f001..03559b43a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayCreateExpression.cs @@ -69,9 +69,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 f9ce09152..ea15c49be 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs @@ -85,7 +85,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +119,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + ArrayInitializerExpression? o = other as ArrayInitializerExpression; return o != null && this.Elements.DoMatch(o.Elements, match); } @@ -176,7 +176,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 b01fd4f86..6303dac27 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AsExpression.cs @@ -73,9 +73,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 378b33bfa..3fe7b3fa8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/AssignmentExpression.cs @@ -103,9 +103,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 5084d0e04..9076b1cfd 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs @@ -63,9 +63,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 1386e1029..db0d470ac 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BinaryOperatorExpression.cs @@ -105,9 +105,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 f3bd22ec2..20a78de71 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CastExpression.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 baff6c51a..313f18c7e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/CheckedExpression.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a1576e5cc..94b19addb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ConditionalExpression.cs @@ -87,9 +87,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 558456524..37f4f2156 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DeclarationExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DeclarationExpression.cs @@ -50,7 +50,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 372325a40..dd5eab75d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DefaultValueExpression.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 e92115530..e26062f1f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/DirectionExpression.cs @@ -93,9 +93,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 89f9fcfdd..252ec224e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ErrorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ErrorExpression.cs @@ -72,7 +72,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 c5d73352e..fe121170e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs @@ -56,7 +56,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 76fc8c2a5..6205080d6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IdentifierExpression.cs @@ -79,9 +79,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 e688b2a74..26f95c306 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IndexerExpression.cs @@ -54,7 +54,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public IndexerExpression(Expression target, IEnumerable arguments) + public IndexerExpression(Expression? target, IEnumerable? arguments) { AddChild(target, Roles.TargetExpression); if (arguments != null) @@ -66,7 +66,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 562755a0a..2573c9a5d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InterpolatedStringExpression.cs @@ -40,9 +40,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + InterpolatedStringExpression? o = other as InterpolatedStringExpression; return o != null && !o.IsNull && this.Content.DoMatch(o.Content, match); } } @@ -75,7 +75,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; } @@ -106,7 +106,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax public int Alignment { get; } - public string Suffix { get; } + public string? Suffix { get; } public CSharpTokenNode RBraceToken { get { return GetChildByRole(RBrace); } @@ -117,7 +117,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } - public Interpolation(Expression expression, int alignment = 0, string suffix = null) + public Interpolation(Expression expression, int alignment = 0, string? suffix = null) { Expression = expression; Alignment = alignment; @@ -139,9 +139,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + Interpolation? o = other as Interpolation; return o != null && this.Expression.DoMatch(o.Expression, match); } } @@ -175,9 +175,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 3ed91cefc..3fbb984ff 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/InvocationExpression.cs @@ -85,9 +85,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - 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; + 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 fa1bea0bc..c1c721571 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/IsExpression.cs @@ -74,9 +74,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 8782aa1d8..8320f99c6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/LambdaExpression.cs @@ -82,9 +82,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 fcda03b54..77afc0be0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs @@ -80,7 +80,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public MemberReferenceExpression(Expression target, string memberName, IEnumerable arguments = null) + public MemberReferenceExpression(Expression target, string memberName, IEnumerable? arguments = null) { AddChild(target, Roles.TargetExpression); MemberName = memberName; @@ -112,9 +112,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 5f3fb3627..eae728b50 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedArgumentExpression.cs @@ -77,9 +77,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 d8fe23df8..768b6af42 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NamedExpression.cs @@ -86,7 +86,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 ee67fb20f..796e016f1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/NullReferenceExpression.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 f559f6a89..4a71917fc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ObjectCreateExpression.cs @@ -66,7 +66,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public ObjectCreateExpression(AstType type, IEnumerable arguments = null) + public ObjectCreateExpression(AstType type, IEnumerable? arguments = null) { AddChild(type, Roles.Type); if (arguments != null) @@ -97,9 +97,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 022987e80..4699a8f83 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/OutVarDeclarationExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/OutVarDeclarationExpression.cs @@ -64,7 +64,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 b662ab3d4..1e33acee0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ParenthesizedExpression.cs @@ -69,9 +69,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 d678cdaf8..51987aec9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PointerReferenceExpression.cs @@ -80,9 +80,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a1e8fcc3b..0ba154a39 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/PrimitiveExpression.cs @@ -143,9 +143,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 87315b01f..5093bc564 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/QueryExpression.cs @@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +74,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + QueryExpression? o = other as QueryExpression; return o != null && !o.IsNull && this.Clauses.DoMatch(o.Clauses, match); } } @@ -148,9 +148,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + QueryContinuationClause? o = other as QueryContinuationClause; return o != null && MatchString(this.Identifier, o.Identifier) && this.PrecedingQuery.DoMatch(o.PrecedingQuery, match); } } @@ -206,9 +206,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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); } @@ -259,9 +259,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + QueryLetClause? o = other as QueryLetClause; return o != null && MatchString(this.Identifier, o.Identifier) && this.Expression.DoMatch(o.Expression, match); } } @@ -295,9 +295,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + QueryWhereClause? o = other as QueryWhereClause; return o != null && this.Condition.DoMatch(o.Condition, match); } } @@ -404,9 +404,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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) @@ -443,9 +443,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + QueryOrderClause? o = other as QueryOrderClause; return o != null && this.Orderings.DoMatch(o.Orderings, match); } } @@ -488,9 +488,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + QueryOrdering? o = other as QueryOrdering; return o != null && this.Direction == o.Direction && this.Expression.DoMatch(o.Expression, match); } } @@ -530,9 +530,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + QuerySelectClause? o = other as QuerySelectClause; return o != null && this.Expression.DoMatch(o.Expression, match); } } @@ -577,9 +577,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 3a26d735b..4c92a9341 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/RecursivePatternExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/RecursivePatternExpression.cs @@ -55,7 +55,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 b5daa0a9f..60e777361 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SizeOfExpression.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 f3c1c9b85..50d767324 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/StackAllocExpression.cs @@ -77,9 +77,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 ca66a0796..438202592 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs @@ -63,9 +63,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + SwitchExpression? o = other as SwitchExpression; return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match); } } @@ -109,9 +109,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 db61e2dad..e82a4f0e5 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThisReferenceExpression.cs @@ -63,9 +63,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 736d2da6d..895ec32a6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ThrowExpression.cs @@ -58,9 +58,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 143726af4..bd1ed58af 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TupleExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TupleExpression.cs @@ -43,7 +43,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 b6605ab63..4064708eb 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeOfExpression.cs @@ -76,9 +76,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 57c8ea9fa..eec542070 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/TypeReferenceExpression.cs @@ -54,9 +54,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 460f9a421..596b13b77 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UnaryOperatorExpression.cs @@ -87,14 +87,14 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + UnaryOperatorExpression? o = other as UnaryOperatorExpression; return o != null && (this.Operator == UnaryOperatorType.Any || this.Operator == o.Operator) && 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/Expressions/UncheckedExpression.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs index aa8160127..f2ca9fd4e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UncheckedExpression.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 7de290d8d..dbf6ea68c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/UndocumentedExpression.cs @@ -95,9 +95,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 809dfb367..3ff877de6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/WithInitializerExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/WithInitializerExpression.cs @@ -57,7 +57,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 96aee3ee9..d5eab341c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/FunctionPointerAstType.cs @@ -66,7 +66,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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) @@ -74,7 +74,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax && 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 b07bca2b2..3709476d6 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Attribute.cs @@ -77,13 +77,13 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 cf8658fe0..fedcacd32 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/AttributeSection.cs @@ -66,7 +66,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +129,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 b2a84f0ff..fc7783a41 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Comment.cs @@ -143,9 +143,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 4b0c18618..ba88d9443 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/Constraint.cs @@ -73,9 +73,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 0d85f5a59..f15538aa1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/DelegateDeclaration.cs @@ -80,9 +80,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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/ExternAliasDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs index 353e71f2c..c2fe80d66 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs @@ -83,7 +83,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 b41e9f882..24ba4ab54 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs @@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// public string FullName { get { - NamespaceDeclaration parentNamespace = Parent as NamespaceDeclaration; + NamespaceDeclaration? parentNamespace = Parent as NamespaceDeclaration; if (parentNamespace != null) return BuildQualifiedName(parentNamespace.FullName, Name); return Name; @@ -150,9 +150,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a1b175d1c..cd5e9a1dc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/PreProcessorDirective.cs @@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public LinePreprocessorDirective(string argument = null) : base(PreProcessorDirectiveType.Line, argument) + public LinePreprocessorDirective(string? argument = null) : base(PreProcessorDirectiveType.Line, argument) { } } @@ -115,7 +115,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public PragmaWarningPreprocessorDirective(string argument = null) : base(PreProcessorDirectiveType.Pragma, argument) + public PragmaWarningPreprocessorDirective(string? argument = null) : base(PreProcessorDirectiveType.Pragma, argument) { } @@ -172,7 +172,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax this.endLocation = endLocation; } - public PreProcessorDirective(PreProcessorDirectiveType type, string argument = null) + public PreProcessorDirective(PreProcessorDirectiveType type, string? argument = null) { this.Type = type; this.Argument = argument; @@ -193,9 +193,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a60d12843..115fd5dcc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs @@ -147,9 +147,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 db5c622cf..3bb397607 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeParameterDeclaration.cs @@ -104,9 +104,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 1b3ab140f..d9172161d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingAliasDeclaration.cs @@ -99,9 +99,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 d7246003c..966cae60c 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/UsingDeclaration.cs @@ -115,9 +115,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a82a9d54f..6a033f8e1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs @@ -42,7 +42,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// /// The type of the annotation. /// - object Annotation(Type type); + object? Annotation(Type type); /// /// Adds an annotation to this instance. @@ -89,7 +89,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax // 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. @@ -101,7 +101,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// protected void CloneAnnotations() { - ICloneable cloneable = annotations as ICloneable; + ICloneable? cloneable = annotations as ICloneable; if (cloneable != null) annotations = cloneable.Clone(); } @@ -123,7 +123,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; @@ -136,12 +136,12 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 } - AnnotationList list = oldAnnotation as AnnotationList; + AnnotationList? list = oldAnnotation as AnnotationList; if (list == null) { // we need to transform the old annotation into a list @@ -167,8 +167,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax public virtual void RemoveAnnotations() where T : class { retry: // Retry until successful - object oldAnnotations = this.annotations; - AnnotationList list = oldAnnotations as AnnotationList; + object? oldAnnotations = this.annotations; + AnnotationList? list = oldAnnotations as AnnotationList; if (list != null) { lock (list) @@ -189,8 +189,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax if (type == null) throw new ArgumentNullException(nameof(type)); retry: // Retry until successful - object oldAnnotations = this.annotations; - AnnotationList list = oldAnnotations as AnnotationList; + object? oldAnnotations = this.annotations; + AnnotationList? list = oldAnnotations as AnnotationList; if (list != null) { lock (list) @@ -206,17 +206,17 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - public T Annotation() where T : class + public T? Annotation() where T : class { - object annotations = this.annotations; - AnnotationList list = annotations as AnnotationList; + object? annotations = this.annotations; + 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; } @@ -229,12 +229,12 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - public object Annotation(Type type) + public object? Annotation(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); - object annotations = this.annotations; - AnnotationList list = annotations as AnnotationList; + object? annotations = this.annotations; + AnnotationList? list = annotations as AnnotationList; if (list != null) { lock (list) @@ -259,8 +259,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// public IEnumerable Annotations { get { - object annotations = this.annotations; - AnnotationList list = annotations as AnnotationList; + object? annotations = this.annotations; + AnnotationList? list = annotations as AnnotationList; if (list != null) { lock (list) diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs b/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs index 37dfd40a3..48e419e9e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/IAstVisitor.cs @@ -173,148 +173,148 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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/Identifier.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs index 726c939fb..1dc8c399f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs @@ -54,7 +54,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +164,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 78ee9359d..2783e354b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs @@ -41,7 +41,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 5dddbfb56..ad178e275 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/InvocationAstType.cs @@ -55,14 +55,14 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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) && 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 00abace78..bad911c0b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/MemberType.cs @@ -112,23 +112,23 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 00b2107e2..7afa2a669 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNode.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching 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 7ce94c72e..7090a68ef 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNodeOrNull.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/AnyNodeOrNull.cs @@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching get { return groupName; } } - public AnyNodeOrNull(string groupName = null) + public AnyNodeOrNull(string? groupName = null) { this.groupName = groupName; } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs index d1e3fc6e7..d3a68e43d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs @@ -25,9 +25,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching /// public interface INode { - Role Role { get; } - INode FirstChild { get; } - INode NextSibling { get; } + Role? Role { get; } + INode? FirstChild { get; } + INode? NextSibling { get; } bool IsNull { get; } bool DoMatch(INode other, Match match); diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs index 70a4dbc97..3c08979cc 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Match.cs @@ -27,7 +27,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching { // 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching internal static Match CreateNew() { Match m; - m.results = new List>(); + m.results = new List>(); return m; } @@ -88,7 +88,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching { if (groupName != null && node != null) { - results.Add(new KeyValuePair(groupName, node)); + results.Add(new KeyValuePair(groupName, node)); } } @@ -96,7 +96,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching { if (groupName != null) { - results.Add(new KeyValuePair(groupName, null)); + results.Add(new KeyValuePair(groupName, null)); } } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs index f644813f5..b196d9483 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Pattern.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching /// 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; } @@ -52,15 +52,15 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching 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 a99c60be0..2faf4150b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs @@ -44,7 +44,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching 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/PrimitiveType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs index a6f112542..cec4ba107 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/PrimitiveType.cs @@ -100,18 +100,18 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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; } - 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/Role.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Role.cs index 2411a2652..4c755579a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Role.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Role.cs @@ -69,7 +69,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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/Syntax/Roles.cs b/ICSharpCode.Decompiler/CSharp/Syntax/Roles.cs index 60d0791a6..eae240691 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/SimpleType.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs index 17a19e345..231ba13e8 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SimpleType.cs @@ -60,12 +60,12 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,13 +141,13 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 9965c7af9..5ef3ae374 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BlockStatement.cs @@ -60,7 +60,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +140,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 df8732e81..81c0375f9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/BreakStatement.cs @@ -57,9 +57,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 c701dcfc5..11e487210 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/CheckedStatement.cs @@ -67,9 +67,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a4b8abacf..8fac0c894 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ContinueStatement.cs @@ -57,9 +57,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 ce05ff6b6..79c8a6a65 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/DoWhileStatement.cs @@ -80,9 +80,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 c76016963..d7ea9f661 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/EmptyStatement.cs @@ -64,9 +64,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 5a4f2a413..4c5a9ac77 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ExpressionStatement.cs @@ -65,9 +65,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 3b34ea2fb..bfbb173a9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/FixedStatement.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 91784f0d4..2a418afb1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForStatement.cs @@ -86,9 +86,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a01bc05de..a6e39f1ae 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ForeachStatement.cs @@ -96,9 +96,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 b1b064c01..f5f28d40e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/GotoStatement.cs @@ -78,9 +78,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + GotoStatement? o = other as GotoStatement; return o != null && MatchString(this.Label, o.Label); } } @@ -128,9 +128,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + GotoCaseStatement? o = other as GotoCaseStatement; return o != null && this.LabelExpression.DoMatch(o.LabelExpression, match); } } @@ -170,9 +170,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 fece09f10..f7a3ab46f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/IfElseStatement.cs @@ -84,9 +84,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - 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 ca56ec478..8218b0a34 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LabelStatement.cs @@ -65,9 +65,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 da2d1550f..0a2f4ad26 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LocalFunctionDeclarationStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LocalFunctionDeclarationStatement.cs @@ -49,7 +49,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 a8f25c579..c988127d7 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/LockStatement.cs @@ -71,9 +71,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 75b96f4fe..74b9dae6d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ReturnStatement.cs @@ -71,9 +71,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 b278d1e3f..92198d5a0 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs @@ -55,7 +55,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; } @@ -63,7 +63,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax #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; } @@ -96,7 +96,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 a3412d1c8..364e6df94 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/SwitchStatement.cs @@ -79,9 +79,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + SwitchStatement? o = other as SwitchStatement; return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match); } } @@ -122,7 +122,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +165,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + SwitchSection? o = other as SwitchSection; return o != null && this.CaseLabels.DoMatch(o.CaseLabels, match) && this.Statements.DoMatch(o.Statements, match); } } @@ -219,9 +219,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 a16d67a34..cb6fc857f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/ThrowStatement.cs @@ -71,9 +71,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 f3ad325bc..a3352f0ff 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/TryCatchStatement.cs @@ -75,9 +75,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +251,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 f24f7213e..4b91caec5 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UncheckedStatement.cs @@ -67,9 +67,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 1a977d5b9..afa19a96d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UnsafeStatement.cs @@ -58,9 +58,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 33bf9d839..2524726d3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs @@ -87,9 +87,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 1a6066f17..15b58fa8e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/VariableDeclarationStatement.cs @@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - 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)); @@ -79,9 +79,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 3e852e35d..5f9d8f80d 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/WhileStatement.cs @@ -71,9 +71,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 4a777afa9..cfcd65162 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldBreakStatement.cs @@ -62,9 +62,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 235201ab2..f741a9519 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/Statements/YieldReturnStatement.cs @@ -67,9 +67,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + YieldReturnStatement? o = other as YieldReturnStatement; return o != null && this.Expression.DoMatch(o.Expression, match); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs index 8d6cc4bc6..41a506d31 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxExtensions.cs @@ -54,7 +54,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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/SyntaxTree.cs b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs index 92e3bb63d..d4a0fed7b 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/SyntaxTree.cs @@ -58,7 +58,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ -117,9 +117,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } - 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; + 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 487a9cc1c..307b13b53 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TextLocation.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TextLocation.cs @@ -98,7 +98,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// /// Equality test. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is TextLocation)) return false; @@ -187,17 +187,17 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 16f5cd4aa..c944f392f 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TupleAstType.cs @@ -49,7 +49,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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(), @@ -57,7 +57,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax ); } - 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 def135ba9..acd671315 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/Accessor.cs @@ -57,7 +57,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; } @@ -76,7 +76,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// 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 @@ -89,7 +89,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - public BlockStatement Body { + public BlockStatement? Body { get { return GetChildByRole(Roles.Body); } set { SetChildByRole(Roles.Body, value); } } @@ -109,9 +109,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 890b77088..12d1a13e9 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ConstructorDeclaration.cs @@ -77,9 +77,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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); } @@ -127,7 +127,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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,9 +180,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 5039831ee..a11ddbce1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/DestructorDeclaration.cs @@ -67,9 +67,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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/EntityDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs index 28cfb0798..5507fbc75 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EntityDeclaration.cs @@ -89,7 +89,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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/EnumMemberDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs index cbf983454..cc42720a4 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EnumMemberDeclaration.cs @@ -40,7 +40,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax get { return GetChildByRole(Roles.Assign); } } - public Expression Initializer { + public Expression? Initializer { get { return GetChildByRole(InitializerRole); } set { SetChildByRole(InitializerRole, value); } } @@ -60,9 +60,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 1abb7c739..ff5ab3e54 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs @@ -76,9 +76,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + EventDeclaration? o = other as EventDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.Variables.DoMatch(o.Variables, match); } @@ -139,9 +139,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 548b0333e..933d7adc1 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FieldDeclaration.cs @@ -70,9 +70,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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/FixedFieldDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedFieldDeclaration.cs index 2d31d86ab..f803db180 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedFieldDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedFieldDeclaration.cs @@ -59,7 +59,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 56c602300..f6f71d346 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/FixedVariableInitializer.cs @@ -42,7 +42,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public FixedVariableInitializer(string name, Expression initializer = null) + public FixedVariableInitializer(string name, Expression? initializer = null) { this.Name = name; this.CountExpression = initializer; @@ -94,7 +94,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 bad5ce81b..b42b54a6e 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/IndexerDeclaration.cs @@ -116,9 +116,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 d01822868..dd6666a03 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/MethodDeclaration.cs @@ -70,7 +70,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax public bool IsExtensionMethod { get { - ParameterDeclaration pd = (ParameterDeclaration)GetChildByRole(Roles.Parameter); + ParameterDeclaration? pd = GetChildByRole(Roles.Parameter) as ParameterDeclaration; return pd != null && pd.HasThisModifier; } } @@ -90,9 +90,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 9ffc9058b..e004eabc2 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/OperatorDeclaration.cs @@ -293,7 +293,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax /// /// 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; @@ -353,9 +353,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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/ParameterDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ParameterDeclaration.cs index 98a86fd69..069e03e7a 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ParameterDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/ParameterDeclaration.cs @@ -97,7 +97,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax bool isParams; bool isScopedRef; - public CSharpTokenNode ThisKeyword { + public CSharpTokenNode? ThisKeyword { get { if (hasThisModifier) { @@ -141,21 +141,21 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - 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); } } diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs index f7fd87434..657cad0df 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/PropertyDeclaration.cs @@ -97,9 +97,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 d5b74faa8..98768ede3 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/VariableInitializer.cs @@ -55,7 +55,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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); } @@ -118,7 +118,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { } - public VariableInitializer(string name, Expression initializer = null) + public VariableInitializer(string name, Expression? initializer = null) { this.Name = name; this.Initializer = initializer; @@ -166,9 +166,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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; + 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 c26998303..8eeda4157 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs @@ -20,6 +20,7 @@ using System; 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; @@ -461,13 +462,13 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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); @@ -509,7 +510,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 +568,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { 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 +624,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 +708,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - bool IsValidNamespace(string firstNamespacePart, out NamespaceResolveResult nrr) + bool IsValidNamespace(string firstNamespacePart, out NamespaceResolveResult? nrr) { nrr = null; if (resolver == null) @@ -813,7 +814,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 +845,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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) { @@ -1052,7 +1053,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } 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) { @@ -1081,7 +1082,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } } - 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)) @@ -1212,7 +1213,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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) @@ -1231,7 +1232,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 +1250,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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) @@ -1290,11 +1291,11 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax } 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); - object constantValue = field.GetConstantValue(); + object? constantValue = field.GetConstantValue(); if (constantValue == null) return (-1, null); return ((long)CSharpPrimitiveCast.Cast(TypeCode.Int64, constantValue, checkForOverflow: false), field); @@ -1363,7 +1364,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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) @@ -1442,7 +1443,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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() { @@ -1463,7 +1464,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax return new CastExpression(ConvertType(type), fieldRef); } - Expression ExtractExpression(long n, long d) + Expression? ExtractExpression(long n, long d) { Expression fieldReference = MakeFieldReference(); @@ -1698,7 +1699,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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); @@ -1889,7 +1890,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax DelegateDeclaration ConvertDelegate(IMethod invokeMethod, Modifiers modifiers) { - ITypeDefinition d = invokeMethod.DeclaringTypeDefinition; + ITypeDefinition? d = invokeMethod.DeclaringTypeDefinition; DelegateDeclaration decl = new DelegateDeclaration(); decl.Modifiers = modifiers & ~Modifiers.Sealed; @@ -1970,7 +1971,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax { ct.HasReadOnlySpecifier = true; } - Expression initializer = null; + Expression? initializer = null; if (field.IsConst && this.ShowConstantValues) { try @@ -2018,7 +2019,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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, @@ -2399,7 +2400,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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)) { @@ -2459,7 +2460,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ -2470,7 +2471,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ -2492,7 +2493,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax return new NamespaceDeclaration(ns.FullName); } - AstType GetExplicitInterfaceType(IMember member) + AstType? GetExplicitInterfaceType(IMember member) { if (member.IsExplicitInterfaceImplementation) { diff --git a/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs b/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs index 8d7991dec..9712d1a18 100644 --- a/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs +++ b/ICSharpCode.Decompiler/CSharp/Syntax/VariableDesignation.cs @@ -50,7 +50,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax 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/CSharp/Transforms/AddCheckedBlocks.cs b/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs index 7ffaf24e4..eb181384f 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/AddCheckedBlocks.cs @@ -241,10 +241,10 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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) + for (AstNode? child = node.FirstChild; child != null; child = child.NextSibling) { Run(child, context); } @@ -262,20 +262,20 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms // 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(); + 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; @@ -348,7 +348,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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/AddXmlDocumentationTransform.cs b/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs index b3f02dee0..4a76fbb98 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs @@ -63,7 +63,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 ad92d1a27..842f16103 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs @@ -47,18 +47,18 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms { 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms { RemoveTransparentIdentifierReferences(child, fromOrLetIdentifiers); } - MemberReferenceExpression mre = node as MemberReferenceExpression; + MemberReferenceExpression? mre = node as MemberReferenceExpression; if (mre != null) { - IdentifierExpression ident = mre.Target as IdentifierExpression; + IdentifierExpression? ident = mre.Target as IdentifierExpression; if (ident != null && CSharpDecompiler.IsTransparentIdentifier(ident.Identifier)) { IdentifierExpression newIdent = new IdentifierExpression(mre.MemberName); diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs b/ICSharpCode.Decompiler/CSharp/Transforms/ContextTrackingVisitor.cs index 5f60b62f7..3346c3914 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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/CustomPatterns.cs b/ICSharpCode.Decompiler/CSharp/Transforms/CustomPatterns.cs index 0926035ed..51e25a056 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/CustomPatterns.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/CustomPatterns.cs @@ -38,8 +38,8 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms public override bool DoMatch(INode other, Match match) { - ComposedType ct = other as ComposedType; - AstType o; + ComposedType? ct = other as ComposedType; + AstType? o; if (ct != null && !ct.HasRefSpecifier && !ct.HasNullableSpecifier && ct.PointerRank == 0 && !ct.ArraySpecifiers.Any()) { // Special case: ILSpy sometimes produces a ComposedType but then removed all array specifiers @@ -73,7 +73,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms public override bool DoMatch(INode other, Match match) { - InvocationExpression ie = other as InvocationExpression; + InvocationExpression? ie = other as InvocationExpression; if (ie != null && ie.Annotation() != 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 c84d9e81a..30fbeae6c 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; @@ -138,7 +139,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } readonly Dictionary variableDict = new Dictionary(); - TransformContext context; + TransformContext? context; public void Run(AstNode rootNode, TransformContext context) { @@ -284,7 +285,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms /// 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. @@ -296,7 +297,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } 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); } @@ -320,7 +321,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms { 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); @@ -355,7 +356,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } } } - if (variableDict.TryGetValue(variable, out VariableToDeclare v)) + if (variableDict.TryGetValue(variable, out VariableToDeclare? v)) { v.InsertionPoint = FindCommonParent(v.InsertionPoint, newPoint); } @@ -552,7 +553,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } } - 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) @@ -657,7 +658,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms else { // Insert a separate declaration statement. - Expression initializer = null; + Expression? initializer = null; AstType type = context.TypeSystemAstBuilder.ConvertType(v.Type); if (v.DefaultInitialization == VariableInitKind.NeedsDefaultValue) { @@ -731,7 +732,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } } - 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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) { @@ -765,7 +766,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms { 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 4048df940..db9031008 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs @@ -50,7 +50,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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); @@ -67,8 +67,8 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms { 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/IntroduceExtensionMethods.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceExtensionMethods.cs index 754044666..976262ef3 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceExtensionMethods.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceExtensionMethods.cs @@ -147,9 +147,9 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } 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 8e5e55368..ab6f1c7f0 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; @@ -50,7 +51,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } // 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 +59,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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()); @@ -79,7 +80,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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()) @@ -87,8 +88,8 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; @@ -102,11 +103,11 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return context.Settings.Discards; } - QueryExpression DecompileQuery(InvocationExpression invocation) + 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) @@ -118,7 +119,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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())); @@ -133,8 +134,8 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms { 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(); @@ -151,7 +152,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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())); @@ -166,11 +167,11 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; - 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); @@ -193,7 +194,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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())); @@ -212,7 +213,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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)) { @@ -256,12 +257,12 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; + 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); @@ -350,13 +351,13 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms /// /// 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; @@ -370,7 +371,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } /// 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/IntroduceUnsafeModifier.cs b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs index 40ba71aca..7a7e3ab25 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUnsafeModifier.cs @@ -40,8 +40,8 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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. @@ -116,7 +116,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 1b4523399..6c2c4ed45 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUsingDeclarations.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/IntroduceUsingDeclarations.cs @@ -205,7 +205,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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/NormalizeBlockStatements.cs b/ICSharpCode.Decompiler/CSharp/Transforms/NormalizeBlockStatements.cs index 80d177a12..8371d0601 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/NormalizeBlockStatements.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/NormalizeBlockStatements.cs @@ -12,7 +12,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms { 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 3605d968d..72fcb5be9 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; @@ -34,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) { @@ -61,7 +62,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms // 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 @@ -76,7 +77,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms public override AstNode VisitExpressionStatement(ExpressionStatement expressionStatement) { - AstNode result = TransformForeachOnMultiDimArray(expressionStatement); + AstNode? result = TransformForeachOnMultiDimArray(expressionStatement); if (result != null) return result; result = TransformFor(expressionStatement); @@ -87,7 +88,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms public override AstNode VisitForStatement(ForStatement forStatement) { - AstNode result = TransformForeachOnArray(forStatement); + AstNode? result = TransformForeachOnArray(forStatement); if (result != null) return result; return base.VisitForStatement(forStatement); @@ -173,7 +174,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } }; - public ForStatement TransformFor(ExpressionStatement node) + public ForStatement? TransformFor(ExpressionStatement node) { if (!context.Settings.ForStatement) return null; @@ -181,7 +182,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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(); @@ -338,7 +339,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return false; } - Statement TransformForeachOnArray(ForStatement forStatement) + Statement? TransformForeachOnArray(ForStatement forStatement) { if (!context.Settings.ForEachStatement) return null; @@ -431,7 +432,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms ) ))); - 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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) @@ -476,14 +477,14 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return true; } - Statement TransformForeachOnMultiDimArray(ExpressionStatement expressionStatement) + Statement? TransformForeachOnMultiDimArray(ExpressionStatement expressionStatement) { if (!context.Settings.ForEachStatement) 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 @@ -608,12 +609,12 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return true; } - PropertyDeclaration TransformAutomaticProperty(PropertyDeclaration propertyDeclaration) + 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,16 +703,16 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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); @@ -735,7 +736,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return true; } - Identifier ReplaceBackingFieldUsage(Identifier identifier) + Identifier? ReplaceBackingFieldUsage(Identifier identifier) { if (NameCouldBeBackingFieldOfAutomaticProperty(identifier.Name, out _)) { @@ -756,7 +757,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return null; } - Identifier ReplaceEventFieldAnnotation(Identifier identifier) + Identifier? ReplaceEventFieldAnnotation(Identifier identifier) { var parent = identifier.Parent; var mrr = parent.Annotation(); @@ -994,7 +995,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return true; } - EventDeclaration TransformAutomaticEvents(CustomEventDeclaration ev) + EventDeclaration? TransformAutomaticEvents(CustomEventDeclaration ev) { if (!ev.PrivateImplementationType.IsNull) return null; @@ -1054,7 +1055,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms Body = destructorBodyPattern }; - DestructorDeclaration TransformDestructor(MethodDeclaration methodDef) + DestructorDeclaration? TransformDestructor(MethodDeclaration methodDef) { Match m = destructorPattern.Match(methodDef); if (m.Success) @@ -1071,7 +1072,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms return null; } - DestructorDeclaration TransformDestructorBody(DestructorDeclaration dtorDef) + DestructorDeclaration? TransformDestructorBody(DestructorDeclaration dtorDef) { Match m = destructorBodyPattern.Match(dtorDef.Body); if (m.Success) @@ -1098,7 +1099,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms /// 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)) { @@ -1129,7 +1130,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms } }; - AstNode SimplifyCascadingIfElseStatements(IfElseStatement node) + AstNode? SimplifyCascadingIfElseStatements(IfElseStatement node) { Match m = cascadingIfElsePattern.Match(node); if (m.Success) diff --git a/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs b/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs index ae490e1d7..649407a0e 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) { @@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms // 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 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 36624535b..028acf8d0 100644 --- a/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs +++ b/ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs @@ -41,7 +41,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms MemberName = "TypeHandle" }; - TransformContext context; + TransformContext? context; public override void VisitInvocationExpression(InvocationExpression invocationExpression) { @@ -495,7 +495,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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 8bcf924fa..326551ddf 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) { @@ -66,7 +66,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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) @@ -184,7 +184,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; @@ -206,7 +206,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; @@ -330,7 +330,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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,13 +340,13 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms 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; + 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 ad864b5ac..8ad8b704c 100644 --- a/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs +++ b/ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs @@ -156,7 +156,7 @@ namespace ICSharpCode.Decompiler.CSharp { 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); @@ -664,7 +664,7 @@ namespace ICSharpCode.Decompiler.CSharp /// 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 1bb991dee..ab3d55d79 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs @@ -70,7 +70,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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 986ee1020..8a0374f2c 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,12 +26,12 @@ 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) + public CSharpTypeResolveContext(IModule module, ResolvedUsingScope? usingScope = null, ITypeDefinition? typeDefinition = null, IMember? member = null) { if (module == null) throw new ArgumentNullException(nameof(module)); @@ -40,7 +41,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem this.methodTypeParameterNames = methodTypeParameterNames; } - public ResolvedUsingScope CurrentUsingScope { + public ResolvedUsingScope? CurrentUsingScope { get { return currentUsingScope; } } @@ -61,30 +62,31 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs index 4418f9cd3..c1e4acd84 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs @@ -86,7 +86,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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/ResolvedUsingScope.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs index c6e10cfbd..0d42b9786 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs @@ -70,7 +70,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem public INamespace Namespace { get { - INamespace result = LazyInit.VolatileRead(ref this.@namespace); + INamespace? result = LazyInit.VolatileRead(ref this.@namespace); if (result != null) { return result; @@ -213,12 +213,12 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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/SimpleTypeOrNamespaceReference.cs b/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs index ded6bccbc..0367c6c2d 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs @@ -75,7 +75,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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 c9ed00c32..749aeee14 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/TypeOrNamespaceReference.cs @@ -43,9 +43,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem /// /// 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; + 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 05ef4e6eb..684d15573 100644 --- a/ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs +++ b/ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs @@ -155,7 +155,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem 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/IDebugInfoProvider.cs b/ICSharpCode.Decompiler/DebugInfo/IDebugInfoProvider.cs index 810919e56..0e233d775 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; @@ -19,8 +20,8 @@ namespace ICSharpCode.Decompiler.DebugInfo public struct PdbExtraTypeInfo { - public string[] TupleElementNames; - public bool[] DynamicFlags; + public string?[]? TupleElementNames; + public bool[]? DynamicFlags; } public interface IDebugInfoProvider @@ -28,8 +29,8 @@ namespace ICSharpCode.Decompiler.DebugInfo 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/DebugInfo/ImportScopeInfo.cs b/ICSharpCode.Decompiler/DebugInfo/ImportScopeInfo.cs index c6625350d..cd10e158c 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/DebugInfo/PortablePdbWriter.cs b/ICSharpCode.Decompiler/DebugInfo/PortablePdbWriter.cs index 3779ace15..dcc20f632 100644 --- a/ICSharpCode.Decompiler/DebugInfo/PortablePdbWriter.cs +++ b/ICSharpCode.Decompiler/DebugInfo/PortablePdbWriter.cs @@ -72,7 +72,7 @@ namespace ICSharpCode.Decompiler.DebugInfo 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 @@ namespace ICSharpCode.Decompiler.DebugInfo { 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 b32563526..63f06f720 100644 --- a/ICSharpCode.Decompiler/DecompilerException.cs +++ b/ICSharpCode.Decompiler/DecompilerException.cs @@ -36,16 +36,16 @@ 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, - Exception innerException, string message = null) + public DecompilerException(MetadataModule module, IEntity? decompiledEntity, + Exception innerException, string? message = null) : base(message ?? GetDefaultMessage(decompiledEntity), innerException) { this.File = module.MetadataFile; @@ -98,7 +98,7 @@ namespace ICSharpCode.Decompiler 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 @@ namespace ICSharpCode.Decompiler 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,10 +123,10 @@ namespace ICSharpCode.Decompiler b.AppendLine(); b.Append(" at "); - Type declaringType = method.DeclaringType; + Type? declaringType = method.DeclaringType; if (declaringType != null) { - b.Append(declaringType.FullName.Replace('+', '.')); + b.Append(declaringType.FullName?.Replace('+', '.')); b.Append('.'); } b.Append(method.Name); @@ -168,12 +168,12 @@ namespace ICSharpCode.Decompiler b.Append(')'); // source location - if (frame.GetILOffset() >= 0) + if (frame?.GetILOffset() >= 0) { - string filename = null; + string? filename = null; try { - string fullpath = frame.GetFileName(); + string? fullpath = frame.GetFileName(); if (fullpath != null) filename = Path.GetFileName(fullpath); } diff --git a/ICSharpCode.Decompiler/DecompilerSettings.cs b/ICSharpCode.Decompiler/DecompilerSettings.cs index 773128bc8..f910afa84 100644 --- a/ICSharpCode.Decompiler/DecompilerSettings.cs +++ b/ICSharpCode.Decompiler/DecompilerSettings.cs @@ -2173,9 +2173,9 @@ namespace ICSharpCode.Decompiler } } - 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.Decompiler/Disassembler/DisassemblerHelpers.cs b/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs index a1d4cc743..78d1f8259 100644 --- a/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs +++ b/ICSharpCode.Decompiler/Disassembler/DisassemblerHelpers.cs @@ -96,7 +96,7 @@ namespace ICSharpCode.Decompiler.Disassembler 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(); @@ -150,7 +150,7 @@ namespace ICSharpCode.Decompiler.Disassembler 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) @@ -189,7 +189,7 @@ namespace ICSharpCode.Decompiler.Disassembler if (operand == null) throw new ArgumentNullException(nameof(operand)); - string s = operand as string; + string? s = operand as string; if (s != null) { WriteOperand(writer, s); @@ -339,7 +339,7 @@ namespace ICSharpCode.Decompiler.Disassembler } return sb.ToString(); } - public static string PrimitiveTypeName(string fullName) + public static string? PrimitiveTypeName(string fullName) { switch (fullName) { diff --git a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs index fbd386d4f..e89afa56a 100644 --- a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs @@ -68,7 +68,7 @@ namespace ICSharpCode.Decompiler.Disassembler /// public IDebugInfoProvider DebugInfo { get; set; } - IList sequencePoints; + IList? sequencePoints; int nextSequencePointIndex; // cache info @@ -440,7 +440,7 @@ namespace ICSharpCode.Decompiler.Disassembler metadataToken = blob.ReadInt32(); output.Write(' '); UserStringHandle? userString; - string text; + string? text; try { userString = MetadataTokens.UserStringHandle(metadataToken); diff --git a/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs b/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs index 931bc671d..8c2228f37 100644 --- a/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs +++ b/ICSharpCode.Decompiler/Disassembler/OpCodeInfo.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.Decompiler.Disassembler public readonly ILOpCode Code; public readonly string Name; - string encodedName; + string? encodedName; public OpCodeInfo(ILOpCode code, string name) { @@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.Disassembler 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/Disassembler/ReflectionDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs index 11c8bdb9a..7d083b406 100644 --- a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs @@ -322,7 +322,7 @@ namespace ICSharpCode.Decompiler.Disassembler 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)); @@ -475,7 +475,7 @@ namespace ICSharpCode.Decompiler.Disassembler } } - class SecurityDeclarationDecoder : ICustomAttributeTypeProvider<(PrimitiveTypeCode, string)> + class SecurityDeclarationDecoder : ICustomAttributeTypeProvider<(PrimitiveTypeCode, string?)> { readonly ITextOutput output; readonly IAssemblyResolver resolver; @@ -488,32 +488,32 @@ namespace ICSharpCode.Decompiler.Disassembler 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 @@ namespace ICSharpCode.Decompiler.Disassembler 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; } @@ -539,7 +539,7 @@ namespace ICSharpCode.Decompiler.Disassembler { 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 @@ namespace ICSharpCode.Decompiler.Disassembler MetadataFile mscorlib; - bool TryResolveMscorlib(out MetadataFile mscorlib) + bool TryResolveMscorlib(out MetadataFile? mscorlib) { mscorlib = null; if (this.mscorlib != null) @@ -642,8 +642,8 @@ namespace ICSharpCode.Decompiler.Disassembler output.WriteLine(" = {"); output.Indent(); - string currentAssemblyName = null; - string currentFullAssemblyName = null; + string? currentAssemblyName = null; + string? currentFullAssemblyName = null; if (module.Metadata.IsAssembly) { try @@ -1040,10 +1040,10 @@ namespace ICSharpCode.Decompiler.Disassembler 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; @@ -1188,7 +1188,7 @@ namespace ICSharpCode.Decompiler.Disassembler break; default: var blob = metadata.GetBlobReader(constant.Value); - object value; + object? value; try { value = blob.ReadConstant(constant.TypeCode); @@ -1862,7 +1862,7 @@ namespace ICSharpCode.Decompiler.Disassembler output.Indent(); } - void CloseBlock(string comment = null) + void CloseBlock(string? comment = null) { output.Unindent(); output.Write("}"); @@ -1912,16 +1912,16 @@ namespace ICSharpCode.Decompiler.Disassembler } - 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/Documentation/GetPotentiallyNestedClassTypeReference.cs b/ICSharpCode.Decompiler/Documentation/GetPotentiallyNestedClassTypeReference.cs index 754fe1f9a..8422b93a1 100644 --- a/ICSharpCode.Decompiler/Documentation/GetPotentiallyNestedClassTypeReference.cs +++ b/ICSharpCode.Decompiler/Documentation/GetPotentiallyNestedClassTypeReference.cs @@ -57,7 +57,7 @@ namespace ICSharpCode.Decompiler.Documentation { 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/IdStringMemberReference.cs b/ICSharpCode.Decompiler/Documentation/IdStringMemberReference.cs index 3b0ad8bdc..a9226da95 100644 --- a/ICSharpCode.Decompiler/Documentation/IdStringMemberReference.cs +++ b/ICSharpCode.Decompiler/Documentation/IdStringMemberReference.cs @@ -61,7 +61,7 @@ namespace ICSharpCode.Decompiler.Documentation 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/IdStringProvider.cs b/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs index 75470a24d..59000a1f9 100644 --- a/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs +++ b/ICSharpCode.Decompiler/Documentation/IdStringProvider.cs @@ -71,13 +71,13 @@ namespace ICSharpCode.Decompiler.Documentation 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('('); @@ -155,7 +155,7 @@ namespace ICSharpCode.Decompiler.Documentation b.Append('@'); break; default: - IType declType = type.DeclaringType; + IType? declType = type.DeclaringType; if (declType != null) { AppendTypeName(b, declType, explicitInterfaceImpl); @@ -180,7 +180,7 @@ namespace ICSharpCode.Decompiler.Documentation 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/XmlDocLoader.cs b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs index 3d4c9ce6c..5b5d68f31 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs @@ -31,10 +31,10 @@ 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() + static XmlDocumentationProvider? LoadMscorlibDocumentation() { string xmlDocFile = FindXmlDocumentation("mscorlib.dll", TargetRuntime.Net_4_0) ?? FindXmlDocumentation("mscorlib.dll", TargetRuntime.Net_2_0); @@ -44,19 +44,19 @@ namespace ICSharpCode.Decompiler.Documentation 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)); lock (cache) { - if (!cache.TryGetValue(module, out XmlDocumentationProvider xmlDoc)) + 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 @@ namespace ICSharpCode.Decompiler.Documentation 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: @@ -120,7 +120,7 @@ namespace ICSharpCode.Decompiler.Documentation /// 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 cae69da09..40f39261e 100644 --- a/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs +++ b/ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs @@ -67,7 +67,7 @@ namespace ICSharpCode.Decompiler.Documentation 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) { @@ -81,7 +81,7 @@ namespace ICSharpCode.Decompiler.Documentation 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 @@ namespace ICSharpCode.Decompiler.Documentation 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 @@ namespace ICSharpCode.Decompiler.Documentation 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 @@ namespace ICSharpCode.Decompiler.Documentation 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 @@ namespace ICSharpCode.Decompiler.Documentation } } - string ReloadAndGetDocumentation(string key) + string? ReloadAndGetDocumentation(string key) { try { @@ -407,7 +407,7 @@ namespace ICSharpCode.Decompiler.Documentation #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 @@ namespace ICSharpCode.Decompiler.Documentation { if (r.NodeType == XmlNodeType.Element) { - string memberAttr = r.GetAttribute("name"); + string? memberAttr = r.GetAttribute("name"); if (memberAttr == key) { return r.ReadInnerXml(); @@ -437,7 +437,7 @@ namespace ICSharpCode.Decompiler.Documentation } #endregion - public virtual void OnDeserialization(object sender) + public virtual void OnDeserialization(object? sender) { cache = new XmlDocumentationCache(); } diff --git a/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs b/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs index 713fd360f..4dd360de5 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs @@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis /// /// User data. /// - public object UserData; + public object? UserData; /// /// Visited flag, used in various algorithms. @@ -62,13 +62,13 @@ namespace ICSharpCode.Decompiler.FlowAnalysis /// 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 @@ namespace ICSharpCode.Decompiler.FlowAnalysis 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/DataFlowVisitor.cs b/ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs index 06d4a24d3..fd050c349 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs @@ -237,7 +237,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis #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 @@ namespace ICSharpCode.Decompiler.FlowAnalysis /// State GetBlockInputState(Block block) { - if (stateOnBranch.TryGetValue(block, out State s)) + if (stateOnBranch.TryGetValue(block, out State? s)) { return s; } @@ -398,7 +398,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis 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 @@ namespace ICSharpCode.Decompiler.FlowAnalysis 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 @@ namespace ICSharpCode.Decompiler.FlowAnalysis 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/FlowAnalysis/Dominance.cs b/ICSharpCode.Decompiler/FlowAnalysis/Dominance.cs index 815b92046..7285bdc64 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/Dominance.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/Dominance.cs @@ -69,7 +69,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis { 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/FlowAnalysis/ReachingDefinitionsVisitor.cs b/ICSharpCode.Decompiler/FlowAnalysis/ReachingDefinitionsVisitor.cs index 0f57fab07..1aba19e7a 100644 --- a/ICSharpCode.Decompiler/FlowAnalysis/ReachingDefinitionsVisitor.cs +++ b/ICSharpCode.Decompiler/FlowAnalysis/ReachingDefinitionsVisitor.cs @@ -331,7 +331,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis 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/Humanizer/Vocabulary.cs b/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs index f90125416..620107f2b 100644 --- a/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs +++ b/ICSharpCode.Decompiler/Humanizer/Vocabulary.cs @@ -119,7 +119,7 @@ namespace Humanizer.Inflections 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 @@ namespace Humanizer.Inflections _replacement = replacement; } - public string Apply(string word) + public string? Apply(string word) { if (!_regex.IsMatch(word)) { diff --git a/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj b/ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj index 583adedeb..bc037ace5 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 @@ -41,6 +40,7 @@ true ICSharpCode.Decompiler.ruleset true + enable diff --git a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs index 259367b2d..d8789bd13 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs @@ -20,6 +20,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Metadata; @@ -73,29 +74,29 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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; @@ -294,15 +295,15 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } 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)) @@ -339,8 +340,8 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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)) @@ -482,7 +483,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// /// 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; @@ -609,7 +610,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } 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 +645,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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; @@ -803,7 +804,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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) { @@ -824,7 +825,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 +870,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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; // ... @@ -1083,8 +1084,8 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow bool IsBuilderFieldOnThis(ILInstruction inst) { - IField field; - ILInstruction target; + IField? field; + ILInstruction? target; if (builderType.IsReferenceType == true) { // ldfld(StateMachine::<>t__builder, ldloc(this)) @@ -1423,7 +1424,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } } - 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow { pos--; } + block.Instructions.RemoveRange(pos, block.Instructions.Count - pos); return true; } @@ -1538,7 +1540,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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) @@ -1819,7 +1821,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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; @@ -1929,7 +1931,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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/AwaitInCatchTransform.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs index 5ac50c1c1..569ccede8 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; @@ -66,7 +67,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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(); @@ -101,7 +102,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow break; case SwitchSection jumpTableEntry: Debug.Assert(switchInstructionOpt == null || jumpTableEntry.Parent == switchInstructionOpt); - switchInstructionOpt = (SwitchInstruction)jumpTableEntry.Parent; + switchInstructionOpt = jumpTableEntry.Parent as SwitchInstruction; break; } @@ -141,7 +142,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow if (result.NextBlockOrExitContainer is Block nextBlock && nextBlock.IncomingEdgeCount == 0) { List dependentBlocks = new List(); - Block current = nextBlock; + Block? current = nextBlock; do { @@ -198,10 +199,10 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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)) + 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); @@ -222,8 +223,8 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// /// 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) + static bool AnalyzeHandlers(InstructionCollection handlers, out ILVariable? catchHandlerIdentifier, + [NotNullWhen(true)] out List transformableCatchBlocks) { transformableCatchBlocks = new List(); catchHandlerIdentifier = null; @@ -254,9 +255,9 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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; @@ -354,7 +355,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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; @@ -419,7 +420,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // => // 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/ControlFlow/AwaitInFinallyTransform.cs b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs index 7cccce8bd..e70846af5 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs @@ -81,7 +81,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 bc6e10344..265516c01 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; @@ -44,9 +45,9 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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. @@ -58,7 +59,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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. @@ -200,7 +201,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 +611,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// 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/ControlFlowSimplification.cs b/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs index af864827e..282e198fc 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs @@ -120,11 +120,11 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // (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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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) { @@ -247,7 +247,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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 3475d4d61..defe7bd6f 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; @@ -56,7 +57,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// public class DetectPinnedRegions : IILTransform { - ILTransformContext context; + ILTransformContext? context; public void Run(ILFunction function, ILTransformContext context) { @@ -105,7 +106,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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) { @@ -162,7 +163,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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); @@ -175,7 +176,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow ((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); @@ -241,8 +242,8 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // ... // 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // } 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)) @@ -431,7 +432,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } } condition = condition.UnwrapConv(ConversionKind.Truncate); - if (condition.MatchLdLen(StackType.I, out ILInstruction array)) + if (condition.MatchLdLen(StackType.I, out ILInstruction? array)) { // OK } @@ -450,7 +451,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } 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; @@ -467,7 +468,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // } 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) { @@ -495,7 +496,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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) @@ -602,7 +603,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 +705,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow { // 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 +791,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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,13 +864,12 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow if (nativeVar.Type.GetStackType() != StackType.I) return; - Block targetBlock; - Block adjustOffsetToStringData = null; + 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; @@ -950,8 +950,8 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } 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 @@ -977,13 +977,13 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow { 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; @@ -1014,7 +1014,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 d8f2be9be..099d5325c 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/LoopDetection.cs @@ -78,7 +78,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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)) @@ -311,7 +311,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// 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) @@ -332,7 +332,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } return NoExitPoint; } - ControlFlowNode exitPoint = null; + ControlFlowNode? exitPoint = null; int exitPointILOffset = -1; ConsiderReturnAsExitPoint((Block)loopHead.UserData, ref exitPoint, ref exitPointILOffset); foreach (var node in loopHead.DominatorTreeChildren) @@ -540,7 +540,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow { rev[i] = new ControlFlowNode { UserIndex = i, UserData = cfg[i].UserData }; } - ControlFlowNode nodeTreatedAsExitNode = null; + ControlFlowNode? nodeTreatedAsExitNode = null; bool multipleNodesTreatedAsExitNodes = false; ControlFlowNode exitNode = new ControlFlowNode { UserIndex = -1 }; rev[cfg.Length] = exitNode; @@ -584,7 +584,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow return rev; } - static bool IsPossibleForeachLoop(Block loopHead, out Branch exitBranch) + static bool IsPossibleForeachLoop(Block loopHead, out Branch? exitBranch) { exitBranch = null; var container = (BlockContainer)loopHead.Parent; @@ -613,6 +613,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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 cd40c9223..d319b975b 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchAnalysis.cs @@ -24,7 +24,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// 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. @@ -126,7 +126,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow { return; } - if (inst.MatchBranch(out Block targetBlock)) + if (inst.MatchBranch(out Block? targetBlock)) { if (targetBlockToSectionIndex.TryGetValue(targetBlock, out int index)) { @@ -252,7 +252,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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)) { @@ -314,7 +314,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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/SwitchDetection.cs b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs index dc6bd309c..e973c5b4d 100644 --- a/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs +++ b/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs @@ -38,10 +38,10 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow { 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 @@ -233,9 +233,9 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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; @@ -403,7 +403,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// /// 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;" @@ -438,13 +438,13 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow // 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 dbea7d4cf..f24308444 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; @@ -72,15 +73,15 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// 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() @@ -89,7 +90,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// 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, @@ -105,17 +106,17 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow /// /// 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) @@ -268,7 +269,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow return false; } - ILInstruction newObj; + ILInstruction? newObj; if (body.Instructions.Count == 1) { // No parameters passed to enumerator (not even 'this'): @@ -942,7 +943,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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: @@ -1130,7 +1131,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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('>'); @@ -1232,7 +1233,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow { 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 @@ -1334,7 +1335,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow IMethod FindFinallyMethod(int state) { - IMethod foundMethod = null; + IMethod? foundMethod = null; foreach (var (method, stateRange) in finallyMethodToStateRange) { if (stateRange.Contains(state)) @@ -1426,7 +1427,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow } 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) @@ -1435,7 +1436,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow 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/ILReader.cs b/ICSharpCode.Decompiler/IL/ILReader.cs index 2ec9da40a..99b2419e0 100644 --- a/ICSharpCode.Decompiler/IL/ILReader.cs +++ b/ICSharpCode.Decompiler/IL/ILReader.cs @@ -312,7 +312,7 @@ namespace ICSharpCode.Decompiler.IL } 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 d49a684de..28fb6e394 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 @@ namespace ICSharpCode.Decompiler.IL 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 @@ namespace ICSharpCode.Decompiler.IL 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/PointerArithmeticOffset.cs b/ICSharpCode.Decompiler/IL/PointerArithmeticOffset.cs index b4c4008b3..344ab6db8 100644 --- a/ICSharpCode.Decompiler/IL/PointerArithmeticOffset.cs +++ b/ICSharpCode.Decompiler/IL/PointerArithmeticOffset.cs @@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.IL /// 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 bee806143..c30339837 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs @@ -227,7 +227,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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; @@ -371,7 +371,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ -463,7 +463,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return SplitName(proposedName, out _); } - static string GetNameFromInstruction(ILInstruction inst) + static string? GetNameFromInstruction(ILInstruction inst) { switch (inst) { @@ -506,7 +506,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return null; } - static string GetNameForArgument(ILInstruction parent, int i) + static string? GetNameForArgument(ILInstruction parent, int i) { switch (parent) { @@ -566,7 +566,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms return name; } - static string CleanUpVariableName(string name) + static string? CleanUpVariableName(string name) { // remove the backtick (generics) int pos = name.IndexOf('`'); @@ -701,7 +701,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } 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 4bfa3a996..22c064254 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CachedDelegateInitialization.cs @@ -84,13 +84,13 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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]; - 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; @@ -114,13 +114,13 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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()) + 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; @@ -154,10 +154,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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()) + 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; @@ -186,10 +186,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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()) + 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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/CombineExitsTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs index 03e6ffbf1..fa067c882 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CombineExitsTransform.cs @@ -30,7 +30,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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/CopyPropagation.cs b/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs index 1f3251fd2..33e90a01e 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs @@ -61,11 +61,11 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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++) { - if (block.Instructions[i].MatchStLoc(out ILVariable v, out ILInstruction copiedExpr)) + if (block.Instructions[i].MatchStLoc(out ILVariable? v, out ILInstruction? copiedExpr)) { if (v.IsSingleDefinition && v.LoadCount == 0 && v.Kind == VariableKind.StackSlot) { diff --git a/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/DeconstructionTransform.cs index 8a765b7e3..9e7836ed8 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; @@ -33,11 +34,11 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// class DeconstructionTransform : IStatementTransform { - StatementTransformContext context; + 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)) @@ -103,7 +104,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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,9 +190,9 @@ namespace ICSharpCode.Decompiler.IL.Transforms bool TransformDeconstruction(Block block, int pos) { int startPos = pos; - Action delayedActions = null; - if (MatchDeconstruction(block.Instructions[pos], out IMethod deconstructMethod, - out ILInstruction rootTestedOperand)) + Action? delayedActions = null; + if (MatchDeconstruction(block.Instructions[pos], out IMethod? deconstructMethod, + out ILInstruction? rootTestedOperand)) { pos++; } @@ -262,8 +263,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - bool MatchAssignment(ILInstruction inst, out IType targetType, out ILInstruction valueInst, out 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 bf8734357..6d0909158 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; @@ -79,8 +80,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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, + [NotNullWhen(true)] out ILInstruction? target, [NotNullWhen(true)] out IType? delegateType, bool allowTransformed = false) { targetMethod = null; target = null; @@ -164,7 +165,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return new GenericContext(classTypeParameters, methodTypeParameters); } - ILFunction TransformDelegateConstruction( + ILFunction? TransformDelegateConstruction( ILInstruction value, IMethod targetMethod, ILInstruction target, IType delegateType) { @@ -285,7 +286,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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 f68c6d076..d539039d0 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms return false; if (right.MatchLdNull()) { + return branch.MatchBranch(out whenConditionBlock); } } @@ -218,7 +220,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 2c78d42f9..54b8cd5cf 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; @@ -146,7 +147,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms container.SortBlocks(deleteUnreachableBlocks: true); } - ILInstruction MakeDynamicInstruction(CallSiteInfo callsite, CallVirt targetInvokeCall, List deadArguments) + ILInstruction? MakeDynamicInstruction(CallSiteInfo callsite, CallVirt targetInvokeCall, List deadArguments) { switch (callsite.Kind) { @@ -272,7 +273,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 9afcb2706..f81355bec 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 @@ -79,7 +80,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// } /// 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 +122,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 3d99d0400..54458029a 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; @@ -103,7 +104,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms // This transform is required because ILInlining only works with stloc/ldloc internal static bool StObjToStLoc(StObj 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) @@ -131,7 +132,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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) @@ -175,7 +176,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -221,6 +222,5 @@ namespace ICSharpCode.Decompiler.IL.Transforms } return false; } - } } diff --git a/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs b/ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs index ed086d68f..5a28917a6 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; @@ -140,7 +141,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } 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) @@ -166,7 +167,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -301,8 +302,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms protected internal override void VisitNewObj(NewObj inst) { - Block block; - if (TransformSpanTCtorContainingStackAlloc(inst, out ILInstruction locallocSpan)) + Block? block; + if (TransformSpanTCtorContainingStackAlloc(inst, out ILInstruction? locallocSpan)) { context.Step("new Span(stackalloc) -> stackalloc Span", inst); inst.ReplaceWith(locallocSpan); @@ -328,7 +329,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -342,7 +343,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// => /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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)) { @@ -461,7 +462,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -542,14 +543,14 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; - 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); @@ -570,8 +571,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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) @@ -628,7 +629,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { // 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 d912ae247..7ed3818d2 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms ExpressionTransforms.RunOnSingleStatment(inst, context); } }*/ - return true; } @@ -156,21 +156,21 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 _)); @@ -199,7 +199,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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) { @@ -240,7 +240,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } // 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms (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)); @@ -419,7 +419,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms // split conditions: var conditions = new List(); SplitConditions(whileCondition.Condition, conditions); - IfInstruction forCondition = null; + IfInstruction? forCondition = null; int numberOfConditions = 0; foreach (var condition in conditions) { @@ -480,7 +480,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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/ILExtraction.cs b/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs index a3627a221..12432ff90 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ILExtraction.cs @@ -97,7 +97,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 7b38b2e90..bfcc4afec 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs @@ -170,7 +170,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -577,7 +577,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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); @@ -741,10 +741,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -784,7 +784,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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/IndexRangeTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/IndexRangeTransform.cs index f21c7fb0a..dd8136a8a 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; @@ -37,7 +38,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { if (!context.Settings.Ranges) return false; - if (!ldelema.Array.MatchLdLoc(out ILVariable array)) + if (!ldelema.Array.MatchLdLoc(out ILVariable? array)) return false; if (ldelema.Indices.Count != 1) return false; // the index/range feature doesn't support multi-dimensional arrays @@ -150,9 +151,9 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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)) + if (MatchContainerLengthStore(block.Instructions[pos], out var containerLengthVar, ref containerVar)) { // stloc containerLengthVar(call get_Length/get_Count(ldloc container)) pos++; @@ -175,7 +176,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } // stloc startOffsetVar(call GetOffset(startIndexLoad, ldloc length)) - if (!(block.Instructions[pos].MatchStLoc(out ILVariable startOffsetVar, out ILInstruction startOffsetVarInit) + if (!(block.Instructions[pos].MatchStLoc(out ILVariable? startOffsetVar, out ILInstruction? startOffsetVarInit) && startOffsetVar.IsSingleDefinition && startOffsetVar.StackType == StackType.I4)) { // Not our primary indexing/slicing pattern. @@ -274,8 +275,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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, @@ -302,7 +303,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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)) { @@ -410,7 +411,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } 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 +466,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 ed26c0402..640f9a872 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; @@ -31,7 +32,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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, @@ -104,7 +105,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 f00fc48b0..a68dc8cc4 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/LocalFunctionDecompiler.cs @@ -20,6 +20,7 @@ using System; 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; @@ -307,7 +308,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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) { @@ -320,7 +321,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return null; } - private ILVariable ResolveAncestorScopeReference(ILInstruction inst) + private ILVariable? ResolveAncestorScopeReference(ILInstruction inst) { if (!inst.MatchLdFld(out var target, out var field)) return null; @@ -337,7 +338,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return null; } - private ILFunction GetDeclaringFunction(ILFunction localFunction) + private ILFunction? GetDeclaringFunction(ILFunction localFunction) { if (localFunction.DeclarationScope == null) return null; @@ -445,7 +446,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - ILFunction ReadLocalFunctionDefinition(ILFunction rootFunction, IMethod targetMethod, int skipCount) + ILFunction? ReadLocalFunctionDefinition(ILFunction rootFunction, IMethod targetMethod, int skipCount) { var methodDefinition = context.PEFile.Metadata.GetMethodDefinition((MethodDefinitionHandle)targetMethod.MetadataToken); var genericContext = GenericContextFromTypeArguments(targetMethod, skipCount); @@ -722,7 +723,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms function.DeclarationScope = FindCommonAncestorInstruction(function.DeclarationScope, closureVar.CaptureScope); return true; - ILInstruction GetClosureInitializer(ILVariable variable) + ILInstruction? GetClosureInitializer(ILVariable variable) { var type = variable.Type.UnwrapByRef().GetDefinition(); if (type == null) @@ -758,7 +759,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +798,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +832,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 084c3bd79..07a691282 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 @@ -292,7 +294,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -331,7 +333,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 cb7d2161c..6e988f724 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; @@ -70,7 +71,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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"); @@ -106,7 +107,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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; @@ -237,7 +238,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms ).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; @@ -445,7 +446,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms // => // 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 +476,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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 111cac3ce..bf4d45691 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; @@ -41,7 +42,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms struct NullableLiftingTransform { readonly ILTransformContext context; - List nullableVars; + List? nullableVars; public NullableLiftingTransform(ILTransformContext context) { @@ -175,7 +176,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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. @@ -371,7 +372,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -478,7 +479,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - internal ILInstruction MakeLifted(ComparisonKind newComparisonKind, ILInstruction left, ILInstruction right) + internal ILInstruction? MakeLifted(ComparisonKind newComparisonKind, ILInstruction left, ILInstruction right) { if (Instruction is Comp comp) { @@ -518,7 +519,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms #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 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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/ProxyCallReplacer.cs b/ICSharpCode.Decompiler/IL/Transforms/ProxyCallReplacer.cs index 164b806e2..f409c85b7 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ProxyCallReplacer.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ProxyCallReplacer.cs @@ -63,7 +63,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 2876f141e..b870bc10d 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/ReduceNestingTransform.cs @@ -54,7 +54,7 @@ namespace ICSharpCode.Decompiler.IL } } - private void Visit(BlockContainer container, Block continueTarget) + private void Visit(BlockContainer container, Block? continueTarget) { switch (container.Kind) { @@ -84,7 +84,7 @@ namespace ICSharpCode.Decompiler.IL /// /// 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 @@ namespace ICSharpCode.Decompiler.IL /// 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 @@ namespace ICSharpCode.Decompiler.IL /// /// 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)) @@ -451,7 +451,7 @@ namespace ICSharpCode.Decompiler.IL /// /// [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/RemoveDeadVariableInit.cs b/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs index 7501338b3..bd4b6de12 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/RemoveDeadVariableInit.cs @@ -85,7 +85,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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/SplitVariables.cs b/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs index 4f3bbd698..ce24e3a31 100644 --- a/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs +++ b/ICSharpCode.Decompiler/IL/Transforms/SplitVariables.cs @@ -175,7 +175,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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/SwitchOnNullableTransform.cs b/ICSharpCode.Decompiler/IL/Transforms/SwitchOnNullableTransform.cs index 7490a3206..efbbd1309 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 e254d243b..419ea000f 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; @@ -105,9 +106,9 @@ namespace ICSharpCode.Decompiler.IL.Transforms context.Step("Remove hashtable initializer", actual); if (jumpToNext != null) { - actual.Instructions.SecondToLastOrDefault().ReplaceWith(jumpToNext); + actual.Instructions.SecondToLastOrDefault()?.ReplaceWith(jumpToNext); } - actual.Instructions.LastOrDefault().ReplaceWith(new Branch(next)); + actual.Instructions.LastOrDefault()?.ReplaceWith(new Branch(next)); omittedBlocks.Add(containingBlock, previous); changedContainers.Add(body); } @@ -195,7 +196,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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) { @@ -216,13 +217,13 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -231,7 +232,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return true; } - ILInstruction switchValue = null; + ILInstruction? switchValue = null; if (isVBCompareString && string.IsNullOrEmpty(firstBlockValue)) { if (!AddSwitchSection(null, firstBlock ?? firstBlockOrDefaultJump)) @@ -305,14 +306,14 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } // 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)) { @@ -421,8 +422,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -439,9 +440,9 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -473,7 +474,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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,19 +504,20 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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) { @@ -532,21 +534,21 @@ namespace ICSharpCode.Decompiler.IL.Transforms } else { - return null; + return (null, null); } - if (nextBlockBranch.MatchBranch(out Block nextBlock)) + if (nextBlockBranch.MatchBranch(out Block? nextBlock)) { // success - return nextBlock; + return (nextBlock, caseBlockOrLeave); } - else if (nextBlockBranch.MatchLeave(out BlockContainer blockContainer)) + else if (nextBlockBranch.MatchLeave(out BlockContainer? blockContainer)) { // success - return blockContainer; + return (blockContainer, caseBlockOrLeave); } else { - return null; + return (null, caseBlockOrLeave); } } @@ -569,7 +571,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +586,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -703,7 +705,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return true; } - bool FixCasesWithoutValue(List sections, List<(string, int)> stringValues) + bool FixCasesWithoutValue(List sections, List<(string?, int)> stringValues) { bool HasLabel(SwitchSection section) { @@ -740,7 +742,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +762,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 +775,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 +799,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +824,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// -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 +943,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +998,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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)) { @@ -1029,20 +1031,20 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -1167,9 +1169,9 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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; + 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,10 +1204,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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(); + List<(string?, ILInstruction)> stringValues = new(); foreach (var b in blocksByLength) { if (b.Length.Count() != 1) @@ -1230,7 +1232,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } } - 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; @@ -1268,7 +1270,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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()) { @@ -1310,12 +1312,12 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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) return false; - SwitchInstruction @switch; + SwitchInstruction? @switch; List> sections; int index; switch (block.Instructions.Count) @@ -1399,12 +1401,12 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; - ILInstruction getLengthCall; - ILVariable lengthVar; + SwitchInstruction? @switch; + ILInstruction? getLengthCall; + ILVariable? lengthVar; switch (switchOnLengthBlock.Instructions.Count - startOffset) { case 1: @@ -1475,6 +1477,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms default: return false; } + if (@switch == null) return true; blocks = new(@switch.Sections.Count); @@ -1506,7 +1509,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 +1535,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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, out Block? defaultOrExitBlock, out string? stringValue, out bool emptyStringEqualsNull) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1592,7 +1595,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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, out Block? defaultOrExitBlock) { bodyOrLeave = null; defaultOrExitBlock = null; @@ -1602,7 +1605,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -1627,6 +1630,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return false; if (bodyBranch.MatchLeave(out _)) { + bodyOrLeave = bodyBranch; return true; } @@ -1660,7 +1664,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// - 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 +1686,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 +1696,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 7ddec2e56..26dd639d6 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; @@ -33,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) { @@ -114,7 +115,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms elementType = ((PointerType)finalStore.Variable.Type).ElementType; } instructionsToRemove += elementCount; - return elementCount <= values.Length; } @@ -498,7 +498,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms // 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms } 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. @@ -656,7 +656,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -671,7 +671,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { // 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 b5530fb70..75bbd4671 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; @@ -176,7 +177,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +265,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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)) @@ -544,7 +545,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; } @@ -570,7 +571,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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()) { @@ -677,8 +678,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// /// 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; @@ -766,10 +767,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 +871,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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))) { @@ -1025,7 +1026,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 c433c3b81..086f27c73 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; @@ -51,7 +52,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { private readonly DisplayClass container; private readonly IField field; - private ILVariable declaredVariable; + private ILVariable? declaredVariable; public string Name => field.Name; @@ -60,7 +61,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -69,7 +70,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms Debug.Assert(declaredVariable == null || declaredVariable.StateMachineField == field); } - public void Propagate(ILVariable variable) + public void Propagate(ILVariable? variable) { this.declaredVariable = variable; this.CanPropagate = variable != null; @@ -93,8 +94,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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) { @@ -104,8 +105,8 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - ILTransformContext context; - ITypeResolveContext decompilationContext; + ILTransformContext? context; + ITypeResolveContext? decompilationContext; readonly Dictionary displayClasses = new Dictionary(); readonly Dictionary displayClassCopyMap = new Dictionary(); @@ -245,7 +246,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - private DisplayClass AnalyzeVariable(ILVariable v) + private DisplayClass? AnalyzeVariable(ILVariable v) { switch (v.Kind) { @@ -264,9 +265,9 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - DisplayClass DetectDisplayClass(ILVariable v) + DisplayClass? DetectDisplayClass(ILVariable v) { - ITypeDefinition definition; + ITypeDefinition? definition; if (v.Kind != VariableKind.StackSlot) { definition = v.Type.GetDefinition(); @@ -363,7 +364,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -384,7 +385,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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; @@ -501,7 +502,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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) @@ -519,7 +520,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 +554,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +589,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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) { @@ -633,7 +634,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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; @@ -673,7 +674,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } 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)) @@ -840,18 +841,18 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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 81632f6a5..3a7e3f1e8 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -80,7 +81,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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")) @@ -153,7 +154,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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 +199,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - (Func, IType) ConvertQuote(CallInstruction invocation) + (Func?, IType) ConvertQuote(CallInstruction invocation) { if (invocation.Arguments.Count != 1) return (null, SpecialType.UnknownType); @@ -266,7 +267,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - (Func, IType) ConvertInstruction(ILInstruction instruction, IType typeHint = null) + (Func?, IType) ConvertInstruction(ILInstruction instruction, IType? typeHint = null) { var (inst, type) = Convert(); @@ -289,7 +290,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } return (DoConvert, typeHint ?? type); - (Func, IType) Convert() + (Func?, IType) Convert() { switch (instruction) { @@ -397,7 +398,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { if (function.Kind == ILFunctionKind.ExpressionTree) { - function.DelegateType = UnwrapExpressionTree(function.DelegateType); + function.DelegateType = UnwrapExpressionTree(function.DelegateType!); function.Kind = ILFunctionKind.Delegate; } return function; @@ -446,7 +447,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return delegateType; } - (Func, IType) ConvertArrayIndex(CallInstruction invocation) + (Func?, IType) ConvertArrayIndex(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -458,7 +459,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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++) @@ -473,7 +474,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +484,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -535,7 +536,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - (Func, IType) ConvertBind(CallInstruction invocation) + (Func?, IType) ConvertBind(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -574,13 +575,13 @@ namespace ICSharpCode.Decompiler.IL.Transforms return (null, SpecialType.UnknownType); } - (Func, IType) ConvertCall(CallInstruction invocation) + (Func?, IType) ConvertCall(CallInstruction invocation) { 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 @@ -682,7 +683,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -697,7 +698,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +712,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +743,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms }, 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 +791,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +809,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +822,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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,11 +850,11 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); - Func targetConverter = null; + Func? targetConverter = null; if (!invocation.Arguments[0].MatchLdNull()) { targetConverter = ConvertInstruction(invocation.Arguments[0]).Item1; @@ -896,7 +897,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - (Func, IType) ConvertInvoke(CallInstruction invocation) + (Func?, IType) ConvertInvoke(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -922,7 +923,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +979,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +1017,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - (Func, IType) ConvertMemberInit(CallInstruction invocation) + (Func?, IType) ConvertMemberInit(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -1064,7 +1065,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +1086,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -1124,7 +1125,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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") @@ -1154,7 +1155,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - (Func, IType) ConvertNewObject(CallInstruction invocation) + (Func?, IType) ConvertNewObject(CallInstruction invocation) { switch (invocation.Arguments.Count) { @@ -1203,7 +1204,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return (null, SpecialType.UnknownType); } - (Func, IType) ConvertNotOperator(CallInstruction invocation) + (Func?, IType) ConvertNotOperator(CallInstruction invocation) { if (invocation.Arguments.Count < 1) return (null, SpecialType.UnknownType); @@ -1229,12 +1230,12 @@ namespace ICSharpCode.Decompiler.IL.Transforms } } - (Func, IType) ConvertProperty(CallInstruction invocation) + (Func?, IType) ConvertProperty(CallInstruction invocation) { 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]); @@ -1272,7 +1273,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 +1294,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return (BuildTypeAs, type); } - (Func, IType) ConvertTypeIs(CallInstruction invocation) + (Func?, IType) ConvertTypeIs(CallInstruction invocation) { if (invocation.Arguments.Count != 2) return (null, SpecialType.UnknownType); @@ -1306,7 +1307,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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); @@ -1358,7 +1359,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms return (null, SpecialType.UnknownType); } - ILInstruction ConvertValue(ILInstruction value, ILInstruction context) + ILInstruction? ConvertValue(ILInstruction value, ILInstruction context) { switch (value) { @@ -1413,7 +1414,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms && 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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 7b6f5cdbe..d7e3497ac 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 @@ namespace ICSharpCode.Decompiler.IL /// 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 9f1221385..559e107ff 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 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -146,7 +147,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms /// 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; @@ -163,7 +164,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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; @@ -232,7 +233,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms } // 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 96fe3d13d..c6148085b 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; @@ -245,7 +246,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms { 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 +489,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms 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/DotNetCorePathFinder.cs b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs index 00a208674..d98f2fee3 100644 --- a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs +++ b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs @@ -95,7 +95,7 @@ namespace ICSharpCode.Decompiler.Metadata } 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 @@ namespace ICSharpCode.Decompiler.Metadata } } - public string TryResolveDotNetCoreShared(IAssemblyReference name, out string runtimePack) + public string? TryResolveDotNetCoreShared(IAssemblyReference name, out string? runtimePack) { if (dotnetBasePath == null) { @@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.Metadata return version.ToString(); } - internal static (Version version, DirectoryInfo directory) ConvertToVersion(DirectoryInfo directory) + internal static (Version? version, DirectoryInfo? directory) ConvertToVersion(DirectoryInfo directory) { string RemoveTrailingVersionInfo() { @@ -286,10 +286,10 @@ namespace ICSharpCode.Decompiler.Metadata } } - 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)) + foreach (var item in Environment.GetEnvironmentVariable("PATH")!.Split(Path.PathSeparator)) { try { @@ -312,7 +312,7 @@ namespace ICSharpCode.Decompiler.Metadata 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/DotNetCorePathFinderExtensions.cs b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs index 692515ca9..91e80b102 100644 --- a/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs +++ b/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs @@ -44,7 +44,7 @@ namespace ICSharpCode.Decompiler.Metadata 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/LightJson/JsonValue.cs b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs index c79ac3459..4fb65c955 100644 --- a/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs +++ b/ICSharpCode.Decompiler/Metadata/LightJson/JsonValue.cs @@ -24,7 +24,7 @@ namespace LightJson 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 @@ namespace LightJson /// 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; @@ -329,7 +329,7 @@ namespace LightJson /// Gets this value as a String type. /// /// This value as a String type. - public string AsString { + public string? AsString { get { switch (this.Type) { @@ -354,10 +354,10 @@ namespace LightJson /// Gets this value as an JsonObject. /// /// This value as an JsonObject. - public JsonObject AsJsonObject { + public JsonObject? AsJsonObject { get { return this.IsJsonObject - ? (JsonObject)this.reference + ? (JsonObject?)this.reference : null; } } @@ -366,10 +366,10 @@ namespace LightJson /// Gets this value as an JsonArray. /// /// This value as an JsonArray. - public JsonArray AsJsonArray { + public JsonArray? AsJsonArray { get { return this.IsJsonArray - ? (JsonArray)this.reference + ? (JsonArray?)this.reference : null; } } @@ -382,7 +382,7 @@ namespace LightJson 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; } @@ -397,7 +397,7 @@ namespace LightJson /// 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) { @@ -427,7 +427,7 @@ namespace LightJson get { if (this.IsJsonObject) { - return ((JsonObject)this.reference)[key]; + return ((JsonObject?)this.reference)[key]; } else { @@ -438,7 +438,7 @@ namespace LightJson set { if (this.IsJsonObject) { - ((JsonObject)this.reference)[key] = value; + ((JsonObject?)this.reference)[key] = value; } else { @@ -458,7 +458,7 @@ namespace LightJson get { if (this.IsJsonArray) { - return ((JsonArray)this.reference)[index]; + return ((JsonArray?)this.reference)[index]; } else { @@ -469,7 +469,7 @@ namespace LightJson set { if (this.IsJsonArray) { - ((JsonArray)this.reference)[index] = value; + ((JsonArray?)this.reference)[index] = value; } else { @@ -764,7 +764,7 @@ namespace LightJson } /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) { @@ -808,7 +808,7 @@ namespace LightJson } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public JsonObject ObjectView { + public JsonObject? ObjectView { get { if (this.jsonValue.IsJsonObject) { @@ -822,7 +822,7 @@ namespace LightJson } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public JsonArray ArrayView { + public JsonArray? ArrayView { get { if (this.jsonValue.IsJsonArray) { diff --git a/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs b/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs index 90f44096a..fa41f5027 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 @@ namespace ICSharpCode.Decompiler.Metadata $"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 @@ namespace ICSharpCode.Decompiler.Metadata 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 53ef9ea6f..306a8c31e 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 @@ namespace ICSharpCode.Decompiler.Metadata } } - 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/NRExtensions.cs b/ICSharpCode.Decompiler/NRExtensions.cs index 58850d2b8..638c3d63f 100644 --- a/ICSharpCode.Decompiler/NRExtensions.cs +++ b/ICSharpCode.Decompiler/NRExtensions.cs @@ -92,7 +92,7 @@ namespace ICSharpCode.Decompiler } } - 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/TextOutputWriter.cs b/ICSharpCode.Decompiler/Output/TextOutputWriter.cs index afd84cbbc..c2774d404 100644 --- a/ICSharpCode.Decompiler/Output/TextOutputWriter.cs +++ b/ICSharpCode.Decompiler/Output/TextOutputWriter.cs @@ -42,7 +42,7 @@ namespace ICSharpCode.Decompiler output.Write(value); } - public override void Write(string value) + public override void Write(string? value) { output.Write(value); } diff --git a/ICSharpCode.Decompiler/Output/TextTokenWriter.cs b/ICSharpCode.Decompiler/Output/TextTokenWriter.cs index d225feeaa..fbb14dc56 100644 --- a/ICSharpCode.Decompiler/Output/TextTokenWriter.cs +++ b/ICSharpCode.Decompiler/Output/TextTokenWriter.cs @@ -108,7 +108,7 @@ namespace ICSharpCode.Decompiler output.Write(name); } - ISymbol GetCurrentMemberReference() + ISymbol? GetCurrentMemberReference() { AstNode node = nodeStack.Peek(); var symbol = node.GetSymbol(); @@ -130,7 +130,7 @@ namespace ICSharpCode.Decompiler return FilterMember(symbol); } - ISymbol FilterMember(ISymbol symbol) + ISymbol? FilterMember(ISymbol symbol) { if (symbol == null) return null; @@ -141,7 +141,7 @@ namespace ICSharpCode.Decompiler return symbol; } - object GetCurrentLocalReference() + object? GetCurrentLocalReference() { AstNode node = nodeStack.Peek(); ILVariable variable = node.Annotation()?.Variable; @@ -169,7 +169,7 @@ namespace ICSharpCode.Decompiler 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 @@ namespace ICSharpCode.Decompiler return null; } - ISymbol GetCurrentDefinition() + ISymbol? GetCurrentDefinition() { if (nodeStack == null || nodeStack.Count == 0) return null; @@ -363,7 +363,7 @@ namespace ICSharpCode.Decompiler 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 750f49f42..6b12228cb 100644 --- a/ICSharpCode.Decompiler/SRMExtensions.cs +++ b/ICSharpCode.Decompiler/SRMExtensions.cs @@ -628,7 +628,7 @@ namespace ICSharpCode.Decompiler #endregion public static unsafe BlobReader GetInitialValue(this FieldDefinition field, MetadataFile pefile, - ICompilation typeSystem) + ICompilation? typeSystem) { if (!field.HasFlag(FieldAttributes.HasFieldRVA)) return default; @@ -647,10 +647,10 @@ namespace ICSharpCode.Decompiler sealed class FieldValueSizeDecoder : ISignatureTypeProvider { - readonly MetadataModule module; + 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/ConstantResolveResult.cs b/ICSharpCode.Decompiler/Semantics/ConstantResolveResult.cs index d475de1ae..5336def6c 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 @@ namespace ICSharpCode.Decompiler.Semantics get { return true; } } - public override object ConstantValue { + public override object? ConstantValue { get { return constantValue; } } diff --git a/ICSharpCode.Decompiler/Semantics/Conversion.cs b/ICSharpCode.Decompiler/Semantics/Conversion.cs index a92735b4f..1d5248527 100644 --- a/ICSharpCode.Decompiler/Semantics/Conversion.cs +++ b/ICSharpCode.Decompiler/Semantics/Conversion.cs @@ -168,9 +168,9 @@ namespace ICSharpCode.Decompiler.Semantics + " conversion"; } - public override bool Equals(Conversion other) + 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 @@ namespace ICSharpCode.Decompiler.Semantics public override string ToString() { - string name = null; + string? name = null; switch (type) { case 0: @@ -335,9 +335,9 @@ namespace ICSharpCode.Decompiler.Semantics get { return method; } } - public override bool Equals(Conversion other) + 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); } @@ -394,9 +394,9 @@ namespace ICSharpCode.Decompiler.Semantics get { return method; } } - public override bool Equals(Conversion other) + public override bool Equals(Conversion? other) { - MethodGroupConv o = other as MethodGroupConv; + MethodGroupConv? o = other as MethodGroupConv; return o != null && method.Equals(o.method); } @@ -419,7 +419,7 @@ namespace ICSharpCode.Decompiler.Semantics 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 @@ namespace ICSharpCode.Decompiler.Semantics /// /// 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 @@ namespace ICSharpCode.Decompiler.Semantics /// 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 @@ namespace ICSharpCode.Decompiler.Semantics /// 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 @@ namespace ICSharpCode.Decompiler.Semantics return base.GetHashCode(); } - public virtual bool Equals(Conversion other) + public virtual bool Equals(Conversion? other) { return this == other; } diff --git a/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs b/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs index 1b07b653f..69ebb8cd7 100644 --- a/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs @@ -42,10 +42,10 @@ namespace ICSharpCode.Decompiler.Semantics /// public readonly IList InitializerStatements; - public InvocationResolveResult(ResolveResult targetResult, IParameterizedMember member, - IList arguments = null, - IList initializerStatements = null, - IType returnTypeOverride = null) + public InvocationResolveResult(ResolveResult? targetResult, IParameterizedMember member, + 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 ac8be7989..4eb744def 100644 --- a/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs @@ -43,7 +43,7 @@ namespace ICSharpCode.Decompiler.Semantics 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; } @@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.Semantics get { return variable.IsConst; } } - public override object ConstantValue { + public override object? ConstantValue { get { return IsParameter ? null : variable.GetConstantValue(); } } diff --git a/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs b/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs index 358a84386..bfd1729cd 100644 --- a/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/MemberResolveResult.cs @@ -33,11 +33,11 @@ namespace ICSharpCode.Decompiler.Semantics { 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 @@ namespace ICSharpCode.Decompiler.Semantics 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 @@ namespace ICSharpCode.Decompiler.Semantics } } - 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 @@ namespace ICSharpCode.Decompiler.Semantics this.isVirtualCall = isVirtualCall; } - public ResolveResult TargetResult { + public ResolveResult? TargetResult { get { return targetResult; } } @@ -127,7 +127,7 @@ namespace ICSharpCode.Decompiler.Semantics 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 10f6d488f..02c7bdd76 100644 --- a/ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs @@ -50,7 +50,7 @@ namespace ICSharpCode.Decompiler.Semantics /// 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/OperatorResolveResult.cs b/ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs index cd54d315e..45f83eb1e 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 @@ namespace ICSharpCode.Decompiler.Semantics 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.Decompiler/Semantics/ResolveResult.cs b/ICSharpCode.Decompiler/Semantics/ResolveResult.cs index 6ca0a177a..6abb83e96 100644 --- a/ICSharpCode.Decompiler/Semantics/ResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/ResolveResult.cs @@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.Semantics 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 59923dff4..67f3e8f06 100644 --- a/ICSharpCode.Decompiler/Semantics/TupleResolveResult.cs +++ b/ICSharpCode.Decompiler/Semantics/TupleResolveResult.cs @@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.Semantics 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 76418f3b2..971ea2263 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ApplyAttributeTypeVisitor.cs @@ -45,12 +45,12 @@ namespace ICSharpCode.Decompiler.TypeSystem 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; @@ -175,11 +175,11 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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; @@ -253,7 +253,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 f10da4531..8c7a98b18 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ArrayType.cs @@ -43,7 +43,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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."); } @@ -85,9 +85,9 @@ namespace ICSharpCode.Decompiler.TypeSystem return unchecked(elementType.GetHashCode() * 71681 + dimensions); } - public override bool Equals(IType other) + 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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/AssemblyQualifiedTypeName.cs b/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs index 2643842f1..e819fd416 100644 --- a/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs +++ b/ICSharpCode.Decompiler/TypeSystem/AssemblyQualifiedTypeName.cs @@ -45,7 +45,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 1b686012e..4eda51b97 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs @@ -49,9 +49,9 @@ namespace ICSharpCode.Decompiler.TypeSystem return elementType.GetHashCode() ^ 91725813; } - public override bool Equals(IType other) + 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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/DecompilerTypeSystem.cs b/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs index 896f9e802..1c688a03f 100644 --- a/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs +++ b/ICSharpCode.Decompiler/TypeSystem/DecompilerTypeSystem.cs @@ -245,7 +245,7 @@ namespace ICSharpCode.Decompiler.TypeSystem // 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 @@ namespace ICSharpCode.Decompiler.TypeSystem { // 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/FullTypeName.cs b/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs index 36712ee64..fec605b9d 100644 --- a/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs +++ b/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.Decompiler.TypeSystem } readonly TopLevelTypeName topLevelType; - readonly NestedTypeName[] nestedTypes; + readonly NestedTypeName[]? nestedTypes; FullTypeName(TopLevelTypeName topLevelTypeName, NestedTypeName[] nestedTypes) { @@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.TypeSystem } #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 5d71478fd..b5c27eaa4 100644 --- a/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/FunctionPointerType.cs @@ -123,7 +123,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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) { @@ -151,7 +151,7 @@ namespace ICSharpCode.Decompiler.TypeSystem { 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); @@ -179,7 +179,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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/GenericContext.cs b/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs index ddb41c94e..40a4f1c8f 100644 --- a/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs +++ b/ICSharpCode.Decompiler/TypeSystem/GenericContext.cs @@ -25,16 +25,16 @@ 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; } - public GenericContext(IReadOnlyList classTypeParameters, IReadOnlyList methodTypeParameters) + public GenericContext(IReadOnlyList? classTypeParameters, IReadOnlyList? methodTypeParameters) { this.ClassTypeParameters = classTypeParameters; this.MethodTypeParameters = methodTypeParameters; diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs index aca56d7e3..4c6fa71ce 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractFreezable.cs @@ -61,7 +61,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 b6b3bef3a..fd9e25ace 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs @@ -83,16 +83,16 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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; } @@ -101,47 +101,47 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation .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; } @@ -165,7 +165,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/AbstractTypeParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs index 289fc35e7..2104a5edb 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractTypeParameter.cs @@ -29,12 +29,12 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation { 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation get { return ownerType; } } - public IEntity Owner { + public IEntity? Owner { get { return owner; } } @@ -83,7 +83,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation get { return compilation; } } - volatile IType effectiveBaseClass; + volatile IType? effectiveBaseClass; public IType EffectiveBaseClass { get { @@ -132,7 +132,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return result; } - IReadOnlyCollection effectiveInterfaceSet; + IReadOnlyCollection? effectiveInterfaceSet; public IReadOnlyCollection EffectiveInterfaceSet { get { @@ -193,7 +193,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return new NullabilityAnnotatedTypeParameter(this, nullability); } - IType IType.DeclaringType { + IType? IType.DeclaringType { get { return null; } } @@ -265,12 +265,12 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - ITypeDefinition IType.GetDefinition() + ITypeDefinition? IType.GetDefinition() { return null; } - ITypeDefinitionOrUnknown IType.GetDefinitionOrUnknown() + ITypeDefinitionOrUnknown? IType.GetDefinitionOrUnknown() { return null; } @@ -285,17 +285,17 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/AttributeListBuilder.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs index 66d77a735..66eedf359 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/AttributeListBuilder.cs @@ -283,7 +283,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 9ef688330..f760cc27c 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/CustomAttribute.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/CustomAttribute.cs @@ -109,7 +109,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 effeb11a1..777d440a2 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecimalConstantHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecimalConstantHelper.cs @@ -32,7 +32,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/DecoratedType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs index 5107044f2..a3d25f822 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DecoratedType.cs @@ -22,7 +22,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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,64 +42,64 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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) + 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); } - ITypeDefinition IType.GetDefinition() + ITypeDefinition? IType.GetDefinition() { return baseType.GetDefinition(); } - ITypeDefinitionOrUnknown IType.GetDefinitionOrUnknown() + 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/DefaultAssemblyReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs index 6c1b4519c..726390342 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultAssemblyReference.cs @@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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)) @@ -67,7 +67,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 4fa30a818..a5e7f4395 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultParameter.cs @@ -48,8 +48,8 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 3e4398ec3..05df03ba3 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultTypeParameter.cs @@ -33,11 +33,11 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 c81b8d85d..56c86518a 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DefaultVariable.cs @@ -41,7 +41,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } 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/DummyTypeParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs index 16f96c6e5..06b5519a6 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/DummyTypeParameter.cs @@ -163,7 +163,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 ca9b556d7..3bb07edfe 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; @@ -62,7 +63,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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; @@ -94,7 +95,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation string INamedElement.Namespace => DeclaringType?.Namespace; - bool IMember.Equals(IMember obj, TypeVisitor typeNormalization) + bool IMember.Equals(IMember? obj, TypeVisitor typeNormalization) { return Equals(obj); } @@ -113,7 +114,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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; @@ -152,10 +153,10 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/GetClassTypeReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs index 0c161ca5c..56d132108 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetClassTypeReference.cs @@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation /// 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; @@ -84,7 +84,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation /// 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) { @@ -100,7 +100,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 a160a4499..a4cea68c6 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/GetMembersHelper.cs @@ -41,7 +41,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return GetNestedTypes(type, null, filter, options); } - public static IEnumerable 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,14 +53,14 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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; int outerTypeParameterCount = outerTypeDef.TypeParameterCount; - ParameterizedType pt = outerType as ParameterizedType; + ParameterizedType? pt = outerType as ParameterizedType; foreach (ITypeDefinition nestedType in outerTypeDef.NestedTypes) { int totalTypeParameterCount = nestedType.TypeParameterCount; @@ -98,12 +98,12 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation #endregion #region GetMethods - public static IEnumerable 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,15 +127,15 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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) @@ -164,7 +164,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation #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) { @@ -183,7 +183,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation #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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - static IEnumerable 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return declaredMembers; } - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); @@ -241,7 +241,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return declaredProperties; } - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); @@ -267,7 +267,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return declaredFields; } - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); @@ -309,7 +309,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return declaredEvents; } - ParameterizedType pt = baseType as ParameterizedType; + ParameterizedType? pt = baseType as ParameterizedType; if (pt != null) { var substitution = pt.GetSubstitution(); @@ -323,7 +323,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation #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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 30d7aa60b..b63f220b5 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/LocalFunctionMethod.cs @@ -43,7 +43,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation && 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/MergedNamespace.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs index 31a332ad7..f05b248dc 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs @@ -42,7 +42,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation /// 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)); @@ -108,7 +108,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation get { return GetChildNamespaces().Values; } } - public INamespace GetChildNamespace(string name) + public INamespace? GetChildNamespace(string name) { INamespace ns; if (GetChildNamespaces().TryGetValue(name, out ns)) @@ -137,7 +137,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/MetadataEvent.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs index 023276071..4fe48c5c2 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataEvent.cs @@ -99,7 +99,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation { 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; @@ -164,7 +164,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 4486c90f5..3970ea97c 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataField.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataField.cs @@ -258,7 +258,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - public object GetConstantValue(bool throwOnInvalidMetadata) + public object? GetConstantValue(bool throwOnInvalidMetadata) { object val = LazyInit.VolatileRead(ref this.constantValue); if (val != null) @@ -295,7 +295,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is MetadataField f) { @@ -309,7 +309,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 83946c9fa..8bdb5c265 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataMethod.cs @@ -130,7 +130,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation public bool HasBody => module.metadata.GetMethodDefinition(handle).HasBody(); - public IMember AccessorOwner { + public IMember? AccessorOwner { get { if (accessorOwner.IsNil) return null; @@ -186,7 +186,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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; @@ -294,7 +294,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } IMember IMember.MemberDefinition => this; - IMethod IMethod.ReducedFrom => null; + IMethod? IMethod.ReducedFrom => null; TypeParameterSubstitution IMember.Substitution => TypeParameterSubstitution.Identity; public ITypeDefinition DeclaringTypeDefinition { @@ -476,7 +476,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return b.HasAttribute(metadata, def.GetCustomAttributes(), attribute, symbolKind); } - public IAttribute GetAttribute(KnownAttribute attribute) + public IAttribute? GetAttribute(KnownAttribute attribute) { if (!attribute.IsCustomAttribute()) { @@ -602,7 +602,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/MetadataNamespace.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs index 6a35f8568..9a2271358 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataNamespace.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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); @@ -86,7 +86,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 14bee08dc..0222e19b9 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataParameter.cs @@ -156,7 +156,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation bool IVariable.IsConst => false; - public object GetConstantValue(bool throwOnInvalidMetadata) + public object? GetConstantValue(bool throwOnInvalidMetadata) { try { diff --git a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs index da2d8a4cf..f9d6d779b 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataProperty.cs @@ -188,7 +188,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation { 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; @@ -298,7 +298,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 632a3e4cc..a020f991b 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeDefinition.cs @@ -324,7 +324,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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; @@ -549,7 +549,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return this; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is MetadataTypeDefinition td) { @@ -563,13 +563,13 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return 0x2e0520f2 ^ module.MetadataFile.GetHashCode() ^ handle.GetHashCode(); } - bool IEquatable.Equals(IType other) + bool IEquatable.Equals(IType? other) { return Equals(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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - 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/MetadataTypeParameter.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs index 282e5c2bf..36bf02a1f 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MetadataTypeParameter.cs @@ -251,7 +251,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/Implementation/MinimalCorlib.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs index 4f1b9cc8a..11740ab7d 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/MinimalCorlib.cs @@ -62,13 +62,13 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation { 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation { 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/NestedTypeReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs index 2380c7730..6e6bc3cee 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/NestedTypeReference.cs @@ -67,7 +67,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/NullabilityAnnotatedType.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/NullabilityAnnotatedType.cs index abfd5b184..63b9d5085 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/NullabilityAnnotatedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/NullabilityAnnotatedType.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/SimpleCompilation.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs index ade71cf71..1257c0b66 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs @@ -140,7 +140,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 fe4dc9ccc..163660313 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedField.cs @@ -57,7 +57,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 42954b151..63b267aa4 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs @@ -59,7 +59,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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; @@ -89,7 +89,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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) @@ -157,7 +157,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation get { return baseMember.SymbolKind; } } - public ITypeDefinition DeclaringTypeDefinition { + public ITypeDefinition? DeclaringTypeDefinition { get { return baseMember.DeclaringTypeDefinition; } } @@ -214,7 +214,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation get { return baseMember.Compilation; } } - public IModule ParentModule { + public IModule? ParentModule { get { return baseMember.ParentModule; } } @@ -223,18 +223,18 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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; + SpecializedMember? other = obj as SpecializedMember; if (other == null) return false; return this.baseMember.Equals(other.baseMember, typeNormalization) && this.substitution.Equals(other.substitution, typeNormalization); } - public override bool Equals(object obj) + 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 e72d6eeb7..774efea03 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMethod.cs @@ -146,13 +146,13 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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,18 +173,18 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation } } - public override bool Equals(IMember obj, TypeVisitor typeNormalization) + 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) && this.substitutionWithoutSpecializedTypeParameters.Equals(other.substitutionWithoutSpecializedTypeParameters, typeNormalization); } - public override bool Equals(object obj) + 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); @@ -267,11 +267,11 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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); + SpecializedTypeParameter? o = other as SpecializedTypeParameter; + 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/SyntheticRangeIndexer.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/SyntheticRangeIndexer.cs index 2bc60031e..8c0072e2d 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/SyntheticRangeIndexer.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/SyntheticRangeIndexer.cs @@ -105,7 +105,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/TypeSystem/Implementation/TypeParameterReference.cs b/ICSharpCode.Decompiler/TypeSystem/Implementation/TypeParameterReference.cs index c8d943477..21c26ae2e 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/TypeParameterReference.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/TypeParameterReference.cs @@ -70,7 +70,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation { 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 9489194bf..c3c74d80f 100644 --- a/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/Implementation/UnknownType.cs @@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation /// 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)); @@ -122,9 +122,9 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation return (namespaceKnown ? 812571 : 12651) ^ fullTypeName.GetHashCode(); } - public override bool Equals(IType other) + 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 f9b976fe1..b4b82f604 100644 --- a/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/InheritanceHelper.cs @@ -109,7 +109,7 @@ namespace ICSharpCode.Decompiler.TypeSystem /// /// 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)); @@ -121,7 +121,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } } - IProperty property = baseMember as IProperty; + IProperty? property = baseMember as IProperty; if (property != null) { foreach (IProperty derivedProperty in derivedType.Properties) @@ -185,7 +185,7 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } 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/IntersectionType.cs b/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs index 3db10f748..02e6e4fa8 100644 --- a/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/IntersectionType.cs @@ -116,9 +116,9 @@ namespace ICSharpCode.Decompiler.TypeSystem return hashCode; } - public override bool Equals(IType other) + 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++) @@ -135,42 +135,42 @@ namespace ICSharpCode.Decompiler.TypeSystem 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/MetadataModule.cs b/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs index bc7ff1bb4..f8aac8452 100644 --- a/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs +++ b/ICSharpCode.Decompiler/TypeSystem/MetadataModule.cs @@ -192,7 +192,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - public ITypeDefinition GetDefinition(TypeDefinitionHandle handle) + public ITypeDefinition? GetDefinition(TypeDefinitionHandle handle) { if (handle.IsNil) return null; @@ -233,7 +233,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem #region Resolve Module - public IModule ResolveModule(AssemblyReferenceHandle handle) + public IModule? ResolveModule(AssemblyReferenceHandle handle) { if (handle.IsNil) return null; @@ -332,7 +332,7 @@ namespace ICSharpCode.Decompiler.TypeSystem return Compilation.FindModuleByReference(asmRef); } - public IModule ResolveModule(ModuleReferenceHandle handle) + public IModule? ResolveModule(ModuleReferenceHandle handle) { if (handle.IsNil) return null; @@ -348,7 +348,7 @@ namespace ICSharpCode.Decompiler.TypeSystem return null; } - public IModule GetDeclaringModule(TypeReferenceHandle handle) + public IModule? GetDeclaringModule(TypeReferenceHandle handle) { if (handle.IsNil) return null; @@ -471,7 +471,7 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem m.ReturnType = signature.ReturnType; m.IsStatic = !signature.Header.IsInstance; - TypeParameterSubstitution substitution = null; + TypeParameterSubstitution? substitution = null; if (signature.GenericParameterCount > 0) { var typeParameters = new List(); @@ -747,7 +747,7 @@ namespace ICSharpCode.Decompiler.TypeSystem /// * 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } return new UnknownType(typeName); - IModule ResolveModule(ExportedType type) + IModule? ResolveModule(ExportedType type) { switch (type.Implementation.Kind) { diff --git a/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs b/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs index d87668c35..cbe73db36 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs @@ -63,52 +63,52 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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); } @@ -132,7 +132,7 @@ namespace ICSharpCode.Decompiler.TypeSystem.Implementation 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/NullableType.cs b/ICSharpCode.Decompiler/TypeSystem/NullableType.cs index 0fa461890..81580cd86 100644 --- a/ICSharpCode.Decompiler/TypeSystem/NullableType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/NullableType.cs @@ -32,7 +32,7 @@ namespace ICSharpCode.Decompiler.TypeSystem { 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 @@ namespace ICSharpCode.Decompiler.TypeSystem { 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 af823370c..684631440 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ParameterListComparer.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.Decompiler.TypeSystem }; } - public bool Equals(IReadOnlyList x, IReadOnlyList y) + public bool Equals(IReadOnlyList? x, IReadOnlyList? y) { if (x == y) return true; @@ -125,18 +125,18 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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; 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 3acc57860..537440a1b 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ParameterizedType.cs @@ -53,12 +53,12 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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); @@ -291,16 +291,16 @@ namespace ICSharpCode.Decompiler.TypeSystem 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; - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem { 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 3de6cd4b7..fba8536ec 100644 --- a/ICSharpCode.Decompiler/TypeSystem/PointerType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/PointerType.cs @@ -47,9 +47,9 @@ namespace ICSharpCode.Decompiler.TypeSystem return elementType.GetHashCode() ^ 91725811; } - public override bool Equals(IType other) + 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 df8e396f1..9608b6c59 100644 --- a/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs +++ b/ICSharpCode.Decompiler/TypeSystem/ReflectionHelper.cs @@ -227,9 +227,9 @@ namespace ICSharpCode.Decompiler.TypeSystem /// /// 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; + ITypeDefinition? def = type as ITypeDefinition; if (def != null) { KnownTypeCode typeCode = def.KnownTypeCode; @@ -321,7 +321,7 @@ namespace ICSharpCode.Decompiler.TypeSystem { // 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 @@ namespace ICSharpCode.Decompiler.TypeSystem static ITypeReference CreateGetClassTypeReference(string assemblyName, string typeName, int tpc) { - IModuleReference assemblyReference; + IModuleReference? assemblyReference; if (assemblyName != null) { assemblyReference = new DefaultAssemblyReference(assemblyName); @@ -442,7 +442,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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/SimpleTypeResolveContext.cs b/ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs index 782de8da1..5356f8d1d 100644 --- a/ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs +++ b/ICSharpCode.Decompiler/TypeSystem/SimpleTypeResolveContext.cs @@ -79,12 +79,12 @@ namespace ICSharpCode.Decompiler.TypeSystem 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/SpecialType.cs b/ICSharpCode.Decompiler/TypeSystem/SpecialType.cs index c7cf02428..489e0c97b 100644 --- a/ICSharpCode.Decompiler/TypeSystem/SpecialType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/SpecialType.cs @@ -101,7 +101,7 @@ namespace ICSharpCode.Decompiler.TypeSystem #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/TaskType.cs b/ICSharpCode.Decompiler/TypeSystem/TaskType.cs index 5289b75b0..2ab3a2fca 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 @@ namespace ICSharpCode.Decompiler.TypeSystem /// /// 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) @@ -73,8 +74,8 @@ namespace ICSharpCode.Decompiler.TypeSystem 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/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs b/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs index d6039e150..5a20650c6 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TopLevelTypeName.cs @@ -95,7 +95,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 d77387f4f..0ddee615d 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TupleType.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TupleType.cs @@ -53,18 +53,18 @@ namespace ICSharpCode.Decompiler.TypeSystem /// /// 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), - IModule valueTupleAssembly = null) + ImmutableArray elementNames = default(ImmutableArray), + IModule? valueTupleAssembly = null) { this.Compilation = compilation; this.UnderlyingType = CreateUnderlyingType(compilation, elementTypes, valueTupleAssembly); 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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) @@ -144,7 +144,7 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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) @@ -166,7 +166,7 @@ namespace ICSharpCode.Decompiler.TypeSystem /// public static ImmutableArray GetTupleElementTypes(IType tupleType) { - List output = null; + List? output = null; if (Collect(tupleType)) { return output.ToImmutableArray(); @@ -220,7 +220,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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) @@ -236,7 +236,7 @@ namespace ICSharpCode.Decompiler.TypeSystem unchecked { int hash = UnderlyingType.GetHashCode(); - foreach (string name in ElementNames) + foreach (string? name in ElementNames) { hash *= 31; hash += name != null ? name.GetHashCode() : 0; @@ -271,7 +271,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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); } @@ -387,7 +387,7 @@ namespace ICSharpCode.Decompiler.TypeSystem /// public ImmutableArray ElementNames { get; } - public IModuleReference ValueTupleAssembly { get; } + public IModuleReference? ValueTupleAssembly { get; } public TupleTypeReference(ImmutableArray elementTypes) { @@ -396,7 +396,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 0202f72fa..6150688e4 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs @@ -33,8 +33,8 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem && 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - static bool TypeListEquals(IReadOnlyList a, IReadOnlyList b) + static bool TypeListEquals(IReadOnlyList? a, IReadOnlyList? b) { if (a == b) return true; @@ -142,7 +142,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 e26781cfb..7e5554e06 100644 --- a/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs +++ b/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs @@ -83,13 +83,13 @@ namespace ICSharpCode.Decompiler.TypeSystem 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(); } /// /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem /// public static bool IsUnmanagedType(this IType type, bool allowGenerics) { - HashSet types = null; + HashSet? types = null; return IsUnmanagedTypeInternal(type); bool IsUnmanagedTypeInternal(IType type) @@ -354,7 +354,7 @@ namespace ICSharpCode.Decompiler.TypeSystem /// /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem /// 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 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem #endregion #region ResolveResult - public static ISymbol GetSymbol(this ResolveResult rr) + public static ISymbol? GetSymbol(this ResolveResult rr) { if (rr is LocalResolveResult) { @@ -660,7 +660,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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; @@ -713,7 +713,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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 @@ namespace ICSharpCode.Decompiler.TypeSystem } } - 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/TypeSystem/VarArgInstanceMethod.cs b/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs index 07175fc03..efeb56191 100644 --- a/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs +++ b/ICSharpCode.Decompiler/TypeSystem/VarArgInstanceMethod.cs @@ -58,9 +58,9 @@ namespace ICSharpCode.Decompiler.TypeSystem get { return parameters; } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - VarArgInstanceMethod other = obj as VarArgInstanceMethod; + VarArgInstanceMethod? other = obj as VarArgInstanceMethod; return other != null && baseMethod.Equals(other.baseMethod); } @@ -69,9 +69,9 @@ namespace ICSharpCode.Decompiler.TypeSystem return baseMethod.GetHashCode(); } - public bool Equals(IMember obj, TypeVisitor typeNormalization) + 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); } @@ -119,7 +119,7 @@ namespace ICSharpCode.Decompiler.TypeSystem 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; diff --git a/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs b/ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs index b57516b45..f39ee4404 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,11 @@ namespace ICSharpCode.Decompiler.Util /// /// 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("input")] + public static object Cast(TypeCode targetType, [MaybeNull] object input, bool checkForOverflow) { if (input == null) return null; @@ -769,3 +774,35 @@ namespace ICSharpCode.Decompiler.Util } } } +#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 diff --git a/ICSharpCode.Decompiler/Util/LazyInit.cs b/ICSharpCode.Decompiler/Util/LazyInit.cs index d19344cd4..77589b46f 100644 --- a/ICSharpCode.Decompiler/Util/LazyInit.cs +++ b/ICSharpCode.Decompiler/Util/LazyInit.cs @@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.Util /// - 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; diff --git a/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs b/ICSharpCode.Decompiler/Util/ResXResourceWriter.cs index 7d18ef551..d8795da63 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 @@ namespace ICSharpCode.Decompiler.Util 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 @@ namespace ICSharpCode.Decompiler.Util 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/ICSharpCode.ILSpyCmd.csproj b/ICSharpCode.ILSpyCmd/ICSharpCode.ILSpyCmd.csproj index ca25d2eef..179d463c9 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/IlspyCmdProgram.cs b/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs index 57e08d5e3..605e5bd94 100644 --- a/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs +++ b/ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs @@ -122,7 +122,7 @@ Examples: private async Task OnExecuteAsync(CommandLineApplication app) { - Task updateCheckTask = null; + Task? updateCheckTask = null; if (!DisableUpdateCheck) { updateCheckTask = DotNetToolUpdateChecker.CheckForPackageUpdateAsync("ilspycmd"); @@ -214,7 +214,7 @@ Examples: } else if (CreateDebugInfoFlag) { - string pdbFileName = null; + string? pdbFileName = null; if (outputDirectory != null) { string outputName = Path.GetFileNameWithoutExtension(fileName); @@ -317,7 +317,7 @@ Examples: 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/ICSharpCode.ILSpyCmd/ValidationAttributes.cs b/ICSharpCode.ILSpyCmd/ValidationAttributes.cs index 7ddd2ce80..f9d34db37 100644 --- a/ICSharpCode.ILSpyCmd/ValidationAttributes.cs +++ b/ICSharpCode.ILSpyCmd/ValidationAttributes.cs @@ -14,7 +14,7 @@ namespace ICSharpCode.ILSpyCmd { } - 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 @@ namespace ICSharpCode.ILSpyCmd [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 @@ namespace ICSharpCode.ILSpyCmd [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 @@ namespace ICSharpCode.ILSpyCmd { foreach (string path in paths) { - ValidationResult result = ValidatePath(path); + ValidationResult? result = ValidatePath(path); if (result != ValidationResult.Success) return result; } @@ -75,7 +75,7 @@ namespace ICSharpCode.ILSpyCmd 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/Abstractions/ILanguage.cs b/ICSharpCode.ILSpyX/Abstractions/ILanguage.cs index f05c6ded3..bfc6504e3 100644 --- a/ICSharpCode.ILSpyX/Abstractions/ILanguage.cs +++ b/ICSharpCode.ILSpyX/Abstractions/ILanguage.cs @@ -27,7 +27,7 @@ namespace ICSharpCode.ILSpyX.Abstractions { 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/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs b/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs index 4c5217ef6..25b9ebae7 100644 --- a/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs +++ b/ICSharpCode.ILSpyX/Analyzers/AnalyzerHelpers.cs @@ -54,7 +54,7 @@ namespace ICSharpCode.ILSpyX.Analyzers 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 21a9363b0..e0614d694 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 25034616d..e365780ea 100644 --- a/ICSharpCode.ILSpyX/TreeView/TreeTraversal.cs +++ b/ICSharpCode.ILSpyX/TreeView/TreeTraversal.cs @@ -43,7 +43,7 @@ namespace ICSharpCode.ILSpyX.TreeView /// 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 @@ namespace ICSharpCode.ILSpyX.TreeView { T element = stack.Peek().Current; yield return element; - IEnumerable children = recursion(element); + IEnumerable? children = recursion(element); if (children != null) { stack.Push(children.GetEnumerator()); diff --git a/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs b/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs index 970618e8e..3a94ffcae 100644 --- a/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs +++ b/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs @@ -205,11 +205,11 @@ namespace ILSpy.BamlDecompiler.Tests 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.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj b/ILSpy.BamlDecompiler.Tests/ILSpy.BamlDecompiler.Tests.csproj index d92e79c75..d7c1e6b3e 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 788b32ce1..7a573a4e2 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/BamlResourceNodeFactory.cs b/ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs index ecb1e25d1..85d85fdcc 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.BamlDecompiler/ILSpy.BamlDecompiler.csproj b/ILSpy.BamlDecompiler/ILSpy.BamlDecompiler.csproj index 63950dda4..7ac2ce92b 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 dfe925ddd..dc007bde0 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/ReadyToRunDisassembler.cs b/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs index ce9e62a1e..7f4fd0817 100644 --- a/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs +++ b/ILSpy.ReadyToRun/ReadyToRunDisassembler.cs @@ -70,14 +70,14 @@ namespace ICSharpCode.ILSpy.ReadyToRun } } - Dictionary unwindInfo = null; + Dictionary? unwindInfo = null; if (options.IsShowUnwindInfo && bitness == 64) { unwindInfo = WriteUnwindInfo(); } bool isShowDebugInfo = options.IsShowDebugInfo; - DebugInfoHelper debugInfo = null; + DebugInfoHelper? debugInfo = null; if (isShowDebugInfo) { debugInfo = WriteDebugInfo(); @@ -101,7 +101,7 @@ namespace ICSharpCode.ILSpy.ReadyToRun } string disassemblyFormat = options.DisassemblyFormat; - Formatter formatter = null; + Formatter? formatter = null; if (disassemblyFormat.Equals(ReadyToRunOptions.intel)) { formatter = new NasmFormatter(); @@ -174,10 +174,10 @@ namespace ICSharpCode.ILSpy.ReadyToRun 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); @@ -195,17 +195,17 @@ namespace ICSharpCode.ILSpy.ReadyToRun 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 b201a6608..75cbeba08 100644 --- a/ILSpy.ReadyToRun/ReadyToRunLanguage.cs +++ b/ILSpy.ReadyToRun/ReadyToRunLanguage.cs @@ -114,7 +114,7 @@ namespace ICSharpCode.ILSpy.ReadyToRun 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 @@ namespace ICSharpCode.ILSpy.ReadyToRun 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 @@ namespace ICSharpCode.ILSpy.ReadyToRun } if (cacheEntry.methodMap == null) { - IEnumerable readyToRunMethods = null; + IEnumerable? readyToRunMethods = null; if (cacheEntry.compositeReadyToRunReader == null) { readyToRunMethods = reader.Methods; @@ -192,8 +192,8 @@ namespace ICSharpCode.ILSpy.ReadyToRun #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; @@ -216,7 +216,7 @@ namespace ICSharpCode.ILSpy.ReadyToRun } } - public override RichText GetRichTextTooltip(IEntity entity) + public override RichText? GetRichTextTooltip(IEntity entity) { return Languages.ILLanguage.GetRichTextTooltip(entity); } @@ -307,10 +307,10 @@ namespace ICSharpCode.ILSpy.ReadyToRun 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 9b13f7ba7..e6b47e69f 100644 --- a/ILSpy.ReadyToRun/ReadyToRunOptions.cs +++ b/ILSpy.ReadyToRun/ReadyToRunOptions.cs @@ -66,16 +66,16 @@ namespace ICSharpCode.ILSpy.ReadyToRun public void LoadFromXml(XElement e) { - XAttribute format = e.Attribute("DisassemblyFormat"); + XAttribute? format = e.Attribute("DisassemblyFormat"); DisassemblyFormat = format == null ? intel : (string)format; - XAttribute unwind = e.Attribute("IsShowUnwindInfo"); + XAttribute? unwind = e.Attribute("IsShowUnwindInfo"); IsShowUnwindInfo = unwind != null && (bool)unwind; - XAttribute debug = e.Attribute("IsShowDebugInfo"); + XAttribute? debug = e.Attribute("IsShowDebugInfo"); IsShowDebugInfo = debug == null || (bool)debug; - XAttribute showGc = e.Attribute("IsShowGCInfo"); + XAttribute? showGc = e.Attribute("IsShowGCInfo"); IsShowGCInfo = showGc != null && (bool)showGc; } diff --git a/ILSpy.Tests/ILSpy.Tests.csproj b/ILSpy.Tests/ILSpy.Tests.csproj index 0f44621f6..2f31cb000 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/AboutPage.cs b/ILSpy/AboutPage.cs index 9d462e753..4bbe5769d 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.AssemblyTreeModel.NavigateTo( new RequestNavigateEventArgs(new Uri("resource://aboutpage"), null), @@ -90,11 +90,11 @@ namespace ICSharpCode.ILSpy 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/AnalyzeCommand.cs b/ILSpy/Analyzers/AnalyzeCommand.cs index 9a24f29b2..f8230fad7 100644 --- a/ILSpy/Analyzers/AnalyzeCommand.cs +++ b/ILSpy/Analyzers/AnalyzeCommand.cs @@ -76,12 +76,12 @@ namespace ICSharpCode.ILSpy.Analyzers { private static readonly AnalyzerTreeViewModel AnalyzerTreeView = App.ExportProvider.GetExportedValue(); - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return MainWindow.Instance.AssemblyTreeModel.SelectedNodes.All(n => n is IMemberTreeNode); } - public override void Execute(object parameter) + public override void Execute(object? parameter) { foreach (var node in MainWindow.Instance.AssemblyTreeModel.SelectedNodes.OfType()) { diff --git a/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs b/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs index 4217e411c..42451c80f 100644 --- a/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs +++ b/ILSpy/Analyzers/AnalyzerEntityTreeNode.cs @@ -22,8 +22,8 @@ using System.Windows; 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) { @@ -55,7 +55,7 @@ namespace ICSharpCode.ILSpy.Analyzers } 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 e1ce03438..93d641554 100644 --- a/ILSpy/Analyzers/AnalyzerRootNode.cs +++ b/ILSpy/Analyzers/AnalyzerRootNode.cs @@ -14,7 +14,7 @@ public sealed class AnalyzerRootNode : AnalyzerTreeNode 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) { @@ -33,7 +33,7 @@ public sealed class AnalyzerRootNode : AnalyzerTreeNode { 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 fc7def755..a9034f59b 100644 --- a/ILSpy/Analyzers/AnalyzerTreeViewModel.cs +++ b/ILSpy/Analyzers/AnalyzerTreeViewModel.cs @@ -73,7 +73,7 @@ namespace ICSharpCode.ILSpy.Analyzers { Show(); - AnalyzerTreeNode target = default; + AnalyzerTreeNode? target = default; if (node is AnalyzerEntityTreeNode { Member: { } member }) { diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs index 8b6ff6f03..463c74c99 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs @@ -23,6 +23,8 @@ using ICSharpCode.ILSpy.TreeNodes; namespace ICSharpCode.ILSpy.Analyzers.TreeNodes { + using System.Diagnostics.CodeAnalysis; + using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX.Analyzers; @@ -38,7 +40,7 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes this.LazyLoading = true; } - public override IEntity Member => analyzedEvent; + public override IEntity? Member => analyzedEvent; public override object Icon => EventTreeNode.GetIcon(analyzedEvent); @@ -68,7 +70,7 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes } } - 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)) diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs index 1f2b9b9a3..b75a8b384 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedFieldTreeNode.cs @@ -52,6 +52,6 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes } } - 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 b7cee8ede..b4fc0d044 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedMethodTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedMethodTreeNode.cs @@ -54,6 +54,6 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes } } - public override IEntity Member => analyzedMethod; + public override IEntity? Member => analyzedMethod; } } diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs index 7f343fb78..ad8395d31 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedModuleTreeNode.cs @@ -64,6 +64,6 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes MessageBus.Send(this, new NavigateToReferenceEventArgs(analyzedModule.MetadataFile)); } - public override IEntity Member => null; + public override IEntity? Member => null; } } diff --git a/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs b/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs index d19bc3e73..383f41f26 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedPropertyTreeNode.cs @@ -62,6 +62,6 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes } } - 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 6836944eb..09ad9f950 100644 --- a/ILSpy/Analyzers/TreeNodes/AnalyzedTypeTreeNode.cs +++ b/ILSpy/Analyzers/TreeNodes/AnalyzedTypeTreeNode.cs @@ -52,6 +52,6 @@ namespace ICSharpCode.ILSpy.Analyzers.TreeNodes } } - public override IEntity Member => analyzedType; + public override IEntity? Member => analyzedType; } } diff --git a/ILSpy/App.xaml.cs b/ILSpy/App.xaml.cs index d00eb4204..5494bd85d 100644 --- a/ILSpy/App.xaml.cs +++ b/ILSpy/App.xaml.cs @@ -19,11 +19,13 @@ using System; using System.Collections.Generic; 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; @@ -32,20 +34,17 @@ using System.Windows.Threading; using ICSharpCode.ILSpy.AppEnv; using ICSharpCode.ILSpy.AssemblyTree; +using ICSharpCode.ILSpy.Themes; using ICSharpCode.ILSpyX.Analyzers; +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 ICSharpCode.ILSpy.Themes; -using System.Globalization; -using System.Threading; +using TomsToolbox.Wpf.Styles; namespace ICSharpCode.ILSpy { @@ -125,9 +124,9 @@ namespace ICSharpCode.ILSpy SettingsService.Instance.AssemblyListManager.CreateDefaultAssemblyLists(); } - private static void SingleInstance_NewInstanceDetected(object sender, NewInstanceEventArgs e) => ExportProvider.GetExportedValue().HandleSingleInstanceCommandLineArguments(e.Args).HandleExceptions(); + private static void SingleInstance_NewInstanceDetected(object? sender, NewInstanceEventArgs e) => ExportProvider.GetExportedValue().HandleSingleInstanceCommandLineArguments(e.Args).HandleExceptions(); - 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"); @@ -222,7 +221,7 @@ namespace ICSharpCode.ILSpy MainWindow.Show(); } - 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(); @@ -237,7 +236,7 @@ namespace ICSharpCode.ILSpy static void ShowErrorBox(object sender, UnhandledExceptionEventArgs e) { - Exception ex = e.ExceptionObject as Exception; + Exception? ex = e.ExceptionObject as Exception; if (ex != null) { UnhandledException(ex); @@ -250,13 +249,13 @@ namespace ICSharpCode.ILSpy 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/AppEnv/CommandLineTools.cs b/ILSpy/AppEnv/CommandLineTools.cs index 7379db12e..5f7c14dec 100644 --- a/ILSpy/AppEnv/CommandLineTools.cs +++ b/ILSpy/AppEnv/CommandLineTools.cs @@ -56,7 +56,7 @@ namespace ICSharpCode.ILSpy.AppEnv /// - (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/AssemblyTree/AssemblyTreeModel.cs b/ILSpy/AssemblyTree/AssemblyTreeModel.cs index 91cf6f094..20e90fb0a 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; @@ -124,8 +122,8 @@ namespace ICSharpCode.ILSpy.AssemblyTree set => SetProperty(ref root, value); } - private SharpTreeNode selectedItem; - public SharpTreeNode SelectedItem { + private SharpTreeNode? selectedItem; + public SharpTreeNode? SelectedItem { get => selectedItem; set => SetProperty(ref selectedItem, value); } @@ -148,7 +146,7 @@ namespace ICSharpCode.ILSpy.AssemblyTree /// 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; @@ -440,7 +438,7 @@ namespace ICSharpCode.ILSpy.AssemblyTree #endif } - void assemblyList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + void assemblyList_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { @@ -619,7 +617,7 @@ namespace ICSharpCode.ILSpy.AssemblyTree } } - private void JumpToReference(object sender, NavigateToReferenceEventArgs e) + private void JumpToReference(object? sender, NavigateToReferenceEventArgs e) { JumpToReferenceAsync(e.Reference, e.InNewTabPage).HandleExceptions(); } @@ -679,11 +677,11 @@ namespace ICSharpCode.ILSpy.AssemblyTree #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) { @@ -750,7 +748,7 @@ namespace ICSharpCode.ILSpy.AssemblyTree return; - void ContextMenuClosed(object sender, EventArgs e) + void ContextMenuClosed(object? sender, EventArgs e) { ContextMenuProvider.ContextMenuClosed -= ContextMenuClosed; @@ -763,7 +761,7 @@ namespace ICSharpCode.ILSpy.AssemblyTree } } - private void DecompileSelectedNodes(DecompilerTextViewState newState = null) + private void DecompileSelectedNodes(DecompilerTextViewState? newState = null) { var activeTabPage = DockWorkspace.Instance.ActiveTabPage; @@ -924,7 +922,7 @@ namespace ICSharpCode.ILSpy.AssemblyTree 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/AvalonEdit/TextMarkerService.cs b/ILSpy/AvalonEdit/TextMarkerService.cs index 9a1d1598c..ae5e0dc86 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 @@ namespace ICSharpCode.ILSpy.AvalonEdit OnDocumentChanged(null, null); } - void OnDocumentChanged(object sender, EventArgs e) + void OnDocumentChanged(object? sender, EventArgs? e) { if (textView.Document != null) markers = new TextSegmentCollection(textView.Document); @@ -102,7 +102,7 @@ namespace ICSharpCode.ILSpy.AvalonEdit { 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 @@ namespace ICSharpCode.ILSpy.AvalonEdit 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/CheckForUpdatesCommand.cs b/ILSpy/Commands/CheckForUpdatesCommand.cs index 779f854a1..f783933dd 100644 --- a/ILSpy/Commands/CheckForUpdatesCommand.cs +++ b/ILSpy/Commands/CheckForUpdatesCommand.cs @@ -27,12 +27,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(SettingsService.Instance.SpySettings, forceCheck: true); } diff --git a/ILSpy/Commands/CommandWrapper.cs b/ILSpy/Commands/CommandWrapper.cs index 809184391..ad68ac75b 100644 --- a/ILSpy/Commands/CommandWrapper.cs +++ b/ILSpy/Commands/CommandWrapper.cs @@ -41,17 +41,17 @@ namespace ICSharpCode.ILSpy return command; } - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { wrappedCommand.CanExecuteChanged += value; } 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/CopyFullyQualifiedNameContextMenuEntry.cs b/ILSpy/Commands/CopyFullyQualifiedNameContextMenuEntry.cs index 47490e37b..446f434ed 100644 --- a/ILSpy/Commands/CopyFullyQualifiedNameContextMenuEntry.cs +++ b/ILSpy/Commands/CopyFullyQualifiedNameContextMenuEntry.cs @@ -42,7 +42,7 @@ namespace ICSharpCode.ILSpy 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/DecompileAllCommand.cs b/ILSpy/Commands/DecompileAllCommand.cs index b041bf7a7..4f147b06b 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(); @@ -55,7 +55,7 @@ namespace ICSharpCode.ILSpy 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 @@ -92,7 +92,7 @@ namespace ICSharpCode.ILSpy [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/DecompileCommand.cs b/ILSpy/Commands/DecompileCommand.cs index ec35a0cbe..152e7cd52 100644 --- a/ILSpy/Commands/DecompileCommand.cs +++ b/ILSpy/Commands/DecompileCommand.cs @@ -56,7 +56,7 @@ namespace ICSharpCode.ILSpy.Commands 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/DelegateCommand.cs b/ILSpy/Commands/DelegateCommand.cs index 7e2516b1b..80345c32d 100644 --- a/ILSpy/Commands/DelegateCommand.cs +++ b/ILSpy/Commands/DelegateCommand.cs @@ -12,7 +12,7 @@ namespace ICSharpCode.ILSpy.Commands private readonly Action action; private readonly Func canExecute; - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } @@ -28,12 +28,12 @@ namespace ICSharpCode.ILSpy.Commands 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(); } @@ -44,7 +44,7 @@ namespace ICSharpCode.ILSpy.Commands private readonly Action action; private readonly Func canExecute; - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } @@ -60,12 +60,12 @@ namespace ICSharpCode.ILSpy.Commands 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 07afced39..1686f4bcc 100644 --- a/ILSpy/Commands/DisassembleAllCommand.cs +++ b/ILSpy/Commands/DisassembleAllCommand.cs @@ -33,12 +33,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) { var dockWorkspace = Docking.DockWorkspace.Instance; @@ -51,7 +51,7 @@ namespace ICSharpCode.ILSpy 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/ExitCommand.cs b/ILSpy/Commands/ExitCommand.cs index fb475ef01..06873b6f8 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/ExtractPackageEntryContextMenuEntry.cs b/ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs index 3f22fa1cd..8dfc5aae6 100644 --- a/ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs +++ b/ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs @@ -57,7 +57,7 @@ namespace ICSharpCode.ILSpy return; string fileName = dlg.FileName; - string outputFolderOrFileName = fileName; + string? outputFolderOrFileName = fileName; if (selectedNodes.Length > 1) outputFolderOrFileName = Path.GetDirectoryName(outputFolderOrFileName); @@ -89,7 +89,7 @@ namespace ICSharpCode.ILSpy 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/GeneratePdbContextMenuEntry.cs b/ILSpy/Commands/GeneratePdbContextMenuEntry.cs index 4eb744992..1c82faf12 100644 --- a/ILSpy/Commands/GeneratePdbContextMenuEntry.cs +++ b/ILSpy/Commands/GeneratePdbContextMenuEntry.cs @@ -110,14 +110,14 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] class GeneratePdbMainMenuEntry : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return MainWindow.Instance.AssemblyTreeModel.SelectedNodes?.Count() == 1 && MainWindow.Instance.AssemblyTreeModel.SelectedNodes?.FirstOrDefault() is AssemblyTreeNode tn && !tn.LoadedAssembly.HasLoadError; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { var assembly = (MainWindow.Instance.AssemblyTreeModel.SelectedNodes?.FirstOrDefault() as AssemblyTreeNode)?.LoadedAssembly; if (assembly == null) diff --git a/ILSpy/Commands/IProtocolHandler.cs b/ILSpy/Commands/IProtocolHandler.cs index 53f6e7ef3..dbd6552c4 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/ManageAssemblyListsCommand.cs b/ILSpy/Commands/ManageAssemblyListsCommand.cs index 0f2240e14..af5bf0465 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 9d1c31214..991e28fe5 100644 --- a/ILSpy/Commands/OpenFromGacCommand.cs +++ b/ILSpy/Commands/OpenFromGacCommand.cs @@ -36,12 +36,12 @@ namespace ICSharpCode.ILSpy this.assemblyTreeModel = assemblyTreeModel; } - 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 { Owner = MainWindow.Instance diff --git a/ILSpy/Commands/Pdb2XmlCommand.cs b/ILSpy/Commands/Pdb2XmlCommand.cs index b624124cb..10873c58a 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.AssemblyTreeModel.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.AssemblyTreeModel.SelectedNodes.OfType()); } diff --git a/ILSpy/Commands/RemoveAssembliesWithLoadErrors.cs b/ILSpy/Commands/RemoveAssembliesWithLoadErrors.cs index 9cc357374..f5e4b93d5 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.AssemblyTreeModel.AssemblyList?.GetAssemblies().Any(l => l.HasLoadError) == true; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { foreach (var asm in MainWindow.Instance.AssemblyTreeModel.AssemblyList.GetAssemblies()) { @@ -49,12 +49,12 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] class ClearAssemblyList : SimpleCommand { - public override bool CanExecute(object parameter) + public override bool CanExecute(object? parameter) { return MainWindow.Instance.AssemblyTreeModel.AssemblyList?.Count > 0; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { MainWindow.Instance.AssemblyTreeModel.AssemblyList?.Clear(); } diff --git a/ILSpy/Commands/SaveCodeContextMenuEntry.cs b/ILSpy/Commands/SaveCodeContextMenuEntry.cs index 41d45728e..5759c3abd 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,11 +27,11 @@ using ICSharpCode.Decompiler.IL; using ICSharpCode.ILSpy.Options; using ICSharpCode.ILSpy.Properties; using ICSharpCode.ILSpy.TreeNodes; +using ICSharpCode.ILSpy.Util; using ICSharpCode.ILSpy.ViewModels; +using ICSharpCode.ILSpyX.TreeView; using Microsoft.Win32; -using ICSharpCode.ILSpyX.TreeView; -using System.ComponentModel.Composition; using ICSharpCode.ILSpy.Docking; @@ -105,7 +106,7 @@ namespace ICSharpCode.ILSpy.TextView /// 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"; @@ -116,7 +117,7 @@ namespace ICSharpCode.ILSpy.TextView 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 645f9d425..b75c2d140 100644 --- a/ILSpy/Commands/ScopeSearchToNamespace.cs +++ b/ILSpy/Commands/ScopeSearchToNamespace.cs @@ -41,7 +41,7 @@ namespace ICSharpCode.ILSpy 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++) @@ -75,7 +75,7 @@ namespace ICSharpCode.ILSpy 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/Commands/SetThemeCommand.cs b/ILSpy/Commands/SetThemeCommand.cs index 1f9a1226c..ee415cc0d 100644 --- a/ILSpy/Commands/SetThemeCommand.cs +++ b/ILSpy/Commands/SetThemeCommand.cs @@ -3,7 +3,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) { diff --git a/ILSpy/Commands/ShowCFGContextMenuEntry.cs b/ILSpy/Commands/ShowCFGContextMenuEntry.cs index 2067752cc..a1a124192 100644 --- a/ILSpy/Commands/ShowCFGContextMenuEntry.cs +++ b/ILSpy/Commands/ShowCFGContextMenuEntry.cs @@ -38,7 +38,7 @@ namespace ICSharpCode.ILSpy.Commands 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/Commands/ShowPane.cs b/ILSpy/Commands/ShowPane.cs index 372081e0b..de2f9adcf 100644 --- a/ILSpy/Commands/ShowPane.cs +++ b/ILSpy/Commands/ShowPane.cs @@ -13,7 +13,7 @@ namespace ICSharpCode.ILSpy.Commands this.contentId = contentId; } - public override void Execute(object parameter) + public override void Execute(object? parameter) { DockWorkspace.Instance.ShowToolPane(contentId); } @@ -28,7 +28,7 @@ namespace ICSharpCode.ILSpy.Commands 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 67c7f517e..956ad70ce 100644 --- a/ILSpy/Commands/SimpleCommand.cs +++ b/ILSpy/Commands/SimpleCommand.cs @@ -24,14 +24,14 @@ namespace ICSharpCode.ILSpy { public abstract class SimpleCommand : ICommand { - public event EventHandler CanExecuteChanged { + public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } 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; } @@ -41,14 +41,14 @@ namespace ICSharpCode.ILSpy { 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) + void ICommand.Execute(object? parameter) { IsChecked = Execute(parameter); } @@ -64,9 +64,9 @@ namespace ICSharpCode.ILSpy } } - 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 5b7dc67e1..8f744dadf 100644 --- a/ILSpy/Commands/SortAssemblyListCommand.cs +++ b/ILSpy/Commands/SortAssemblyListCommand.cs @@ -31,7 +31,7 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class SortAssemblyListCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { MainWindow.Instance.AssemblyTreeModel.SortAssemblyList(); } @@ -42,7 +42,7 @@ namespace ICSharpCode.ILSpy [PartCreationPolicy(CreationPolicy.Shared)] sealed class CollapseAllCommand : SimpleCommand { - public override void Execute(object parameter) + public override void Execute(object? parameter) { MainWindow.Instance.AssemblyTreeModel.CollapseAll(); diff --git a/ILSpy/ContextMenuEntry.cs b/ILSpy/ContextMenuEntry.cs index 4da82c40d..ce581f6e2 100644 --- a/ILSpy/ContextMenuEntry.cs +++ b/ILSpy/ContextMenuEntry.cs @@ -24,9 +24,9 @@ using System.Windows; using System.Windows.Controls; 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; @@ -47,37 +47,37 @@ namespace ICSharpCode.ILSpy /// 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. @@ -90,9 +90,9 @@ namespace ICSharpCode.ILSpy /// 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; + ReferenceSegment? reference; if (textView is not null) { @@ -312,7 +312,7 @@ namespace ICSharpCode.ILSpy 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) diff --git a/ILSpy/Controls/CustomDialog.cs b/ILSpy/Controls/CustomDialog.cs index 994bedffc..036aff29a 100644 --- a/ILSpy/Controls/CustomDialog.cs +++ b/ILSpy/Controls/CustomDialog.cs @@ -113,9 +113,9 @@ namespace ICSharpCode.ILSpy.Controls } } - 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/Controls/ExtensionMethods.cs b/ILSpy/Controls/ExtensionMethods.cs index 15e40eb7b..a0931e3fb 100644 --- a/ILSpy/Controls/ExtensionMethods.cs +++ b/ILSpy/Controls/ExtensionMethods.cs @@ -60,7 +60,7 @@ namespace ICSharpCode.ILSpy.Controls this.targetProperty = property; } - public object GetService(Type serviceType) + public object? GetService(Type serviceType) { if (serviceType == typeof(IProvideValueTarget)) return this; diff --git a/ILSpy/Controls/GridViewColumnAutoSize.cs b/ILSpy/Controls/GridViewColumnAutoSize.cs index 5c833b1cf..0d8f6edf3 100644 --- a/ILSpy/Controls/GridViewColumnAutoSize.cs +++ b/ILSpy/Controls/GridViewColumnAutoSize.cs @@ -52,25 +52,25 @@ namespace ICSharpCode.ILSpy.Controls 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 4795bbe11..5c701652b 100644 --- a/ILSpy/Controls/SearchBox.cs +++ b/ILSpy/Controls/SearchBox.cs @@ -84,7 +84,7 @@ namespace ICSharpCode.ILSpy.Controls #region Overrides - DispatcherTimer timer; + DispatcherTimer? timer; protected override void OnTextChanged(TextChangedEventArgs e) { @@ -110,7 +110,7 @@ namespace ICSharpCode.ILSpy.Controls 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; @@ -137,7 +137,7 @@ namespace ICSharpCode.ILSpy.Controls { 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 336f5442c..7fe23d447 100644 --- a/ILSpy/Controls/SortableGridViewColumn.cs +++ b/ILSpy/Controls/SortableGridViewColumn.cs @@ -73,7 +73,7 @@ namespace ICSharpCode.ILSpy.Controls 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 @@ namespace ICSharpCode.ILSpy.Controls 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 @@ namespace ICSharpCode.ILSpy.Controls 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 @@ namespace ICSharpCode.ILSpy.Controls 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 @@ namespace ICSharpCode.ILSpy.Controls 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/LinesRenderer.cs b/ILSpy/Controls/TreeView/LinesRenderer.cs index ca62d3b31..4508cc071 100644 --- a/ILSpy/Controls/TreeView/LinesRenderer.cs +++ b/ILSpy/Controls/TreeView/LinesRenderer.cs @@ -32,7 +32,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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 a7cca8838..cecb3cfea 100644 --- a/ILSpy/Controls/TreeView/SharpTreeNodeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeNodeView.cs @@ -43,7 +43,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView set { SetValue(TextBackgroundProperty, value); } } - public SharpTreeNode Node { + public SharpTreeNode? Node { get { return DataContext as SharpTreeNode; } } @@ -103,7 +103,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView } } - 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 80558388e..12a68bf04 100644 --- a/ILSpy/Controls/TreeView/SharpTreeView.cs +++ b/ILSpy/Controls/TreeView/SharpTreeView.cs @@ -172,13 +172,13 @@ namespace ICSharpCode.ILSpy.Controls.TreeView } } - 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) { - List selectedOldItems = null; - foreach (SharpTreeNode node in e.OldItems) + List? selectedOldItems = null; + foreach (SharpTreeNode node in e.OldItems!) { if (node.IsSelected) { @@ -195,7 +195,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView } } - void UpdateFocusedNode(List newSelection, int topSelectedIndex) + void UpdateFocusedNode(List? newSelection, int topSelectedIndex) { if (updatesLocked) return; @@ -223,7 +223,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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) @@ -245,7 +245,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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; @@ -270,7 +270,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView protected override void OnKeyDown(KeyEventArgs e) { - SharpTreeViewItem container = e.OriginalSource as SharpTreeViewItem; + SharpTreeViewItem? container = e.OriginalSource as SharpTreeViewItem; switch (e.Key) { case Key.Left: @@ -421,9 +421,9 @@ namespace ICSharpCode.ILSpy.Controls.TreeView base.ScrollIntoView(node); } - object OnFocusItem(object item) + 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(); @@ -532,7 +532,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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; @@ -607,7 +607,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView void TryAddDropTarget(List targets, SharpTreeViewItem item, DropPlace place, DragEventArgs e) { - SharpTreeNode node; + SharpTreeNode? node; int index; GetNodeAndIndex(item, place, out node, out index); @@ -628,7 +628,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView } } - 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; @@ -656,7 +656,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView } } - SharpTreeNodeView previewNodeView; + SharpTreeNodeView? previewNodeView; InsertMarker insertMarker; DropPlace previewPlace; @@ -698,7 +698,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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/SharpTreeViewItem.cs b/ILSpy/Controls/TreeView/SharpTreeViewItem.cs index 5ec32d855..727f8822d 100644 --- a/ILSpy/Controls/TreeView/SharpTreeViewItem.cs +++ b/ILSpy/Controls/TreeView/SharpTreeViewItem.cs @@ -34,7 +34,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView new FrameworkPropertyMetadata(typeof(SharpTreeViewItem))); } - public SharpTreeNode Node { + public SharpTreeNode? Node { get { return DataContext as SharpTreeNode; } } diff --git a/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs b/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs index ca38c4ea4..98bef52e5 100644 --- a/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs +++ b/ILSpy/Controls/TreeView/SharpTreeViewItemAutomationPeer.cs @@ -32,7 +32,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView : 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 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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/Controls/TreeView/SharpTreeViewTextSearch.cs b/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs index 731744c14..19532e66f 100644 --- a/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs +++ b/ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs @@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView typeof(SharpTreeViewTextSearch), typeof(SharpTreeViewTextSearch), new FrameworkPropertyMetadata(null)); static readonly DependencyProperty TextSearchInstanceProperty = TextSearchInstancePropertyKey.DependencyProperty; - DispatcherTimer timer; + DispatcherTimer? timer; bool isActive; int lastMatchIndex; @@ -116,7 +116,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView 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 21e258963..a6373fcc4 100644 --- a/ILSpy/Controls/ZoomScrollViewer.cs +++ b/ILSpy/Controls/ZoomScrollViewer.cs @@ -103,7 +103,7 @@ namespace ICSharpCode.ILSpy.Controls 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 @@ namespace ICSharpCode.ILSpy.Controls 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/DecompilationOptions.cs b/ILSpy/DecompilationOptions.cs index c7c87322d..b8b328b6f 100644 --- a/ILSpy/DecompilationOptions.cs +++ b/ILSpy/DecompilationOptions.cs @@ -85,7 +85,7 @@ namespace ICSharpCode.ILSpy 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/CloseAllDocumentsCommand.cs b/ILSpy/Docking/CloseAllDocumentsCommand.cs index 2c0ceb41b..273eda623 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 @@ namespace ICSharpCode.ILSpy.Docking [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/DockLayoutSettings.cs b/ILSpy/Docking/DockLayoutSettings.cs index 73ca3aa59..42533f41a 100644 --- a/ILSpy/Docking/DockLayoutSettings.cs +++ b/ILSpy/Docking/DockLayoutSettings.cs @@ -76,7 +76,7 @@ namespace ICSharpCode.ILSpy.Docking } } - public XElement SaveAsXml() + public XElement? SaveAsXml() { try { diff --git a/ILSpy/Docking/DockWorkspace.cs b/ILSpy/Docking/DockWorkspace.cs index 9ca68cc26..7a7251d1e 100644 --- a/ILSpy/Docking/DockWorkspace.cs +++ b/ILSpy/Docking/DockWorkspace.cs @@ -65,7 +65,7 @@ namespace ICSharpCode.ILSpy.Docking 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) { @@ -90,7 +90,7 @@ namespace ICSharpCode.ILSpy.Docking } } - private void TabPages_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + private void TabPages_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { @@ -110,7 +110,7 @@ namespace ICSharpCode.ILSpy.Docking } } - public void AddTabPage(TabPageModel tabPage = null) + public void AddTabPage(TabPageModel? tabPage = null) { tabPages.Add(tabPage ?? new TabPageModel()); } @@ -138,8 +138,8 @@ namespace ICSharpCode.ILSpy.Docking tool.IsVisible = false; } - private TabPageModel activeTabPage = null; - public TabPageModel ActiveTabPage { + private TabPageModel? activeTabPage = null; + public TabPageModel? ActiveTabPage { get { return activeTabPage; } @@ -183,7 +183,7 @@ namespace ICSharpCode.ILSpy.Docking } } - void LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e) + void LayoutSerializationCallback(object? sender, LayoutSerializationCallbackEventArgs e) { switch (e.Model) { @@ -213,7 +213,7 @@ namespace ICSharpCode.ILSpy.Docking 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,7 +266,7 @@ namespace ICSharpCode.ILSpy.Docking { 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; } } @@ -286,6 +286,6 @@ namespace ICSharpCode.ILSpy.Docking } // 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/TabPageGuardConverter.cs b/ILSpy/Docking/TabPageGuardConverter.cs index b6c2d2361..94a2f1b17 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/ILSpy.csproj b/ILSpy/ILSpy.csproj index 9b0dd6259..ee4bc3253 100644 --- a/ILSpy/ILSpy.csproj +++ b/ILSpy/ILSpy.csproj @@ -8,6 +8,7 @@ false false true + enable ICSharpCode.ILSpy True diff --git a/ILSpy/ILSpyTraceListener.cs b/ILSpy/ILSpyTraceListener.cs index 66bca5561..b68190b3b 100644 --- a/ILSpy/ILSpyTraceListener.cs +++ b/ILSpy/ILSpyTraceListener.cs @@ -43,12 +43,12 @@ namespace ICSharpCode.ILSpy 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/ISmartTextOutput.cs b/ILSpy/ISmartTextOutput.cs index 1cee54e59..3bb46afe3 100644 --- a/ILSpy/ISmartTextOutput.cs +++ b/ILSpy/ISmartTextOutput.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.ILSpy /// /// 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 49dfde0fd..4f24c3d0c 100644 --- a/ILSpy/Images/Images.cs +++ b/ILSpy/Images/Images.cs @@ -122,7 +122,7 @@ namespace ICSharpCode.ILSpy 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 @@ namespace ICSharpCode.ILSpy 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); @@ -150,12 +150,12 @@ namespace ICSharpCode.ILSpy 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 @@ namespace ICSharpCode.ILSpy 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 @@ namespace ICSharpCode.ILSpy 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/LanguageSettings.cs b/ILSpy/LanguageSettings.cs index 3748038bd..e38d50da0 100644 --- a/ILSpy/LanguageSettings.cs +++ b/ILSpy/LanguageSettings.cs @@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy /// 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, ISettingsSection parent) { @@ -150,7 +150,7 @@ namespace ICSharpCode.ILSpy } } - LanguageVersion languageVersion; + LanguageVersion? languageVersion; /// /// Gets/Sets the current language version. @@ -159,7 +159,7 @@ namespace ICSharpCode.ILSpy /// 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/CSharpBracketSearcher.cs b/ILSpy/Languages/CSharpBracketSearcher.cs index 28a7a4fd2..9967d4f6b 100644 --- a/ILSpy/Languages/CSharpBracketSearcher.cs +++ b/ILSpy/Languages/CSharpBracketSearcher.cs @@ -33,7 +33,7 @@ namespace ICSharpCode.ILSpy 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 fe229607a..dfddf721e 100644 --- a/ILSpy/Languages/CSharpHighlightingTokenWriter.cs +++ b/ILSpy/Languages/CSharpHighlightingTokenWriter.cs @@ -73,7 +73,7 @@ namespace ICSharpCode.ILSpy 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#"); @@ -122,7 +122,7 @@ namespace ICSharpCode.ILSpy public override void WriteKeyword(Role role, string keyword) { - HighlightingColor color = null; + HighlightingColor? color = null; switch (keyword) { case "namespace": @@ -299,7 +299,7 @@ namespace ICSharpCode.ILSpy public override void WritePrimitiveType(string type) { - HighlightingColor color = null; + HighlightingColor? color = null; switch (type) { case "new": @@ -348,7 +348,7 @@ namespace ICSharpCode.ILSpy 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) @@ -452,9 +452,9 @@ namespace ICSharpCode.ILSpy } } - 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; + HighlightingColor? color = null; if (value is null) { color = valueKeywordColor; @@ -474,7 +474,7 @@ namespace ICSharpCode.ILSpy } } - ISymbol GetCurrentDefinition() + ISymbol? GetCurrentDefinition() { if (nodeStack == null || nodeStack.Count == 0) return null; @@ -488,7 +488,7 @@ namespace ICSharpCode.ILSpy return null; } - ISymbol GetCurrentMemberReference() + ISymbol? GetCurrentMemberReference() { if (nodeStack == null || nodeStack.Count == 0) return null; @@ -529,8 +529,8 @@ namespace ICSharpCode.ILSpy 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 4d3436d23..6007cc18f 100644 --- a/ILSpy/Languages/CSharpILMixedLanguage.cs +++ b/ILSpy/Languages/CSharpILMixedLanguage.cs @@ -82,9 +82,9 @@ namespace ICSharpCode.ILSpy { 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/Languages/CSharpLanguage.cs b/ILSpy/Languages/CSharpLanguage.cs index f7cf47367..d261f181e 100644 --- a/ILSpy/Languages/CSharpLanguage.cs +++ b/ILSpy/Languages/CSharpLanguage.cs @@ -94,7 +94,7 @@ namespace ICSharpCode.ILSpy get { return ".csproj"; } } - IReadOnlyList versions; + IReadOnlyList? versions; public override IReadOnlyList LanguageVersions { get { @@ -150,7 +150,7 @@ namespace ICSharpCode.ILSpy 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); @@ -181,7 +181,7 @@ namespace ICSharpCode.ILSpy public void Run(AstNode rootNode, TransformContext context) { - ConstructorDeclaration ctorDecl = null; + ConstructorDeclaration? ctorDecl = null; foreach (var node in rootNode.Children) { switch (node) @@ -246,7 +246,7 @@ namespace ICSharpCode.ILSpy 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); @@ -257,7 +257,7 @@ namespace ICSharpCode.ILSpy 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); @@ -347,7 +347,7 @@ namespace ICSharpCode.ILSpy 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); @@ -379,8 +379,8 @@ namespace ICSharpCode.ILSpy 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) { @@ -417,7 +417,7 @@ namespace ICSharpCode.ILSpy } } - 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) @@ -701,7 +701,7 @@ namespace ICSharpCode.ILSpy } } - 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) @@ -774,7 +774,7 @@ namespace ICSharpCode.ILSpy 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/ILAstLanguage.cs b/ILSpy/Languages/ILAstLanguage.cs index b0f467b4b..c3fa7755b 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/Languages/ILLanguage.cs b/ILSpy/Languages/ILLanguage.cs index dae303124..b484406d4 100644 --- a/ILSpy/Languages/ILLanguage.cs +++ b/ILSpy/Languages/ILLanguage.cs @@ -73,7 +73,7 @@ namespace ICSharpCode.ILSpy 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 @@ namespace ICSharpCode.ILSpy 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 @@ namespace ICSharpCode.ILSpy 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 @@ namespace ICSharpCode.ILSpy 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 @@ namespace ICSharpCode.ILSpy 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,13 +157,13 @@ namespace ICSharpCode.ILSpy 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)); } - 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,14 +195,14 @@ namespace ICSharpCode.ILSpy return null; } - public override RichText GetRichTextTooltip(IEntity entity) + public override RichText? GetRichTextTooltip(IEntity entity) { var output = new AvalonEditTextOutput() { IgnoreNewLineAndIndent = true }; var settingsService = SettingsService.Instance; var dockWorkspace = DockWorkspace.Instance; var disasm = CreateDisassembler(output, settingsService.CreateDecompilationOptions(dockWorkspace.ActiveTabPage)); - MetadataFile module = entity.ParentModule?.MetadataFile; + MetadataFile? module = entity.ParentModule?.MetadataFile; if (module == null) { return null; diff --git a/ILSpy/Languages/Language.cs b/ILSpy/Languages/Language.cs index 26410fe24..28af50d6a 100644 --- a/ILSpy/Languages/Language.cs +++ b/ILSpy/Languages/Language.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.ILSpy /// public abstract string FileExtension { get; } - public virtual string ProjectFileExtension { + public virtual string? ProjectFileExtension { get { return null; } } @@ -107,7 +107,7 @@ namespace ICSharpCode.ILSpy WriteCommentLine(output, nameSpace); } - public virtual ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) + public virtual ProjectId? DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, assembly.FileName); var asm = assembly.GetMetadataFileOrNull(); @@ -125,7 +125,7 @@ namespace ICSharpCode.ILSpy { WriteCommentLine(output, metadata.GetString(name.Name) + " [WinRT]"); } - else if (metadata.TryGetFullAssemblyName(out string assemblyName)) + else if (metadata.TryGetFullAssemblyName(out string? assemblyName)) { WriteCommentLine(output, assemblyName); } @@ -364,7 +364,7 @@ namespace ICSharpCode.ILSpy /// 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); } @@ -478,7 +478,7 @@ namespace ICSharpCode.ILSpy /// /// 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 c5232ef83..eb0b2288f 100644 --- a/ILSpy/MainWindow.xaml.cs +++ b/ILSpy/MainWindow.xaml.cs @@ -29,7 +29,6 @@ using System.Windows.Media; using AvalonDock.Layout.Serialization; using ICSharpCode.ILSpy.AssemblyTree; -using ICSharpCode.ILSpy.Docking; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpy.Updates; using ICSharpCode.ILSpyX.FileLoaders; @@ -150,7 +149,7 @@ namespace ICSharpCode.ILSpy public async Task ShowMessageIfUpdatesAvailableAsync(ISettingsProvider spySettings, bool forceCheck = false) { - string downloadUrl; + string? downloadUrl; if (forceCheck) { downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(spySettings); @@ -178,12 +177,12 @@ namespace ICSharpCode.ILSpy else { updatePanel.Visibility = Visibility.Collapsed; - string downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(SettingsService.Instance.SpySettings); + string? downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(SettingsService.Instance.SpySettings); AdjustUpdateUIAfterCheck(downloadUrl, true); } } - void AdjustUpdateUIAfterCheck(string downloadUrl, bool displayMessage) + void AdjustUpdateUIAfterCheck(string? downloadUrl, bool displayMessage) { updateAvailableDownloadUrl = downloadUrl; updatePanel.Visibility = displayMessage ? Visibility.Visible : Visibility.Collapsed; diff --git a/ILSpy/Metadata/CoffHeaderTreeNode.cs b/ILSpy/Metadata/CoffHeaderTreeNode.cs index 36b9c8be8..065b1b6c1 100644 --- a/ILSpy/Metadata/CoffHeaderTreeNode.cs +++ b/ILSpy/Metadata/CoffHeaderTreeNode.cs @@ -118,7 +118,7 @@ namespace ICSharpCode.ILSpy.Metadata 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 d47f49a1a..3dbdd38a8 100644 --- a/ILSpy/Metadata/CorTables/AssemblyRefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/AssemblyRefTableTreeNode.cs @@ -89,7 +89,7 @@ namespace ICSharpCode.ILSpy.Metadata [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/ClassLayoutTableTreeNode.cs b/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs index 4d654da91..d6b8fd795 100644 --- a/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ClassLayoutTableTreeNode.cs @@ -100,8 +100,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 2b2ea571f..e6ccc60c2 100644 --- a/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs @@ -91,13 +91,13 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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); - public string ValueTooltip { + public string? ValueTooltip { get { return null; } diff --git a/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs b/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs index 370532d14..ca6089cf4 100644 --- a/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/CustomAttributeTableTreeNode.cs @@ -86,8 +86,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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,13 +97,13 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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); - public string ValueTooltip { + public string? ValueTooltip { get { return null; } diff --git a/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs b/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs index f37bdb87d..dce6bd87b 100644 --- a/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs @@ -87,8 +87,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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; @@ -102,7 +102,7 @@ namespace ICSharpCode.ILSpy.Metadata [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/EventMapTableTreeNode.cs b/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs index 3018d8970..b138480f9 100644 --- a/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs @@ -98,8 +98,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 14dabb3e0..966620c1c 100644 --- a/ILSpy/Metadata/CorTables/EventTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/EventTableTreeNode.cs @@ -92,7 +92,7 @@ namespace ICSharpCode.ILSpy.Metadata public string Name => metadataFile.Metadata.GetString(eventDef.Name); - IEntity IMemberTreeNode.Member { + IEntity? IMemberTreeNode.Member { get { return ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); } @@ -106,8 +106,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 f1075c16b..62e33ec2c 100644 --- a/ILSpy/Metadata/CorTables/ExportedTypeTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ExportedTypeTableTreeNode.cs @@ -110,8 +110,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 6fe92c597..c76104422 100644 --- a/ILSpy/Metadata/CorTables/FieldLayoutTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldLayoutTableTreeNode.cs @@ -99,8 +99,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 befd90a8c..d1ca21b22 100644 --- a/ILSpy/Metadata/CorTables/FieldMarshalTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldMarshalTableTreeNode.cs @@ -98,8 +98,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 959225bdb..10971d52e 100644 --- a/ILSpy/Metadata/CorTables/FieldRVATableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldRVATableTreeNode.cs @@ -102,8 +102,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 c8e8e310d..7d2b5f2dd 100644 --- a/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FieldTableTreeNode.cs @@ -95,13 +95,13 @@ namespace ICSharpCode.ILSpy.Metadata 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); - 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/FileTableTreeNode.cs b/ILSpy/Metadata/CorTables/FileTableTreeNode.cs index f48edcb39..896774477 100644 --- a/ILSpy/Metadata/CorTables/FileTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/FileTableTreeNode.cs @@ -90,7 +90,7 @@ namespace ICSharpCode.ILSpy.Metadata [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/GenericParamConstraintTableTreeNode.cs b/ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs index 0e2180210..a6b69295e 100644 --- a/ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/GenericParamConstraintTableTreeNode.cs @@ -87,9 +87,9 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 29509426b..c09cf535c 100644 --- a/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/GenericParamTableTreeNode.cs @@ -95,8 +95,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 efe6e6fa1..bec563233 100644 --- a/ILSpy/Metadata/CorTables/ImplMapTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ImplMapTableTreeNode.cs @@ -116,8 +116,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 04b87015d..b37d097e3 100644 --- a/ILSpy/Metadata/CorTables/InterfaceImplTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/InterfaceImplTableTreeNode.cs @@ -99,8 +99,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 5bd75eb91..0f655e357 100644 --- a/ILSpy/Metadata/CorTables/ManifestResourceTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ManifestResourceTableTreeNode.cs @@ -96,8 +96,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 9f858434d..daba41c50 100644 --- a/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs @@ -86,8 +86,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata [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 2344f6ff1..3a5de96d0 100644 --- a/ILSpy/Metadata/CorTables/MethodImplTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodImplTableTreeNode.cs @@ -85,8 +85,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 49cb863f0..63270937d 100644 --- a/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs @@ -93,8 +93,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 d25a71dd3..12a1dae83 100644 --- a/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs @@ -88,8 +88,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 cfea5f2ae..a351da9b1 100644 --- a/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/MethodTableTreeNode.cs @@ -109,9 +109,9 @@ namespace ICSharpCode.ILSpy.Metadata [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,8 +121,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(new EntityReference(metadataFile, methodDef.GetParameters().FirstOrDefault(), protocol: "metadata"))); } - string paramListTooltip; - public string ParamListTooltip { + string? paramListTooltip; + public string? ParamListTooltip { get { var param = methodDef.GetParameters().FirstOrDefault(); if (param.IsNil) @@ -131,7 +131,7 @@ namespace ICSharpCode.ILSpy.Metadata } } - 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/ModuleTableTreeNode.cs b/ILSpy/Metadata/CorTables/ModuleTableTreeNode.cs index 490d0ed5c..1a2b26990 100644 --- a/ILSpy/Metadata/CorTables/ModuleTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/ModuleTableTreeNode.cs @@ -83,12 +83,12 @@ namespace ICSharpCode.ILSpy.Metadata [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/NestedClassTableTreeNode.cs b/ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs index e95619be7..a2af5d434 100644 --- a/ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs @@ -98,8 +98,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 6071961f3..70370559b 100644 --- a/ILSpy/Metadata/CorTables/PropertyMapTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/PropertyMapTableTreeNode.cs @@ -98,8 +98,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 05ff38b71..4c799241c 100644 --- a/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs @@ -92,13 +92,13 @@ namespace ICSharpCode.ILSpy.Metadata 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); - 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 cf196ef03..de76f4018 100644 --- a/ILSpy/Metadata/CorTables/PtrTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/PtrTableTreeNode.cs @@ -115,8 +115,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 24c5cf163..8b5b78b1a 100644 --- a/ILSpy/Metadata/CorTables/StandAloneSigTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/StandAloneSigTableTreeNode.cs @@ -80,8 +80,8 @@ namespace ICSharpCode.ILSpy.Metadata [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 129f76907..053f393aa 100644 --- a/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs @@ -114,7 +114,7 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(new EntityReference(metadataFile, typeDef.BaseType, protocol: "metadata"))); } - public string BaseTypeTooltip { + public string? BaseTypeTooltip { get { var output = new PlainTextOutput(); var provider = new DisassemblerSignatureTypeProvider(metadataFile, output); @@ -145,8 +145,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(new EntityReference(metadataFile, typeDef.GetFields().FirstOrDefault(), protocol: "metadata"))); } - string fieldListTooltip; - public string FieldListTooltip { + string? fieldListTooltip; + public string? FieldListTooltip { get { var field = typeDef.GetFields().FirstOrDefault(); if (field.IsNil) @@ -163,8 +163,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(new EntityReference(metadataFile, typeDef.GetMethods().FirstOrDefault(), protocol: "metadata"))); } - string methodListTooltip; - public string MethodListTooltip { + string? methodListTooltip; + public string? MethodListTooltip { get { var method = typeDef.GetMethods().FirstOrDefault(); if (method.IsNil) @@ -173,7 +173,7 @@ namespace ICSharpCode.ILSpy.Metadata } } - 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/CorTables/TypeRefTableTreeNode.cs b/ILSpy/Metadata/CorTables/TypeRefTableTreeNode.cs index 6b086fea1..8457f1007 100644 --- a/ILSpy/Metadata/CorTables/TypeRefTableTreeNode.cs +++ b/ILSpy/Metadata/CorTables/TypeRefTableTreeNode.cs @@ -86,8 +86,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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/CustomDebugInformationTableTreeNode.cs b/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs index b020f5a97..ea4dc5b04 100644 --- a/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs @@ -47,7 +47,7 @@ namespace ICSharpCode.ILSpy.Metadata view.RowDetailsTemplateSelector = new CustomDebugInformationDetailsTemplateSelector(); var list = new List(); - CustomDebugInformationEntry scrollTargetEntry = default; + CustomDebugInformationEntry? scrollTargetEntry = default; foreach (var row in metadataFile.Metadata.CustomDebugInformation) { @@ -243,7 +243,7 @@ namespace ICSharpCode.ILSpy.Metadata 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 320fdffff..c24b6f19f 100644 --- a/ILSpy/Metadata/DebugTables/DocumentTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/DocumentTableTreeNode.cs @@ -84,7 +84,7 @@ namespace ICSharpCode.ILSpy.Metadata [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 @@ namespace ICSharpCode.ILSpy.Metadata [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 @@ namespace ICSharpCode.ILSpy.Metadata [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/LocalScopeTableTreeNode.cs b/ILSpy/Metadata/DebugTables/LocalScopeTableTreeNode.cs index f25412f98..0a4fb3e07 100644 --- a/ILSpy/Metadata/DebugTables/LocalScopeTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/LocalScopeTableTreeNode.cs @@ -84,8 +84,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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/MethodDebugInformationTableTreeNode.cs b/ILSpy/Metadata/DebugTables/MethodDebugInformationTableTreeNode.cs index 5453ce6f7..a93054fac 100644 --- a/ILSpy/Metadata/DebugTables/MethodDebugInformationTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/MethodDebugInformationTableTreeNode.cs @@ -86,7 +86,7 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(new EntityReference(metadataFile, debugInfo.Document, protocol: "metadata"))); } - public string DocumentTooltip { + public string? DocumentTooltip { get { if (debugInfo.Document.IsNil) return null; @@ -98,7 +98,7 @@ namespace ICSharpCode.ILSpy.Metadata [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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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/DebugTables/StateMachineMethodTableTreeNode.cs b/ILSpy/Metadata/DebugTables/StateMachineMethodTableTreeNode.cs index d4f778ed2..8602a955b 100644 --- a/ILSpy/Metadata/DebugTables/StateMachineMethodTableTreeNode.cs +++ b/ILSpy/Metadata/DebugTables/StateMachineMethodTableTreeNode.cs @@ -86,8 +86,8 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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 @@ namespace ICSharpCode.ILSpy.Metadata MessageBus.Send(this, new NavigateToReferenceEventArgs(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/FlagsFilterControl.xaml.cs b/ILSpy/Metadata/FlagsFilterControl.xaml.cs index 7a8225a69..6ebaf42f4 100644 --- a/ILSpy/Metadata/FlagsFilterControl.xaml.cs +++ b/ILSpy/Metadata/FlagsFilterControl.xaml.cs @@ -114,7 +114,7 @@ namespace ICSharpCode.ILSpy.Metadata this.Mask = mask; } - public bool IsMatch(object value) + public bool IsMatch(object? value) { if (value == null) return true; diff --git a/ILSpy/Metadata/FlagsTooltip.xaml.cs b/ILSpy/Metadata/FlagsTooltip.xaml.cs index 8e670fca3..c66128a38 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 @@ namespace ICSharpCode.ILSpy.Metadata 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 @@ namespace ICSharpCode.ILSpy.Metadata 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 @@ namespace ICSharpCode.ILSpy.Metadata 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 @@ namespace ICSharpCode.ILSpy.Metadata } } - public string Header { get; set; } + public string? Header { get; set; } public IList Flags { get; protected set; } } diff --git a/ILSpy/Metadata/GoToTokenCommand.cs b/ILSpy/Metadata/GoToTokenCommand.cs index 164f9b451..17c488d5b 100644 --- a/ILSpy/Metadata/GoToTokenCommand.cs +++ b/ILSpy/Metadata/GoToTokenCommand.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.ILSpy.Commands 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) @@ -76,7 +76,7 @@ namespace ICSharpCode.ILSpy.Commands { public void Execute(TextViewContext context) { - string content = GetSelectedCellContent(context.OriginalSource); + string? content = GetSelectedCellContent(context.OriginalSource); Clipboard.SetText(content); } @@ -91,7 +91,7 @@ namespace ICSharpCode.ILSpy.Commands && GetSelectedCellContent(context.OriginalSource) != null; } - private static string GetSelectedCellContent(DependencyObject originalSource) + private static string? GetSelectedCellContent(DependencyObject originalSource) { var cell = originalSource.AncestorsAndSelf().OfType().FirstOrDefault(); diff --git a/ILSpy/Metadata/Helpers.cs b/ILSpy/Metadata/Helpers.cs index aee8137ac..94c733498 100644 --- a/ILSpy/Metadata/Helpers.cs +++ b/ILSpy/Metadata/Helpers.cs @@ -89,13 +89,13 @@ namespace ICSharpCode.ILSpy.Metadata 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/HexFilterControl.xaml.cs b/ILSpy/Metadata/HexFilterControl.xaml.cs index 26f4d5ea7..6c3a14217 100644 --- a/ILSpy/Metadata/HexFilterControl.xaml.cs +++ b/ILSpy/Metadata/HexFilterControl.xaml.cs @@ -71,7 +71,7 @@ namespace ICSharpCode.ILSpy.Metadata 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 a87b065e3..eaf7f960c 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; } @@ -43,7 +43,7 @@ namespace ICSharpCode.ILSpy.Metadata 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 @@ namespace ICSharpCode.ILSpy.Metadata } } - 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); @@ -76,7 +76,7 @@ namespace ICSharpCode.ILSpy.Metadata 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 @@ namespace ICSharpCode.ILSpy.Metadata } } - public ViewState GetState() + public ViewState? GetState() { return new ViewState { DecompiledNodes = SelectedTreeNode == null diff --git a/ILSpy/Metadata/MetadataProtocolHandler.cs b/ILSpy/Metadata/MetadataProtocolHandler.cs index 8a50cac36..a70cb523b 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 2df51f1c6..bbee36ce2 100644 --- a/ILSpy/Metadata/MetadataTableTreeNode.cs +++ b/ILSpy/Metadata/MetadataTableTreeNode.cs @@ -66,7 +66,7 @@ namespace ICSharpCode.ILSpy.Metadata 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 50f739868..e475ba69b 100644 --- a/ILSpy/Metadata/MetadataTreeNode.cs +++ b/ILSpy/Metadata/MetadataTreeNode.cs @@ -120,9 +120,9 @@ namespace ICSharpCode.ILSpy.Metadata 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/NavigationState.cs b/ILSpy/NavigationState.cs index e7400b40e..1d72b66b7 100644 --- a/ILSpy/NavigationState.cs +++ b/ILSpy/NavigationState.cs @@ -38,7 +38,7 @@ namespace ICSharpCode.ILSpy 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; } @@ -49,7 +49,7 @@ namespace ICSharpCode.ILSpy } - public bool Equals(NavigationState other) + public bool Equals(NavigationState? other) { if (!this.treeNodes.SetEquals(other.treeNodes)) return false; diff --git a/ILSpy/Options/DecompilerSettingsViewModel.cs b/ILSpy/Options/DecompilerSettingsViewModel.cs index 27cc520de..eb0b9d5a8 100644 --- a/ILSpy/Options/DecompilerSettingsViewModel.cs +++ b/ILSpy/Options/DecompilerSettingsViewModel.cs @@ -112,7 +112,7 @@ namespace ICSharpCode.ILSpy.Options 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/DisplaySettingsPanel.xaml.cs b/ILSpy/Options/DisplaySettingsPanel.xaml.cs index 3b51a16ba..66c965b2a 100644 --- a/ILSpy/Options/DisplaySettingsPanel.xaml.cs +++ b/ILSpy/Options/DisplaySettingsPanel.xaml.cs @@ -69,7 +69,7 @@ namespace ICSharpCode.ILSpy.Options 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 @@ namespace ICSharpCode.ILSpy.Options 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 783488175..79323e5b8 100644 --- a/ILSpy/Options/OptionsDialog.xaml.cs +++ b/ILSpy/Options/OptionsDialog.xaml.cs @@ -69,7 +69,7 @@ namespace ICSharpCode.ILSpy.Options 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/Search/SearchPane.xaml.cs b/ILSpy/Search/SearchPane.xaml.cs index 4c21ac145..e1484c806 100644 --- a/ILSpy/Search/SearchPane.xaml.cs +++ b/ILSpy/Search/SearchPane.xaml.cs @@ -54,7 +54,7 @@ namespace ICSharpCode.ILSpy.Search { 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; @@ -207,7 +207,7 @@ namespace ICSharpCode.ILSpy.Search listBox.SelectedIndex = 0; } - void UpdateResults(object sender, EventArgs e) + void UpdateResults(object? sender, EventArgs e) { if (currentSearch == null) return; @@ -235,7 +235,7 @@ namespace ICSharpCode.ILSpy.Search currentSearch.Cancel(); } - async void StartSearch(string searchTerm) + async void StartSearch(string? searchTerm) { if (currentSearch != null) { @@ -249,7 +249,7 @@ namespace ICSharpCode.ILSpy.Search SearchResult.ComparerByName; Results.Clear(); - RunningSearch startedSearch = null; + RunningSearch? startedSearch = null; if (!string.IsNullOrEmpty(searchTerm)) { @@ -303,7 +303,7 @@ namespace ICSharpCode.ILSpy.Search SearchRequest request = new(); List keywords = new(); - Regex regex = null; + Regex? regex = null; request.Mode = searchMode; foreach (string part in parts) @@ -329,7 +329,7 @@ namespace ICSharpCode.ILSpy.Search prefixLength = part.IndexOf(':', 0, prefixLength); delimiterLength = 1; } - string prefix; + string? prefix; if (prefixLength <= 0) { prefix = null; @@ -439,7 +439,7 @@ namespace ICSharpCode.ILSpy.Search } } - Regex CreateRegex(string s) + Regex? CreateRegex(string s) { try { @@ -496,7 +496,7 @@ namespace ICSharpCode.ILSpy.Search } } - AbstractSearchStrategy GetSearchStrategy(SearchRequest request) + AbstractSearchStrategy? GetSearchStrategy(SearchRequest request) { if (request.Keywords.Length == 0 && request.RegEx == null) return null; diff --git a/ILSpy/SessionSettings.cs b/ILSpy/SessionSettings.cs index 59a939887..e76544b19 100644 --- a/ILSpy/SessionSettings.cs +++ b/ILSpy/SessionSettings.cs @@ -86,7 +86,7 @@ namespace ICSharpCode.ILSpy } } - public string ActiveAssemblyList { + public string? ActiveAssemblyList { get => activeAssemblyList; set { if (value != null && value != activeAssemblyList) @@ -139,7 +139,7 @@ namespace ICSharpCode.ILSpy } static Regex regex = new("\\\\x(?[0-9A-f]{4})"); - private string activeAssemblyList; + private string? activeAssemblyList; static string Escape(string p) { @@ -159,7 +159,7 @@ namespace ICSharpCode.ILSpy 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; @@ -180,14 +180,14 @@ namespace ICSharpCode.ILSpy 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/TaskHelper.cs b/ILSpy/TaskHelper.cs index 5b33bff3c..462143edd 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 @@ namespace ICSharpCode.ILSpy /// /// 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 @@ namespace ICSharpCode.ILSpy 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"); @@ -174,7 +174,7 @@ namespace ICSharpCode.ILSpy 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 da62890a0..6517a1783 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/BracketHighlightRenderer.cs b/ILSpy/TextView/BracketHighlightRenderer.cs index 4b958d407..2336bca8c 100644 --- a/ILSpy/TextView/BracketHighlightRenderer.cs +++ b/ILSpy/TextView/BracketHighlightRenderer.cs @@ -33,14 +33,14 @@ namespace ICSharpCode.ILSpy.TextView /// 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 { public static readonly DefaultBracketSearcher DefaultInstance = new DefaultBracketSearcher(); - public BracketSearchResult SearchBracket(IDocument document, int offset) + public BracketSearchResult? SearchBracket(IDocument document, int offset) { return null; } @@ -71,12 +71,12 @@ namespace ICSharpCode.ILSpy.TextView 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/DecompilerTextView.cs b/ILSpy/TextView/DecompilerTextView.cs index bbcc3674f..927215a25 100644 --- a/ILSpy/TextView/DecompilerTextView.cs +++ b/ILSpy/TextView/DecompilerTextView.cs @@ -392,7 +392,7 @@ namespace ICSharpCode.ILSpy.TextView { 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 @@ namespace ICSharpCode.ILSpy.TextView 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 @@ namespace ICSharpCode.ILSpy.TextView { 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 4d0c5eb78..75b3d552f 100644 --- a/ILSpy/TextView/DocumentationUIBuilder.cs +++ b/ILSpy/TextView/DocumentationUIBuilder.cs @@ -49,7 +49,7 @@ namespace ICSharpCode.ILSpy.TextView readonly IHighlightingDefinition highlightingDefinition; readonly FlowDocument document; BlockCollection blockCollection; - InlineCollection inlineCollection; + InlineCollection? inlineCollection; public DocumentationUIBuilder(IAmbience ambience, IHighlightingDefinition highlightingDefinition) { @@ -106,7 +106,7 @@ namespace ICSharpCode.ILSpy.TextView 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(); @@ -127,7 +127,7 @@ namespace ICSharpCode.ILSpy.TextView AddBlock(block); } - public void AddXmlDocumentation(string xmlDocumentation, IEntity declaringEntity, Func resolver) + public void AddXmlDocumentation(string xmlDocumentation, IEntity? declaringEntity, Func? resolver) { if (xmlDocumentation == null) return; @@ -374,7 +374,7 @@ namespace ICSharpCode.ILSpy.TextView void AddSee(XmlDocumentationElement element) { - IEntity referencedEntity = element.ReferencedEntity; + IEntity? referencedEntity = element.ReferencedEntity; if (referencedEntity != null) { if (element.Children.Any()) @@ -396,7 +396,7 @@ namespace ICSharpCode.ILSpy.TextView } 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 c061c543e..4fceb1176 100644 --- a/ILSpy/TextView/FoldingCommands.cs +++ b/ILSpy/TextView/FoldingCommands.cs @@ -43,7 +43,7 @@ namespace ICSharpCode.ILSpy.TextView { 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 @@ namespace ICSharpCode.ILSpy.TextView 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 @@ namespace ICSharpCode.ILSpy.TextView 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/TextView/ReferenceElementGenerator.cs b/ILSpy/TextView/ReferenceElementGenerator.cs index f1255990a..ebcfb2774 100644 --- a/ILSpy/TextView/ReferenceElementGenerator.cs +++ b/ILSpy/TextView/ReferenceElementGenerator.cs @@ -52,7 +52,7 @@ namespace ICSharpCode.ILSpy.TextView 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 e0c254e61..26a763fd5 100644 --- a/ILSpy/TextView/UIElementGenerator.cs +++ b/ILSpy/TextView/UIElementGenerator.cs @@ -24,7 +24,7 @@ using ICSharpCode.AvalonEdit.Rendering; namespace ICSharpCode.ILSpy.TextView { - using Pair = KeyValuePair>; + using Pair = KeyValuePair?>; /// /// Embeds UIElements in the text output. @@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy.TextView /// 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) { @@ -53,7 +53,7 @@ namespace ICSharpCode.ILSpy.TextView return -1; } - public override VisualLineElement ConstructElement(int offset) + public override VisualLineElement? ConstructElement(int offset) { if (this.UIElements == null) return null; diff --git a/ILSpy/Themes/WindowStyleManagerBehavior.cs b/ILSpy/Themes/WindowStyleManagerBehavior.cs index 681fbf97e..4b8aa62a2 100644 --- a/ILSpy/Themes/WindowStyleManagerBehavior.cs +++ b/ILSpy/Themes/WindowStyleManagerBehavior.cs @@ -64,7 +64,7 @@ namespace ICSharpCode.ILSpy.Themes SettingsService.Instance.DisplaySettings.PropertyChanged -= DisplaySettings_PropertyChanged; } - private void Color_Changed(object sender, EventArgs e) + private void Color_Changed(object? sender, EventArgs e) { ApplyThemeToWindowCaption(); } @@ -82,7 +82,7 @@ namespace ICSharpCode.ILSpy.Themes 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)) { @@ -113,7 +113,7 @@ namespace ICSharpCode.ILSpy.Themes } 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 e8a984087..ee8bae8ef 100644 --- a/ILSpy/TreeNodes/AssemblyListTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyListTreeNode.cs @@ -57,7 +57,7 @@ namespace ICSharpCode.ILSpy.TreeNodes { 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: @@ -95,7 +95,7 @@ namespace ICSharpCode.ILSpy.TreeNodes 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) @@ -127,7 +127,7 @@ namespace ICSharpCode.ILSpy.TreeNodes } #region Find*Node - public ILSpyTreeNode FindResourceNode(Resource resource) + public ILSpyTreeNode? FindResourceNode(Resource resource) { if (resource == null) return null; @@ -166,14 +166,14 @@ namespace ICSharpCode.ILSpy.TreeNodes 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; @@ -200,6 +200,8 @@ namespace ICSharpCode.ILSpy.TreeNodes } return null; + + static SharpTreeNodeCollection ExpandAndGetChildren(SharpTreeNode node) { if (node is not PackageFolderTreeNode) @@ -213,14 +215,14 @@ namespace ICSharpCode.ILSpy.TreeNodes /// 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; var declaringType = def.DeclaringTypeDefinition; if (declaringType != null) { - TypeTreeNode decl = FindTypeNode(declaringType); + TypeTreeNode? decl = FindTypeNode(declaringType); if (decl != null) { decl.EnsureLazyChildren(); @@ -242,14 +244,14 @@ namespace ICSharpCode.ILSpy.TreeNodes /// 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); + 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) { @@ -283,9 +285,9 @@ namespace ICSharpCode.ILSpy.TreeNodes /// 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); + TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) return null; typeNode.EnsureLazyChildren(); @@ -296,9 +298,9 @@ namespace ICSharpCode.ILSpy.TreeNodes /// 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); + TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) return null; typeNode.EnsureLazyChildren(); @@ -309,9 +311,9 @@ namespace ICSharpCode.ILSpy.TreeNodes /// 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); + TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition); if (typeNode == null) return null; typeNode.EnsureLazyChildren(); @@ -322,7 +324,7 @@ namespace ICSharpCode.ILSpy.TreeNodes /// 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 335871fff..724688d59 100644 --- a/ILSpy/TreeNodes/AssemblyTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyTreeNode.cs @@ -62,7 +62,7 @@ namespace ICSharpCode.ILSpy.TreeNodes { } - internal AssemblyTreeNode(LoadedAssembly assembly, PackageEntry packageEntry) + internal AssemblyTreeNode(LoadedAssembly assembly, PackageEntry? packageEntry) { this.LoadedAssembly = assembly ?? throw new ArgumentNullException(nameof(assembly)); this.LazyLoading = true; @@ -80,7 +80,7 @@ namespace ICSharpCode.ILSpy.TreeNodes /// 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 { @@ -125,7 +125,7 @@ namespace ICSharpCode.ILSpy.TreeNodes } } - TextBlock tooltip; + TextBlock? tooltip; public override object ToolTip { get { @@ -249,7 +249,7 @@ namespace ICSharpCode.ILSpy.TreeNodes 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) { @@ -281,7 +281,7 @@ namespace ICSharpCode.ILSpy.TreeNodes NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace) { - if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode ns)) + if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode? ns)) { if (useNestedStructure) { @@ -347,7 +347,7 @@ namespace ICSharpCode.ILSpy.TreeNodes NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace) { - if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode ns)) + if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode? ns)) { if (useNestedStructure) { @@ -388,12 +388,12 @@ namespace ICSharpCode.ILSpy.TreeNodes /// /// Finds the node for a top-level type. /// - public TypeTreeNode FindTypeNode(ITypeDefinition type) + public TypeTreeNode? FindTypeNode(ITypeDefinition type) { if (type == null) return null; EnsureLazyChildren(); - TypeTreeNode node; + TypeTreeNode? node; if (typeDict.TryGetValue((TypeDefinitionHandle)type.MetadataToken, out node)) return node; else @@ -403,7 +403,7 @@ namespace ICSharpCode.ILSpy.TreeNodes /// /// Finds the node for a namespace. /// - public NamespaceTreeNode FindNamespaceNode(string namespaceName) + public NamespaceTreeNode? FindNamespaceNode(string namespaceName) { if (string.IsNullOrEmpty(namespaceName)) return null; @@ -731,7 +731,7 @@ namespace ICSharpCode.ILSpy.TreeNodes }); } - internal static AssemblyTreeNode GetAssemblyTreeNode(SharpTreeNode node) + internal static AssemblyTreeNode? GetAssemblyTreeNode(SharpTreeNode node) { while (node != null) { diff --git a/ILSpy/TreeNodes/ILSpyTreeNode.cs b/ILSpy/TreeNodes/ILSpyTreeNode.cs index 99e63e36e..edbb9c213 100644 --- a/ILSpy/TreeNodes/ILSpyTreeNode.cs +++ b/ILSpy/TreeNodes/ILSpyTreeNode.cs @@ -28,8 +28,8 @@ using System.Windows.Threading; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX.Abstractions; -using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; using ICSharpCode.ILSpyX.TreeView; +using ICSharpCode.ILSpyX.TreeView.PlatformAbstractions; namespace ICSharpCode.ILSpy.TreeNodes { @@ -127,7 +127,7 @@ namespace ICSharpCode.ILSpy.TreeNodes } } - protected virtual void Settings_Changed(object sender, PropertyChangedEventArgs e) + protected virtual void Settings_Changed(object? sender, PropertyChangedEventArgs e) { if (sender is not ILSpy.LanguageSettings) return; diff --git a/ILSpy/TreeNodes/PackageFolderTreeNode.cs b/ILSpy/TreeNodes/PackageFolderTreeNode.cs index 9fc528b3f..b6f743288 100644 --- a/ILSpy/TreeNodes/PackageFolderTreeNode.cs +++ b/ILSpy/TreeNodes/PackageFolderTreeNode.cs @@ -33,7 +33,7 @@ namespace ICSharpCode.ILSpy.TreeNodes { 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/ResourceNodes/CursorResourceEntryNode.cs b/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs index 993c22bdf..393b3198d 100644 --- a/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs @@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy.TreeNodes { static readonly string[] imageFileExtensions = { ".cur" }; - public ITreeNode CreateNode(Resource resource) + public ITreeNode? CreateNode(Resource resource) { string key = resource.Name; foreach (string fileExt in imageFileExtensions) @@ -50,7 +50,7 @@ namespace ICSharpCode.ILSpy.TreeNodes sealed class CursorResourceEntryNode : ResourceEntryNode { - public CursorResourceEntryNode(string key, Func openStream) + public CursorResourceEntryNode(string key, Func openStream) : base(key, openStream) { } @@ -70,7 +70,7 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 a9dba6c6f..9989fccd1 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 075aa1ca0..b3618772d 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 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 7a3d9c795..be339b801 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 cad4098eb..c98e36d8e 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs @@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy.TreeNodes { 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 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 5786c88c8..6b0e34633 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 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 @@ namespace ICSharpCode.ILSpy.TreeNodes 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/ResourceTreeNode.cs b/ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs index 69502149f..04dccc7b9 100644 --- a/ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs @@ -71,7 +71,7 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 324390af2..0b1ce8d85 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 @@ namespace ICSharpCode.ILSpy.TreeNodes return null; } - public ILSpyTreeNode CreateNode(string key, object data) + public ILSpyTreeNode? CreateNode(string key, object data) { return null; } @@ -71,7 +71,7 @@ namespace ICSharpCode.ILSpy.TreeNodes protected override void LoadChildren() { - Stream s = Resource.TryOpenStream(); + Stream? s = Resource.TryOpenStream(); if (s == null) return; s.Position = 0; @@ -128,7 +128,7 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 @@ namespace ICSharpCode.ILSpy.TreeNodes 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 @@ namespace ICSharpCode.ILSpy.TreeNodes } 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 e017948df..cd2b796b8 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,16 +45,16 @@ namespace ICSharpCode.ILSpy.Xaml 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) { } 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/ResourceNodes/XmlResourceNode.cs b/ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs index 740947602..32947bc18 100644 --- a/ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs +++ b/ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs @@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy.Xaml { 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 @@ namespace ICSharpCode.ILSpy.Xaml 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 @@ namespace ICSharpCode.ILSpy.Xaml 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 ce1d87515..c42c7cba7 100644 --- a/ILSpy/TreeNodes/ThreadingSupport.cs +++ b/ILSpy/TreeNodes/ThreadingSupport.cs @@ -40,7 +40,7 @@ namespace ICSharpCode.ILSpy.TreeNodes { readonly Stopwatch stopwatch = new Stopwatch(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - Task> loadChildrenTask; + Task>? loadChildrenTask; public bool IsRunning { get { return loadChildrenTask != null && !loadChildrenTask.IsCompleted; } @@ -67,7 +67,7 @@ namespace ICSharpCode.ILSpy.TreeNodes CancellationToken ct = cancellationTokenSource.Token; var fetchChildrenEnumerable = fetchChildren(ct); - Task> 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 d2ab85fc9..166d87d42 100644 --- a/ILSpy/Updates/NotifyOfUpdatesStrategy.cs +++ b/ILSpy/Updates/NotifyOfUpdatesStrategy.cs @@ -46,7 +46,7 @@ namespace ICSharpCode.ILSpy.Updates 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 @@ -61,7 +61,7 @@ namespace ICSharpCode.ILSpy.Updates /// 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(ISettingsProvider spySettings) + public static async Task CheckForUpdatesIfEnabledAsync(ISettingsProvider spySettings) { UpdateSettings s = new UpdateSettings(spySettings); @@ -87,13 +87,13 @@ namespace ICSharpCode.ILSpy.Updates } } - public static Task CheckForUpdatesAsync(ISettingsProvider spySettings) + public static Task CheckForUpdatesAsync(ISettingsProvider spySettings) { UpdateSettings s = new UpdateSettings(spySettings); return CheckForUpdateInternal(s); } - static async Task CheckForUpdateInternal(UpdateSettings s) + static async Task CheckForUpdateInternal(UpdateSettings s) { try { diff --git a/ILSpy/Updates/UpdateSettings.cs b/ILSpy/Updates/UpdateSettings.cs index 23b4b0663..dbf18fbc4 100644 --- a/ILSpy/Updates/UpdateSettings.cs +++ b/ILSpy/Updates/UpdateSettings.cs @@ -78,9 +78,9 @@ namespace ICSharpCode.ILSpy.Updates SettingsService.Instance.SpySettings.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/ManageAssemblyListsViewModel.cs b/ILSpy/ViewModels/ManageAssemblyListsViewModel.cs index 76ab7aedb..a9e5ae7af 100644 --- a/ILSpy/ViewModels/ManageAssemblyListsViewModel.cs +++ b/ILSpy/ViewModels/ManageAssemblyListsViewModel.cs @@ -100,9 +100,9 @@ namespace ICSharpCode.ILSpy.ViewModels public List PreconfiguredAssemblyLists { get; } - private string selectedAssemblyList; + private string? selectedAssemblyList; - public string SelectedAssemblyList { + public string? SelectedAssemblyList { get => selectedAssemblyList; set { if (selectedAssemblyList != value) @@ -282,7 +282,7 @@ namespace ICSharpCode.ILSpy.ViewModels 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; diff --git a/ILSpy/ViewModels/PaneModel.cs b/ILSpy/ViewModels/PaneModel.cs index f9ef1b90e..0f4ce987d 100644 --- a/ILSpy/ViewModels/PaneModel.cs +++ b/ILSpy/ViewModels/PaneModel.cs @@ -46,7 +46,7 @@ namespace ICSharpCode.ILSpy.ViewModels 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)) { @@ -54,14 +54,14 @@ namespace ICSharpCode.ILSpy.ViewModels } } - public event EventHandler CanExecuteChanged; + 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 abcaa4666..90ff9ce57 100644 --- a/ILSpy/ViewModels/TabPageModel.cs +++ b/ILSpy/ViewModels/TabPageModel.cs @@ -100,6 +100,6 @@ namespace ICSharpCode.ILSpy.ViewModels public interface IHaveState { - ViewState GetState(); + ViewState? GetState(); } } \ No newline at end of file diff --git a/ILSpy/ViewModels/ViewModelBase.cs b/ILSpy/ViewModels/ViewModelBase.cs index f4517670c..330c68085 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)); } diff --git a/ILSpy/Views/DebugSteps.xaml.cs b/ILSpy/Views/DebugSteps.xaml.cs index b2745089e..42cb93f95 100644 --- a/ILSpy/Views/DebugSteps.xaml.cs +++ b/ILSpy/Views/DebugSteps.xaml.cs @@ -47,12 +47,12 @@ namespace ICSharpCode.ILSpy #endif } - private void WritingOptions_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + private void WritingOptions_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { 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 @@ namespace ICSharpCode.ILSpy }); } - 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) @@ -82,7 +82,7 @@ namespace ICSharpCode.ILSpy #endif } - private void ILAstStepperUpdated(object sender, EventArgs e) + private void ILAstStepperUpdated(object? sender, EventArgs? e) { #if DEBUG if (language == null) diff --git a/TestPlugin/CustomLanguage.cs b/TestPlugin/CustomLanguage.cs index 7e38fdffe..bfd2ac285 100644 --- a/TestPlugin/CustomLanguage.cs +++ b/TestPlugin/CustomLanguage.cs @@ -41,7 +41,7 @@ namespace TestPlugin 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/MainMenuCommand.cs b/TestPlugin/MainMenuCommand.cs index 8c28e7fe1..99c1c0958 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.AssemblyTreeModel.AssemblyList.GetAssemblies()) { diff --git a/TestPlugin/TestPlugin.csproj b/TestPlugin/TestPlugin.csproj index c527fbcae..fc7d4b508 100644 --- a/TestPlugin/TestPlugin.csproj +++ b/TestPlugin/TestPlugin.csproj @@ -5,6 +5,7 @@ Test.Plugin true true + enable