diff --git a/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs b/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs index fcc4ab9b9047f..86d05bdded3a9 100644 --- a/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs +++ b/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs @@ -757,7 +757,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..58ec6eea33c5b 100644 --- a/src/Compilers/Core/Portable/AssemblyUtilities.cs +++ b/src/Compilers/Core/Portable/AssemblyUtilities.cs @@ -106,6 +106,7 @@ public static ImmutableArray FindSatelliteAssemblies(string filePath) var builder = ImmutableArray.CreateBuilder(); 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/CommandLine/CommonCompiler.cs b/src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs index 364ec2aefc490..b38a019d339e6 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..f066afd5a295a 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs @@ -29,6 +29,7 @@ internal static void AppendData(this IncrementalHash hash, IEnumerable segment) { + RoslynDebug.AssertNotNull(segment.Array); 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..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; + keySize = privateKey.Value.Modulus!.Length; } if (keySize == 0) 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! 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 { diff --git a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs index 4d37f47d11f81..5915540821aa9 100644 --- a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs +++ b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs @@ -231,7 +231,7 @@ where node.IsKind(SyntaxKind.IdentifierName) { if (ctor.Initializer != null) { - bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens); + bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty()); } } 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..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; } 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..]; 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..854537adf0dd8 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs @@ -533,7 +533,7 @@ 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); 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 21743014759f0..75d04b04128e8 100644 --- a/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs @@ -172,7 +172,7 @@ await TryCreatePersistentStorageAsync(solutionKey, workingFolderPath).ConfigureA // 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 322c33a6ffc84..9b8b9f8084646 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPoolService.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPoolService.cs @@ -147,6 +147,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..ad0da9a5af9ad 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -85,15 +85,15 @@ public XElement ToXElement() => 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()) { @@ -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..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 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,