From b844dc6f4a723f3ce426b5b397544dd1dbb7c57a Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 28 Jan 2021 17:47:56 +0800 Subject: [PATCH 01/11] Resolve NRT warnings in Compiler layer. --- .../CSharp/Portable/Compilation/CSharpCompilation.cs | 2 +- src/Compilers/Core/Portable/AssemblyUtilities.cs | 2 +- src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs | 2 +- .../Portable/InternalUtilities/IncrementalHashExtensions.cs | 2 +- .../Core/Portable/InternalUtilities/RoslynLazyInitializer.cs | 4 ++-- src/Compilers/Core/Portable/InternalUtilities/XmlUtilities.cs | 2 +- src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs | 2 +- .../Core/Portable/Syntax/SyntaxNodeExtensions_Tracking.cs | 2 +- src/Compilers/Core/Portable/TreeDumper.cs | 2 +- 9 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs b/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs index 6ef99f77133ab..9dc60b99d7325 100644 --- a/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs +++ b/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs @@ -753,7 +753,7 @@ internal override bool HasSubmissionResult() } // Is there a trailing expression? - var lastGlobalStatement = (GlobalStatementSyntax)root.Members.LastOrDefault(m => m.IsKind(SyntaxKind.GlobalStatement)); + var lastGlobalStatement = (GlobalStatementSyntax?)root.Members.LastOrDefault(m => m.IsKind(SyntaxKind.GlobalStatement)); if (lastGlobalStatement != null) { var statement = lastGlobalStatement.Statement; diff --git a/src/Compilers/Core/Portable/AssemblyUtilities.cs b/src/Compilers/Core/Portable/AssemblyUtilities.cs index 8cdc514410546..4d05b663571aa 100644 --- a/src/Compilers/Core/Portable/AssemblyUtilities.cs +++ b/src/Compilers/Core/Portable/AssemblyUtilities.cs @@ -105,7 +105,7 @@ public static ImmutableArray FindSatelliteAssemblies(string filePath) var builder = ImmutableArray.CreateBuilder(); - string? directory = Path.GetDirectoryName(filePath); + string directory = Path.GetDirectoryName(filePath)!; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; diff --git a/src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs b/src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs index 40c6121301440..a47aa0c004a1b 100644 --- a/src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs +++ b/src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs @@ -994,7 +994,7 @@ private void CompileAndEmit( var path = Path.Combine(Arguments.GeneratedFilesOutputDirectory!, tree.FilePath); if (Directory.Exists(Arguments.GeneratedFilesOutputDirectory)) { - Directory.CreateDirectory(Path.GetDirectoryName(path)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); } var fileStream = OpenFile(path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); diff --git a/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs b/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs index 2bba8fea4f88b..ee9d233136756 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs @@ -29,7 +29,7 @@ internal static void AppendData(this IncrementalHash hash, IEnumerable segment) { - hash.AppendData(segment.Array, segment.Offset, segment.Count); + hash.AppendData(segment.Array!, segment.Offset, segment.Count); } } } diff --git a/src/Compilers/Core/Portable/InternalUtilities/RoslynLazyInitializer.cs b/src/Compilers/Core/Portable/InternalUtilities/RoslynLazyInitializer.cs index 3004f30f8d1f8..4af2957860f1e 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/RoslynLazyInitializer.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/RoslynLazyInitializer.cs @@ -19,11 +19,11 @@ public static T EnsureInitialized([NotNull] ref T? target, Func valueFacto => LazyInitializer.EnsureInitialized(ref target!, valueFactory); /// - public static T EnsureInitialized([NotNull] ref T? target, ref bool initialized, [NotNull] ref object? syncLock) + public static T EnsureInitialized([NotNull] ref T? target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock) => LazyInitializer.EnsureInitialized(ref target!, ref initialized, ref syncLock); /// - public static T EnsureInitialized([NotNull] ref T? target, ref bool initialized, [NotNull] ref object? syncLock, Func valueFactory) + public static T EnsureInitialized([NotNull] ref T? target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock, Func valueFactory) => LazyInitializer.EnsureInitialized(ref target!, ref initialized, ref syncLock, valueFactory); } } diff --git a/src/Compilers/Core/Portable/InternalUtilities/XmlUtilities.cs b/src/Compilers/Core/Portable/InternalUtilities/XmlUtilities.cs index e527350be8e48..f940bdcb430d9 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/XmlUtilities.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/XmlUtilities.cs @@ -27,7 +27,7 @@ internal static TNode Copy(this TNode node, bool copyAttributeAnnotations { XContainer temp = new XElement("temp"); temp.Add(node); - copy = temp.LastNode; + copy = temp.LastNode!; temp.RemoveNodes(); } diff --git a/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs b/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs index 3c053b60089b8..d32ffcc523ef8 100644 --- a/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs +++ b/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs @@ -62,7 +62,7 @@ internal static int CalculateStrongNameSignatureSize(CommonPEModuleBuilder modul if (keySize == 0 && privateKey.HasValue) { - keySize = privateKey.Value.Modulus.Length; + keySize = privateKey.Value.Modulus?.Length ?? 0; } if (keySize == 0) diff --git a/src/Compilers/Core/Portable/Syntax/SyntaxNodeExtensions_Tracking.cs b/src/Compilers/Core/Portable/Syntax/SyntaxNodeExtensions_Tracking.cs index fef07023ea008..41d5b08ee93b6 100644 --- a/src/Compilers/Core/Portable/Syntax/SyntaxNodeExtensions_Tracking.cs +++ b/src/Compilers/Core/Portable/Syntax/SyntaxNodeExtensions_Tracking.cs @@ -89,7 +89,7 @@ public static IEnumerable GetCurrentNodes(this SyntaxNode root, TN /// /// The root of the subtree containing the current node corresponding to the original tracked node. /// The node instance originally tracked. - public static TNode GetCurrentNode(this SyntaxNode root, TNode node) + public static TNode? GetCurrentNode(this SyntaxNode root, TNode node) where TNode : SyntaxNode { return GetCurrentNodes(root, node).SingleOrDefault(); diff --git a/src/Compilers/Core/Portable/TreeDumper.cs b/src/Compilers/Core/Portable/TreeDumper.cs index e37e47d2a0190..6eec8da558f03 100644 --- a/src/Compilers/Core/Portable/TreeDumper.cs +++ b/src/Compilers/Core/Portable/TreeDumper.cs @@ -223,7 +223,7 @@ public TreeDumperNode(string text) : this(text, null, null) { } public object? Value { get; } public string Text { get; } public IEnumerable Children { get; } - public TreeDumperNode this[string child] + public TreeDumperNode? this[string child] { get { From bd953a37e03d03becbcd4b21002d9eec86b07262 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 29 Jan 2021 16:17:02 +0800 Subject: [PATCH 02/11] Resolve NRT warnings in workspace layer core. --- .../Core/Portable/Editing/SyntaxEditor.cs | 8 ++++++-- .../Finders/ParameterSymbolReferenceFinder.cs | 4 ++-- .../ConflictEngine/ConflictResolver.Session.cs | 2 +- .../Rename/ConflictEngine/ConflictResolver.cs | 2 +- .../Shared/Extensions/ISymbolExtensions.cs | 4 ++-- .../Storage/AbstractPersistentStorageService.cs | 2 +- .../SQLite/v2/SQLiteConnectionPoolService.cs | 2 ++ .../CSharp/Extensions/SyntaxTreeExtensions.cs | 4 ++-- .../Core/CodeStyle/CodeStyleOption2`1.cs | 4 ++-- .../Core/Extensions/SyntaxNodeExtensions.cs | 16 +++------------- .../Compiler/Core/Utilities/TaskExtensions.cs | 2 +- .../Compiler/Core/Utilities/TopologicalSorter.cs | 2 ++ .../ContextQuery/CSharpSyntaxContext.cs | 8 ++++---- 13 files changed, 29 insertions(+), 31 deletions(-) diff --git a/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs b/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs index 355414829b47a..b31d871818732 100644 --- a/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs +++ b/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs @@ -316,10 +316,10 @@ public ReplaceChange( public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); + Contract.ThrowIfNull(current, $"GetCurrentNode returned null with the following node: {this.Node}"); + var newNode = _modifier(current, generator); newNode = _editor.ApplyTrackingToNewNode(newNode); - - Contract.ThrowIfNull(current, $"GetCurrentNode returned null with the following node: {this.Node}"); return generator.ReplaceNode(root, current, newNode); } } @@ -342,6 +342,8 @@ public ReplaceWithCollectionChange( public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); + Contract.ThrowIfNull(current, $"GetCurrentNode returned null with the following node: {this.Node}"); + var newNodes = _modifier(current, generator).ToList(); for (var i = 0; i < newNodes.Count; i++) { @@ -373,6 +375,8 @@ public ReplaceChange( public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); + Contract.ThrowIfNull(current, $"GetCurrentNode returned null with the following node: {this.Node}"); + var newNode = _modifier(current, generator, _argument); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ParameterSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ParameterSymbolReferenceFinder.cs index ff20f519990f5..f3ecf8aa7d8a3 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ParameterSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ParameterSymbolReferenceFinder.cs @@ -136,7 +136,7 @@ private static async Task CascadeBetweenAnonymousFunctionParametersAsync( { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var lambdaNode = parameter.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); + var lambdaNode = parameter.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType != null) @@ -176,7 +176,7 @@ private static void CascadeBetweenAnonymousFunctionParameters( SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(parameter.ContainingSymbol, symbol.ContainingSymbol, syntaxFacts.IsCaseSensitive) && ParameterNamesMatch(syntaxFacts, (IMethodSymbol)parameter.ContainingSymbol, (IMethodSymbol)symbol.ContainingSymbol)) { - var lambdaNode = symbol.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); + var lambdaNode = symbol.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType2 = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType1.Equals(convertedType2)) diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs index af0f45213f2ab..aec85d6edf428 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs @@ -537,7 +537,7 @@ private async Task CheckForConflictAsync( foreach (var originalReference in conflictAnnotation.RenameDeclarationLocationReferences.Where(loc => loc.IsSourceLocation)) { var adjustedStartPosition = conflictResolution.GetAdjustedTokenStartingPosition(originalReference.TextSpan.Start, originalReference.DocumentId); - if (newLocations.Any(loc => loc.SourceSpan.Start == adjustedStartPosition)) + if (newLocations.Any(loc => loc!.SourceSpan.Start == adjustedStartPosition)) { hasConflict = false; break; diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs index 7400e7b1d8498..a4c7935760335 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.cs @@ -377,7 +377,7 @@ private static string GetString(ISymbol symbol) /// /// Gives the First Location for a given Symbol by ordering the locations using DocumentId first and Location starting position second /// - private static async Task GetSymbolLocationAsync(Solution solution, ISymbol symbol, CancellationToken cancellationToken) + private static async Task GetSymbolLocationAsync(Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var locations = symbol.Locations; diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/ISymbolExtensions.cs b/src/Workspaces/Core/Portable/Shared/Extensions/ISymbolExtensions.cs index c9aebbe7584a3..85ea4c5dc0d83 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/ISymbolExtensions.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/ISymbolExtensions.cs @@ -412,7 +412,7 @@ private static XNode[] RewriteMany(ISymbol symbol, HashSet? visitedSymb string xpathValue; if (string.IsNullOrEmpty(pathAttribute?.Value)) { - xpathValue = BuildXPathForElement(element.Parent); + xpathValue = BuildXPathForElement(element.Parent!); } else { @@ -571,7 +571,7 @@ private static TNode Copy(TNode node, bool copyAttributeAnnotations) { XContainer temp = new XElement("temp"); temp.Add(node); - copy = temp.LastNode; + copy = temp.LastNode!; temp.RemoveNodes(); } diff --git a/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs b/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs index 7f176b0b7600e..75129c70b8276 100644 --- a/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs @@ -175,7 +175,7 @@ await TryCreatePersistentStorageAsync(solutionKey, bulkLoadSnapshot, workingFold // this was not a normal exception that we expected during DB open. // Report this so we can try to address whatever is causing this. FatalError.ReportAndCatch(ex); - IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath), recursive: true)); + IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath)!, recursive: true)); } return null; diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPoolService.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPoolService.cs index e7127332da696..f297e3553a5f3 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPoolService.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPoolService.cs @@ -148,6 +148,8 @@ public void Dispose() private static void EnsureDirectory(string databaseFilePath) { var directory = Path.GetDirectoryName(databaseFilePath); + Contract.ThrowIfNull(directory); + if (Directory.Exists(directory)) { return; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTreeExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTreeExtensions.cs index 2a7ea210e20bc..b35949920d477 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTreeExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTreeExtensions.cs @@ -83,13 +83,13 @@ public static ISet GetPrecedingModifiers( return result; } - public static TypeDeclarationSyntax GetContainingTypeDeclaration( + public static TypeDeclarationSyntax? GetContainingTypeDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeDeclarations(position, cancellationToken).FirstOrDefault(); } - public static BaseTypeDeclarationSyntax GetContainingTypeOrEnumDeclaration( + public static BaseTypeDeclarationSyntax? GetContainingTypeOrEnumDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeOrEnumDeclarations(position, cancellationToken).FirstOrDefault(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs index 0f45e0fe0a664..d3cafb411b4ca 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -82,7 +82,7 @@ public XElement ToXElement() => new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat. new XAttribute(nameof(SerializationVersion), SerializationVersion), new XAttribute("Type", GetTypeNameForSerialization()), - new XAttribute(nameof(Value), GetValueForSerialization()), + new XAttribute(nameof(Value), GetValueForSerialization()!), new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); private object? GetValueForSerialization() @@ -133,7 +133,7 @@ public static CodeStyleOption2 FromXElement(XElement element) var typeAttribute = element.Attribute("Type"); var valueAttribute = element.Attribute(nameof(Value)); var severityAttribute = element.Attribute(nameof(DiagnosticSeverity)); - var version = (int)element.Attribute(nameof(SerializationVersion)); + var version = (int)element.Attribute(nameof(SerializationVersion))!; if (typeAttribute == null || valueAttribute == null || severityAttribute == null) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs index 9c3274e0e2f6a..1fc89dc81bbf7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs @@ -493,29 +493,19 @@ public static async Task ReplaceSyntaxAsync( { if (nodesToReplace.TryGetValue(span, out var currentNode)) { - var original = (SyntaxNode)retryAnnotations.GetAnnotations(currentNode).SingleOrDefault() ?? currentNode; + var original = (SyntaxNode?)retryAnnotations.GetAnnotations(currentNode).SingleOrDefault() ?? currentNode; var newNode = await computeReplacementNodeAsync!(original, currentNode, cancellationToken).ConfigureAwait(false); nodeReplacements[currentNode] = newNode; } else if (tokensToReplace.TryGetValue(span, out var currentToken)) { - var original = (SyntaxToken)retryAnnotations.GetAnnotations(currentToken).SingleOrDefault(); - if (original == default) - { - original = currentToken; - } - + var original = (SyntaxToken?)retryAnnotations.GetAnnotations(currentToken).SingleOrDefault() ?? currentToken; var newToken = await computeReplacementTokenAsync!(original, currentToken, cancellationToken).ConfigureAwait(false); tokenReplacements[currentToken] = newToken; } else if (triviaToReplace.TryGetValue(span, out var currentTrivia)) { - var original = (SyntaxTrivia)retryAnnotations.GetAnnotations(currentTrivia).SingleOrDefault(); - if (original == default) - { - original = currentTrivia; - } - + var original = (SyntaxTrivia?)retryAnnotations.GetAnnotations(currentTrivia).SingleOrDefault() ?? currentTrivia; var newTrivia = await computeReplacementTriviaAsync!(original, currentTrivia, cancellationToken).ConfigureAwait(false); triviaReplacements[currentTrivia] = newTrivia; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs index bc8a437bbe741..7de91358a394b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs @@ -33,7 +33,7 @@ internal static partial class TaskExtensions var threadParameter = Expression.Parameter(typeof(Thread), "thread"); var expression = Expression.Lambda>( - Expression.Call(threadParameter, property.GetMethod), + Expression.Call(threadParameter, property.GetMethod!), threadParameter); return expression.Compile(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TopologicalSorter.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TopologicalSorter.cs index 0033d0a1b249c..42f7c6fe89ad2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TopologicalSorter.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TopologicalSorter.cs @@ -24,6 +24,7 @@ public static IEnumerable TopologicalSort(this IEnumerable items, Func< } public static IEnumerable TopologicalSort(this IEnumerable items, Func> itemsBefore, Func> itemsAfter) + where T : notnull { var combinedItemsBefore = CreateCombinedItemsBefore(items, itemsBefore, itemsAfter); return TopologicalSort(items, combinedItemsBefore); @@ -47,6 +48,7 @@ private static void Visit( } private static Func> CreateCombinedItemsBefore(IEnumerable items, Func> itemsBefore, Func> itemsAfter) + where T : notnull { // create initial list var itemToItemsBefore = items.ToDictionary(item => item, item => diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/CSharpSyntaxContext.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/CSharpSyntaxContext.cs index 67a76849998b0..c2e776b00ed15 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/CSharpSyntaxContext.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/CSharpSyntaxContext.cs @@ -14,8 +14,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { internal sealed class CSharpSyntaxContext : SyntaxContext { - public readonly TypeDeclarationSyntax ContainingTypeDeclaration; - public readonly BaseTypeDeclarationSyntax ContainingTypeOrEnumDeclaration; + public readonly TypeDeclarationSyntax? ContainingTypeDeclaration; + public readonly BaseTypeDeclarationSyntax? ContainingTypeOrEnumDeclaration; public readonly bool IsInNonUserCode; @@ -58,8 +58,8 @@ private CSharpSyntaxContext( int position, SyntaxToken leftToken, SyntaxToken targetToken, - TypeDeclarationSyntax containingTypeDeclaration, - BaseTypeDeclarationSyntax containingTypeOrEnumDeclaration, + TypeDeclarationSyntax? containingTypeDeclaration, + BaseTypeDeclarationSyntax? containingTypeOrEnumDeclaration, bool isInNonUserCode, bool isPreProcessorDirectiveContext, bool isPreProcessorKeywordContext, From 3d29d6944b3b421f34b7bb2a3dcf3daafd71d3b6 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 29 Jan 2021 16:19:42 +0800 Subject: [PATCH 03/11] Resolve NRT warnings in Features. --- .../Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs | 4 +++- .../AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs | 2 +- .../SyncNamespace/AbstractChangeNamespaceService.cs | 2 +- .../AbstractTypeImportCompletionService.cs | 2 +- ...emberFromParameterCodeRefactoringProviderMemberCreation.cs | 2 +- .../Portable/MetadataAsSource/MetadataAsSourceFileService.cs | 2 +- .../ReplaceMethodWithPropertyCodeRefactoringProvider.cs | 2 +- 7 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs index f4d5c0bf08a94..ffa1a8be58784 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs @@ -229,7 +229,9 @@ where node.IsKind(SyntaxKind.IdentifierName) { if (ctor.Initializer != null) { - bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens); + bodyTokens = bodyTokens != null + ? ctor.Initializer.DescendantTokens().Concat(bodyTokens) + : ctor.Initializer.DescendantTokens(); } } diff --git a/src/Features/Core/Portable/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs index abe6ff26ad6fe..8b32808fe75a2 100644 --- a/src/Features/Core/Portable/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs @@ -175,7 +175,7 @@ protected override async Task FixAllAsync( var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var spanNodes = diagnostics.SelectAsArray( d => root.FindNode(d.Location.SourceSpan, getInnermostNodeForTie: true) - .GetAncestorsOrThis().FirstOrDefault()); + .GetAncestorsOrThis().First()); await editor.ApplyExpressionLevelSemanticEditsAsync( document, spanNodes, diff --git a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs index 74576bd7a7bd7..68a512f186446 100644 --- a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs @@ -744,7 +744,7 @@ await FixReferencesAsync(document, changeNamespaceService, addImportService, ref var fixedDocument = editor.GetChangedDocument(); root = await fixedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var result = (fixedDocument, containers.SelectAsArray(c => root.GetCurrentNode(c))); + var result = (fixedDocument, containers.SelectAsArray(c => root.GetCurrentNode(c)!)); return result; } diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs index 29eb315aade39..ea0955c11d75a 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs @@ -95,7 +95,7 @@ ImmutableArray GetItemsFromCacheResult(GetCacheResult cacheResul { var compilation = await referencedProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var assembly = SymbolFinder.FindSimilarSymbols(compilation.Assembly, currentCompilation, cancellationToken).SingleOrDefault(); - var metadataReference = currentCompilation.GetMetadataReference(assembly); + var metadataReference = assembly != null ? currentCompilation.GetMetadataReference(assembly) : null; if (HasGlobalAlias(metadataReference)) { diff --git a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs index 7e707faa74cc4..0bd6bf77a7d47 100644 --- a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs +++ b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs @@ -386,7 +386,7 @@ private async Task AddAllSymbolInitializationsAsync( IBlockOperation? currentBlockStatementOpt = null; if (blockStatementOpt != null) { - currentBlockStatementOpt = (IBlockOperation?)currentSemanticModel.GetOperation(currentRoot.GetCurrentNode(blockStatementOpt.Syntax), cancellationToken); + currentBlockStatementOpt = (IBlockOperation?)currentSemanticModel.GetOperation(currentRoot.GetCurrentNode(blockStatementOpt.Syntax)!, cancellationToken); if (currentBlockStatementOpt == null) continue; } diff --git a/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs b/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs index dc5e022cf6e27..fdf72c80dd21d 100644 --- a/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs +++ b/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs @@ -151,7 +151,7 @@ public async Task GetGeneratedFileAsync(Project project, I // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. - var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath); + var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath)!; while (!Directory.Exists(directoryToCreate)) { try diff --git a/src/Features/Core/Portable/ReplaceMethodWithProperty/ReplaceMethodWithPropertyCodeRefactoringProvider.cs b/src/Features/Core/Portable/ReplaceMethodWithProperty/ReplaceMethodWithPropertyCodeRefactoringProvider.cs index 4e89365bad6b8..c5c43c951fe26 100644 --- a/src/Features/Core/Portable/ReplaceMethodWithProperty/ReplaceMethodWithPropertyCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ReplaceMethodWithProperty/ReplaceMethodWithPropertyCodeRefactoringProvider.cs @@ -100,7 +100,7 @@ private static bool HasGetPrefix(string text) private static bool HasPrefix(string text, string prefix) => text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && text.Length > prefix.Length && !char.IsLower(text[prefix.Length]); - private static IMethodSymbol FindSetMethod(IMethodSymbol getMethod) + private static IMethodSymbol? FindSetMethod(IMethodSymbol getMethod) { var containingType = getMethod.ContainingType; var setMethodName = "Set" + getMethod.Name[GetPrefix.Length..]; From 00fb401c52e66a4cea0441fef654c7b6ebd1e008 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sun, 31 Jan 2021 01:55:01 +0800 Subject: [PATCH 04/11] Add assertion. --- src/Compilers/Core/Portable/AssemblyUtilities.cs | 3 ++- .../Portable/InternalUtilities/IncrementalHashExtensions.cs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Compilers/Core/Portable/AssemblyUtilities.cs b/src/Compilers/Core/Portable/AssemblyUtilities.cs index 4d05b663571aa..58ec6eea33c5b 100644 --- a/src/Compilers/Core/Portable/AssemblyUtilities.cs +++ b/src/Compilers/Core/Portable/AssemblyUtilities.cs @@ -105,7 +105,8 @@ public static ImmutableArray FindSatelliteAssemblies(string filePath) var builder = ImmutableArray.CreateBuilder(); - string directory = Path.GetDirectoryName(filePath)!; + string? directory = Path.GetDirectoryName(filePath); + RoslynDebug.AssertNotNull(directory); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; diff --git a/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs b/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs index ee9d233136756..f066afd5a295a 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs @@ -29,7 +29,8 @@ internal static void AppendData(this IncrementalHash hash, IEnumerable segment) { - hash.AppendData(segment.Array!, segment.Offset, segment.Count); + RoslynDebug.AssertNotNull(segment.Array); + hash.AppendData(segment.Array, segment.Offset, segment.Count); } } } From 4ecfa02ded6f0ae15fbf5f414c62516ea7696278 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 27 Feb 2021 02:49:25 +0800 Subject: [PATCH 05/11] Remove reflection of IsThreadPoolThread. --- .../Compiler/Core/Utilities/TaskExtensions.cs | 36 +------------------ 1 file changed, 1 insertion(+), 35 deletions(-) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs index 7de91358a394b..2b7e6ffe74b06 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs @@ -12,49 +12,15 @@ using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; -#if DEBUG -using System.Linq.Expressions; -#endif - namespace Roslyn.Utilities { [SuppressMessage("ApiDesign", "CA1068", Justification = "Matching TPL Signatures")] internal static partial class TaskExtensions { -#if DEBUG - private static readonly Lazy?> s_isThreadPoolThread = new( - () => - { - var property = typeof(Thread).GetTypeInfo().GetDeclaredProperty("IsThreadPoolThread"); - if (property is null) - { - return null; - } - - var threadParameter = Expression.Parameter(typeof(Thread), "thread"); - var expression = Expression.Lambda>( - Expression.Call(threadParameter, property.GetMethod!), - threadParameter); - - return expression.Compile(); - }); - - public static bool IsThreadPoolThread(Thread thread) - { - if (s_isThreadPoolThread.Value is null) - { - // This platform doesn't support IsThreadPoolThread - return false; - } - - return s_isThreadPoolThread.Value(thread); - } -#endif - public static T WaitAndGetResult(this Task task, CancellationToken cancellationToken) { #if DEBUG - if (IsThreadPoolThread(Thread.CurrentThread)) + if (Thread.CurrentThread.IsThreadPoolThread) { // If you hit this when running tests then your code is in error. WaitAndGetResult // should only be called from a foreground thread. There are a few ways you may From 910f40721104797692e1a8e48e9cfd3569fae047 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 27 Feb 2021 19:12:31 +0800 Subject: [PATCH 06/11] Fix PublicAPI annotation for GetCurrentNode. --- src/Compilers/Core/Portable/PublicAPI.Shipped.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Compilers/Core/Portable/PublicAPI.Shipped.txt b/src/Compilers/Core/Portable/PublicAPI.Shipped.txt index dbc535ca58321..69ec8f1d5b621 100644 --- a/src/Compilers/Core/Portable/PublicAPI.Shipped.txt +++ b/src/Compilers/Core/Portable/PublicAPI.Shipped.txt @@ -3327,7 +3327,7 @@ static Microsoft.CodeAnalysis.SyntaxList.implicit operator Microsoft.Code static Microsoft.CodeAnalysis.SyntaxList.implicit operator Microsoft.CodeAnalysis.SyntaxList(Microsoft.CodeAnalysis.SyntaxList nodes) -> Microsoft.CodeAnalysis.SyntaxList static Microsoft.CodeAnalysis.SyntaxList.operator !=(Microsoft.CodeAnalysis.SyntaxList left, Microsoft.CodeAnalysis.SyntaxList right) -> bool static Microsoft.CodeAnalysis.SyntaxList.operator ==(Microsoft.CodeAnalysis.SyntaxList left, Microsoft.CodeAnalysis.SyntaxList right) -> bool -static Microsoft.CodeAnalysis.SyntaxNodeExtensions.GetCurrentNode(this Microsoft.CodeAnalysis.SyntaxNode! root, TNode! node) -> TNode! +static Microsoft.CodeAnalysis.SyntaxNodeExtensions.GetCurrentNode(this Microsoft.CodeAnalysis.SyntaxNode! root, TNode! node) -> TNode? static Microsoft.CodeAnalysis.SyntaxNodeExtensions.GetCurrentNodes(this Microsoft.CodeAnalysis.SyntaxNode! root, System.Collections.Generic.IEnumerable! nodes) -> System.Collections.Generic.IEnumerable! static Microsoft.CodeAnalysis.SyntaxNodeExtensions.GetCurrentNodes(this Microsoft.CodeAnalysis.SyntaxNode! root, TNode! node) -> System.Collections.Generic.IEnumerable! static Microsoft.CodeAnalysis.SyntaxNodeExtensions.InsertNodesAfter(this TRoot! root, Microsoft.CodeAnalysis.SyntaxNode! nodeInList, System.Collections.Generic.IEnumerable! newNodes) -> TRoot! From d837ee9db1a6162ba96812a40620f8ae159a4467 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 27 Feb 2021 20:34:39 +0800 Subject: [PATCH 07/11] Address review comments. --- src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs | 2 +- .../Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs | 4 +--- .../Rename/ConflictEngine/ConflictResolver.Session.cs | 4 ++-- .../Compiler/Core/CodeStyle/CodeStyleOption2`1.cs | 2 +- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs b/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs index d32ffcc523ef8..57bc552a68878 100644 --- a/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs +++ b/src/Compilers/Core/Portable/PEWriter/SigningUtilities.cs @@ -62,7 +62,7 @@ internal static int CalculateStrongNameSignatureSize(CommonPEModuleBuilder modul if (keySize == 0 && privateKey.HasValue) { - keySize = privateKey.Value.Modulus?.Length ?? 0; + keySize = privateKey.Value.Modulus!.Length; } if (keySize == 0) diff --git a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs index ace16863c1e1a..5915540821aa9 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs @@ -231,9 +231,7 @@ where node.IsKind(SyntaxKind.IdentifierName) { if (ctor.Initializer != null) { - bodyTokens = bodyTokens != null - ? ctor.Initializer.DescendantTokens().Concat(bodyTokens) - : ctor.Initializer.DescendantTokens(); + bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty()); } } diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs index aec85d6edf428..854537adf0dd8 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs @@ -533,11 +533,11 @@ private async Task CheckForConflictAsync( hasConflict = true; var newLocationTasks = newReferencedSymbols.Select(async symbol => await GetSymbolLocationAsync(solution, symbol, _cancellationToken).ConfigureAwait(false)); - var newLocations = (await Task.WhenAll(newLocationTasks).ConfigureAwait(false)).Where(loc => loc != null && loc.IsInSource); + var newLocations = (await Task.WhenAll(newLocationTasks).ConfigureAwait(false)).WhereNotNull().Where(loc => loc.IsInSource); foreach (var originalReference in conflictAnnotation.RenameDeclarationLocationReferences.Where(loc => loc.IsSourceLocation)) { var adjustedStartPosition = conflictResolution.GetAdjustedTokenStartingPosition(originalReference.TextSpan.Start, originalReference.DocumentId); - if (newLocations.Any(loc => loc!.SourceSpan.Start == adjustedStartPosition)) + if (newLocations.Any(loc => loc.SourceSpan.Start == adjustedStartPosition)) { hasConflict = false; break; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs index d3cafb411b4ca..608b65ef9d671 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -133,7 +133,7 @@ public static CodeStyleOption2 FromXElement(XElement element) var typeAttribute = element.Attribute("Type"); var valueAttribute = element.Attribute(nameof(Value)); var severityAttribute = element.Attribute(nameof(DiagnosticSeverity)); - var version = (int)element.Attribute(nameof(SerializationVersion))!; + var version = (int?)element.Attribute(nameof(SerializationVersion)); if (typeAttribute == null || valueAttribute == null || severityAttribute == null) { From a0496e9adc52118cffb99eb2e210ca43ef7dd49d Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 4 Mar 2021 20:40:28 +0800 Subject: [PATCH 08/11] Add notnull for CodeStyleOption. --- src/Workspaces/Core/Portable/Options/OptionsExtensions.cs | 2 ++ .../Compiler/Core/CodeStyle/CodeStyleOption2`1.cs | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs b/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs index 2d565ab4ed494..5768f997de00f 100644 --- a/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs +++ b/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs @@ -10,6 +10,7 @@ namespace Microsoft.CodeAnalysis.Options internal static class OptionsExtensions { public static Option> ToPublicOption(this Option2> option) + where T : notnull { RoslynDebug.Assert(option != null); @@ -20,6 +21,7 @@ public static Option> ToPublicOption(this Option2> ToPublicOption(this PerLanguageOption2> option) + where T : notnull { RoslynDebug.Assert(option != null); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs index 608b65ef9d671..7986b566f5a87 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -38,6 +38,7 @@ internal interface ICodeStyleOption : IObjectWritable /// then those values will write back as false/true. /// internal partial class CodeStyleOption2 : ICodeStyleOption, IEquatable?> + where T : notnull { static CodeStyleOption2() { @@ -82,10 +83,10 @@ public XElement ToXElement() => new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat. new XAttribute(nameof(SerializationVersion), SerializationVersion), new XAttribute("Type", GetTypeNameForSerialization()), - new XAttribute(nameof(Value), GetValueForSerialization()!), + new XAttribute(nameof(Value), GetValueForSerialization()), new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); - private object? GetValueForSerialization() + private object GetValueForSerialization() { if (typeof(T) == typeof(string)) { From 2752737389d9b1403984964c8a73cd1f79579998 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 4 Mar 2021 20:56:39 +0800 Subject: [PATCH 09/11] Throw instead of supress. --- .../SyncNamespace/AbstractChangeNamespaceService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs index 68a512f186446..09be6f5434dad 100644 --- a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs @@ -744,7 +744,8 @@ await FixReferencesAsync(document, changeNamespaceService, addImportService, ref var fixedDocument = editor.GetChangedDocument(); root = await fixedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var result = (fixedDocument, containers.SelectAsArray(c => root.GetCurrentNode(c)!)); + var result = (fixedDocument, containers.SelectAsArray(c => root.GetCurrentNode(c) + ?? throw new InvalidOperationException("Can't get SyntaxNode from GetCurrentNode."))); return result; } From 6a48567a47d0661b9fbe3d99c0a9c7e228c46034 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 4 Mar 2021 22:22:20 +0800 Subject: [PATCH 10/11] Revert "Add notnull for CodeStyleOption." This reverts commit a0496e9adc52118cffb99eb2e210ca43ef7dd49d. --- src/Workspaces/Core/Portable/Options/OptionsExtensions.cs | 2 -- .../Compiler/Core/CodeStyle/CodeStyleOption2`1.cs | 5 ++--- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs b/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs index 5768f997de00f..2d565ab4ed494 100644 --- a/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs +++ b/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs @@ -10,7 +10,6 @@ namespace Microsoft.CodeAnalysis.Options internal static class OptionsExtensions { public static Option> ToPublicOption(this Option2> option) - where T : notnull { RoslynDebug.Assert(option != null); @@ -21,7 +20,6 @@ public static Option> ToPublicOption(this Option2> ToPublicOption(this PerLanguageOption2> option) - where T : notnull { RoslynDebug.Assert(option != null); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs index 7986b566f5a87..608b65ef9d671 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -38,7 +38,6 @@ internal interface ICodeStyleOption : IObjectWritable /// then those values will write back as false/true. /// internal partial class CodeStyleOption2 : ICodeStyleOption, IEquatable?> - where T : notnull { static CodeStyleOption2() { @@ -83,10 +82,10 @@ public XElement ToXElement() => new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat. new XAttribute(nameof(SerializationVersion), SerializationVersion), new XAttribute("Type", GetTypeNameForSerialization()), - new XAttribute(nameof(Value), GetValueForSerialization()), + new XAttribute(nameof(Value), GetValueForSerialization()!), new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); - private object GetValueForSerialization() + private object? GetValueForSerialization() { if (typeof(T) == typeof(string)) { From cf722859b83b04d5c7dbfd9f57cdabe64cc02551 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 4 Mar 2021 22:25:49 +0800 Subject: [PATCH 11/11] Make GetValueForSerialization non-nullable. --- .../Compiler/Core/CodeStyle/CodeStyleOption2`1.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs index 608b65ef9d671..ad0da9a5af9ad 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -82,18 +82,18 @@ public XElement ToXElement() => new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat. new XAttribute(nameof(SerializationVersion), SerializationVersion), new XAttribute("Type", GetTypeNameForSerialization()), - new XAttribute(nameof(Value), GetValueForSerialization()!), + new XAttribute(nameof(Value), GetValueForSerialization()), new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); - private object? GetValueForSerialization() + private object GetValueForSerialization() { if (typeof(T) == typeof(string)) { - return Value; + return Value!; } else if (typeof(T) == typeof(bool)) { - return Value; + return Value!; } else if (IsZeroOrOneValueOfEnum()) {