diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/EditSessionTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/EditSessionTests.cs index 63de84147c43c2148440eadf4ff9d7a194e6e7ea..ef20d4027b8d9823659ed98b5c69ad561fc02d18 100644 --- a/src/EditorFeatures/CSharpTest/EditAndContinue/EditSessionTests.cs +++ b/src/EditorFeatures/CSharpTest/EditAndContinue/EditSessionTests.cs @@ -98,35 +98,34 @@ IEnumerable Enumerate() var exportProvider = exportProviderFactory.CreateExportProvider(); - using (var workspace = TestWorkspace.CreateCSharp( + using var workspace = TestWorkspace.CreateCSharp( ActiveStatementsDescription.ClearTags(markedSource), - exportProvider: exportProvider)) + exportProvider: exportProvider); + + var baseSolution = workspace.CurrentSolution; + if (adjustSolution != null) { - var baseSolution = workspace.CurrentSolution; - if (adjustSolution != null) - { - baseSolution = adjustSolution(baseSolution); - } + baseSolution = adjustSolution(baseSolution); + } - var docsIds = from p in baseSolution.Projects - from d in p.DocumentIds - select d; + var docsIds = from p in baseSolution.Projects + from d in p.DocumentIds + select d; - var debuggingSession = new DebuggingSession(baseSolution); - var activeStatementProvider = new TestActiveStatementProvider(activeStatements); + var debuggingSession = new DebuggingSession(baseSolution); + var activeStatementProvider = new TestActiveStatementProvider(activeStatements); - var editSession = new EditSession( - baseSolution, - debuggingSession, - activeStatementProvider, - ImmutableDictionary.Empty, - nonRemappableRegions ?? ImmutableDictionary>.Empty, - stoppedAtException: false); + var editSession = new EditSession( + baseSolution, + debuggingSession, + activeStatementProvider, + ImmutableDictionary.Empty, + nonRemappableRegions ?? ImmutableDictionary>.Empty, + stoppedAtException: false); - return (await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false), - await editSession.BaseActiveExceptionRegions.GetValueAsync(CancellationToken.None).ConfigureAwait(false), - docsIds.ToImmutableArray()); - } + return (await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false), + await editSession.BaseActiveExceptionRegions.GetValueAsync(CancellationToken.None).ConfigureAwait(false), + docsIds.ToImmutableArray()); } private static string Delete(string src, string marker) diff --git a/src/EditorFeatures/Core.Wpf/InlineRename/InlineRenameSession.OpenTextBufferManager.cs b/src/EditorFeatures/Core.Wpf/InlineRename/InlineRenameSession.OpenTextBufferManager.cs index 7769585dcc04472ee50ce40f168c3c7885d4e90e..6a9c21a8ccac413e66dd832697308d974e395a15 100644 --- a/src/EditorFeatures/Core.Wpf/InlineRename/InlineRenameSession.OpenTextBufferManager.cs +++ b/src/EditorFeatures/Core.Wpf/InlineRename/InlineRenameSession.OpenTextBufferManager.cs @@ -351,15 +351,14 @@ internal void ApplyConflictResolutionEdits(IInlineRenameReplacementInfo conflict _session.UndoManager.CreateConflictResolutionUndoTransaction(_subjectBuffer, () => { - using (var edit = _subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, s_propagateSpansEditTag)) - { - foreach (var change in changes) - { - edit.Replace(change.Span.Start, change.Span.Length, change.NewText); - } + using var edit = _subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, s_propagateSpansEditTag); - edit.ApplyAndLogExceptions(); + foreach (var change in changes) + { + edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } + + edit.ApplyAndLogExceptions(); }); // 2. We want to update referenceSpanToLinkedRenameSpanMap where spans were affected by conflict resolution. diff --git a/src/EditorFeatures/Core.Wpf/InlineRename/UndoManagerServiceFactory.cs b/src/EditorFeatures/Core.Wpf/InlineRename/UndoManagerServiceFactory.cs index 9957630477690466f4b1008fc5b96cbf59464c07..8d60b638e083950c745d556ae2f585b960aff170 100644 --- a/src/EditorFeatures/Core.Wpf/InlineRename/UndoManagerServiceFactory.cs +++ b/src/EditorFeatures/Core.Wpf/InlineRename/UndoManagerServiceFactory.cs @@ -55,12 +55,11 @@ public void CreateStartRenameUndoTransaction(ITextBuffer subjectBuffer) var undoHistory = this.UndoManagers[subjectBuffer].TextUndoHistory; // Create an undo transaction to mark the starting point of the rename session in this buffer - using (var undoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Start_Rename)) - { - undoTransaction.Complete(); - this.UndoManagers[subjectBuffer].StartRenameSessionUndoTransaction = undoTransaction; - this.UndoManagers[subjectBuffer].ConflictResolutionUndoTransaction = null; - } + using var undoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Start_Rename); + + undoTransaction.Complete(); + this.UndoManagers[subjectBuffer].StartRenameSessionUndoTransaction = undoTransaction; + this.UndoManagers[subjectBuffer].ConflictResolutionUndoTransaction = null; } public void CreateConflictResolutionUndoTransaction(ITextBuffer subjectBuffer, Action applyEdit) @@ -123,10 +122,8 @@ public void ApplyCurrentState(ITextBuffer subjectBuffer, object propagateSpansEd var undoHistory = this.UndoManagers[subjectBuffer].TextUndoHistory; foreach (var state in this.RedoStack.Reverse()) { - using (var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(state.ReplacementText))) - { - transaction.Complete(); - } + using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(state.ReplacementText)); + transaction.Complete(); } if (this.RedoStack.Any()) diff --git a/src/EditorFeatures/Core.Wpf/SymbolSearch/SymbolSearchUpdateEngine.Update.cs b/src/EditorFeatures/Core.Wpf/SymbolSearch/SymbolSearchUpdateEngine.Update.cs index 84f8817a5691fe493078e1d81146578e080d6539..9eb1f464a0bdf44c716e5c5a0d71b830dfc0e757 100644 --- a/src/EditorFeatures/Core.Wpf/SymbolSearch/SymbolSearchUpdateEngine.Update.cs +++ b/src/EditorFeatures/Core.Wpf/SymbolSearch/SymbolSearchUpdateEngine.Update.cs @@ -560,33 +560,32 @@ private async Task TryDownloadFileAsync(IRemoteControlClient client) // "ReturnsNull": Only return a file if we have it locally *and* it's not older than our polling time (1 day). - using (var stream = await client.ReadFileAsync(BehaviorOnStale.ReturnNull).ConfigureAwait(false)) + using var stream = await client.ReadFileAsync(BehaviorOnStale.ReturnNull).ConfigureAwait(false); + + if (stream == null) { - if (stream == null) - { - await _service.LogInfoAsync("Read file completed. Client returned no data").ConfigureAwait(false); - return null; - } + await _service.LogInfoAsync("Read file completed. Client returned no data").ConfigureAwait(false); + return null; + } - await _service.LogInfoAsync("Read file completed. Client returned data").ConfigureAwait(false); - await _service.LogInfoAsync("Converting data to XElement").ConfigureAwait(false); + await _service.LogInfoAsync("Read file completed. Client returned data").ConfigureAwait(false); + await _service.LogInfoAsync("Converting data to XElement").ConfigureAwait(false); - // We're reading in our own XML file, but even so, use conservative settings - // just to be on the safe side. First, disallow DTDs entirely (we will never - // have one ourself). And also, prevent any external resolution of files when - // processing the XML. - var settings = new XmlReaderSettings - { - DtdProcessing = DtdProcessing.Prohibit, - XmlResolver = null - }; + // We're reading in our own XML file, but even so, use conservative settings + // just to be on the safe side. First, disallow DTDs entirely (we will never + // have one ourself). And also, prevent any external resolution of files when + // processing the XML. + var settings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null + }; - using var reader = XmlReader.Create(stream, settings); + using var reader = XmlReader.Create(stream, settings); - var result = XElement.Load(reader); - await _service.LogInfoAsync("Converting data to XElement completed").ConfigureAwait(false); - return result; - } + var result = XElement.Load(reader); + await _service.LogInfoAsync("Converting data to XElement completed").ConfigureAwait(false); + return result; } private async Task RepeatIOAsync(Func action) @@ -656,19 +655,18 @@ private async Task ConvertContentAttributeAsync(XAttribute contentsAttri var text = contentsAttribute.Value; var compressedBytes = Convert.FromBase64String(text); - using (var outStream = new MemoryStream()) + using var outStream = new MemoryStream(); + + using (var inStream = new MemoryStream(compressedBytes)) + using (var deflateStream = new DeflateStream(inStream, CompressionMode.Decompress)) { - using (var inStream = new MemoryStream(compressedBytes)) - using (var deflateStream = new DeflateStream(inStream, CompressionMode.Decompress)) - { - await deflateStream.CopyToAsync(outStream).ConfigureAwait(false); - } + await deflateStream.CopyToAsync(outStream).ConfigureAwait(false); + } - var bytes = outStream.ToArray(); + var bytes = outStream.ToArray(); - await _service.LogInfoAsync($"Parsing complete. bytes.length={bytes.Length}").ConfigureAwait(false); - return bytes; - } + await _service.LogInfoAsync($"Parsing complete. bytes.length={bytes.Length}").ConfigureAwait(false); + return bytes; } } } diff --git a/src/EditorFeatures/Core/Implementation/AutomaticCompletion/BraceCompletionSessionProvider.BraceCompletionSession.cs b/src/EditorFeatures/Core/Implementation/AutomaticCompletion/BraceCompletionSessionProvider.BraceCompletionSession.cs index 70fecf49caa060adba06bcf05ba92db07fc9407f..dfbb61bc230f58318fc294ce9c049e6393058e2e 100644 --- a/src/EditorFeatures/Core/Implementation/AutomaticCompletion/BraceCompletionSessionProvider.BraceCompletionSession.cs +++ b/src/EditorFeatures/Core/Implementation/AutomaticCompletion/BraceCompletionSessionProvider.BraceCompletionSession.cs @@ -99,43 +99,42 @@ private void Start(CancellationToken cancellationToken) return; } - using (var undo = CreateUndoTransaction()) + using var undo = CreateUndoTransaction(); + + // insert the closing brace + using (var edit = SubjectBuffer.CreateEdit()) { - // insert the closing brace - using (var edit = SubjectBuffer.CreateEdit()) - { - edit.Insert(closingSnapshotPoint, ClosingBrace.ToString()); + edit.Insert(closingSnapshotPoint, ClosingBrace.ToString()); - if (edit.HasFailedChanges) - { - Debug.Fail("Unable to insert closing brace"); + if (edit.HasFailedChanges) + { + Debug.Fail("Unable to insert closing brace"); - // exit without setting the closing point which will take us off the stack - edit.Cancel(); - undo.Cancel(); - return; - } - else - { - snapshot = edit.ApplyAndLogExceptions(); - } + // exit without setting the closing point which will take us off the stack + edit.Cancel(); + undo.Cancel(); + return; + } + else + { + snapshot = edit.ApplyAndLogExceptions(); } + } - var beforePoint = beforeTrackingPoint.GetPoint(TextView.TextSnapshot); + var beforePoint = beforeTrackingPoint.GetPoint(TextView.TextSnapshot); - // switch from positive to negative tracking so it stays against the closing brace - ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(ClosingPoint.GetPoint(snapshot), PointTrackingMode.Negative); + // switch from positive to negative tracking so it stays against the closing brace + ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(ClosingPoint.GetPoint(snapshot), PointTrackingMode.Negative); - Debug.Assert(ClosingPoint.GetPoint(snapshot).Position > 0 && (new SnapshotSpan(ClosingPoint.GetPoint(snapshot).Subtract(1), 1)) - .GetText().Equals(ClosingBrace.ToString()), "The closing point does not match the closing brace character"); + Debug.Assert(ClosingPoint.GetPoint(snapshot).Position > 0 && (new SnapshotSpan(ClosingPoint.GetPoint(snapshot).Subtract(1), 1)) + .GetText().Equals(ClosingBrace.ToString()), "The closing point does not match the closing brace character"); - // move the caret back between the braces - TextView.Caret.MoveTo(beforePoint); + // move the caret back between the braces + TextView.Caret.MoveTo(beforePoint); - _session.AfterStart(this, cancellationToken); + _session.AfterStart(this, cancellationToken); - undo.Complete(); - } + undo.Complete(); } public void PreBackspace(out bool handledCommand) diff --git a/src/Features/CSharp/Portable/CodeFixes/Nullable/CSharpDeclareAsNullableCodeFixProvider.cs b/src/Features/CSharp/Portable/CodeFixes/Nullable/CSharpDeclareAsNullableCodeFixProvider.cs index a931ed1c984e503d26d316d51bdf58fbb7eaecd7..bb6dc4ba2b8fbda31000c909bc5e9368b3a48c6b 100644 --- a/src/Features/CSharp/Portable/CodeFixes/Nullable/CSharpDeclareAsNullableCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/CodeFixes/Nullable/CSharpDeclareAsNullableCodeFixProvider.cs @@ -97,28 +97,27 @@ private static TypeSyntax TryGetDeclarationTypeToFix(SyntaxNode node) var onYield = node.IsParentKind(SyntaxKind.YieldReturnStatement); - switch (containingMember) + return containingMember switch { - case MethodDeclarationSyntax method: + MethodDeclarationSyntax method => // string M() { return null; } // async Task M() { return null; } // IEnumerable M() { yield return null; } - return TryGetReturnType(method.ReturnType, method.Modifiers, onYield); + TryGetReturnType(method.ReturnType, method.Modifiers, onYield), - case LocalFunctionStatementSyntax localFunction: + LocalFunctionStatementSyntax localFunction => // string local() { return null; } // async Task local() { return null; } // IEnumerable local() { yield return null; } - return TryGetReturnType(localFunction.ReturnType, localFunction.Modifiers, onYield); + TryGetReturnType(localFunction.ReturnType, localFunction.Modifiers, onYield), - case PropertyDeclarationSyntax property: + PropertyDeclarationSyntax property => // string x { get { return null; } } // IEnumerable Property { get { yield return null; } } - return TryGetReturnType(property.Type, modifiers: default, onYield); + TryGetReturnType(property.Type, modifiers: default, onYield), - default: - return null; - } + _ => null, + }; } // string x = null; diff --git a/src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelService.cs b/src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelService.cs index 9881273f190485362fd486942c34c1ba6b9cf2d6..5ee155d187255ab15e193a56781cf722545aaa70 100644 --- a/src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelService.cs +++ b/src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelService.cs @@ -1028,27 +1028,19 @@ public override string GetExternalSymbolFullName(ISymbol symbol) } public override EnvDTE.vsCMAccess GetAccess(ISymbol symbol) - { - switch (symbol.DeclaredAccessibility) - { - case Accessibility.Public: - return EnvDTE.vsCMAccess.vsCMAccessPublic; - case Accessibility.Private: - return EnvDTE.vsCMAccess.vsCMAccessPrivate; - case Accessibility.Internal: - return EnvDTE.vsCMAccess.vsCMAccessProject; - case Accessibility.Protected: - return EnvDTE.vsCMAccess.vsCMAccessProtected; - case Accessibility.ProtectedOrInternal: - return EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected; - case Accessibility.ProtectedAndInternal: + => symbol.DeclaredAccessibility switch + { + Accessibility.Public => EnvDTE.vsCMAccess.vsCMAccessPublic, + Accessibility.Private => EnvDTE.vsCMAccess.vsCMAccessPrivate, + Accessibility.Internal => EnvDTE.vsCMAccess.vsCMAccessProject, + Accessibility.Protected => EnvDTE.vsCMAccess.vsCMAccessProtected, + Accessibility.ProtectedOrInternal => EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected, + Accessibility.ProtectedAndInternal => // there is no appropriate mapping for private protected in EnvDTE.vsCMAccess // See https://github.com/dotnet/roslyn/issues/22406 - return EnvDTE.vsCMAccess.vsCMAccessProtected; - default: - throw Exceptions.ThrowEFail(); - } - } + EnvDTE.vsCMAccess.vsCMAccessProtected, + _ => throw Exceptions.ThrowEFail(), + }; public override EnvDTE.vsCMAccess GetAccess(SyntaxNode node) { diff --git a/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs b/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs index 08df06d909b35b4c32216c7eada9ce48ed8395e5..baa16c8b9e16e9766e8b028fc98f22810085ed36 100644 --- a/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs +++ b/src/VisualStudio/CSharp/Test/Debugging/NameResolverTests.cs @@ -15,13 +15,12 @@ public class NameResolverTests { private async Task TestAsync(string text, string searchText, params string[] expectedNames) { - using (var workspace = TestWorkspace.CreateCSharp(text)) - { - var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText); - var results = await nameResolver.DoAsync(CancellationToken.None); + using var workspace = TestWorkspace.CreateCSharp(text); - Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt)); - } + var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText); + var results = await nameResolver.DoAsync(CancellationToken.None); + + Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] diff --git a/src/VisualStudio/CSharp/Test/ProjectSystemShim/LegacyProject/OutputPathTests.cs b/src/VisualStudio/CSharp/Test/ProjectSystemShim/LegacyProject/OutputPathTests.cs index eefcca2befddc7fc1bb5f402c761c6850d613b3e..24e9e92b48e78c101fee6eeddc84e848c9dfc73a 100644 --- a/src/VisualStudio/CSharp/Test/ProjectSystemShim/LegacyProject/OutputPathTests.cs +++ b/src/VisualStudio/CSharp/Test/ProjectSystemShim/LegacyProject/OutputPathTests.cs @@ -18,20 +18,19 @@ public class OutputPathTests [InlineData(null)] public void RefPathPassedToWorkspace(string expectedRefPath) { - using (var environment = new TestEnvironment()) - { - var hierarchyWithRefPath = - environment.CreateHierarchy( - "WithRefPath", - @"Z:\WithRefPath.dll", - expectedRefPath, - "CSharp"); + using var environment = new TestEnvironment(); - var project = CSharpHelpers.CreateCSharpProject(environment, "WithRefPath", hierarchyWithRefPath); - var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); + var hierarchyWithRefPath = + environment.CreateHierarchy( + "WithRefPath", + @"Z:\WithRefPath.dll", + expectedRefPath, + "CSharp"); - Assert.Equal(expectedRefPath, workspaceProject.OutputRefFilePath); - } + var project = CSharpHelpers.CreateCSharpProject(environment, "WithRefPath", hierarchyWithRefPath); + var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); + + Assert.Equal(expectedRefPath, workspaceProject.OutputRefFilePath); } } } diff --git a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs index 7db6381559873abfd1a2552d8a463641217323e1..f71bdbe42735583b636f5e61c398836022b9e5f2 100644 --- a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs +++ b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs @@ -346,35 +346,34 @@ private IEnumerable GetSubTextChanges(SourceText originalText, TextC SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List changes) { // these are expensive. but hopefully we don't hit this as much except the boundary cases. - using (var leftPool = SharedPools.Default>().GetPooledObject()) - using (var rightPool = SharedPools.Default>().GetPooledObject()) - { - var spansInLeftText = leftPool.Object; - var spansInRightText = rightPool.Object; + using var leftPool = SharedPools.Default>().GetPooledObject(); + using var rightPool = SharedPools.Default>().GetPooledObject(); + + var spansInLeftText = leftPool.Object; + var spansInRightText = rightPool.Object; - if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText)) + if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText)) + { + for (var i = 0; i < spansInLeftText.Count; i++) { - for (var i = 0; i < spansInLeftText.Count; i++) + var spanInLeftText = spansInLeftText[i]; + var spanInRightText = spansInRightText[i]; + if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty) { - var spanInLeftText = spansInLeftText[i]; - var spanInRightText = spansInRightText[i]; - if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty) - { - continue; - } - - var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); - if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out var textChange)) - { - changes.Add(textChange); - } + continue; } - return true; + var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); + if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out var textChange)) + { + changes.Add(textChange); + } } - return false; + return true; } + + return false; } private IEnumerable GetSubTextChanges( @@ -705,37 +704,36 @@ public IEnumerable GetEditorVisibleSpans() IList visibleSpansInOriginal, out IEnumerable affectedVisibleSpansInNew) { - using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) - { - var affectedSpans = SharedPools.Default>().AllocateAndClear(); - affectedVisibleSpansInNew = affectedSpans; + using var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null); - var currentVisibleSpanIndex = 0; - foreach (var change in changes) - { - // Find the next visible span that either overlaps or intersects with - while (currentVisibleSpanIndex < visibleSpansInOriginal.Count && - visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start) - { - currentVisibleSpanIndex++; - } + var affectedSpans = SharedPools.Default>().AllocateAndClear(); + affectedVisibleSpansInNew = affectedSpans; - // no more place to apply text changes - if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count) - { - break; - } + var currentVisibleSpanIndex = 0; + foreach (var change in changes) + { + // Find the next visible span that either overlaps or intersects with + while (currentVisibleSpanIndex < visibleSpansInOriginal.Count && + visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start) + { + currentVisibleSpanIndex++; + } - var newText = change.NewText; - var span = change.Span.ToSpan(); + // no more place to apply text changes + if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count) + { + break; + } - edit.Replace(span, newText); + var newText = change.NewText; + var span = change.Span.ToSpan(); - affectedSpans.Add(currentVisibleSpanIndex); - } + edit.Replace(span, newText); - edit.ApplyAndLogExceptions(); + affectedSpans.Add(currentVisibleSpanIndex); } + + edit.ApplyAndLogExceptions(); } private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable visibleSpanIndex) @@ -788,29 +786,28 @@ private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable { var root = document.GetSyntaxRootSynchronously(CancellationToken.None); - using (var rulePool = SharedPools.Default>().GetPooledObject()) - using (var spanPool = SharedPools.Default>().GetPooledObject()) - { - var venusFormattingRules = rulePool.Object; - var visibleSpans = spanPool.Object; + using var rulePool = SharedPools.Default>().GetPooledObject(); + using var spanPool = SharedPools.Default>().GetPooledObject(); - venusFormattingRules.Add(baseIndentationRule); - venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); + var venusFormattingRules = rulePool.Object; + var visibleSpans = spanPool.Object; - var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document)); + venusFormattingRules.Add(baseIndentationRule); + venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); - var workspace = document.Project.Solution.Workspace; - var changes = Formatter.GetFormattedTextChanges( - root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) }, - workspace, options, formattingRules, CancellationToken.None); + var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document)); - visibleSpans.Add(visibleSpan); - var newChanges = FilterTextChanges(document.GetTextSynchronously(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span)); + var workspace = document.Project.Solution.Workspace; + var changes = Formatter.GetFormattedTextChanges( + root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) }, + workspace, options, formattingRules, CancellationToken.None); - foreach (var change in newChanges) - { - edit.Replace(change.Span.ToSpan(), change.NewText); - } + visibleSpans.Add(visibleSpan); + var newChanges = FilterTextChanges(document.GetTextSynchronously(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span)); + + foreach (var change in newChanges) + { + edit.Replace(change.Span.ToSpan(), change.NewText); } } diff --git a/src/VisualStudio/Core/Def/Implementation/Watson/WatsonExtensions.cs b/src/VisualStudio/Core/Def/Implementation/Watson/WatsonExtensions.cs index 3d71e233cafae935e807257e43cdbd40fda0b326..4bf4647b7597f89adbbe33bfdfbef6283ac2e69f 100644 --- a/src/VisualStudio/Core/Def/Implementation/Watson/WatsonExtensions.cs +++ b/src/VisualStudio/Core/Def/Implementation/Watson/WatsonExtensions.cs @@ -81,18 +81,14 @@ public static string CalculateHash(this AggregateException exception) } public static string GetParameterString(this Exception exception) - { - switch (exception) + => exception switch { - case RemoteInvocationException remote: - return $"{remote.ErrorCode} {remote.StackTrace ?? exception.Message}"; - case AggregateException aggregate when aggregate.InnerException != null: + RemoteInvocationException remote => $"{remote.ErrorCode} {remote.StackTrace ?? exception.Message}", + AggregateException aggregate when aggregate.InnerException != null => // get first exception that is not aggregated exception - return GetParameterString(aggregate.InnerException); - default: - return $"{exception.GetType().ToString()} {(exception.StackTrace ?? exception.ToString())}"; - } - } + GetParameterString(aggregate.InnerException), + _ => $"{exception.GetType().ToString()} {(exception.StackTrace ?? exception.ToString())}", + }; /// /// hold onto last issue we reported. we use hash diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIntellisense.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIntellisense.cs index 588d89b2cf93205098c4e4f74f663ef0c149d474..6009ccbbf2160402a9df533e76feb1577966e692 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIntellisense.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIntellisense.cs @@ -81,16 +81,14 @@ public void VerifyCorrectIntellisenseSelectionOnEnter() [WpfFact] public void VerifyCompletionListForLoadMembers() { - using (var temporaryTextFile = new TemporaryTextFile( + using var temporaryTextFile = new TemporaryTextFile( "c.csx", - "int x = 2; class Complex { public int goo() { return 4; } }")) - { - temporaryTextFile.Create(); - VisualStudio.InteractiveWindow.SubmitText(string.Format("#load \"{0}\"", temporaryTextFile.FullName)); - VisualStudio.InteractiveWindow.InvokeCompletionList(); - VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("x", "Complex"); - VisualStudio.SendKeys.Send(VirtualKey.Escape); - } + "int x = 2; class Complex { public int goo() { return 4; } }"); + temporaryTextFile.Create(); + VisualStudio.InteractiveWindow.SubmitText(string.Format("#load \"{0}\"", temporaryTextFile.FullName)); + VisualStudio.InteractiveWindow.InvokeCompletionList(); + VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("x", "Complex"); + VisualStudio.SendKeys.Send(VirtualKey.Escape); } } } diff --git a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs index 3c65cd0a95750478dd31855a784318aaf248662a..085bdeea187bd064bc479bf52b4c0fe9765838e7 100644 --- a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs +++ b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs @@ -132,22 +132,17 @@ public static CodeStyleOption FromXElement(XElement element) } private static Func GetParser(string type) - { - switch (type) + => type switch { - case nameof(Boolean): + nameof(Boolean) => // Try to map a boolean value. Either map it to true/false if we're a // CodeStyleOption or map it to the 0 or 1 value for an enum if we're // a CodeStyleOption. - return v => Convert(bool.Parse(v)); - case nameof(Int32): - return v => Convert(int.Parse(v)); - case nameof(String): - return v => (T)(object)v; - default: - throw new ArgumentException(nameof(type)); - } - } + (Func)(v => Convert(bool.Parse(v))), + nameof(Int32) => v => Convert(int.Parse(v)), + nameof(String) => v => (T)(object)v, + _ => throw new ArgumentException(nameof(type)), + }; private static T Convert(bool b) { diff --git a/src/Workspaces/Remote/ServiceHub/Shared/Extensions.cs b/src/Workspaces/Remote/ServiceHub/Shared/Extensions.cs index ab93df5fd5b09c60efbeca2c5f6ecfa9667f2088..84c897177d019d243a0082d20dd1f4e2af08c0c7 100644 --- a/src/Workspaces/Remote/ServiceHub/Shared/Extensions.cs +++ b/src/Workspaces/Remote/ServiceHub/Shared/Extensions.cs @@ -85,42 +85,41 @@ internal static partial class Extensions { Task task = null; - using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) - using (var stream = new ServerDirectStream()) + using var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using var stream = new ServerDirectStream(); + + try { - try - { - // send request to asset source - task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken); + // send request to asset source + task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken); - // if invoke throws an exception, make sure we raise cancellation. - RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken); + // if invoke throws an exception, make sure we raise cancellation. + RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken); - // wait for asset source to respond - await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false); + // wait for asset source to respond + await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false); - // run user task with direct stream - var result = await funcWithDirectStreamAsync(stream, mergedCancellation.Token).ConfigureAwait(false); + // run user task with direct stream + var result = await funcWithDirectStreamAsync(stream, mergedCancellation.Token).ConfigureAwait(false); - // wait task to finish - await task.ConfigureAwait(false); + // wait task to finish + await task.ConfigureAwait(false); - return result; - } - catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken)) - { - // important to use cancelationToken here rather than mergedCancellationToken. - // there is a slight delay when merged cancellation token will be notified once cancellation token - // is raised, it can cause one to be in cancelled mode and the other is not. here, one we - // actually care is the cancellation token given in, not the merged cancellation token. - cancellationToken.ThrowIfCancellationRequested(); + return result; + } + catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken)) + { + // important to use cancelationToken here rather than mergedCancellationToken. + // there is a slight delay when merged cancellation token will be notified once cancellation token + // is raised, it can cause one to be in cancelled mode and the other is not. here, one we + // actually care is the cancellation token given in, not the merged cancellation token. + cancellationToken.ThrowIfCancellationRequested(); - // record reason why task got aborted. use NFW here since we don't want to - // crash VS on explicitly killing OOP. - task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed"); + // record reason why task got aborted. use NFW here since we don't want to + // crash VS on explicitly killing OOP. + task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed"); - throw; - } + throw; } } @@ -130,40 +129,39 @@ internal static partial class Extensions { Task task = null; - using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) - using (var stream = new ServerDirectStream()) + using var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using var stream = new ServerDirectStream(); + + try { - try - { - // send request by adding direct stream name to end of arguments - task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken); + // send request by adding direct stream name to end of arguments + task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken); - // if invoke throws an exception, make sure we raise cancellation. - RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken); + // if invoke throws an exception, make sure we raise cancellation. + RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken); - // wait for asset source to respond - await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false); + // wait for asset source to respond + await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false); - // run user task with direct stream - actionWithDirectStream(stream, mergedCancellation.Token); + // run user task with direct stream + actionWithDirectStream(stream, mergedCancellation.Token); - // wait task to finish - await task.ConfigureAwait(false); - } - catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken)) - { - // important to use cancelationToken here rather than mergedCancellationToken. - // there is a slight delay when merged cancellation token will be notified once cancellation token - // is raised, it can cause one to be in cancelled mode and the other is not. here, one we - // actually care is the cancellation token given in, not the merged cancellation token. - cancellationToken.ThrowIfCancellationRequested(); + // wait task to finish + await task.ConfigureAwait(false); + } + catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken)) + { + // important to use cancelationToken here rather than mergedCancellationToken. + // there is a slight delay when merged cancellation token will be notified once cancellation token + // is raised, it can cause one to be in cancelled mode and the other is not. here, one we + // actually care is the cancellation token given in, not the merged cancellation token. + cancellationToken.ThrowIfCancellationRequested(); - // record reason why task got aborted. use NFW here since we don't want to - // crash VS on explicitly killing OOP. - task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed"); + // record reason why task got aborted. use NFW here since we don't want to + // crash VS on explicitly killing OOP. + task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed"); - throw; - } + throw; } } @@ -173,42 +171,41 @@ internal static partial class Extensions { Task task = null; - using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) - using (var stream = new ServerDirectStream()) + using var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using var stream = new ServerDirectStream(); + + try { - try - { - // send request to asset source - task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken); + // send request to asset source + task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken); - // if invoke throws an exception, make sure we raise cancellation. - RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken); + // if invoke throws an exception, make sure we raise cancellation. + RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken); - // wait for asset source to respond - await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false); + // wait for asset source to respond + await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false); - // run user task with direct stream - var result = funcWithDirectStream(stream, mergedCancellation.Token); + // run user task with direct stream + var result = funcWithDirectStream(stream, mergedCancellation.Token); - // wait task to finish - await task.ConfigureAwait(false); + // wait task to finish + await task.ConfigureAwait(false); - return result; - } - catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken)) - { - // important to use cancelationToken here rather than mergedCancellationToken. - // there is a slight delay when merged cancellation token will be notified once cancellation token - // is raised, it can cause one to be in cancelled mode and the other is not. here, one we - // actually care is the cancellation token given in, not the merged cancellation token. - cancellationToken.ThrowIfCancellationRequested(); + return result; + } + catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken)) + { + // important to use cancelationToken here rather than mergedCancellationToken. + // there is a slight delay when merged cancellation token will be notified once cancellation token + // is raised, it can cause one to be in cancelled mode and the other is not. here, one we + // actually care is the cancellation token given in, not the merged cancellation token. + cancellationToken.ThrowIfCancellationRequested(); - // record reason why task got aborted. use NFW here since we don't want to - // crash VS on explicitly killing OOP. - task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed"); + // record reason why task got aborted. use NFW here since we don't want to + // crash VS on explicitly killing OOP. + task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed"); - throw; - } + throw; } }