From 0571a498aa15e10182aebaec8e7cfb826f31979a Mon Sep 17 00:00:00 2001 From: David Wengier Date: Tue, 30 Dec 2025 10:14:02 +1100 Subject: [PATCH] Revert "Update methods to be `async`." --- .../CSharpAddBracesCodeFixProvider.cs | 7 +- .../ConvertNamespaceCodeFixProvider.cs | 3 +- ...tchStatementToExpressionCodeFixProvider.cs | 3 +- ...rpFixIncorrectConstraintCodeFixProvider.cs | 4 +- .../CSharpInlineDeclarationCodeFixProvider.cs | 3 +- ...ateWithConditionalAccessCodeFixProvider.cs | 7 +- .../Iterator/CSharpAddYieldCodeFixProvider.cs | 2 +- ...SharpChangeToIEnumerableCodeFixProvider.cs | 2 +- ...eAnonymousFunctionStaticCodeFixProvider.cs | 8 +- .../MakeLocalFunctionStaticCodeFixProvider.cs | 7 +- ...uredVariablesAsArgumentsCodeFixProvider.cs | 4 +- ...CSharpMakeMemberRequiredCodeFixProvider.cs | 4 +- ...akeStatementAsynchronousCodeFixProvider.cs | 4 +- ...MakeStructFieldsWritableCodeFixProvider.cs | 7 +- ...MakeStructMemberReadOnlyCodeFixProvider.cs | 7 +- ...CSharpMakeStructReadOnlyCodeFixProvider.cs | 7 +- ...xpressionClausePlacementCodeFixProvider.cs | 3 +- ...ionalExpressionPlacementCodeFixProvider.cs | 3 +- ...onsecutiveBracePlacementCodeFixProvider.cs | 3 +- ...ctorInitializerPlacementCodeFixProvider.cs | 3 +- ...beddedStatementPlacementCodeFixProvider.cs | 3 +- ...moveConfusingSuppressionCodeFixProvider.cs | 4 +- ...nnecessaryUnsafeModifierCodeFixProvider.cs | 4 +- ...arpRemoveUnnecessaryCastCodeFixProvider.cs | 3 +- ...essaryDiscardDesignationCodeFixProvider.cs | 7 +- ...ecessaryLambdaExpressionCodeFixProvider.cs | 7 +- ...cessaryNullableDirectiveCodeFixProvider.cs | 8 +- ...lableWarningSuppressionsCodeFixProvider.cs | 4 +- ...arpRemoveUnreachableCodeCodeFixProvider.cs | 8 +- ...emoveUnusedLocalFunctionCodeFixProvider.cs | 7 +- ...lifyLinqTypeCheckAndCastCodeFixProvider.cs | 7 +- ...SimplifyPropertyAccessorCodeFixProvider.cs | 7 +- ...pSimplifyPropertyPatternCodeFixProvider.cs | 7 +- ...rpTransposeRecordKeywordCodeFixProvider.cs | 8 +- ...dateProjectToAllowUnsafeCodeFixProvider.cs | 5 +- .../CSharpUseAutoPropertyCodeFixProvider.cs | 6 +- ...ectionExpressionForEmptyCodeFixProvider.cs | 3 +- ...mpoundCoalesceAssignmentCodeFixProvider.cs | 3 +- .../CSharpUseDeconstructionCodeFixProvider.cs | 3 +- .../CSharpUseDefaultLiteralCodeFixProvider.cs | 3 +- .../UseExpressionBodyCodeFixProvider.cs | 3 +- ...seImplicitObjectCreationCodeFixProvider.cs | 3 +- .../UseExplicitTypeCodeFixProvider.cs | 3 +- .../UseImplicitTypeCodeFixProvider.cs | 7 +- ...seImplicitObjectCreationCodeFixProvider.cs | 3 +- .../CSharpUseIndexOperatorCodeFixProvider.cs | 7 +- .../CSharpUseRangeOperatorCodeFixProvider.cs | 3 +- ...terpolatedVerbatimStringCodeFixProvider.cs | 7 +- ...rCastAndEqualityOperatorCodeFixProvider.cs | 8 +- ...seNullCheckOverTypeCheckCodeFixProvider.cs | 7 +- .../CSharpUseLocalFunctionCodeFixProvider.cs | 3 +- ...harpUseNameofInAttributeCodeFixProvider.cs | 7 +- ...arpUsePatternCombinatorsCodeFixProvider.cs | 4 +- .../CSharpAsAndMemberAccessCodeFixProvider.cs | 7 +- .../CSharpAsAndNullCheckCodeFixProvider.cs | 3 +- .../CSharpIsAndCastCheckCodeFixProvider.cs | 7 +- .../CSharpUseNotPatternCodeFixProvider.cs | 3 +- ...arpUsePrimaryConstructorCodeFixProvider.cs | 4 +- .../UseSimpleUsingStatementCodeFixProvider.cs | 7 +- ...rpUseSystemThreadingLockCodeFixProvider.cs | 4 +- .../UseThrowExpressionCodeFixProvider.cs | 7 +- .../CSharpUseTupleSwapCodeFixProvider.cs | 7 +- ...boundGenericTypeInNameOfCodeFixProvider.cs | 7 +- .../UseUtf8StringLiteralCodeFixProvider.cs | 3 +- ...ddAccessibilityModifiersCodeFixProvider.cs | 4 +- .../AbstractAddExplicitCastCodeFixProvider.cs | 4 +- .../AddRequiredParenthesesCodeFixProvider.cs | 7 +- ...stractAliasAmbiguousTypeCodeFixProvider.cs | 4 +- .../AbstractConvertToAsyncCodeFixProvider.cs | 2 +- ...actConvertTypeOfToNameOfCodeFixProvider.cs | 3 +- .../AbstractFileHeaderCodeFixProvider.cs | 4 +- .../AbstractForEachCastCodeFixProvider.cs | 4 +- .../Formatting/FormattingCodeFixProvider.cs | 4 +- ...AbstractGenerateConversionService.State.cs | 8 +- .../AbstractGenerateMethodService.State.cs | 8 +- ...bstractMakeFieldReadonlyCodeFixProvider.cs | 3 +- ...AbstractMakeMemberStaticCodeFixProvider.cs | 8 +- ...actMakeMethodSynchronousCodeFixProvider.cs | 4 +- ...AbstractMakeTypeAbstractCodeFixProvider.cs | 8 +- .../AbstractMakeTypePartialCodeFixProvider.cs | 3 +- ...geNamespaceToMatchFolderCodeFixProvider.cs | 4 +- ...cutiveStatementPlacementCodeFixProvider.cs | 3 +- ...stractMultipleBlankLinesCodeFixProvider.cs | 3 +- .../AbstractPopulateSwitchCodeFixProvider.cs | 4 +- ...tractQualifyMemberAccessCodeFixProvider.cs | 7 +- ...RemoveUnnecessaryImportsCodeFixProvider.cs | 3 +- ...veUnnecessaryParenthesesCodeFixProvider.cs | 3 +- ...aryAttributeSuppressionsCodeFixProvider.cs | 4 +- ...essaryPragmaSuppressionsCodeFixProvider.cs | 4 +- ...tractRemoveUnusedMembersCodeFixProvider.cs | 3 +- .../SimplifyConditionalCodeFixProvider.cs | 3 +- ...actSimplifyInterpolationCodeFixProvider.cs | 3 +- .../SimplifyLinqExpressionCodeFixProvider.cs | 7 +- ...UpdateLegacySuppressionsCodeFixProvider.cs | 4 +- .../AbstractUpgradeProjectCodeFixProvider.cs | 15 ++-- .../AbstractUseAutoPropertyCodeFixProvider.cs | 4 +- .../UseAutoPropertyFixAllProvider.cs | 6 +- ...nForIfNullStatementCheckCodeFixProvider.cs | 3 +- ...eTernaryConditionalCheckCodeFixProvider.cs | 3 +- ...rTernaryConditionalCheckCodeFixProvider.cs | 3 +- ...actUseCompoundAssignmentCodeFixProvider.cs | 7 +- ...lExpressionForAssignmentCodeFixProvider.cs | 3 +- ...ionalExpressionForReturnCodeFixProvider.cs | 3 +- .../UseExplicitTupleNameCodeFixProvider.cs | 7 +- ...actUseInferredMemberNameCodeFixProvider.cs | 7 +- ...IsNullForReferenceEqualsCodeFixProvider.cs | 8 +- .../UseSystemHashCodeCodeFixProvider.cs | 3 +- .../CSharpEndConstructGenerationService.cs | 4 +- .../CSharpFormattingInteractionService.cs | 18 ++-- .../AddUsing/AddUsingNuGetTests.cs | 22 ++--- .../CodeActions/ApplyChangesOperationTests.cs | 7 +- ...ateEqualsAndGetHashCodeFromMembersTests.cs | 4 +- .../CSharpMoveStaticMembersTests.cs | 4 +- .../ErrorCases/ExceptionInCodeAction.cs | 3 +- .../CSharpTest/CodeActions/PreviewTests.cs | 7 +- .../FixAllProvider/BatchFixerTests.cs | 2 +- .../EventHookup/MockSuggestionService.cs | 4 +- .../Formatting/CodeCleanupTests.TestFixers.cs | 16 ++-- .../NavigateTo/NavigateToSearcherTests.cs | 28 ++++--- .../NullResultMetadataAsSourceFileProvider.cs | 4 +- .../TestSourceLinkService.cs | 12 +-- .../TaskList/NoCompilationTaskListTests.cs | 6 +- .../DynamicKeywordRecommenderTests.cs | 2 +- .../KeywordRecommenderTests.cs | 2 +- .../NativeIntegerKeywordRecommenderTests.cs | 2 +- .../NotnullKeywordRecommenderTests.cs | 2 +- .../ScopedKeywordRecommenderTests.cs | 2 +- .../VarKeywordRecommenderTests.cs | 2 +- .../BraceHighlightingViewTaggerProvider.cs | 8 +- ...lassificationTaggerProvider.TagComputer.cs | 10 +-- .../TotalClassificationTaggerProvider.cs | 9 +- ...lotGenerateDocumentationCommentProvider.cs | 6 +- .../DocumentationCommentSuggestion.cs | 9 +- .../Aggregator/SettingsAggregator.cs | 3 +- .../NamingStyleSettingsProvider.cs | 3 +- .../AbstractEditorNavigationBarItemService.cs | 6 +- .../VSTypeScriptEditorInlineRenameService.cs | 4 +- ...neRenameService.FailureInlineRenameInfo.cs | 2 +- .../AbstractEditorInlineRenameService.cs | 4 +- .../AsyncCompletion/ItemManager.cs | 4 +- .../InteractiveDocumentNavigationService.cs | 4 +- .../Core/Interactive/InteractiveSession.cs | 6 +- .../AbstractInProcLanguageClient.cs | 7 +- .../DefaultNavigateToLinkService.cs | 17 ++-- .../NavigateToItemProvider.Callback.cs | 4 +- .../OrganizeDocumentCommandHandler.cs | 2 +- .../Core/Preview/SolutionPreviewItem.cs | 2 +- ...ReferenceHighlightingViewTaggerProvider.cs | 12 +-- .../RenameTrackingCodeRefactoringProvider.cs | 4 +- ...TaggerProvider.RenameTrackingCodeAction.cs | 6 +- ...ventSources.WorkspaceChangedEventSource.cs | 3 +- ...Controller.Session_SetModelSelectedItem.cs | 2 +- .../RefineUsingCopilotCodeAction.cs | 4 +- .../SuggestedActions/EditorSuggestedAction.cs | 8 +- .../EditorSuggestedActionWithNestedActions.cs | 8 +- ...ousTaggerProvider.TagSource_ProduceTags.cs | 6 +- ...ousTaggerProvider.TagSource_TagsChanged.cs | 6 +- .../ITextBufferVisibilityTracker.cs | 8 +- .../CodeActions/AbstractCodeActionTest.cs | 4 +- .../Debugger/GlassTestsHotReloadService.cs | 6 +- .../Test/CodeFixes/CodeFixServiceTests.cs | 34 +++++--- .../CodeRefactoringServiceTest.cs | 14 +++- .../Test/Completion/CompletionServiceTests.cs | 8 +- .../DiagnosticAnalyzerServiceTests.cs | 5 +- .../FindReferencesCommandHandlerTests.cs | 4 +- .../VSTypeScriptHandlerTests.cs | 4 +- .../LinkedFileDiffMergingEditorTests.cs | 2 +- .../AbstractMetadataAsSourceTests.cs | 8 +- .../Test/Tagging/AsynchronousTaggerTests.cs | 4 +- .../UnusedReferencesRemoverTests.cs | 4 +- .../FindUsages/FindUsagesTestContext.cs | 4 +- .../NavigateTo/AbstractNavigateToTests.cs | 4 +- ...NoCompilationDocumentDiagnosticAnalyzer.cs | 6 +- ...eCodeRefactoringProvider.FixAllProvider.cs | 4 +- .../UseImplicitTypeCodeRefactoringProvider.cs | 3 +- ...ecursivePatternsCodeRefactoringProvider.cs | 2 +- .../Completion/CSharpCompletionService.cs | 2 +- ...tributeNamedParameterCompletionProvider.cs | 4 +- .../CrefCompletionProvider.cs | 4 +- ...ExplicitInterfaceTypeCompletionProvider.cs | 12 +-- ...ExtensionMemberImportCompletionProvider.cs | 4 +- .../NamedParameterCompletionProvider.cs | 6 +- .../TupleNameCompletionProvider.cs | 6 +- .../Providers/DefaultArgumentProvider.cs | 4 +- .../Providers/OutVariableArgumentProvider.cs | 7 +- ...odeFixProvider.DismissChangesCodeAction.cs | 9 +- .../CSharpDocumentHighlightsService.cs | 2 +- .../CSharpExtractInterfaceService.cs | 4 +- ...nerator.MultipleStatementsCodeGenerator.cs | 4 +- ...eGenerator.SingleStatementCodeGenerator.cs | 4 +- .../CSharpGoToDefinitionSymbolService.cs | 4 +- ...IntroduceVariableService_IntroduceField.cs | 6 +- ...DisplayService.SymbolDescriptionBuilder.cs | 10 +-- ...harpDiagnosticAnalyzerQuickInfoProvider.cs | 4 +- .../CSharpSyntacticQuickInfoProvider.cs | 8 +- ...onSignatureHelpProviderBase_MethodGroup.cs | 4 +- ...stractCSharpAutoPropertySnippetProvider.cs | 6 +- .../AbstractCSharpForLoopSnippetProvider.cs | 8 +- .../Snippets/CSharpElseSnippetProvider.cs | 4 +- .../CSharpForEachLoopSnippetProvider.cs | 4 +- .../Snippets/CSharpLockSnippetProvider.cs | 4 +- .../Snippets/CSharpUsingSnippetProvider.cs | 4 +- ...sAndCastCheckWithoutNameCodeFixProvider.cs | 3 +- ...NotImplementedExceptionFixProviderTests.cs | 40 ++++----- .../ExtractClass/ExtractClassTests.cs | 4 +- .../AssemblyReferenceCodeAction.cs | 6 +- .../InstallWithPackageManagerCodeAction.cs | 6 +- .../MetadataSymbolReferenceCodeAction.cs | 4 +- .../ProjectSymbolReferenceCodeAction.cs | 14 ++-- .../AddMissingReferenceCodeAction.cs | 8 +- .../InstallPackageDirectlyCodeAction.cs | 4 +- .../InstallWithPackageManagerCodeAction.cs | 6 +- .../AbstractBraceCompletionService.cs | 8 +- .../DelegateInvokeMethodReferenceFinder.cs | 4 +- .../Portable/CodeFixes/CodeFixCollection.cs | 1 + ...ConfigureCodeStyleOptionCodeFixProvider.cs | 8 +- .../ConfigureSeverityLevelCodeFixProvider.cs | 8 +- ...vice.FixAllPredefinedDiagnosticProvider.cs | 12 +-- .../AbstractSuppressionBatchFixAllProvider.cs | 5 +- ...r.GlobalSuppressMessageFixAllCodeAction.cs | 4 +- ....RemoveSuppressionCodeAction.BatchFixer.cs | 2 +- .../AbstractSuppressionCodeFixProvider.cs | 6 +- .../CodeLens/CodeLensReferencesService.cs | 6 +- ...bstractMoveTypeService.RenameFileEditor.cs | 5 +- .../Completion/CommonCompletionProvider.cs | 4 +- .../Portable/Completion/CompletionProvider.cs | 8 +- .../CompletionService.ProviderManager.cs | 4 +- .../Portable/Completion/CompletionService.cs | 4 +- .../AbstractKeywordCompletionProvider.cs | 4 +- ...bstractObjectCreationCompletionProvider.cs | 20 ++--- .../AbstractPartialTypeCompletionProvider.cs | 4 +- .../AbstractSymbolCompletionProvider.cs | 8 +- .../AbstractImportCompletionProvider.cs | 3 +- ...stractConvertLinqQueryToForEachProvider.cs | 2 +- ...stractConvertForEachToLinqQueryProvider.cs | 4 +- ...rtNumericLiteralCodeRefactoringProvider.cs | 4 +- ...ToInterpolatedStringRefactoringProvider.cs | 6 +- .../DebugInformationReaderProvider.cs | 4 +- .../AbstractDocumentHighlightsService.cs | 4 +- .../EditAndContinue/EditAndContinueService.cs | 16 ++-- .../IPdbMatchingSourceTextProvider.cs | 4 +- .../DateAndTimeEmbeddedCompletionProvider.cs | 14 ++-- .../AbstractJsonDetectionCodeFixProvider.cs | 7 +- .../RegexEmbeddedCompletionProvider.cs | 14 ++-- .../ExtensionMessageHandlerService.cs | 12 +-- .../API/NewUnitTestingIncrementalAnalyzer.cs | 3 +- .../API/UnitTestingHotReloadService.cs | 14 ++-- ...UnitTestingLegacySolutionEventsListener.cs | 3 +- ...tractGlobalOperationNotificationService.cs | 4 +- .../DefaultExternalDefinitionItemProvider.cs | 4 +- .../IExternalDefinitionItemProvider.cs | 2 +- ...erCodeRefactoringProviderMemberCreation.cs | 4 +- .../AbstractSymbolDisplayService.cs | 6 +- .../AbstractMoveToNamespaceService.cs | 8 +- ...ateToSearchService.CachedDocumentSearch.cs | 9 +- .../Portable/NavigateTo/NavigateToSearcher.cs | 9 +- .../DefaultSymbolNavigationService.cs | 12 +-- .../Navigation/IDocumentNavigationService.cs | 8 +- .../Portable/Navigation/INavigableLocation.cs | 5 +- .../OrganizeImportsCodeRefactoringProvider.cs | 2 +- .../PreferFrameworkTypeCodeFixProvider.cs | 4 +- .../CommonSemanticQuickInfoProvider.cs | 4 +- .../Portable/QuickInfo/QuickInfoService.cs | 4 +- .../SearchCompilationFailureDefinitionItem.cs | 4 +- .../SearchExceptionDefinitionItem.cs | 4 +- ...AbstractSimplifyThisOrMeCodeFixProvider.cs | 3 +- ...AbstractConditionalBlockSnippetProvider.cs | 6 +- .../AbstractLockSnippetProvider.cs | 4 +- .../AbstractMainMethodSnippetProvider.cs | 4 +- .../AbstractSnippetProvider.cs | 12 +-- ...SplitIfStatementCodeRefactoringProvider.cs | 2 +- ...tiveIfStatementsCodeRefactoringProvider.cs | 2 +- ...stedIfStatementsCodeRefactoringProvider.cs | 5 +- .../StackFrameMethodSymbolResolver.cs | 4 +- .../StackTraceExplorer/StackTraceAnalyzer.cs | 4 +- .../SymbolMappingServiceFactory.cs | 4 +- .../SymbolSearchUpdateNoOpEngine.cs | 12 +-- .../SymbolSearchUpdateEngine.Update.cs | 6 +- .../Windows/SymbolSearchUpdateEngine.cs | 14 ++-- ...seNamedArgumentsCodeRefactoringProvider.cs | 4 +- .../ValueTracker.OperationCollector.cs | 33 ++++---- .../Wrapping/AbstractCodeActionComputer.cs | 2 +- .../CSharpCodeRefactoringVerifier`1+Test.cs | 6 +- ...sualBasicCodeRefactoringVerifier`1+Test.cs | 6 +- .../AbstractCodeActionTest_NoEditor.cs | 4 +- .../AbstractCopilotCodeAnalysisService.cs | 4 +- .../CSharpCopilotCodeAnalysisService.cs | 54 ++++++------ .../CSharpContextProviderService.cs | 4 +- .../CopilotSemanticSearchQueryExecutor.cs | 11 ++- .../CopilotSemanticSearchUtilities.cs | 4 +- .../HotReload/Api/HotReloadService.cs | 12 +-- .../EditAndContinueWorkspaceServiceTests.cs | 8 +- .../RemoteEditAndContinueServiceTests.cs | 4 +- .../BrokeredServices/MockServiceBroker.cs | 4 +- .../EditAndContinueWorkspaceTestBase.cs | 2 +- .../MockActiveStatementSpanProvider.cs | 8 +- .../MockEditAndContinueService.cs | 16 ++-- ...ckManagedEditAndContinueDebuggerService.cs | 14 ++-- .../MockPdbMatchingSourceTextProvider.cs | 4 +- .../Options/TestOptionsProvider.cs | 4 +- .../VisualDiagnosticsServiceFactory.cs | 3 +- .../LspFileChangeWatcherTests.cs | 8 +- .../BrokeredServiceContainer.cs | 10 +-- .../BrokeredServiceBridgeManifestService.cs | 7 +- .../CanonicalMiscFilesProjectLoader.cs | 3 +- .../FileBasedProgramsProjectSystem.cs | 3 +- .../LspDidChangeWatchedFilesHandler.cs | 3 +- .../LanguageServerProjectSystem.cs | 3 +- .../HostWorkspace/Razor/RazorInitializer.cs | 6 +- .../WorkspaceProjectFactoryService.cs | 4 +- .../WorkspaceDebugConfigurationHandler.cs | 4 +- .../Handler/Logging/UpdateLogLevelHandler.cs | 3 +- .../Restore/RestorableProjectsHandler.cs | 4 +- .../ExampleRequestContextFactory.cs | 4 +- .../Mocks/TestRequestContext.cs | 4 +- .../TestExampleLanguageServer.cs | 6 +- .../Handlers/InitializeHandler.cs | 4 +- .../Handlers/InitializedHandler.cs | 4 +- .../AbstractLanguageServerProtocolTests.cs | 6 +- .../Workspaces/LspTestWorkspace.cs | 3 +- .../DecompiledSource/AssemblyResolver.cs | 8 +- ...ndContinueDiagnosticSource_OpenDocument.cs | 2 +- ...itAndContinueDiagnosticSource_Workspace.cs | 8 +- .../FindUsages/SimpleFindUsagesContext.cs | 10 ++- .../Protocol/Handler/AbstractRefreshQueue.cs | 8 +- .../CodeActions/CodeActionResolveHelper.cs | 4 +- .../Completion/CompletionResolveHandler.cs | 16 ++-- .../AbstractGoToDefinitionHandler.cs | 6 +- .../AbstractDocumentPullDiagnosticHandler.cs | 8 +- .../AbstractPullDiagnosticHandler.cs | 3 +- ...AbstractWorkspacePullDiagnosticsHandler.cs | 6 +- ...ntaxAndSemanticDiagnosticSourceProvider.cs | 4 +- .../AbstractProjectDiagnosticSource.cs | 4 +- ...stractWorkspaceDocumentDiagnosticSource.cs | 4 +- ...ocumentNonLocalDiagnosticSourceProvider.cs | 6 +- .../DocumentChanges/DidChangeHandler.cs | 4 +- ...EditAndContinueDiagnosticSourceProvider.cs | 4 +- .../RegisterSolutionSnapshotHandler.cs | 4 +- .../FoldingRanges/FoldingRangesHandler.cs | 6 +- .../Highlights/DocumentHighlightHandler.cs | 6 +- .../OnAutoInsert/OnAutoInsertHandler.cs | 8 +- .../GetTextDocumentWithContextHandler.cs | 8 +- .../References/FindUsagesLSPContext.cs | 3 +- .../ServerLifetime/InitializeHandler.cs | 6 +- .../LspServiceLifeCycleManager.cs | 4 +- .../SignatureHelp/SignatureHelpHandler.cs | 6 +- .../SourceGeneratorRefreshQueue.cs | 13 +-- .../DocumentTaskDiagnosticSourceProvider.cs | 4 +- .../WorkspaceTaskDiagnosticSourceProvider.cs | 6 +- .../WorkDoneProgressCancelledHandler.cs | 5 +- .../Protocol/RoslynLanguageServer.cs | 3 +- .../LspMiscellaneousFilesWorkspaceProvider.cs | 17 ++-- .../Protocol/Workspaces/SourceTextLoader.cs | 4 +- .../Commands/ExecuteWorkspaceCommandTests.cs | 4 +- .../Completion/CompletionResolveTests.cs | 12 +-- .../AbstractPullDiagnosticTestsBase.cs | 6 +- .../AdditionalFileDiagnosticsTests.cs | 10 +-- .../Diagnostics/DiagnosticsPullCacheTests.cs | 10 +-- .../DocumentChanges/DocumentChangesTests.cs | 4 +- .../ProtocolUnitTests/HandlerTests.cs | 30 +++---- .../Initialize/LocaleTests.cs | 4 +- .../LongRunningNonMutatingRequestHandler.cs | 4 +- .../NonLSPSolutionRequestHandlerProvider.cs | 4 +- .../Rename/WillRenameTests.cs | 4 +- .../Symbols/WorkspaceSymbolsTests.cs | 4 +- .../ProtocolUnitTests/UriTests.cs | 4 +- .../Fixers/AnalyzerReleaseTrackingFix.cs | 8 +- .../ApplyDiagnosticAnalyzerAttributeFix.cs | 4 +- .../Fixers/CompareSymbolsCorrectlyFix.cs | 4 +- .../ConfigureGeneratedCodeAnalysisFix.cs | 4 +- .../Fixers/EnableConcurrentExecutionFix.cs | 4 +- .../MetaAnalyzers/Fixers/PreferIsKindFix.cs | 4 +- .../Core/CodeFixes/AnnotatePublicApiFix.cs | 4 +- .../Core/CodeFixes/DeclarePublicApiFix.cs | 4 +- .../CodeFixes/NullableEnablePublicApiFix.cs | 4 +- .../PreferNullLiteralCodeFixProvider.cs | 4 +- ...ributesFromDifferentVersionsOfMEF.Fixer.cs | 4 +- ...HaveImportingConstructorCodeFixProvider.cs | 4 +- ...structorShouldBeObsoleteCodeFixProvider.cs | 4 +- ...rtedWithMEFv2MustBeMarkedAsShared.Fixer.cs | 4 +- ...sShouldNotBeDiscoverableCodeFixProvider.cs | 4 +- ...entifiersShouldBeSpelledCorrectly.Fixer.cs | 4 +- src/VisualStudio/CSharp/Impl/CSharpPackage.cs | 4 +- .../CSharpCodeStyleSettingsProvider.cs | 4 +- .../CSharpWhitespaceSettingsProvider.cs | 4 +- ...SemanticSearchDocumentNavigationService.cs | 8 +- .../SemanticSearchQueryExecutor.cs | 13 +-- ...DataProviderTests.MockAnalyzerReference.cs | 3 +- .../Commands/TestResetInteractive.cs | 8 +- .../Interactive/TestInteractiveEvaluator.cs | 12 +-- .../CodeLens/ReferenceCodeLensProvider.cs | 10 +-- .../CodeCleanup/AbstractCodeCleanUpFixer.cs | 10 +-- .../VisualStudioDesignerAttributeService.cs | 3 +- .../CommonCodeStyleSettingsProvider.cs | 4 +- .../CommonWhitespaceSettingsProvider.cs | 4 +- ...bstractTableDataSourceFindUsagesContext.cs | 17 ++-- .../Entries/SimpleMessageEntry.cs | 4 +- ...alStudioDefinitionsAndReferencesFactory.cs | 8 +- .../Core/Def/Library/AbstractObjectList.cs | 16 ++-- .../RoslynSearchResultPreviewPanel.cs | 4 +- .../RoslynSearchResultViewFactory.cs | 4 +- .../Def/Options/VisualStudioOptionStorage.cs | 6 +- .../VisualStudioSettingsOptionPersister.cs | 3 +- ...ualStudioUnifiedSettingsOptionPersister.cs | 4 +- .../PackageInstallerServiceFactory.cs | 6 +- .../PreviewUpdater.PreviewDialogWorkspace.cs | 4 +- .../Core/Def/Progression/GraphNodeCreation.cs | 8 +- .../BrokeredService/WorkspaceProject.cs | 9 +- .../WorkspaceProjectFactoryService.cs | 4 +- .../Legacy/SolutionEventsBatchScopeCreator.cs | 12 ++- .../Remote/DefaultRemoteHostClientProvider.cs | 4 +- .../VisualStudioRemoteHostClientProvider.cs | 2 +- src/VisualStudio/Core/Def/RoslynPackage.cs | 12 +-- .../AbstractSnippetFunction.cs | 8 +- .../Core/Def/Telemetry/FileLogger.cs | 4 +- .../VisualStudioNavigateToLinkService.cs | 21 +++-- .../VisualStudioDocumentNavigationService.cs | 2 +- .../RoslynSolutionExplorerSearchProvider.cs | 4 +- ...isualStudioSettingsOptionPersisterTests.cs | 3 +- .../Test.Next/Services/AssetProviderTests.cs | 4 +- .../Services/ServiceHubServicesTests.cs | 3 +- ...ubServicesTests_ExtensionMessageHandler.cs | 4 +- .../FSharpClassificationService.cs | 3 +- .../Editor/FSharpEditorInlineRenameService.cs | 4 +- .../FindUsages/FSharpFindUsagesContext.cs | 3 +- .../WorkspaceFileTextLoaderNoException.cs | 6 +- .../Impl/Client/RoslynLSPClientService.cs | 4 +- .../LiveShare/Impl/LSPSDKInitializeHandler.cs | 4 +- .../Impl/LiveShareInitializeHandler.cs | 4 +- .../MockDocumentNavigationServiceFactory.cs | 4 +- .../VisualStudioDiagnosticsWindowPackage.cs | 4 +- ...lRemoveUnnecessaryUsingsCodeFixProvider.cs | 3 +- .../XamlEditorInlineRenameService.cs | 4 +- .../Core/Portable/CodeActions/CodeAction.cs | 4 +- .../CodeActions/CodeActionWithOptions.cs | 8 +- .../Operations/ApplyChangesOperation.cs | 4 +- .../Operations/CodeActionOperation.cs | 4 +- .../SimplificationCodeCleanupProvider.cs | 4 +- ...xAllState.FixMultipleDiagnosticProvider.cs | 16 ++-- .../FixAllOccurrences/NoOpFixAllProvider.cs | 4 +- .../DefaultFixAllProviderHelpers.cs | 2 +- .../Diagnostics/DocumentDiagnosticAnalyzer.cs | 8 +- .../Core/Portable/Diagnostics/Extensions.cs | 6 +- .../Core/Portable/Editing/SymbolEditor.cs | 12 ++- .../DependentTypeFinder_DerivedClasses.cs | 8 +- .../DependentTypeFinder_DerivedInterfaces.cs | 8 +- ...encesSearchEngine.NonCascadingSymbolSet.cs | 3 +- .../FindReferencesSearchEngine.cs | 3 +- ...sSearchEngine_FindReferencesInDocuments.cs | 4 +- .../AbstractMemberScopedReferenceFinder.cs | 9 +- .../Finders/AbstractReferenceFinder.cs | 28 ++++--- .../Finders/AliasSymbolReferenceFinder.cs | 4 +- .../ConstructorSymbolReferenceFinder.cs | 6 +- .../CrefTypeParameterSymbolReferenceFinder.cs | 4 +- .../DestructorSymbolReferenceFinder.cs | 3 +- .../Finders/EventSymbolReferenceFinder.cs | 4 +- .../ExplicitInterfaceMethodReferenceFinder.cs | 3 +- ...ethodTypeParameterSymbolReferenceFinder.cs | 8 +- .../Finders/NamedTypeSymbolReferenceFinder.cs | 4 +- .../Finders/OperatorSymbolReferenceFinder.cs | 8 +- .../Finders/OrdinaryMethodReferenceFinder.cs | 6 +- .../PropertyAccessorSymbolReferenceFinder.cs | 4 +- .../Finders/PropertySymbolReferenceFinder.cs | 4 +- .../StreamingFindReferencesProgress.cs | 17 ++-- .../SymbolTree/SymbolTreeInfo_Metadata.cs | 2 +- .../Portable/Recommendations/Recommender.cs | 4 +- .../Core/Portable/Remote/RemoteHostClient.cs | 18 ++-- .../AsynchronousOperationListener.cs | 22 ++--- .../v2/SQLitePersistentStorageService.cs | 10 +-- .../SymbolSearch/ISymbolSearchService.cs | 12 +-- .../TrivialTemporaryStorageService.cs | 8 +- .../DocumentService/DocumentExcerptHelper.cs | 8 +- .../NoOpPersistentStorage.cs | 84 +++++++++---------- .../NoOpPersistentStorageService.cs | 4 +- .../Status/DefaultWorkspaceStatusService.cs | 7 +- .../LegacyTemporaryStorageService.cs | 11 +-- .../IsolatedAnalyzerReferenceSet.Core.cs | 2 +- .../IsolatedAnalyzerReferenceSet.Desktop.cs | 4 +- ...ystemProject.BatchingDocumentCollection.cs | 4 +- .../Solution/ConstantTextAndVersionSource.cs | 8 +- .../Portable/Workspace/Solution/Document.cs | 12 +-- .../Solution/DocumentState_TreeTextSource.cs | 4 +- .../Portable/Workspace/Solution/Solution.cs | 18 ++-- ...pilationState.RegularCompilationTracker.cs | 8 +- ...CompilationState.SkeletonReferenceCache.cs | 4 +- ...pilationState.TranslationAction_Actions.cs | 32 +++---- .../Workspace/Solution/TextDocumentState.cs | 6 +- .../Portable/Workspace/Solution/TextLoader.cs | 8 +- .../Core/Portable/Workspace/Workspace.cs | 19 ++--- .../Portable/Workspace/Workspace_Editor.cs | 15 ++-- .../Portable/Workspace/Workspace_Events.cs | 22 +++-- .../CoreTest/BatchFixAllProviderTests.cs | 4 +- .../CoreTest/CodeCleanup/CodeCleanupTests.cs | 4 +- .../CodeCleanup/MockCodeCleanupProvider.cs | 4 +- .../CoreTest/Formatter/FormatterTests.cs | 4 +- src/Workspaces/CoreTest/SyntaxNodeTests.cs | 12 +-- .../CoreTest/UtilityTest/AsyncLazyTests.cs | 12 +-- .../Fakes/SimpleAssetSource.cs | 4 +- .../Remote/InProcRemostHostClient.cs | 4 +- .../Remote/InProcRemoteHostClientProvider.cs | 4 +- ...ynamicFileInfoProviderThatProducesFiles.cs | 6 +- ...amicFileInfoProviderThatProducesNoFiles.cs | 4 +- .../CoreTestUtilities/TestTextLoader.cs | 4 +- .../Workspaces/TestHostDocument.cs | 4 +- .../Workspaces/TestWorkspace`1.cs | 3 +- src/Workspaces/MSBuild/BuildHost/BuildHost.cs | 4 +- .../MSBuild/MSBuildProjectLoader.Worker.cs | 11 +-- src/Workspaces/MSBuild/Test/RpcTests.cs | 6 +- .../ManagedHotReloadLanguageService.cs | 30 ++++--- .../Host/RemoteDocumentDifferenceService.cs | 4 +- .../Remote/ServiceHub/Host/RemoteWorkspace.cs | 4 +- .../ServiceHub/Host/RemoteWorkspaceManager.cs | 2 +- .../RemoteAssetSynchronizationService.cs | 3 +- ...oteAsynchronousOperationListenerService.cs | 7 +- .../BrokeredServiceBase.FactoryBase.cs | 6 +- .../RemoteDiagnosticAnalyzerService.cs | 6 +- .../RemoteEditAndContinueService.cs | 19 +++-- ...eExtensionMethodImportCompletionService.cs | 3 +- .../RemoteInitializationService.cs | 4 +- ...eLegacySolutionEventsAggregationService.cs | 4 +- ...essTelemetryService.PerformanceReporter.cs | 6 +- .../RemoteProcessTelemetryService.cs | 8 +- .../RemoteSemanticSearchService.cs | 8 +- .../RemoteSourceGenerationService.cs | 12 +-- .../Compiler/Core/Utilities/AsyncLazy.cs | 2 +- .../Utilities/ReferenceCountedDisposable.cs | 7 +- .../CSharp/Editing/CSharpImportAdder.cs | 4 +- ...ForkingSyntaxEditorBasedCodeFixProvider.cs | 3 +- .../MultiProjectSafeFixAllProvider.cs | 2 +- .../Core/Extensions/TextDocumentExtensions.cs | 6 +- .../Workspace/Core/Options/OptionsProvider.cs | 4 +- .../Core/SymbolFinder/SymbolFinderInternal.cs | 6 +- .../Core/Utilities/AsyncSymbolVisitor`1.cs | 4 +- .../NonSourceFileRefactoring.cs | 4 +- 534 files changed, 1959 insertions(+), 1479 deletions(-) diff --git a/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs index 7a79db543eed4..64b8379d9d73f 100644 --- a/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/AddBraces/CSharpAddBracesCodeFixProvider.cs @@ -22,12 +22,13 @@ internal sealed class CSharpAddBracesCodeFixProvider() : SyntaxEditorBasedCodeFi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.AddBracesDiagnosticId]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Add_braces, nameof(CSharpAnalyzersResources.Add_braces)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -46,5 +47,7 @@ protected override async Task FixAllAsync( return embeddedStatement is null ? currentStatement : currentStatement.ReplaceNode(embeddedStatement, SyntaxFactory.Block(embeddedStatement)); }); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs index 21b1f57ce35cb..10f9731c35dec 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs @@ -28,7 +28,7 @@ internal sealed class ConvertNamespaceCodeFixProvider() : SyntaxEditorBasedCodeF public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseBlockScopedNamespaceDiagnosticId, IDEDiagnosticIds.UseFileScopedNamespaceDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); @@ -41,6 +41,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) }); RegisterCodeFix(context, title, equivalenceKey); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs index ce30e5a5f9c41..1423b58a90466 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs @@ -32,9 +32,10 @@ internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider( public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Convert_switch_statement_to_expression, nameof(CSharpAnalyzersResources.Convert_switch_statement_to_expression)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs index 37dc4babed8c8..f49ac21d07316 100644 --- a/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/FixIncorrectConstraint/CSharpFixIncorrectConstraintCodeFixProvider.cs @@ -60,7 +60,7 @@ private static bool TryGetConstraint( return enumOrDelegateKeyword.Kind() is SyntaxKind.EnumKeyword or SyntaxKind.DelegateKeyword; } - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; @@ -69,6 +69,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Fix_constraint, nameof(CSharpFixIncorrectConstraintCodeFixProvider)); } + + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs index 5380d0a2c659b..cd2bade5c9d23 100644 --- a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs @@ -36,9 +36,10 @@ internal sealed partial class CSharpInlineDeclarationCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineDeclarationDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Inline_variable_declaration, nameof(CSharpAnalyzersResources.Inline_variable_declaration)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs index 4b2d38b7b33b0..d981874b1ac5c 100644 --- a/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs @@ -35,12 +35,13 @@ internal sealed partial class InvokeDelegateWithConditionalAccessCodeFixProvider protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Properties.ContainsKey(WellKnownDiagnosticTags.Unnecessary); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_delegate_invocation, nameof(CSharpAnalyzersResources.Simplify_delegate_invocation)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -49,6 +50,8 @@ protected override async Task FixAllAsync( cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } + + return Task.CompletedTask; } private static void AddEdits( diff --git a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs index d4e855619b8a4..221a096de9638 100644 --- a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpAddYieldCodeFixProvider.cs @@ -81,7 +81,7 @@ public override ImmutableArray FixableDiagnosticIds return CodeAction.Create( CSharpCodeFixesResources.Replace_return_with_yield_return, - async _ => document.WithSyntaxRoot(root), + _ => Task.FromResult(document.WithSyntaxRoot(root)), nameof(CSharpCodeFixesResources.Replace_return_with_yield_return)); } diff --git a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs index 89b4449d922a4..a1ebbb3099f84 100644 --- a/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/Iterator/CSharpChangeToIEnumerableCodeFixProvider.cs @@ -104,7 +104,7 @@ internal sealed class CSharpChangeToIEnumerableCodeFixProvider() : AbstractItera type.ToMinimalDisplayString(model, node.SpanStart), ienumerableGenericSymbol.ToMinimalDisplayString(model, node.SpanStart)); - return CodeAction.Create(title, async _ => newDocument, title); + return CodeAction.Create(title, _ => Task.FromResult(newDocument), title); } private static bool TryGetIEnumerableSymbols( diff --git a/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs index ccd3760f77478..122513c0fc3b8 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeAnonymousFunctionStatic/CSharpMakeAnonymousFunctionStaticCodeFixProvider.cs @@ -24,16 +24,18 @@ internal sealed class CSharpMakeAnonymousFunctionStaticCodeFixProvider() : Synta public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeAnonymousFunctionStaticDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.Make_anonymous_function_static, nameof(CSharpAnalyzersResources.Make_anonymous_function_static), context.Diagnostics[0].Severity > DiagnosticSeverity.Hidden ? CodeActionPriority.Default : CodeActionPriority.Low); + + return Task.CompletedTask; } - protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; @@ -42,5 +44,7 @@ protected override async Task FixAllAsync(Document document, ImmutableArray generator.WithModifiers(node, generator.GetModifiers(node).WithIsStatic(true))); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs index f0a378e30b634..980bfb21c6060 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs @@ -22,16 +22,19 @@ internal sealed class MakeLocalFunctionStaticCodeFixProvider() : SyntaxEditorBas public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_local_function_static, nameof(CSharpAnalyzersResources.Make_local_function_static)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken)); foreach (var localFunction in localFunctions) editor.ReplaceNode(localFunction, MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier); + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs index e3d71640b338f..46b3d5b773af4 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeLocalFunctionStatic/PassInCapturedVariablesAsArgumentsCodeFixProvider.cs @@ -35,7 +35,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) return WrapFixAsync( context.Document, [diagnostic], - async (document, localFunction, captures) => + (document, localFunction, captures) => { context.RegisterCodeFix( CodeAction.Create( @@ -43,6 +43,8 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) cancellationToken => MakeLocalFunctionStaticCodeFixHelper.MakeLocalFunctionStaticAsync(document, localFunction, captures, cancellationToken), nameof(CSharpCodeFixesResources.Pass_in_captured_variables_as_arguments)), diagnostic); + + return Task.CompletedTask; }, context.CancellationToken); } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs index 1e35d71fd4a78..3e8d66b3a3a39 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs @@ -103,7 +103,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) }; } - protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; var generator = editor.Generator; @@ -138,5 +138,7 @@ protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -57,6 +57,8 @@ protected override async Task FixAllAsync( MakeStatementAsynchronous(editor, statementToFix); } } + + return Task.CompletedTask; } private static void MakeStatementAsynchronous(SyntaxEditor editor, SyntaxNode statementToFix) diff --git a/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs index 8ed6dd53ed0c6..b9b1909edbdc0 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.cs @@ -25,12 +25,13 @@ internal sealed class CSharpMakeStructFieldsWritableCodeFixProvider() : SyntaxEd public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.MakeStructFieldsWritable]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_readonly_fields_writable, nameof(CSharpAnalyzersResources.Make_readonly_fields_writable)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -60,5 +61,7 @@ protected override async Task FixAllAsync( } } } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs index 0620060a17a4f..5fbc782c52ab5 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeStructMemberReadOnly/CSharpMakeStructMemberReadOnlyCodeFixProvider.cs @@ -26,12 +26,13 @@ internal sealed class CSharpMakeStructMemberReadOnlyCodeFixProvider() : SyntaxEd public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeStructMemberReadOnlyDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_member_readonly, nameof(CSharpAnalyzersResources.Make_member_readonly)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -94,7 +95,7 @@ protected override async Task FixAllAsync( } } - return; + return Task.CompletedTask; TNode UpdateReadOnlyModifier(TNode node, bool add) where TNode : SyntaxNode { diff --git a/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs index 5c0d95266813b..697d799433afc 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeStructReadOnly/CSharpMakeStructReadOnlyCodeFixProvider.cs @@ -24,12 +24,13 @@ internal sealed class CSharpMakeStructReadOnlyCodeFixProvider() : SyntaxEditorBa public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.MakeStructReadOnlyDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Make_struct_readonly, nameof(CSharpAnalyzersResources.Make_struct_readonly)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -44,5 +45,7 @@ protected override async Task FixAllAsync( typeDeclaration, (current, generator) => generator.WithModifiers(current, generator.GetModifiers(current).WithIsReadOnly(true))); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs index 0c3edf144a055..8cde1756070e7 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ArrowExpressionClausePlacement/ArrowExpressionClausePlacementCodeFixProvider.cs @@ -27,7 +27,7 @@ internal sealed class ArrowExpressionClausePlacementCodeFixProvider() : CodeFixP public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ArrowExpressionClausePlacementDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -37,6 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_token_on_following_line)), context.Diagnostics); + return Task.CompletedTask; } private static async Task UpdateDocumentAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs index 6861028305f64..13ba977508273 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ConditionalExpressionPlacement/ConditionalExpressionPlacementCodeFixProvider.cs @@ -27,7 +27,7 @@ internal sealed class ConditionalExpressionPlacementCodeFixProvider() : CodeFixP public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConditionalExpressionPlacementDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -37,6 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_token_on_following_line)), context.Diagnostics); + return Task.CompletedTask; } private static async Task UpdateDocumentAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs index 9ad0f6b96a3fb..6f37b38c9fce5 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementCodeFixProvider.cs @@ -28,7 +28,7 @@ internal sealed class ConsecutiveBracePlacementCodeFixProvider() : CodeFixProvid public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConsecutiveBracePlacementDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -38,6 +38,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, diagnostic, c), nameof(CSharpCodeFixesResources.Remove_blank_lines_between_braces)), context.Diagnostics); + return Task.CompletedTask; } private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs index 9330903991dac..fdb85c447f743 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementCodeFixProvider.cs @@ -27,7 +27,7 @@ internal sealed class ConstructorInitializerPlacementCodeFixProvider() : CodeFix public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConstructorInitializerPlacementDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -37,6 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_token_on_following_line)), context.Diagnostics); + return Task.CompletedTask; } private static async Task UpdateDocumentAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs index d7074853367a2..2cb1247d4ee5b 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs @@ -30,7 +30,7 @@ internal sealed class EmbeddedStatementPlacementCodeFixProvider() : CodeFixProvi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.EmbeddedStatementPlacementDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -40,6 +40,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => FixAllAsync(document, [diagnostic], c), nameof(CSharpCodeFixesResources.Place_statement_on_following_line)), context.Diagnostics); + return Task.CompletedTask; } public static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs index e940f7dcb0c68..f7fbba37cde3c 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs @@ -30,7 +30,7 @@ internal sealed partial class CSharpRemoveConfusingSuppressionCodeFixProvider() public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; @@ -49,6 +49,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => FixAllAsync(document, diagnostics, negate: true, c), NegateExpression), context.Diagnostics); + + return Task.CompletedTask; } private static async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs index 7fce5e71ad404..f45b506f74031 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnneccessaryUnsafeModifier/CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider.cs @@ -27,13 +27,15 @@ internal sealed class CSharpRemoveUnnecessaryUnsafeModifierCodeFixProvider() : C { public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryUnsafeModifier]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(CodeAction.Create( AnalyzersResources.Remove_unnecessary_unsafe_modifier, cancellationToken => FixAllAsync(context.Document, context.Diagnostics, cancellationToken), nameof(AnalyzersResources.Remove_unnecessary_unsafe_modifier)), context.Diagnostics); + + return Task.CompletedTask; } private static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs index 51775f24b3145..d901756a39dfb 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastCodeFixProvider.cs @@ -28,9 +28,10 @@ internal sealed partial class CSharpRemoveUnnecessaryCastCodeFixProvider() : Syn public sealed override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Remove_Unnecessary_Cast, nameof(AnalyzersResources.Remove_Unnecessary_Cast)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs index 5f1e8d2232182..bb128253e29e2 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs @@ -25,12 +25,13 @@ internal sealed partial class CSharpRemoveUnnecessaryDiscardDesignationCodeFixPr public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryDiscardDesignationDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Remove_unnessary_discard, nameof(CSharpAnalyzersResources.Remove_unnessary_discard)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -76,5 +77,7 @@ protected override async Task FixAllAsync( break; } } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs index 8d9c0513e355c..07b8668580569 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionCodeFixProvider.cs @@ -31,12 +31,13 @@ internal sealed partial class CSharpRemoveUnnecessaryLambdaExpressionCodeFixProv public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryLambdaExpressionDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Remove_unnecessary_lambda_expression, nameof(CSharpAnalyzersResources.Remove_unnecessary_lambda_expression)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -71,6 +72,8 @@ protected override async Task FixAllAsync( } } } + + return Task.CompletedTask; } private static IEnumerable TakeComments(SyntaxTriviaList triviaList) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs index 2d783e424ada3..ce5e78e396373 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryNullableDirective/CSharpRemoveUnnecessaryNullableDirectiveCodeFixProvider.cs @@ -31,7 +31,7 @@ public override ImmutableArray FixableDiagnosticIds IDEDiagnosticIds.RemoveUnnecessaryNullableDirectiveDiagnosticId, ]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -40,9 +40,11 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) else RegisterCodeFix(context, CSharpAnalyzersResources.Remove_unnecessary_nullable_directive, nameof(CSharpAnalyzersResources.Remove_unnecessary_nullable_directive), diagnostic); } + + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -87,6 +89,8 @@ protected override async Task FixAllAsync( node, node.ReplaceToken(token, token.WithLeadingTrivia(leadingTrivia))); } + + return Task.CompletedTask; } private static bool HasPrecedingBlankLine(SyntaxTriviaList leadingTrivia, int index) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs index 2a7afd050b1fe..78deaf667bcf0 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnnecessarySuppressions/CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixProvider.cs @@ -28,13 +28,15 @@ internal sealed class CSharpRemoveUnnecessaryNullableWarningSuppressionsCodeFixP { public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.RemoveUnnecessaryNullableWarningSuppression]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(CodeAction.Create( AnalyzersResources.Remove_unnecessary_suppression, cancellationToken => FixSingleDocumentAsync(context.Document, context.Diagnostics, cancellationToken), nameof(AnalyzersResources.Remove_unnecessary_suppression)), context.Diagnostics); + + return Task.CompletedTask; } private static async Task FixSingleDocumentAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs index f8d26dfee78da..fc80ca447fac3 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs @@ -24,7 +24,7 @@ internal sealed class CSharpRemoveUnreachableCodeCodeFixProvider() : SyntaxEdito public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; @@ -37,6 +37,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) : CodeActionPriority.Default; RegisterCodeFix(context, CSharpCodeFixesResources.Remove_unreachable_code, nameof(CSharpCodeFixesResources.Remove_unreachable_code), priority); + + return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) @@ -45,7 +47,7 @@ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) private static bool IsSubsequentSection(Diagnostic diagnostic) => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection); - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -72,7 +74,7 @@ protected override async Task FixAllAsync( } } - return; + return Task.CompletedTask; // Local function static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement) diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs index 44b394122ab9d..427d2f54205b2 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnusedLocalFunction/CSharpRemoveUnusedLocalFunctionCodeFixProvider.cs @@ -28,12 +28,13 @@ internal sealed class CSharpRemoveUnusedLocalFunctionCodeFixProvider() : SyntaxE public sealed override ImmutableArray FixableDiagnosticIds => [CS8321]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Remove_unused_function, nameof(CSharpCodeFixesResources.Remove_unused_function)); + return Task.CompletedTask; } - protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; @@ -50,5 +51,7 @@ protected override async Task FixAllAsync(Document document, ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.SimplifyLinqTypeCheckAndCastDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_LINQ_expression, nameof(AnalyzersResources.Simplify_LINQ_expression)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -74,5 +75,7 @@ protected override async Task FixAllAsync( // Snip out the `.Where(...)` portion so that `expr.Where(...).OfType()` becomes `expr.OfType()` editor.ReplaceNode(whereInvocation, whereMemberAccess.Expression); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs index 01bdce215f0b5..e52ed94b96f79 100644 --- a/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/SimplifyPropertyAccessor/CSharpSimplifyPropertyAccessorCodeFixProvider.cs @@ -28,12 +28,13 @@ internal sealed class CSharpSimplifyPropertyAccessorCodeFixProvider() : SyntaxEd public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.SimplifyPropertyAccessorDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_property_accessor, nameof(CSharpAnalyzersResources.Simplify_property_accessor)); + return Task.CompletedTask; } - protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { using var _ = PooledHashSet.GetInstance(out var seenPartialProperties); @@ -67,5 +68,7 @@ protected override async Task FixAllAsync(Document document, ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.SimplifyPropertyPatternDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_property_pattern, nameof(CSharpAnalyzersResources.Simplify_property_pattern)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -55,6 +56,8 @@ protected override async Task FixAllAsync( return simplified ?? currentSubpattern; }); } + + return Task.CompletedTask; } private static SubpatternSyntax? TrySimplify(SubpatternSyntax currentSubpattern) diff --git a/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs index 48fd0a3b07481..b9294d8b975de 100644 --- a/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/TransposeRecordKeyword/CSharpTransposeRecordKeywordCodeFixProvider.cs @@ -78,7 +78,7 @@ private static bool TryGetTokens( return false; } - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; @@ -88,9 +88,11 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Fix_record_declaration, nameof(CSharpCodeFixesResources.Fix_record_declaration)); } + + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -112,5 +114,7 @@ protected override async Task FixAllAsync( }); } } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs index ff8287b43bda6..3151c2fcc7490 100644 --- a/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UpdateProjectToAllowUnsafe/CSharpUpdateProjectToAllowUnsafeCodeFixProvider.cs @@ -28,10 +28,11 @@ internal sealed class CSharpUpdateProjectToAllowUnsafeCodeFixProvider() : CodeFi return null; } - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(ProjectOptionsChangeAction.Create(CSharpCodeFixesResources.Allow_unsafe_code_in_this_project, - async _ => AllowUnsafeOnProject(context.Document.Project)), context.Diagnostics); + _ => Task.FromResult(AllowUnsafeOnProject(context.Document.Project))), context.Diagnostics); + return Task.CompletedTask; } private static Solution AllowUnsafeOnProject(Project project) diff --git a/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs index cb7830781b485..f6efc25c5c38a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs @@ -77,7 +77,7 @@ protected override PropertyDeclarationSyntax RewriteFieldReferencesInProperty( return (PropertyDeclarationSyntax)rewriter.Visit(property); } - protected override async Task UpdatePropertyAsync( + protected override Task UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, @@ -105,7 +105,7 @@ protected override async Task UpdatePropertyAsync( // Nothing to actually do. We're not changing the accessors to `get;set;` accessors, and we didn't have to // add an setter. We also had no field initializer to move over. This can happen when we're converting to // using `field` and that rewrite already happened. - return propertyDeclaration; + return Task.FromResult(propertyDeclaration); } // 1. If we have a trivial getters/setter then we want to convert to an accessor list to have `get;set;` @@ -140,7 +140,7 @@ protected override async Task UpdatePropertyAsync( var finalProperty = updatedProperty .WithTrailingTrivia(propertyDeclaration.GetTrailingTrivia()) .WithAdditionalAnnotations(SpecializedFormattingAnnotation); - return finalProperty; + return Task.FromResult(finalProperty); static PropertyDeclarationSyntax MoveAttributes( PropertyDeclarationSyntax property, diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs index 0eaf179f1f5f5..be93c2fc486f8 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyCodeFixProvider.cs @@ -30,7 +30,7 @@ internal sealed partial class CSharpUseCollectionExpressionForEmptyCodeFixProvid public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseCollectionExpressionForEmptyDiagnosticId]; - protected override async Task FixAsync( + protected override Task FixAsync( Document document, SyntaxEditor editor, SyntaxNode diagnosticNode, @@ -40,5 +40,6 @@ protected override async Task FixAsync( editor.ReplaceNode( diagnosticNode, (current, _) => s_emptyCollection.WithTriviaFrom(current)); + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs index ebfcc25be18c7..a9ec9d8f034e8 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs @@ -31,9 +31,10 @@ internal sealed class CSharpUseCompoundCoalesceAssignmentCodeFixProvider() : Syn public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseCoalesceCompoundAssignmentDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_compound_assignment, nameof(AnalyzersResources.Use_compound_assignment)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs index f031ce7ecb7d6..a7420b3863e3a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs @@ -28,9 +28,10 @@ internal sealed class CSharpUseDeconstructionCodeFixProvider() : SyntaxEditorBas public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseDeconstructionDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Deconstruct_variable_declaration, nameof(CSharpAnalyzersResources.Deconstruct_variable_declaration)); + return Task.CompletedTask; } protected override Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs index 9002fd6727194..880a706cd682c 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs @@ -25,9 +25,10 @@ internal sealed partial class CSharpUseDefaultLiteralCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseDefaultLiteralDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Simplify_default_expression, nameof(CSharpAnalyzersResources.Simplify_default_expression)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs index a75749b19ef3d..f7546f54ed3a2 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs @@ -36,7 +36,7 @@ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed || diagnostic.Properties.ContainsKey(UseExpressionBodyDiagnosticAnalyzer.FixesError); - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); @@ -47,6 +47,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) var title = diagnostic.GetMessage(); RegisterCodeFix(context, title, title, priority); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs index ddfa9a6186316..cd77173715f61 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationCodeFixProvider.cs @@ -37,9 +37,10 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_new, nameof(CSharpAnalyzersResources.Use_new)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs index 1e67d7e427ede..96db15d5bd13d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs @@ -34,12 +34,13 @@ internal sealed class UseExplicitTypeCodeFixProvider() : SyntaxEditorBasedCodeFi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseExplicitTypeDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.Use_explicit_type_instead_of_var, context.Diagnostics.First().Properties[CSharpTypeStyleUtilities.EquivalenceyKey]!); + return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string? equivalenceKey, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs index 1344e83810207..8de161fe7de4c 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs @@ -25,18 +25,19 @@ internal sealed class UseImplicitTypeCodeFixProvider() : SyntaxEditorBasedCodeFi public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseImplicitTypeDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.use_var_instead_of_explicit_type, context.Diagnostics.First().Properties[CSharpTypeStyleUtilities.EquivalenceyKey]!); + return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string? equivalenceKey, CancellationToken cancellationToken) => diagnostic.Properties[CSharpTypeStyleUtilities.EquivalenceyKey] == equivalenceKey; - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -47,6 +48,8 @@ protected override async Task FixAllAsync( var typeSyntax = (TypeSyntax)root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); ReplaceTypeWithVar(editor, typeSyntax); } + + return Task.CompletedTask; } internal static void ReplaceTypeWithVar(SyntaxEditor editor, TypeSyntax type) diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs index 6837260355098..c7e1193eedf8b 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitlyTypedLambdaExpression/CSharpUseImplicitObjectCreationCodeFixProvider.cs @@ -30,9 +30,10 @@ internal sealed class CSharpUseImplicitlyTypedLambdaExpressionCodeFixProvider() public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseImplicitlyTypedLambdaExpressionDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_implicitly_typed_lambda, nameof(CSharpAnalyzersResources.Use_implicitly_typed_lambda)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs index e9d3aa908d4de..01b8a9424b779 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs @@ -26,12 +26,13 @@ internal sealed class CSharpUseIndexOperatorCodeFixProvider() : SyntaxEditorBase public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseIndexOperatorDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_index_operator, nameof(CSharpAnalyzersResources.Use_index_operator)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -44,5 +45,7 @@ protected override async Task FixAllAsync( node, (currentNode, _) => IndexExpression(((BinaryExpressionSyntax)currentNode).Right)); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs index 277800dcddeda..555091f418c3c 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs @@ -36,9 +36,10 @@ internal sealed class CSharpUseRangeOperatorCodeFixProvider() : SyntaxEditorBase public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseRangeOperatorDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_range_operator, nameof(CSharpAnalyzersResources.Use_range_operator)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs index a7da9bfd3a529..a099c36cde8f4 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseInterpolatedVerbatimString/CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs @@ -26,12 +26,13 @@ internal sealed partial class CSharpUseInterpolatedVerbatimStringCodeFixProvider private const string InterpolatedVerbatimText = "$@\""; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpCodeFixesResources.Use_interpolated_verbatim_string, nameof(CSharpCodeFixesResources.Use_interpolated_verbatim_string)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -40,6 +41,8 @@ protected override async Task FixAllAsync( cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } + + return Task.CompletedTask; } private static void AddEdits( diff --git a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs index 1990f6ded9988..e9d06f96ab129 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs @@ -33,7 +33,7 @@ public override ImmutableArray FixableDiagnosticIds private static bool IsSupportedDiagnostic(Diagnostic diagnostic) => diagnostic.Properties[UseIsNullConstants.Kind] == UseIsNullConstants.CastAndEqualityKey; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); if (IsSupportedDiagnostic(diagnostic)) @@ -43,9 +43,11 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) RegisterCodeFix(context, title, title); } + + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -60,6 +62,8 @@ protected override async Task FixAllAsync( binary, (current, g) => Rewrite((BinaryExpressionSyntax)current)); } + + return Task.CompletedTask; } private static ExpressionSyntax Rewrite(BinaryExpressionSyntax binary) diff --git a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs index aee7dee18239c..6b3a01664eb5f 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs @@ -28,12 +28,13 @@ internal sealed class CSharpUseNullCheckOverTypeCheckCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Prefer_null_check_over_type_check, nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -55,5 +56,7 @@ protected override async Task FixAllAsync( editor.ReplaceNode(node, replacement.WithTriviaFrom(node)); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs index 74ceb2260804d..968fc5a76882a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs @@ -43,9 +43,10 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_local_function, nameof(CSharpAnalyzersResources.Use_local_function)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs index 13fb02d51e49b..59059f826e54d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseNameofInAttribute/CSharpUseNameofInAttributeCodeFixProvider.cs @@ -23,15 +23,16 @@ internal sealed class CSharpUseNameofInAttributeCodeFixProvider() : SyntaxEditor { public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseNameofInAttributeDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, CSharpAnalyzersResources.Use_nameof, nameof(CSharpAnalyzersResources.Use_nameof)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -47,5 +48,7 @@ protected override async Task FixAllAsync( expression, editor.Generator.NameOfExpression(editor.Generator.IdentifierName(name)).WithTriviaFrom(expression)); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs index 3b5064ff79125..d16b47757308d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs @@ -55,7 +55,7 @@ protected override bool IncludeDiagnosticDuringFixAll( return isSafe == (equivalenceKey == SafeEquivalenceKey); } - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var isSafe = CSharpUsePatternCombinatorsDiagnosticAnalyzer.IsSafe(diagnostic); @@ -65,6 +65,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) isSafe ? CSharpAnalyzersResources.Use_pattern_matching : CSharpAnalyzersResources.Use_pattern_matching_may_change_code_meaning, isSafe ? SafeEquivalenceKey : UnsafeEquivalenceKey, CodeActionPriority.Low); + + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs index 359fa58c3382f..6d46376acf94d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndMemberAccessCodeFixProvider.cs @@ -30,17 +30,20 @@ internal sealed partial class CSharpAsAndMemberAccessCodeFixProvider() : SyntaxE public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UsePatternMatchingAsAndMemberAccessDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start)) FixOne(editor, diagnostic, cancellationToken); + + return Task.CompletedTask; } private static void FixOne(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs index 3ff3aeed98e00..c46ae30e09d37 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs @@ -30,9 +30,10 @@ internal sealed partial class CSharpAsAndNullCheckCodeFixProvider() : SyntaxEdit public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineAsTypeCheckId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs index f9ba72ad7b190..d234b3148fd34 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs @@ -27,12 +27,13 @@ internal sealed partial class CSharpIsAndCastCheckCodeFixProvider() : SyntaxEdit public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineIsTypeCheckId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -41,6 +42,8 @@ protected override async Task FixAllAsync( cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } + + return Task.CompletedTask; } private static void AddEdits( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs index 6818cd55b0ec9..1a3f54bbdcb20 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpUseNotPatternCodeFixProvider.cs @@ -25,9 +25,10 @@ internal sealed class CSharpUseNotPatternCodeFixProvider() : SyntaxEditorBasedCo public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseNotPatternDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs index 8d5d1e6283c79..c496dfd59323a 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider.cs @@ -53,7 +53,7 @@ public override ImmutableArray FixableDiagnosticIds => new CSharpUsePrimaryConstructorFixAllProvider(); #endif - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; @@ -88,6 +88,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) diagnostic); } } + + return Task.CompletedTask; } private static async Task UsePrimaryConstructorAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs index ebee946519d5d..038b093530b9c 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.cs @@ -34,12 +34,13 @@ internal sealed class UseSimpleUsingStatementCodeFixProvider() : SyntaxEditorBas public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_simple_using_statement, nameof(CSharpAnalyzersResources.Use_simple_using_statement)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -55,6 +56,8 @@ protected override async Task FixAllAsync( (original, current) => RewriteBlock(original, current, topmostUsingStatements)); editor.ReplaceNode(root, updatedRoot); + + return Task.CompletedTask; } private static SyntaxNode RewriteBlock( diff --git a/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs index 339636b12d5c4..4f1d7464f385c 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseSystemThreadingLock/CSharpUseSystemThreadingLockCodeFixProvider.cs @@ -37,7 +37,7 @@ internal sealed partial class CSharpUseSystemThreadingLockCodeFixProvider() : Co #endif - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; @@ -54,6 +54,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) nameof(CSharpAnalyzersResources.Use_primary_constructor)), diagnostic); } + + return Task.CompletedTask; } private static async Task UseSystemThreadingLockAsync( diff --git a/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs index 0b4d255c22335..598b1cdca3762 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs @@ -30,12 +30,13 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_throw_expression, nameof(AnalyzersResources.Use_throw_expression)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -77,5 +78,7 @@ protected override async Task FixAllAsync( } } } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs index fcd3ff922cb9a..deff3bf44e9f2 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseTupleSwap/CSharpUseTupleSwapCodeFixProvider.cs @@ -27,17 +27,20 @@ internal sealed partial class CSharpUseTupleSwapCodeFixProvider() : SyntaxEditor public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseTupleSwapDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_tuple_to_swap_values, nameof(CSharpAnalyzersResources.Use_tuple_to_swap_values)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) FixOne(editor, diagnostic, cancellationToken); + + return Task.CompletedTask; } private static void FixOne( diff --git a/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs index 09c1d415413d4..61565a07875fc 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseUnboundGenericTypeInNameOf/CSharpUseUnboundGenericTypeInNameOfCodeFixProvider.cs @@ -30,17 +30,20 @@ internal sealed partial class CSharpUseUnboundGenericTypeInNameOfCodeFixProvider public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseUnboundGenericTypeInNameOfDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_unbound_generic_type, nameof(CSharpAnalyzersResources.Use_unbound_generic_type)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) FixOne(editor, diagnostic, cancellationToken); + + return Task.CompletedTask; } private static void FixOne( diff --git a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs index a7643443ae778..2e505e0fffed8 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs @@ -33,9 +33,10 @@ internal sealed class UseUtf8StringLiteralCodeFixProvider() : SyntaxEditorBasedC public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseUtf8StringLiteralDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_Utf8_string_literal, nameof(CSharpAnalyzersResources.Use_Utf8_string_literal)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs index 7be88decf6ec1..048011d9bf94b 100644 --- a/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs @@ -21,7 +21,7 @@ internal abstract class AbstractAddOrRemoveAccessibilityModifiersCodeFixProvider public sealed override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.AddOrRemoveAccessibilityModifiersDiagnosticId]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); @@ -34,6 +34,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) : (AnalyzersResources.Remove_accessibility_modifiers, nameof(AnalyzersResources.Remove_accessibility_modifiers)); RegisterCodeFix(context, title, key, priority); + + return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs index b015865197eac..d1d7eebefb81a 100644 --- a/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddExplicitCast/AbstractAddExplicitCastCodeFixProvider.cs @@ -93,11 +93,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) actions.Add(CodeAction.Create( title, - async cancellationToken => + cancellationToken => { var (finalTarget, replacement) = ApplyFix(document, semanticModel, targetNode, conversionType, cancellationToken); - return document.WithSyntaxRoot(root.ReplaceNode(finalTarget, replacement)); + return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(finalTarget, replacement))); }, title)); diff --git a/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs index 945189bfa33b5..02183781df90d 100644 --- a/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs @@ -27,13 +27,14 @@ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Doc => diagnostic.Properties.ContainsKey(AddRequiredParenthesesConstants.IncludeInFixAll) && diagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey] == equivalenceKey; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix( context, AnalyzersResources.Add_parentheses_for_clarity, context.Diagnostics[0].Properties[AddRequiredParenthesesConstants.EquivalenceKey]!); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -50,5 +51,7 @@ protected override async Task FixAllAsync( (current, _) => generator.AddParentheses( current, includeElasticTrivia: false, addSimplifierAnnotation: false)); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs index 6b465f0cd097c..25db71024c464 100644 --- a/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/AliasAmbiguousType/AbstractAliasAmbiguousTypeCodeFixProvider.cs @@ -56,11 +56,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) actions.Add(CodeAction.Create( title, - async cancellationToken => + cancellationToken => { var aliasDirective = syntaxGenerator.AliasImportDeclaration(typeName, symbol); var newRoot = addImportService.AddImport(semanticModel, root, diagnosticNode, aliasDirective, syntaxGenerator, placementOption, cancellationToken); - return document.WithSyntaxRoot(newRoot); + return Task.FromResult(document.WithSyntaxRoot(newRoot)); }, title)); } diff --git a/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs index 744602ebb1c6d..9bf189a0dcdf0 100644 --- a/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ConvertToAsync/AbstractConvertToAsyncCodeFixProvider.cs @@ -61,7 +61,7 @@ private static bool TryGetNode( var title = await GetDescriptionAsync(diagnostic, node, semanticModel, cancellationToken).ConfigureAwait(false); return CodeAction.Create( title, - async token => otherDocument.WithSyntaxRoot(newRoot), + token => Task.FromResult(otherDocument.WithSyntaxRoot(newRoot)), title); } } diff --git a/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs index ad7752ceff8bf..8dd9ef89348a6 100644 --- a/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ConvertTypeOfToNameOf/AbstractConvertTypeOfToNameOfCodeFixProvider.cs @@ -24,10 +24,11 @@ internal abstract class AbstractConvertTypeOfToNameOfCodeFixProvider< public sealed override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConvertTypeOfToNameOfDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var title = GetCodeFixTitle(); RegisterCodeFix(context, title, title); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs index cb67623808adf..07605e3783cdf 100644 --- a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs @@ -27,7 +27,7 @@ internal abstract class AbstractFileHeaderCodeFixProvider : CodeFixProvider public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.FileHeaderMismatch]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -38,6 +38,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) nameof(AbstractFileHeaderCodeFixProvider)), diagnostic); } + + return Task.CompletedTask; } private async Task GetTransformedDocumentAsync(Document document, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs index 1e1cdebd44e31..db699f6212104 100644 --- a/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/ForEachCast/AbstractForEachCastCodeFixProvider.cs @@ -24,12 +24,14 @@ internal abstract class AbstractForEachCastCodeFixProvider FixableDiagnosticIds => [IDEDiagnosticIds.ForEachCastDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.First().Properties.ContainsKey(ForEachCastHelpers.IsFixable)) { RegisterCodeFix(context, AnalyzersResources.Add_explicit_cast, nameof(AbstractForEachCastCodeFixProvider<>)); } + + return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) diff --git a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs index 4614e063cf9c7..04c840a6d90f1 100644 --- a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs @@ -46,7 +46,7 @@ public sealed override ImmutableArray FixableDiagnosticIds protected override CodeActionRequestPriority ComputeRequestPriority() => CodeActionRequestPriority.High; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -63,6 +63,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix(codeAction, diagnostic); } + + return Task.CompletedTask; } private async Task FixOneAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs index e980fed0db02e..959c63b9c913e 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateConversionService.State.cs @@ -30,7 +30,7 @@ public static async Task GenerateConversionStateAsync( return state; } - private async ValueTask TryInitializeConversionAsync( + private Task TryInitializeConversionAsync( TService service, SemanticDocument document, SyntaxNode node, @@ -40,18 +40,18 @@ private async ValueTask TryInitializeConversionAsync( { if (!TryInitializeImplicitConversion(service, document, node, cancellationToken)) { - return false; + return SpecializedTasks.False; } } else if (service.IsExplicitConversionGeneration(node)) { if (!TryInitializeExplicitConversion(service, document, node, cancellationToken)) { - return false; + return SpecializedTasks.False; } } - return await TryFinishInitializingStateAsync(service, document, cancellationToken).ConfigureAwait(false); + return TryFinishInitializingStateAsync(service, document, cancellationToken); } private bool TryInitializeExplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs index b4f213ae211fe..5e252f1496c75 100644 --- a/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs +++ b/src/Analyzers/Core/CodeFixes/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs @@ -37,7 +37,7 @@ public static async Task GenerateMethodStateAsync( return state; } - private async Task TryInitializeMethodAsync( + private Task TryInitializeMethodAsync( TService service, SemanticDocument document, SyntaxNode node, @@ -62,18 +62,18 @@ private async Task TryInitializeMethodAsync( { if (!TryInitializeExplicitInterface(service, document, node, cancellationToken)) { - return false; + return SpecializedTasks.False; } } else if (service.IsSimpleNameGeneration(node)) { if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { - return false; + return SpecializedTasks.False; } } - return await TryFinishInitializingStateAsync(service, document, cancellationToken).ConfigureAwait(false); + return TryFinishInitializingStateAsync(service, document, cancellationToken); } private bool TryInitializeExplicitInterface( diff --git a/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs index 13f70eaefdd2e..092139a4ba4a8 100644 --- a/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeFieldReadonly/AbstractMakeFieldReadonlyCodeFixProvider.cs @@ -28,9 +28,10 @@ public override ImmutableArray FixableDiagnosticIds protected abstract SyntaxNode? GetInitializerNode(TSymbolSyntax declaration); protected abstract ImmutableList GetVariableDeclarators(TFieldDeclarationSyntax declaration); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Add_readonly_modifier, nameof(AnalyzersResources.Add_readonly_modifier)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs index 8d32d65b4ed11..4dfca14b6c208 100644 --- a/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs @@ -16,16 +16,18 @@ internal abstract class AbstractMakeMemberStaticCodeFixProvider : SyntaxEditorBa { protected abstract bool TryGetMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? memberDeclaration); - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.Length == 1 && TryGetMemberDeclaration(context.Diagnostics[0].Location.FindNode(context.CancellationToken), out _)) { RegisterCodeFix(context, CodeFixesResources.Make_member_static, nameof(AbstractMakeMemberStaticCodeFixProvider)); } + + return Task.CompletedTask; } - protected sealed override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, + protected sealed override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { for (var i = 0; i < diagnostics.Length; i++) @@ -39,5 +41,7 @@ protected sealed override async Task FixAllAsync(Document document, ImmutableArr editor.ReplaceNode(declaration, newNode); } } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs index 2ac4264ee72c3..59272426c5d3a 100644 --- a/src/Analyzers/Core/CodeFixes/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs @@ -26,7 +26,7 @@ internal abstract class AbstractMakeMethodSynchronousCodeFixProvider : CodeFixPr public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var diagnostic = context.Diagnostics.First(); @@ -42,6 +42,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) nameof(CodeFixesResources.Make_method_synchronous)), context.Diagnostics); } + + return Task.CompletedTask; } private const string AsyncSuffix = "Async"; diff --git a/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs index d7be70bac2f24..024c04392cf5e 100644 --- a/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeTypeAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs @@ -17,15 +17,17 @@ internal abstract class AbstractMakeTypeAbstractCodeFixProvider diagnostics, SyntaxEditor editor, + protected sealed override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { for (var i = 0; i < diagnostics.Length; i++) @@ -36,5 +38,7 @@ protected sealed override async Task FixAllAsync(Document document, ImmutableArr (currentTypeDeclaration, generator) => generator.WithModifiers(currentTypeDeclaration, generator.GetModifiers(currentTypeDeclaration).WithIsAbstract(true))); } } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs index a89eb9789ddf7..7460dff1673ce 100644 --- a/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MakeTypePartial/AbstractMakeTypePartialCodeFixProvider.cs @@ -15,9 +15,10 @@ namespace Microsoft.CodeAnalysis.MakeTypePartial; internal abstract class AbstractMakeTypePartialCodeFixProvider() : SyntaxEditorBasedCodeFixProvider(supportsFixAll: false) { - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CodeFixesResources.Make_type_partial, nameof(CodeFixesResources.Make_type_partial)); + return Task.CompletedTask; } protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs index ce45c5066c963..25f7c018648d6 100644 --- a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs @@ -22,7 +22,7 @@ internal abstract partial class AbstractChangeNamespaceToMatchFolderCodeFixProvi { public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var service = context.Document.Project.Solution.Services.GetRequiredService(); if (service.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo)) @@ -35,6 +35,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) nameof(AnalyzersResources.Change_namespace_to_match_folder_structure)), context.Diagnostics); } + + return Task.CompletedTask; } private static async Task FixAllInDocumentAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs index 25cb8536c45b7..b79c4bc2147e8 100644 --- a/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs @@ -26,7 +26,7 @@ internal sealed class ConsecutiveStatementPlacementCodeFixProvider() : CodeFixPr public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.ConsecutiveStatementPlacementDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -35,6 +35,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, diagnostic, c), nameof(CodeFixesResources.Add_blank_line_after_block)), context.Diagnostics); + return Task.CompletedTask; } private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs index 009bcf10ff16a..282b5aac5e27b 100644 --- a/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.cs @@ -26,7 +26,7 @@ internal sealed class MultipleBlankLinesCodeFixProvider() : CodeFixProvider public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.MultipleBlankLinesDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); @@ -35,6 +35,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) c => UpdateDocumentAsync(document, diagnostic, c), nameof(CodeFixesResources.Remove_extra_blank_lines)), context.Diagnostics); + return Task.CompletedTask; } private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs index e671cfe1c1a79..a39f26bbbfa16 100644 --- a/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/PopulateSwitch/AbstractPopulateSwitchCodeFixProvider.cs @@ -47,7 +47,7 @@ protected abstract void FixOneDiagnostic( bool hasMissingCases, bool hasMissingDefaultCase, TSwitchSyntax switchNode, TSwitchOperation switchOperation); - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var properties = diagnostic.Properties; @@ -92,6 +92,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) nameof(CodeFixesResources.Add_both)), context.Diagnostics); } + + return Task.CompletedTask; } private Task FixAsync( diff --git a/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs index 0cd18c1d0d76a..1c7d70e0c4d0e 100644 --- a/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/QualifyMemberAccess/AbstractQualifyMemberAccessCodeFixProvider.cs @@ -23,13 +23,14 @@ internal abstract class AbstractQualifyMemberAccessCodeFixprovider FixableDiagnosticIds => [IDEDiagnosticIds.AddThisOrMeQualificationDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var title = GetTitle(); RegisterCodeFix(context, title, title); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -49,5 +50,7 @@ protected override async Task FixAllAsync( editor.ReplaceNode(node, qualifiedAccess); } } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs index 6cbe099f21e0e..61d48f8bc0827 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs @@ -27,7 +27,7 @@ public sealed override ImmutableArray FixableDiagnosticIds protected override CodeActionCleanup Cleanup => CodeActionCleanup.None; #endif - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var title = GetTitle(); context.RegisterCodeFix( @@ -39,6 +39,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) // code action is preferred over virtually any others that could be located at that position. priority: CodeActionPriority.High), context.Diagnostics); + return Task.CompletedTask; } private static Task RemoveUnnecessaryImportsAsync( diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs index f36c23625649e..41407b1e686b0 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.cs @@ -23,9 +23,10 @@ public override ImmutableArray FixableDiagnosticIds protected abstract bool CanRemoveParentheses( TParenthesizedExpressionSyntax current, SemanticModel semanticModel, CancellationToken cancellationToken); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Remove_unnecessary_parentheses, nameof(AnalyzersResources.Remove_unnecessary_parentheses)); + return Task.CompletedTask; } protected override Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs index 93c9143116fea..df44ed978de39 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryAttributeSuppressionsCodeFixProvider.cs @@ -36,12 +36,14 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var node = editor.OriginalRoot.FindNode(diagnostic.Location.SourceSpan); editor.RemoveNode(node); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs index 20cb1e704ca96..fcb86a7ac9f86 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs @@ -42,7 +42,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // We need to track unique set of processed nodes when removing the nodes. // This is because we generate an unnecessary pragma suppression diagnostic at both the pragma disable and matching pragma restore location @@ -61,7 +61,7 @@ protected override async Task FixAllAsync(Document document, ImmutableArray FixableDiagnosticIds /// protected abstract void AdjustAndAddAppropriateDeclaratorsToRemove(HashSet fieldDeclarators, HashSet declarators); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Remove_unused_member, nameof(AnalyzersResources.Remove_unused_member)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs index 50ed0e34b3dd9..129a02507c1e6 100644 --- a/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs @@ -26,9 +26,10 @@ internal sealed class SimplifyConditionalCodeFixProvider() : SyntaxEditorBasedCo public sealed override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.SimplifyConditionalExpressionDiagnosticId]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_conditional_expression, nameof(AnalyzersResources.Simplify_conditional_expression)); + return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs index 15b585fce129d..88f5603c5e898 100644 --- a/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs @@ -37,9 +37,10 @@ internal abstract class AbstractSimplifyInterpolationCodeFixProvider< protected abstract TInterpolationSyntax WithFormatClause(TInterpolationSyntax interpolation, TInterpolationFormatClause? formatClause); protected abstract string Escape(TInterpolatedStringExpressionSyntax interpolatedString, string formatString); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_interpolation, nameof(AnalyzersResources.Simplify_interpolation)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs index 07223b269cd8c..d75e75c4921c7 100644 --- a/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/SimplifyLinqExpression/SimplifyLinqExpressionCodeFixProvider.cs @@ -24,12 +24,13 @@ internal sealed class SimplifyLinqExpressionCodeFixProvider() : SyntaxEditorBase public sealed override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.SimplifyLinqExpressionDiagnosticId]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Simplify_LINQ_expression, nameof(AnalyzersResources.Simplify_LINQ_expression)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, @@ -65,5 +66,7 @@ protected override async Task FixAllAsync( return innerInvocationExpression.ReplaceNode(innerName, outerName.WithTriviaFrom(innerName)).WithTrailingTrivia(current.GetTrailingTrivia()); }); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs index 9501336e1a081..1770445ee3502 100644 --- a/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UpdateLegacySuppressions/UpdateLegacySuppressionsCodeFixProvider.cs @@ -37,7 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) + protected override Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { @@ -45,5 +45,7 @@ protected override async Task FixAllAsync(Document document, ImmutableArray GetUpgradeProjectCodeActions(CodeFixContext context) @@ -55,7 +56,7 @@ protected ImmutableArray GetUpgradeProjectCodeActions(CodeFixContext var fixOneProjectTitle = string.Format(UpgradeThisProjectResource, newVersion); var fixOneProject = ProjectOptionsChangeAction.Create(fixOneProjectTitle, - async _ => UpgradeProject(project, newVersion)); + _ => Task.FromResult(UpgradeProject(project, newVersion))); result.Add(fixOneProject); @@ -64,7 +65,7 @@ protected ImmutableArray GetUpgradeProjectCodeActions(CodeFixContext var fixAllProjectsTitle = string.Format(UpgradeAllProjectsResource, newVersion); var fixAllProjects = ProjectOptionsChangeAction.Create(fixAllProjectsTitle, - async ct => UpgradeAllProjects(solution, language, newVersion, ct)); + ct => Task.FromResult(UpgradeAllProjects(solution, language, newVersion, ct))); result.Add(fixAllProjects); } @@ -110,8 +111,8 @@ private ProjectOptionsChangeAction(string title, Func> createChangedSolution) => new(title, createChangedSolution); - protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) - => []; + protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + => SpecializedTasks.EmptyEnumerable(); protected override async Task GetChangedSolutionAsync(CancellationToken cancellationToken) => await _createChangedSolution(cancellationToken).ConfigureAwait(false); @@ -131,8 +132,8 @@ private ProjectOptionsChangeAction(string title, Func, CancellationToken, Task> createChangedSolution) => new(title, createChangedSolution); - protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) - => []; + protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + => SpecializedTasks.EmptyEnumerable(); } #endif diff --git a/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs index 9fe40519093af..0ed1c2ac62ce2 100644 --- a/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs @@ -80,7 +80,7 @@ protected abstract Task UpdatePropertyAsync( bool isTrivialSetAccessor, CancellationToken cancellationToken); - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var solution = context.Document.Project.Solution; @@ -97,6 +97,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) priority), diagnostic); } + + return Task.CompletedTask; } private async Task ProcessResultAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs b/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs index 5fd4cf91167d8..092e4c68cef62 100644 --- a/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseAutoProperty/UseAutoPropertyFixAllProvider.cs @@ -27,11 +27,11 @@ private sealed class UseAutoPropertyFixAllProvider(TProvider provider) : FixAllP { #if CODE_STYLE - public override async Task GetFixAsync(FixAllContext fixAllContext) + public override Task GetFixAsync(FixAllContext fixAllContext) { - return CodeAction.Create( + return Task.FromResult(CodeAction.Create( fixAllContext.GetDefaultFixAllTitle(), - cancellationToken => FixAllAsync(fixAllContext, cancellationToken)); + cancellationToken => FixAllAsync(fixAllContext, cancellationToken))); } private async Task FixAllAsync(FixAllContext fixAllContext, CancellationToken cancellationToken) diff --git a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs index af540d7bf7a1e..6c11e4cfffccb 100644 --- a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/AbstractUseCoalesceExpressionForIfNullStatementCheckCodeFixProvider.cs @@ -18,9 +18,10 @@ internal abstract class AbstractUseCoalesceExpressionForIfNullStatementCheckCode public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseCoalesceExpressionForIfNullCheckDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); + return Task.CompletedTask; } protected virtual ITypeSymbol? TryGetExplicitCast( diff --git a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs index 27e935b36a486..3e3a0eecc8621 100644 --- a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableTernaryConditionalCheckCodeFixProvider.cs @@ -27,9 +27,10 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs index 301cf4f60f597..2334bc175a664 100644 --- a/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForTernaryConditionalCheckCodeFixProvider.cs @@ -28,9 +28,10 @@ public override ImmutableArray FixableDiagnosticIds protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_coalesce_expression, nameof(AnalyzersResources.Use_coalesce_expression)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs index d66b0fdb0b127..a5ae0ef3a13e9 100644 --- a/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs @@ -41,12 +41,13 @@ protected abstract TAssignmentSyntax Assignment( protected abstract TExpressionSyntax Decrement(TExpressionSyntax left, bool postfix); protected abstract SyntaxTriviaList PrepareRightExpressionLeadingTrivia(SyntaxTriviaList initialTrivia); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_compound_assignment, nameof(AnalyzersResources.Use_compound_assignment)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -90,6 +91,8 @@ protected override async Task FixAllAsync( (TExpressionSyntax)rightExpr); }); } + + return Task.CompletedTask; } protected virtual bool PreferPostfix(ISyntaxFactsService syntaxFacts, TAssignmentSyntax currentAssignment) diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs index 9280a7d13e982..5d492d9355e9b 100644 --- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs @@ -40,13 +40,14 @@ internal abstract class AbstractUseConditionalExpressionForAssignmentCodeFixProv public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseConditionalExpressionForAssignmentDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var (title, key) = context.Diagnostics.First().Properties.ContainsKey(UseConditionalExpressionHelpers.CanSimplifyName) ? (AnalyzersResources.Simplify_check, nameof(AnalyzersResources.Simplify_check)) : (AnalyzersResources.Convert_to_conditional_expression, nameof(AnalyzersResources.Convert_to_conditional_expression)); RegisterCodeFix(context, title, key); + return Task.CompletedTask; } /// diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs index 1f0f55239374f..3d1cc7843dd7b 100644 --- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs @@ -31,13 +31,14 @@ internal abstract class AbstractUseConditionalExpressionForReturnCodeFixProvider public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var (title, key) = context.Diagnostics.First().Properties.ContainsKey(UseConditionalExpressionHelpers.CanSimplifyName) ? (AnalyzersResources.Simplify_check, nameof(AnalyzersResources.Simplify_check)) : (AnalyzersResources.Convert_to_conditional_expression, nameof(AnalyzersResources.Convert_to_conditional_expression)); RegisterCodeFix(context, title, key); + return Task.CompletedTask; } protected override async Task FixOneAsync( diff --git a/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs index 8379ee12addf7..6d57a354baa1b 100644 --- a/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseExplicitTupleName/UseExplicitTupleNameCodeFixProvider.cs @@ -23,12 +23,13 @@ internal sealed partial class UseExplicitTupleNameCodeFixProvider() : SyntaxEdit public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseExplicitTupleNameDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_explicitly_provided_tuple_name, nameof(AnalyzersResources.Use_explicitly_provided_tuple_name)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -46,5 +47,7 @@ protected override async Task FixAllAsync( editor.ReplaceNode(oldNameNode, newNameNode); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs index dd6c9b0a273bd..8d95c70a6f730 100644 --- a/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs @@ -18,12 +18,13 @@ internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEdi public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseInferredMemberNameDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_inferred_member_name, nameof(AnalyzersResources.Use_inferred_member_name)); + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -34,5 +35,7 @@ protected override async Task FixAllAsync( var node = root.FindNode(diagnostic.Location.SourceSpan); LanguageSpecificRemoveSuggestedNode(editor, node); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs index 6bbcb601ed4b3..5ccde3abcabc1 100644 --- a/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs @@ -31,7 +31,7 @@ public override ImmutableArray FixableDiagnosticIds private static bool IsSupportedDiagnostic(Diagnostic diagnostic) => diagnostic.Properties[UseIsNullConstants.Kind] == UseIsNullConstants.ReferenceEqualsKey; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); if (IsSupportedDiagnostic(diagnostic)) @@ -40,9 +40,11 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) var title = GetTitle(negated, diagnostic.Location.SourceTree!.Options); RegisterCodeFix(context, title, title); } + + return Task.CompletedTask; } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { @@ -74,5 +76,7 @@ protected override async Task FixAllAsync( toReplace, replacement.WithTriviaFrom(toReplace)); } + + return Task.CompletedTask; } } diff --git a/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs index 53a7aaf02ec19..9ddd4ddfb27f0 100644 --- a/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs @@ -25,9 +25,10 @@ internal sealed class UseSystemHashCodeCodeFixProvider() : SyntaxEditorBasedCode public override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.UseSystemHashCode]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, AnalyzersResources.Use_System_HashCode, nameof(AnalyzersResources.Use_System_HashCode)); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs b/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs index d4b0e304231d0..ce65cec44f0f4 100644 --- a/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs +++ b/src/EditorFeatures/CSharp/EndConstruct/CSharpEndConstructGenerationService.cs @@ -21,6 +21,6 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.EndConstructGeneration; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class CSharpEndConstructGenerationService() : IEndConstructGenerationService { - public async Task TryDoAsync(ITextView textView, ITextBuffer subjectBuffer, char typedChar, CancellationToken cancellationToken) - => false; + public Task TryDoAsync(ITextView textView, ITextBuffer subjectBuffer, char typedChar, CancellationToken cancellationToken) + => SpecializedTasks.False; } diff --git a/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs b/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs index b81b4b633dcde..fd247d02858f6 100644 --- a/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs +++ b/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs @@ -73,7 +73,7 @@ public bool SupportsFormattingOnTypedCharacter(Document document, char ch) return s_supportedChars.IndexOf(ch) >= 0; } - public async Task> GetFormattingChangesAsync( + public Task> GetFormattingChangesAsync( Document document, ITextBuffer textBuffer, TextSpan? textSpan, @@ -85,21 +85,21 @@ public async Task> GetFormattingChangesAsync( var span = textSpan ?? new TextSpan(0, parsedDocument.Root.FullSpan.Length); var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(parsedDocument.Root, span); - return Formatter.GetFormattedTextChanges(parsedDocument.Root, [formattingSpan], document.Project.Solution.Services, options, cancellationToken).ToImmutableArray(); + return Task.FromResult(Formatter.GetFormattedTextChanges(parsedDocument.Root, [formattingSpan], document.Project.Solution.Services, options, cancellationToken).ToImmutableArray()); } - public async Task> GetFormattingChangesOnPasteAsync(Document document, ITextBuffer textBuffer, TextSpan textSpan, CancellationToken cancellationToken) + public Task> GetFormattingChangesOnPasteAsync(Document document, ITextBuffer textBuffer, TextSpan textSpan, CancellationToken cancellationToken) { var parsedDocument = ParsedDocument.CreateSynchronously(document, cancellationToken); var options = textBuffer.GetSyntaxFormattingOptions(_editorOptionsService, document.Project.GetFallbackAnalyzerOptions(), parsedDocument.LanguageServices, explicitFormat: true); var service = parsedDocument.LanguageServices.GetRequiredService(); - return service.GetFormattingChangesOnPaste(parsedDocument, textSpan, options, cancellationToken); + return Task.FromResult(service.GetFormattingChangesOnPaste(parsedDocument, textSpan, options, cancellationToken)); } - public async Task> GetFormattingChangesOnReturnAsync(Document document, int caretPosition, CancellationToken cancellationToken) - => []; + public Task> GetFormattingChangesOnReturnAsync(Document document, int caretPosition, CancellationToken cancellationToken) + => SpecializedTasks.EmptyImmutableArray(); - public async Task> GetFormattingChangesAsync(Document document, ITextBuffer textBuffer, char typedChar, int position, CancellationToken cancellationToken) + public Task> GetFormattingChangesAsync(Document document, ITextBuffer textBuffer, char typedChar, int position, CancellationToken cancellationToken) { var parsedDocument = ParsedDocument.CreateSynchronously(document, cancellationToken); var service = parsedDocument.LanguageServices.GetRequiredService(); @@ -107,9 +107,9 @@ public async Task> GetFormattingChangesAsync(Document if (service.ShouldFormatOnTypedCharacter(parsedDocument, typedChar, position, cancellationToken)) { var indentationOptions = textBuffer.GetIndentationOptions(_editorOptionsService, document.Project.GetFallbackAnalyzerOptions(), parsedDocument.LanguageServices, explicitFormat: false); - return service.GetFormattingChangesOnTypedCharacter(parsedDocument, position, indentationOptions, cancellationToken); + return Task.FromResult(service.GetFormattingChangesOnTypedCharacter(parsedDocument, position, indentationOptions, cancellationToken)); } - return []; + return SpecializedTasks.EmptyImmutableArray(); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs index 286adec7ccaf1..eef6fe5e746ba 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/AddUsing/AddUsingNuGetTests.cs @@ -62,7 +62,7 @@ public async Task TestSearchPackageCustomFeedName() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -99,7 +99,7 @@ public async Task TestSearchPackageFakeNugetFeed() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync( "nuget.org", new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -134,7 +134,7 @@ public async Task TestSearchPackageSingleName() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -169,7 +169,7 @@ public async Task TestSearchPackageMultipleNames() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); @@ -202,7 +202,7 @@ public async Task TestMissingIfPackageAlreadyInstalled() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); @@ -230,7 +230,7 @@ public async Task TestOptionsOffered() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); @@ -280,7 +280,7 @@ public async Task TestInstallGetsCalledNoVersion() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync( PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -318,7 +318,7 @@ public async Task TestInstallGetsCalledWithVersion() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync(PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -355,7 +355,7 @@ public async Task TestFailedInstallRollsBackFile() var packageServiceMock = new Mock(MockBehavior.Strict); packageServiceMock.Setup(s => s.FindReferenceAssembliesAsync(new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) - .Returns(async () => ImmutableArray.Empty); + .Returns(() => ValueTask.FromResult(ImmutableArray.Empty)); packageServiceMock.Setup(s => s.FindPackagesAsync(PackageSourceHelper.NugetOrgSourceName, new TypeQuery("NuGetType", 0), It.IsAny(), It.IsAny())) .Returns(() => CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); @@ -383,8 +383,8 @@ private static ValueTask> CreateSearchResult( version: null, containingNamespaceNames: containingNamespaceNames)); } - private static async ValueTask> CreateSearchResult(params PackageResult[] results) - => [.. results]; + private static ValueTask> CreateSearchResult(params PackageResult[] results) + => new(ImmutableArray.Create(results)); private static ImmutableArray CreateNameParts(params string[] parts) => [.. parts]; diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs index 2eb2efeb5e28f..db111a0b9322f 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ApplyChangesOperationTests.cs @@ -31,10 +31,11 @@ public MyCodeRefactoringProvider(Func changeSolution) _changeSolution = changeSolution; } - public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new TestCodeAction(_changeSolution(context.Document.Project.Solution)); context.RegisterRefactoring(codeAction); + return Task.CompletedTask; } private sealed class TestCodeAction : CodeAction @@ -48,8 +49,8 @@ public TestCodeAction(Solution changedSolution) public override string Title => "Title"; - protected override async Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) - => _changedSolution; + protected override Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) + => Task.FromResult(_changedSolution); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs index 2a02bc32afa2a..690a27ad8c479 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs @@ -38,7 +38,7 @@ private sealed class TestWithDialog : VerifyCS.Test public ImmutableArray MemberNames; public Action> OptionsCallback; - protected override async Task CreateWorkspaceImplAsync() + protected override Task CreateWorkspaceImplAsync() { // If we're a dialog test, then mixin our mock and initialize its values to the ones the test asked for. var workspace = new AdhocWorkspace(s_composition.GetHostServices()); @@ -47,7 +47,7 @@ protected override async Task CreateWorkspaceImplAsync() service.MemberNames = MemberNames; service.OptionsCallback = OptionsCallback; - return workspace; + return Task.FromResult(workspace); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs index 6f2eaf92221ce..d199c6cc666c3 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveStaticMembers/CSharpMoveStaticMembersTests.cs @@ -3436,7 +3436,7 @@ public Test( private readonly bool _testPreselection; - protected override async Task CreateWorkspaceImplAsync() + protected override Task CreateWorkspaceImplAsync() { var hostServices = s_testServices.GetHostServices(); @@ -3448,7 +3448,7 @@ protected override async Task CreateWorkspaceImplAsync() testOptionsService.CreateNew = _createNew; testOptionsService.ExpectedPrecheckedMembers = _testPreselection ? _selection : []; - return workspace; + return Task.FromResult(workspace); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs b/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs index 4c4a8e6a56543..4735afa7e4963 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs @@ -15,9 +15,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ErrorC internal sealed class ExceptionInCodeAction : CodeRefactoringProvider { - public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(new ExceptionCodeAction(), context.Span); + return Task.CompletedTask; } internal sealed class ExceptionCodeAction : CodeAction diff --git a/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs index 33fd873760721..abb67d2e918a3 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/PreviewTests.cs @@ -42,10 +42,11 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(EditorT private sealed class MyCodeRefactoringProvider : CodeRefactoringProvider { - public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new TestCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); + return Task.CompletedTask; } private sealed class TestCodeAction : CodeAction @@ -63,7 +64,7 @@ public override string Title } } - protected override async Task GetChangedSolutionAsync( + protected override Task GetChangedSolutionAsync( IProgress progress, CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; @@ -82,7 +83,7 @@ protected override async Task GetChangedSolutionAsync( // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); - return solution; + return Task.FromResult(solution); } } } diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs index 5728825f7001e..413bd4b1f4caa 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/FixAllProvider/BatchFixerTests.cs @@ -85,7 +85,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) // Disable RS0005 as this is test code and we don't need telemetry for created code action. #pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction - var fix = CodeAction.Create("QualifyWithThisFix", async _ => newDocument); + var fix = CodeAction.Create("QualifyWithThisFix", _ => Task.FromResult(newDocument)); #pragma warning restore RS0005 // Do not use generic CodeAction.Create to create CodeAction context.RegisterCodeFix(fix, context.Diagnostics); diff --git a/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs b/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs index 71d5a8952f6af..0d7d65adc6574 100644 --- a/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs +++ b/src/EditorFeatures/CSharpTest/EventHookup/MockSuggestionService.cs @@ -21,10 +21,10 @@ internal sealed class MockSuggestionService() : SuggestionServiceBase { public bool WasDismissAndBlockCalled { get; private set; } - public override async Task DismissAndBlockProposalsAsync(ITextView textView, ReasonForDismiss reason, CancellationToken cancellationToken) + public override Task DismissAndBlockProposalsAsync(ITextView textView, ReasonForDismiss reason, CancellationToken cancellationToken) { WasDismissAndBlockCalled = true; - return new AsyncDisposableStub(); + return Task.FromResult(new AsyncDisposableStub()); } public override Task TryRegisterProviderAsync(SuggestionProviderBase provider, ITextView view, string name, CancellationToken cancel) diff --git a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs index 0107c0322d2d7..5a21a33eee9cf 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.TestFixers.cs @@ -20,7 +20,7 @@ private abstract class TestThirdPartyCodeFix : CodeFixProvider { public override ImmutableArray FixableDiagnosticIds { get; } = ["HasDefaultCase"]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -42,6 +42,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) nameof(TestThirdPartyCodeFix)), diagnostic); } + + return Task.CompletedTask; } } @@ -80,10 +82,10 @@ public TestThirdPartyCodeFixModifiesSolution() private sealed class ModifySolutionFixAll : FixAllProvider { - public override async Task GetFixAsync(FixAllContext fixAllContext) + public override Task GetFixAsync(FixAllContext fixAllContext) { var solution = fixAllContext.Solution; - return CodeAction.Create( + return Task.FromResult(CodeAction.Create( "Remove default case", async cancellationToken => { @@ -113,7 +115,7 @@ private sealed class ModifySolutionFixAll : FixAllProvider Assumes.NotNull(project); return solution.AddDocument(DocumentId.CreateNewId(project.Id), "new.cs", SourceText.From("")); }, - nameof(TestThirdPartyCodeFix)); + nameof(TestThirdPartyCodeFix))); } } } @@ -130,10 +132,10 @@ private sealed class ModifySolutionFixAll : FixAllProvider public override IEnumerable GetSupportedFixAllScopes() => [FixAllScope.Project, FixAllScope.Solution, FixAllScope.Custom]; - public override async Task GetFixAsync(FixAllContext fixAllContext) + public override Task GetFixAsync(FixAllContext fixAllContext) { var solution = fixAllContext.Solution; - return CodeAction.Create( + return Task.FromResult(CodeAction.Create( "Remove default case", async cancellationToken => { @@ -163,7 +165,7 @@ public override IEnumerable GetSupportedFixAllScopes() Assumes.NotNull(project); return solution.AddDocument(DocumentId.CreateNewId(project.Id), "new.cs", SourceText.From("")); }, - nameof(TestThirdPartyCodeFix)); + nameof(TestThirdPartyCodeFix))); } } } diff --git a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs index 154d6eb5b6ecf..a92871a7b18c4 100644 --- a/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs +++ b/src/EditorFeatures/CSharpTest/NavigateTo/NavigateToSearcherTests.cs @@ -113,8 +113,8 @@ private static void SetupSearchProject( } } - private static async ValueTask IsFullyLoadedAsync(bool projectSystem, bool remoteHost) - => projectSystem && remoteHost; + private static ValueTask IsFullyLoadedAsync(bool projectSystem, bool remoteHost) + => new(projectSystem && remoteHost); [Fact] public async Task NotFullyLoadedOnlyMakesOneSearchProjectCallIfValueReturned() @@ -274,7 +274,7 @@ public async Task DoNotCrashWithoutSearchService() var results = ImmutableArray.Create(new TestNavigateToSearchResult(workspace, new TextSpan(0, 0))); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); // Ensure that returning null for the search service doesn't crash. hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny())).Returns(() => null); @@ -322,7 +322,7 @@ public class D var results = ImmutableArray.Create(new TestNavigateToSearchResult(workspace, new TextSpan(0, 0))); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); var searchGeneratedDocumentsAsyncCalled = false; var searchService = new MockAdvancedNavigateToSearchService @@ -386,7 +386,7 @@ void Goo3() { } """, composition: FirstActiveAndVisibleComposition); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); var project = workspace.CurrentSolution.Projects.Single(); var searchService = project.GetRequiredLanguageService(); @@ -446,7 +446,7 @@ void Goo3() { } """, composition: FirstActiveAndVisibleComposition); var hostMock = new Mock(MockBehavior.Strict); - hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(async () => true); + hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny())).Returns(() => new ValueTask(true)); var project = workspace.CurrentSolution.Projects.Single(); var searchService = project.GetRequiredLanguageService(); @@ -488,10 +488,12 @@ public void ReportIncomplete() { } - public async Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) + public Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) { foreach (var result in results) this.Results.Add(result); + + return Task.CompletedTask; } public void ReportProgress(int current, int maximum) @@ -510,24 +512,28 @@ private sealed class MockAdvancedNavigateToSearchService : IAdvancedNavigateToSe public Action? OnSearchGeneratedDocumentsAsyncCalled { get; set; } public Action? OnSearchProjectsAsyncCalled { get; set; } - public async Task SearchCachedDocumentsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) + public Task SearchCachedDocumentsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) { OnSearchCachedDocumentsAsyncCalled?.Invoke(); + return Task.CompletedTask; } - public async Task SearchDocumentAsync(Document document, string searchPattern, IImmutableSet kinds, Func, Task> onResultsFound, CancellationToken cancellationToken) + public Task SearchDocumentAsync(Document document, string searchPattern, IImmutableSet kinds, Func, Task> onResultsFound, CancellationToken cancellationToken) { OnSearchDocumentsAsyncCalled?.Invoke(); + return Task.CompletedTask; } - public async Task SearchGeneratedDocumentsAsync(Solution solution, ImmutableArray projects, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) + public Task SearchGeneratedDocumentsAsync(Solution solution, ImmutableArray projects, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) { OnSearchGeneratedDocumentsAsyncCalled?.Invoke(); + return Task.CompletedTask; } - public async Task SearchProjectsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) + public Task SearchProjectsAsync(Solution solution, ImmutableArray projects, ImmutableArray priorityDocuments, string searchPattern, IImmutableSet kinds, Document? activeDocument, Func, Task> onResultsFound, Func onProjectCompleted, CancellationToken cancellationToken) { OnSearchProjectsAsyncCalled?.Invoke(); + return Task.CompletedTask; } } diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs index 8f54a1c7a225b..92d85bb06302a 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/NullResultMetadataAsSourceFileProvider.cs @@ -37,9 +37,9 @@ public void CleanupGeneratedFiles(MetadataAsSourceWorkspace workspace) { } - public async Task GetGeneratedFileAsync(MetadataAsSourceWorkspace metadataWorkspace, Workspace sourceWorkspace, Project sourceProject, ISymbol symbol, bool signaturesOnly, MetadataAsSourceOptions options, string tempPath, TelemetryMessage? telemetry, CancellationToken cancellationToken) + public Task GetGeneratedFileAsync(MetadataAsSourceWorkspace metadataWorkspace, Workspace sourceWorkspace, Project sourceProject, ISymbol symbol, bool signaturesOnly, MetadataAsSourceOptions options, string tempPath, TelemetryMessage? telemetry, CancellationToken cancellationToken) { - return NullResult; + return Task.FromResult(NullResult); } public Project? MapDocument(Document document) diff --git a/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs b/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs index efb5c32229790..abb47df12182d 100644 --- a/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs +++ b/src/EditorFeatures/CSharpTest/PdbSourceDocument/TestSourceLinkService.cs @@ -20,23 +20,23 @@ public TestSourceLinkService(string? pdbFilePath = null, string? sourceFilePath _sourceFilePath = sourceFilePath; } - public async Task GetPdbFilePathAsync(string dllPath, PEReader peReader, bool useDefaultSymbolServers, CancellationToken cancellationToken) + public Task GetPdbFilePathAsync(string dllPath, PEReader peReader, bool useDefaultSymbolServers, CancellationToken cancellationToken) { if (_pdbFilePath is null) { - return null; + return Task.FromResult(null); } - return new PdbFilePathResult(_pdbFilePath); + return Task.FromResult(new PdbFilePathResult(_pdbFilePath)); } - public async Task GetSourceFilePathAsync(string url, string relativePath, CancellationToken cancellationToken) + public Task GetSourceFilePathAsync(string url, string relativePath, CancellationToken cancellationToken) { if (_sourceFilePath is null) { - return null; + return Task.FromResult(null); } - return new SourceFilePathResult(_sourceFilePath); + return Task.FromResult(new SourceFilePathResult(_sourceFilePath)); } } diff --git a/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs b/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs index 7bb330b3acbbe..f292c41ea66dc 100644 --- a/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs +++ b/src/EditorFeatures/CSharpTest/TaskList/NoCompilationTaskListTests.cs @@ -57,11 +57,11 @@ public NoCompilationTaskListService() { } - public async Task> GetTaskListItemsAsync(Document document, ImmutableArray descriptors, CancellationToken cancellationToken) - => ImmutableArray.Create(new TaskListItem( + public Task> GetTaskListItemsAsync(Document document, ImmutableArray descriptors, CancellationToken cancellationToken) + => Task.FromResult(ImmutableArray.Create(new TaskListItem( descriptors.First().Priority, "Message", document.Id, Span: new FileLinePositionSpan("dummy", new LinePosition(0, 3), new LinePosition(0, 3)), - MappedSpan: new FileLinePositionSpan("dummy", new LinePosition(0, 3), new LinePosition(0, 3)))); + MappedSpan: new FileLinePositionSpan("dummy", new LinePosition(0, 3), new LinePosition(0, 3))))); } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs index 0eb1fd0fa8789..0fa116020e644 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs @@ -20,7 +20,7 @@ public sealed class DynamicKeywordRecommenderTests : RecommenderTests public DynamicKeywordRecommenderTests() { - this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); + this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs index 6a2b889b73ad8..0927c6073aad6 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/KeywordRecommenderTests.cs @@ -50,6 +50,6 @@ protected KeywordRecommenderTests() s_recommenderMap.TryGetValue(kind, out var recommender); Assert.NotNull(recommender); - RecommendKeywordsAsync = async (position, context) => recommender.GetTestAccessor().RecommendKeywords(position, context); + RecommendKeywordsAsync = (position, context) => Task.FromResult(recommender.GetTestAccessor().RecommendKeywords(position, context)); } } diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs index 25f9f88d95f6c..a7bf14de2fbc1 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NativeIntegerKeywordRecommenderTests.cs @@ -18,7 +18,7 @@ public abstract class NativeIntegerKeywordRecommenderTests : RecommenderTests protected NativeIntegerKeywordRecommenderTests() { - RecommendKeywordsAsync = async (position, context) => Recommender.RecommendKeywords(position, context, CancellationToken.None); + RecommendKeywordsAsync = (position, context) => Task.FromResult(Recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs index eb2d73f9fa0e9..7ac5283b2d4e3 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.cs @@ -19,7 +19,7 @@ public sealed class NotNullKeywordRecommenderTests : RecommenderTests public NotNullKeywordRecommenderTests() { - this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); + this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs index c716d86a20d77..fac11b89f108e 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/ScopedKeywordRecommenderTests.cs @@ -17,7 +17,7 @@ public sealed class ScopedKeywordRecommenderTests : RecommenderTests public ScopedKeywordRecommenderTests() { - this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); + this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact] diff --git a/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs b/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs index 325e8fd97efc3..3d34562407077 100644 --- a/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs +++ b/src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs @@ -20,7 +20,7 @@ public sealed class VarKeywordRecommenderTests : RecommenderTests public VarKeywordRecommenderTests() { - this.RecommendKeywordsAsync = async (position, context) => _recommender.RecommendKeywords(position, context, CancellationToken.None); + this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact] diff --git a/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs b/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs index 63147caddd362..4c1e0d851ada9 100644 --- a/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/BraceMatching/BraceHighlightingViewTaggerProvider.cs @@ -43,19 +43,19 @@ protected override ITaggerEventSource CreateEventSource(ITextView textView, ITex TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } - protected override async Task ProduceTagsAsync( + protected override Task ProduceTagsAsync( TaggerContext context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition, CancellationToken cancellationToken) { var document = documentSnapshotSpan.Document; if (!caretPosition.HasValue || document == null) { - return; + return Task.CompletedTask; } var options = GlobalOptions.GetBraceMatchingOptions(document.Project.Language); - await ProduceTagsAsync( - context, document, documentSnapshotSpan.SnapshotSpan.Snapshot, caretPosition.Value, options, cancellationToken).ConfigureAwait(false); + return ProduceTagsAsync( + context, document, documentSnapshotSpan.SnapshotSpan.Snapshot, caretPosition.Value, options, cancellationToken); } internal async Task ProduceTagsAsync( diff --git a/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs b/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs index 5839be0196cb0..c696fe16032f4 100644 --- a/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs +++ b/src/EditorFeatures/Core/Classification/Syntactic/SyntacticClassificationTaggerProvider.TagComputer.cs @@ -244,7 +244,7 @@ static ITextSnapshot GetLatest(ImmutableSegmentedList snapshots) } } - private async ValueTask ComputeChangedRangeAsync( + private ValueTask ComputeChangedRangeAsync( SolutionServices solutionServices, IClassificationService classificationService, Document currentDocument, @@ -254,20 +254,20 @@ static ITextSnapshot GetLatest(ImmutableSegmentedList snapshots) CancellationToken cancellationToken) { if (lastProcessedDocument is null) - return null; + return ValueTask.FromResult(null); if (lastProcessedRoot != null) { // If we have syntax available fast path the change computation without async or blocking. if (currentRoot is not null) - return classificationService.ComputeSyntacticChangeRange(solutionServices, lastProcessedRoot, currentRoot, _diffTimeout, cancellationToken); + return new(classificationService.ComputeSyntacticChangeRange(solutionServices, lastProcessedRoot, currentRoot, _diffTimeout, cancellationToken)); else - return null; + return ValueTask.FromResult(null); } else { // Otherwise, fall back to the language to compute the difference based on the document contents. - return await classificationService.ComputeSyntacticChangeRangeAsync(lastProcessedDocument, currentDocument, _diffTimeout, cancellationToken).ConfigureAwait(false); + return classificationService.ComputeSyntacticChangeRangeAsync(lastProcessedDocument, currentDocument, _diffTimeout, cancellationToken); } } diff --git a/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs b/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs index f47e6a4dee4f5..87528439091fa 100644 --- a/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs +++ b/src/EditorFeatures/Core/Classification/TotalClassificationTaggerProvider.cs @@ -78,17 +78,20 @@ public override void AddTags(NormalizedSnapshotSpanCollection spans, SegmentedLi AddTagsAsync( spans, totalTags, - addSyntacticSpansAsync: static async (spans, tags, arg) => + addSyntacticSpansAsync: static (spans, tags, arg) => { arg.syntacticTagger.AddTags(spans, tags); + return Task.CompletedTask; }, - addSemanticSpansAsync: static async (spans, tags, arg) => + addSemanticSpansAsync: static (spans, tags, arg) => { arg.semanticTagger.AddTags(spans, tags); + return Task.CompletedTask; }, - addEmbeddedSpansAsync: static async (spans, tags, arg) => + addEmbeddedSpansAsync: static (spans, tags, arg) => { arg.embeddedTagger.AddTags(spans, tags); + return Task.CompletedTask; }, (syntacticTagger, semanticTagger, embeddedTagger)).VerifyCompleted(); } diff --git a/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs b/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs index 54a8bd0f99e96..ef3608d79eeea 100644 --- a/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs +++ b/src/EditorFeatures/Core/DocumentationComments/CopilotGenerateDocumentationCommentProvider.cs @@ -343,13 +343,15 @@ static string BuildCopilotTextForRemarks(string copilotText, string? indentText, } } - public override async Task EnabledAsync(CancellationToken cancel) + public override Task EnabledAsync(CancellationToken cancel) { _enabled = true; + return Task.CompletedTask; } - public override async Task DisabledAsync(CancellationToken cancel) + public override Task DisabledAsync(CancellationToken cancel) { _enabled = false; + return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs b/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs index 94d713258b2c5..62fc19c40626d 100644 --- a/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs +++ b/src/EditorFeatures/Core/DocumentationComments/DocumentationCommentSuggestion.cs @@ -41,8 +41,9 @@ public override async Task OnAcceptedAsync(SuggestionSessionBase session, Propos Logger.Log(FunctionId.Copilot_Generate_Documentation_Accepted, logLevel: LogLevel.Information); } - public override async Task OnChangeProposalAsync(SuggestionSessionBase session, ProposalBase originalProposal, ProposalBase currentProposal, bool forward, CancellationToken cancel) + public override Task OnChangeProposalAsync(SuggestionSessionBase session, ProposalBase originalProposal, ProposalBase currentProposal, bool forward, CancellationToken cancel) { + return Task.CompletedTask; } public override async Task OnDismissedAsync(SuggestionSessionBase session, ProposalBase? originalProposal, ProposalBase? currentProposal, ReasonForDismiss reason, CancellationToken cancel) @@ -53,15 +54,17 @@ public override async Task OnDismissedAsync(SuggestionSessionBase session, Propo Logger.Log(FunctionId.Copilot_Generate_Documentation_Dismissed, logLevel: LogLevel.Information); } - public override async Task OnProposalUpdatedAsync(SuggestionSessionBase session, ProposalBase? originalProposal, ProposalBase? currentProposal, ReasonForUpdate reason, VirtualSnapshotPoint caret, CompletionState? completionState, CancellationToken cancel) + public override Task OnProposalUpdatedAsync(SuggestionSessionBase session, ProposalBase? originalProposal, ProposalBase? currentProposal, ReasonForUpdate reason, VirtualSnapshotPoint caret, CompletionState? completionState, CancellationToken cancel) { // Now that we start the Suggestion Session earlier, we will get buffer changes when the '/' is inserted and the // shell of the documentation comment. In that case, we need to make sure we have actually have a proposal to display. if (originalProposal is not null && reason.HasFlag(ReasonForUpdate.Diverged)) { Logger.Log(FunctionId.Copilot_Generate_Documentation_Diverged, logLevel: LogLevel.Information); - await session.DismissAsync(ReasonForDismiss.DismissedAfterBufferChange, cancel).ConfigureAwait(false); + return session.DismissAsync(ReasonForDismiss.DismissedAfterBufferChange, cancel); } + + return Task.CompletedTask; } /// diff --git a/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs b/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs index 50e5083e7bea7..43f78192c4040 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/Aggregator/SettingsAggregator.cs @@ -91,9 +91,10 @@ private void UpdateProviders(WorkspaceChangeEventArgs e) return null; } - private async ValueTask UpdateProvidersAsync(CancellationToken cancellationToken) + private ValueTask UpdateProvidersAsync(CancellationToken cancellationToken) { UpdateProviders(_workspace.CurrentSolution.SolutionState); + return ValueTask.CompletedTask; } [MemberNotNull(nameof(_whitespaceProvider))] diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs index ccfb17bf1576c..61748691b9c3c 100644 --- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs +++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs @@ -31,7 +31,7 @@ public NamingStyleSettingsProvider( Update(); } - protected override async Task UpdateOptionsAsync( + protected override Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { options.GetInitialLocationAndValue(NamingStyleOptions.NamingPreferences, out var location, out var namingPreferences); @@ -41,5 +41,6 @@ protected override async Task UpdateOptionsAsync( var namingStyles = namingPreferences.Rules.NamingRules.Select(namingRule => new NamingStyleSetting(namingRule, allStyles, SettingsUpdater, fileName)); AddRange(namingStyles); + return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs b/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs index a4a5c3edddc8c..cb4b407e8de55 100644 --- a/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs +++ b/src/EditorFeatures/Core/Extensibility/NavigationBar/AbstractEditorNavigationBarItemService.cs @@ -67,7 +67,7 @@ protected async Task NavigateToPositionAsync(Workspace workspace, DocumentId doc } } - internal virtual async Task<(DocumentId documentId, int position, int virtualSpace)> GetNavigationLocationAsync( + internal virtual Task<(DocumentId documentId, int position, int virtualSpace)> GetNavigationLocationAsync( Document document, NavigationBarItem item, SymbolItem symbolItem, @@ -79,7 +79,7 @@ protected async Task NavigateToPositionAsync(Workspace workspace, DocumentId doc // If the item points to a location in this document, then just determine the where that span currently // is (in case recent edits have moved it) and navigate there. var navigationSpan = item.GetCurrentItemSpan(textVersion, symbolItem.Location.InDocumentInfo.Value.navigationSpan); - return (document.Id, navigationSpan.Start, 0); + return Task.FromResult((document.Id, navigationSpan.Start, 0)); } else { @@ -87,7 +87,7 @@ protected async Task NavigateToPositionAsync(Workspace workspace, DocumentId doc // computed and stored for it. Contract.ThrowIfNull(symbolItem.Location.OtherDocumentInfo); var (documentId, span) = symbolItem.Location.OtherDocumentInfo.Value; - return (documentId, span.Start, 0); + return Task.FromResult((documentId, span.Start, 0)); } } diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs index 75a9977f6ce39..06748d0f67d8d 100644 --- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs +++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptEditorInlineRenameService.cs @@ -36,9 +36,9 @@ public bool IsEnabled } } - public async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return ImmutableDictionary>.Empty; + return Task.FromResult(ImmutableDictionary>.Empty); } public async Task GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs index 904f5ddcd2bec..7827777589572 100644 --- a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs +++ b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs @@ -43,7 +43,7 @@ private sealed class FailureInlineRenameInfo(string localizedErrorMessage) : IIn public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) => null; - public async Task FindRenameLocationsAsync(SymbolRenameOptions options, CancellationToken cancellationToken) => null; + public Task FindRenameLocationsAsync(SymbolRenameOptions options, CancellationToken cancellationToken) => Task.FromResult(null); public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable changedDocumentIDs, string replacementText) => false; diff --git a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs index 8c010d72b9675..12a77bc565221 100644 --- a/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs +++ b/src/EditorFeatures/Core/InlineRename/AbstractEditorInlineRenameService.cs @@ -32,9 +32,9 @@ public async Task GetRenameInfoAsync(Document document, int p _refactorNotifyServices, symbolicInfo, cancellationToken); } - public virtual async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public virtual Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return ImmutableDictionary>.Empty; + return Task.FromResult(ImmutableDictionary>.Empty); } /// diff --git a/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs b/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs index 18c90b8010a7e..730164f11e865 100644 --- a/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs +++ b/src/EditorFeatures/Core/IntelliSense/AsyncCompletion/ItemManager.cs @@ -50,7 +50,7 @@ public Task> SortCompletionListAsync( throw new NotImplementedException(); } - public async Task> SortCompletionItemListAsync( + public Task> SortCompletionItemListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) @@ -73,7 +73,7 @@ public async Task> SortCompletionItemListAsync( } AsyncCompletionLogger.LogItemManagerSortTicksDataPoint(stopwatch.Elapsed); - return itemList; + return Task.FromResult(itemList); } private static void SortCompletionItems(List list, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs b/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs index a39805990d111..514c1b7ed4cd4 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveDocumentNavigationService.cs @@ -24,8 +24,8 @@ public InteractiveDocumentNavigationService(IThreadingContext threadingContext) _threadingContext = threadingContext; } - public override async Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => true; + public override Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => SpecializedTasks.True; public override async Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) { diff --git a/src/EditorFeatures/Core/Interactive/InteractiveSession.cs b/src/EditorFeatures/Core/Interactive/InteractiveSession.cs index 57bbcf8457af0..9a42733794875 100644 --- a/src/EditorFeatures/Core/Interactive/InteractiveSession.cs +++ b/src/EditorFeatures/Core/Interactive/InteractiveSession.cs @@ -132,7 +132,7 @@ private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, Intera { Contract.ThrowIfFalse(result.InitializationResult != null); - _workQueue.AddWork(async () => + _workQueue.AddWork(() => { _workspace.ResetSolution(); @@ -153,6 +153,7 @@ private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, Intera } _pendingBuffers.Clear(); + return Task.CompletedTask; }); } @@ -162,9 +163,10 @@ private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, Intera internal void AddSubmissionProject(ITextBuffer submissionBuffer) { _workQueue.AddWork( - async () => + () => { AddSubmissionProjectNoLock(submissionBuffer, _languageInfo.LanguageName); + return Task.CompletedTask; }); } diff --git a/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs b/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs index d644ebf3be5d3..e53cd9238b5f3 100644 --- a/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs +++ b/src/EditorFeatures/Core/LanguageServer/AbstractInProcLanguageClient.cs @@ -200,9 +200,10 @@ public virtual async Task OnLoadedAsync() /// Signals the extension that the language server has been successfully initialized. /// /// A which completes when actions that need to be performed when the server is ready are done. - public async Task OnServerInitializedAsync() + public Task OnServerInitializedAsync() { // We don't have any tasks that need to be triggered after the server has successfully initialized. + return Task.CompletedTask; } internal async Task> CreateAsync( @@ -264,12 +265,12 @@ public virtual AbstractLanguageServer Create( public abstract ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities); - public async Task OnServerInitializeFailedAsync(ILanguageClientInitializationInfo initializationState) + public Task OnServerInitializeFailedAsync(ILanguageClientInitializationInfo initializationState) { var initializationFailureContext = new InitializationFailureContext(); initializationFailureContext.FailureMessage = string.Format(EditorFeaturesResources.Language_client_initialization_failed, Name, initializationState.StatusMessage, initializationState.InitializationException?.ToString()); - return initializationFailureContext; + return Task.FromResult(initializationFailureContext); } /// diff --git a/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs b/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs index 8e48a08c46987..477ecd75ad962 100644 --- a/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs +++ b/src/EditorFeatures/Core/NavigateTo/DefaultNavigateToLinkService.cs @@ -11,11 +11,16 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation; -[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Default), Shared] -[method: ImportingConstructor] -[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] -internal sealed class DefaultNavigateToLinkService() : INavigateToLinkService +[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Default)] +[Shared] +internal sealed class DefaultNavigateToLinkService : INavigateToLinkService { - public async Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) - => false; + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public DefaultNavigateToLinkService() + { + } + + public Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) + => SpecializedTasks.False; } diff --git a/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs b/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs index d70ee96c8309e..0631b9ec1de83 100644 --- a/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs +++ b/src/EditorFeatures/Core/NavigateTo/NavigateToItemProvider.Callback.cs @@ -42,7 +42,7 @@ public void Done(bool isFullyLoaded) } } - public async Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) + public Task AddResultsAsync(ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) { foreach (var result in results) { @@ -76,6 +76,8 @@ public async Task AddResultsAsync(ImmutableArray result // gets attention and is fixed. } } + + return Task.CompletedTask; } public void ReportProgress(int current, int maximum) diff --git a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs index 3aaff437230fe..ef1fcee6668af 100644 --- a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs +++ b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs @@ -169,7 +169,7 @@ public bool ExecuteCommand(SortImportsCommandArgs args, CommandExecutionContext => ExecuteCommand( args, context, // Only need syntax for this operation. - async (snapshot, context) => snapshot.GetOpenDocumentInCurrentContextWithChanges(), + (snapshot, context) => Task.FromResult(snapshot.GetOpenDocumentInCurrentContextWithChanges()), async (document, cancellationToken) => { var organizeImportsService = document.GetRequiredLanguageService(); diff --git a/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs b/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs index 6fc301ad5c7fa..513627415f4b4 100644 --- a/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs +++ b/src/EditorFeatures/Core/Preview/SolutionPreviewItem.cs @@ -26,7 +26,7 @@ internal sealed class SolutionPreviewItem(ProjectId? projectId, DocumentId? docu public readonly string? Text; public SolutionPreviewItem(ProjectId? projectId, DocumentId? documentId, string text) - : this(projectId, documentId, async c => text) + : this(projectId, documentId, c => Task.FromResult(text)) { Text = text; } diff --git a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs index 157a72879346f..bd1ea87d40c84 100644 --- a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs @@ -90,7 +90,7 @@ protected override bool TryAddSpansToTag(ITextView textViewOpt, ITextBuffer subj return true; } - protected override async Task ProduceTagsAsync( + protected override Task ProduceTagsAsync( TaggerContext context, CancellationToken cancellationToken) { // NOTE(cyrusn): Normally we'd limit ourselves to producing tags in the span we were @@ -99,7 +99,7 @@ protected override async Task ProduceTagsAsync( // don't generate all the tags then the user will cycle through an incorrect subset. if (context.CaretPosition == null) { - return; + return Task.CompletedTask; } var caretPosition = context.CaretPosition.Value; @@ -108,13 +108,13 @@ protected override async Task ProduceTagsAsync( var document = context.SpansToTag.FirstOrDefault(vt => vt.SnapshotSpan.Snapshot == caretPosition.Snapshot).Document; if (document == null) { - return; + return Task.CompletedTask; } // Don't produce tags if the feature is not enabled. if (!this.GlobalOptions.GetOption(ReferenceHighlightingOptionsStorage.ReferenceHighlighting, document.Project.Language)) { - return; + return Task.CompletedTask; } // See if the user is just moving their caret around in an existing tag. If so, we don't want to actually go @@ -125,12 +125,12 @@ protected override async Task ProduceTagsAsync( if (onExistingTags) { context.SetSpansTagged([]); - return; + return Task.CompletedTask; } // Otherwise, we need to go produce all tags. var options = this.GlobalOptions.GetHighlightingOptions(document.Project.Language); - await ProduceTagsAsync(context, caretPosition, document, options, cancellationToken).ConfigureAwait(false); + return ProduceTagsAsync(context, caretPosition, document, options, cancellationToken); } private static async Task ProduceTagsAsync( diff --git a/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs b/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs index 2edf0a6923f17..a66052a722ac7 100644 --- a/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs +++ b/src/EditorFeatures/Core/RenameTracking/RenameTrackingCodeRefactoringProvider.cs @@ -33,7 +33,7 @@ public RenameTrackingCodeRefactoringProvider( this.CustomTags = this.CustomTags.Add(CodeAction.CanBeHighPriorityTag); } - public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, _) = context; @@ -42,6 +42,8 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte if (action != null) context.RegisterRefactoring(action, renameSpan); + + return Task.CompletedTask; } /// diff --git a/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs b/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs index 396be07ea86a7..450c082491b48 100644 --- a/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs +++ b/src/EditorFeatures/Core/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs @@ -56,15 +56,15 @@ public RenameTrackingCodeAction( protected sealed override CodeActionPriority ComputePriority() => CodeActionPriority.High; - protected override async Task> ComputeOperationsAsync( + protected override Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { // Invoked directly without previewing. if (_renameTrackingCommitter == null && !TryInitializeRenameTrackingCommitter()) - return []; + return SpecializedTasks.EmptyImmutableArray(); var committerOperation = new RenameTrackingCommitterOperation(_renameTrackingCommitter, _threadingContext); - return ImmutableArray.Create(committerOperation); + return Task.FromResult(ImmutableArray.Create(committerOperation)); } protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs index 016afce62688c..2ecc88d76e084 100644 --- a/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs +++ b/src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.WorkspaceChangedEventSource.cs @@ -27,9 +27,10 @@ public WorkspaceChangedEventSource( // only process a tag change once. _asyncDelay = new AsyncBatchingWorkQueue( DelayTimeSpan.Short, - processBatchAsync: async cancellationToken => + processBatchAsync: cancellationToken => { RaiseChanged(); + return ValueTask.CompletedTask; }, asyncListener, CancellationToken.None); diff --git a/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs b/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs index 9ce9cf1fe6023..47ce299bf4529 100644 --- a/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs +++ b/src/EditorFeatures/Core/SignatureHelp/Controller.Session_SetModelSelectedItem.cs @@ -18,7 +18,7 @@ private void SetModelExplicitlySelectedItem(Func selec this.Computation.ThreadingContext.ThrowIfNotOnUIThread(); Computation.ChainTaskAndNotifyControllerWhenFinished( - async (model, cancellationToken) => SetModelExplicitlySelectedItemInBackground(model, selector), + (model, cancellationToken) => Task.FromResult(SetModelExplicitlySelectedItemInBackground(model, selector)), updateController: false); } diff --git a/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs b/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs index de8b96a15144a..e53eef6742d31 100644 --- a/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs +++ b/src/EditorFeatures/Core/Suggestions/RefineUsingCopilot/RefineUsingCopilotCodeAction.cs @@ -29,10 +29,10 @@ private sealed class RefineUsingCopilotCodeAction( { public override string Title => EditorFeaturesResources.Refine_using_Copilot; - protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) { // Make sure we don't trigger the refinement session for preview operation - return SpecializedCollections.EmptyEnumerable(); + return Task.FromResult(SpecializedCollections.EmptyEnumerable()); } protected override async Task> ComputeOperationsAsync(IProgress progress, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs index 52203733b741d..96d9164950b36 100644 --- a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs +++ b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedAction.cs @@ -220,13 +220,13 @@ protected async Task GetPreviewResultAsync(CancellationTo public virtual bool HasPreview => false; - public virtual async Task GetPreviewAsync(CancellationToken cancellationToken) - => null; + public virtual Task GetPreviewAsync(CancellationToken cancellationToken) + => SpecializedTasks.Null(); public virtual bool HasActionSets => false; - public virtual async Task> GetActionSetsAsync(CancellationToken cancellationToken) - => []; + public virtual Task> GetActionSetsAsync(CancellationToken cancellationToken) + => SpecializedTasks.EmptyEnumerable(); #region not supported diff --git a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs index 4a040e7621896..feba7ae149989 100644 --- a/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs +++ b/src/EditorFeatures/Core/Suggestions/SuggestedActions/EditorSuggestedActionWithNestedActions.cs @@ -34,15 +34,17 @@ internal sealed class EditorSuggestedActionWithNestedActions( public sealed override bool HasActionSets => true; - public sealed override async Task> GetActionSetsAsync(CancellationToken cancellationToken) - => NestedActionSets; + public sealed override Task> GetActionSetsAsync(CancellationToken cancellationToken) + => Task.FromResult>(NestedActionSets); - protected sealed override async Task InnerInvokeAsync(IProgress progress, CancellationToken cancellationToken) + protected sealed override Task InnerInvokeAsync(IProgress progress, CancellationToken cancellationToken) { // A code action with nested actions is itself never invokable. So just do nothing if this ever gets asked. // Report a message in debug and log a watson exception so that if this is hit we can try to narrow down how // this happened. Debug.Fail($"{nameof(InnerInvokeAsync)} should not be called on a {nameof(EditorSuggestedActionWithNestedActions)}"); FatalError.ReportAndCatch(new InvalidOperationException($"{nameof(InnerInvokeAsync)} should not be called on a {nameof(EditorSuggestedActionWithNestedActions)}"), ErrorSeverity.Critical); + + return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs index 2283c07b01e8b..87237a63e2c1e 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs @@ -102,7 +102,7 @@ private void RemoveTagsThatIntersectEdit(TextContentChangedEventArgs e) // Everything we're passing in here is synchronous. So we can assert that this must complete synchronously // as well. var (oldTagTrees, newTagTrees, _) = CompareAndSwapTagTreesAsync( - static async (oldTagTrees, args, _) => + static (oldTagTrees, args, _) => { var (@this, e, tagsToRemove, allTagsList, allTagsSet) = args; @@ -135,12 +135,12 @@ static async (oldTagTrees, args, _) => snapshot, @this._dataSource.SpanTrackingMode, allTagsList); - return (oldTagTrees.SetItem(buffer, newTagTree), default(VoidResult)); + return ValueTask.FromResult((oldTagTrees.SetItem(buffer, newTagTree), default(VoidResult))); } } // return oldTagTrees to indicate nothing changed. - return (oldTagTrees, default(VoidResult)); + return ValueTask.FromResult((oldTagTrees, default(VoidResult))); }, args: (this, e, tagsToRemove, allTagsList, allTagsSet), _disposalTokenSource.Token).VerifyCompleted(); diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs index 59c0d10b3228f..55a2e9158c3cb 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs @@ -41,12 +41,12 @@ private void OnTagsChangedForBuffer( } } - private async ValueTask ProcessTagsChangedAsync( + private ValueTask ProcessTagsChangedAsync( ImmutableSegmentedList snapshotSpans, CancellationToken cancellationToken) { var tagsChanged = this.TagsChanged; if (tagsChanged == null) - return; + return ValueTask.CompletedTask; foreach (var collection in snapshotSpans) { @@ -65,6 +65,8 @@ private async ValueTask ProcessTagsChangedAsync( foreach (var span in coalesced) tagsChanged(this, new SnapshotSpanEventArgs(span)); } + + return ValueTask.CompletedTask; } } } diff --git a/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs b/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs index c914050bd901f..390bed532d090 100644 --- a/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs +++ b/src/EditorFeatures/Core/Workspaces/ITextBufferVisibilityTracker.cs @@ -42,7 +42,7 @@ internal static class ITextBufferVisibilityTrackerExtensions /// Waits the specified amount of time while the specified is not visible. If /// any document visibility changes happen, the delay will cancel. /// - public static async Task DelayWhileNonVisibleAsync( + public static Task DelayWhileNonVisibleAsync( this ITextBufferVisibilityTracker? service, IThreadingContext threadingContext, IAsynchronousOperationListener listener, @@ -52,7 +52,7 @@ public static async Task DelayWhileNonVisibleAsync( { // Only add a delay if we have access to a service that will tell us when the buffer become visible or not. if (service is null) - return; + return Task.CompletedTask; // Because cancellation is both expensive, and a super common thing to occur while we're delaying the caller // until visibility, we special case the implementation here and transition to the canceled state @@ -63,14 +63,14 @@ public static async Task DelayWhileNonVisibleAsync( // it's very reasonable for the delay-task to complete synchronously (we've already been canceled, or the // buffer is already visible. So fast path that out. if (delayTask.IsCompleted) - await delayTask.ConfigureAwait(false); + return delayTask; var taskOfTask = delayTask.ContinueWith( // Convert a successfully completed task when we were canceled to a canceled task. Otherwise, return // the faulted or non-canceled task as is. task => task.Status == TaskStatus.RanToCompletion && cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : task, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - await taskOfTask.Unwrap().ConfigureAwait(false); + return taskOfTask.Unwrap(); // Normal delay logic, except that this does not throw in the event of cancellation, but instead returns // gracefully. The above task continuation logic then ensures we return a canceled task without needing diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs index c258a6b17a3d3..12f1018088ebb 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs @@ -84,8 +84,8 @@ private static async Task GetFixAllFixAsync( return await refactorAllProvider.GetRefactoringAsync(refactorAllContext).ConfigureAwait(false); } - protected override async Task> GetDiagnosticsWorkerAsync(EditorTestWorkspace workspace, TestParameters parameters) - => []; + protected override Task> GetDiagnosticsWorkerAsync(EditorTestWorkspace workspace, TestParameters parameters) + => SpecializedTasks.EmptyImmutableArray(); internal override async Task GetCodeRefactoringAsync( EditorTestWorkspace workspace, TestParameters parameters) diff --git a/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs b/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs index 79547aee64957..642d144e3d866 100644 --- a/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs +++ b/src/EditorFeatures/ExternalAccess/Debugger/GlassTestsHotReloadService.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.Debugger; internal sealed class GlassTestsHotReloadService { private static readonly ActiveStatementSpanProvider s_noActiveStatementSpanProvider = - async (_, _, _) => ImmutableArray.Empty; + (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); private readonly IManagedHotReloadService _debuggerService; @@ -29,7 +29,7 @@ public GlassTestsHotReloadService(HostWorkspaceServices services, IManagedHotRel } #pragma warning disable IDE0060 // Remove unused parameter - public async Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) + public Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) #pragma warning restore IDE0060 { var newSessionId = _encService.StartDebuggingSession( @@ -40,6 +40,8 @@ public async Task StartSessionAsync(Solution solution, CancellationToken cancell Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; + + return Task.CompletedTask; } private DebuggingSessionId GetSessionId() diff --git a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs index bfa286dd3e922..b828c08c2ff69 100644 --- a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs +++ b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs @@ -394,7 +394,7 @@ public sealed override ImmutableArray FixableDiagnosticIds get { return [Id]; } } - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; ContextDiagnosticsCount = context.Diagnostics.Length; @@ -403,9 +403,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix( CodeAction.Create( _registerFixWithTitle, - createChangedDocument: async _ => context.Document), + createChangedDocument: _ => Task.FromResult(context.Document)), context.Diagnostics); } + + return Task.CompletedTask; } } @@ -554,16 +556,16 @@ public MockDocumentDiagnosticAnalyzer() public override ImmutableArray SupportedDiagnostics { get; } - public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) + public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) { ReceivedCallback = true; - return ImmutableArray.Empty; + return Task.FromResult(ImmutableArray.Empty); } - public override async Task> AnalyzeSemanticsAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) + public override Task> AnalyzeSemanticsAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) { ReceivedCallback = true; - return ImmutableArray.Empty; + return Task.FromResult(ImmutableArray.Empty); } } @@ -779,10 +781,11 @@ protected AbstractNuGetOrVsixCodeFixProvider(ImmutableArray fixableDiagn public override ImmutableArray FixableDiagnosticIds { get; } - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var fixableDiagnostics = context.Diagnostics.WhereAsArray(d => FixableDiagnosticIds.Contains(d.Id)); - context.RegisterCodeFix(CodeAction.Create(_name, async ct => context.Document), fixableDiagnostics); + context.RegisterCodeFix(CodeAction.Create(_name, ct => Task.FromResult(context.Document)), fixableDiagnostics); + return Task.CompletedTask; } } @@ -813,11 +816,13 @@ public CodeFixProviderWithDuplicateEquivalenceKeyActions(string diagnosticId, st public override ImmutableArray FixableDiagnosticIds => [_diagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { // Register duplicate code actions with same equivalence key, but different title. RegisterCodeFix(context, titleSuffix: "1"); RegisterCodeFix(context, titleSuffix: "2"); + + return Task.CompletedTask; } private void RegisterCodeFix(CodeFixContext context, string titleSuffix) @@ -825,7 +830,7 @@ private void RegisterCodeFix(CodeFixContext context, string titleSuffix) context.RegisterCodeFix( CodeAction.Create( nameof(CodeFixProviderWithDuplicateEquivalenceKeyActions) + titleSuffix, - async ct => context.Document, + ct => Task.FromResult(context.Document), _equivalenceKey), context.Diagnostics); } @@ -904,7 +909,7 @@ protected AbstractAdditionalFileCodeFixProvider(string title) public sealed override ImmutableArray FixableDiagnosticIds => [AdditionalFileAnalyzer.DiagnosticId]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(CodeAction.Create(Title, createChangedSolution: async ct => @@ -916,6 +921,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) }, equivalenceKey: Title), context.Diagnostics[0]); + + return Task.CompletedTask; } } @@ -1198,13 +1205,14 @@ private sealed class FixerForDeprioritizedAnalyzer : CodeFixProvider public static readonly string Title = $"Fix {DeprioritizedAnalyzer.Descriptor.Id}"; public override ImmutableArray FixableDiagnosticIds => [DeprioritizedAnalyzer.Descriptor.Id]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( CodeAction.Create(Title, - createChangedDocument: async _ => context.Document, + createChangedDocument: _ => Task.FromResult(context.Document), equivalenceKey: nameof(FixerForDeprioritizedAnalyzer)), context.Diagnostics); + return Task.CompletedTask; } } } diff --git a/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs b/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs index e20a39cbfda71..9804a12d48a13 100644 --- a/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs +++ b/src/EditorFeatures/Test/CodeRefactorings/CodeRefactoringServiceTest.cs @@ -63,9 +63,11 @@ public TypeScriptCodeRefactoringProvider() { } - public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create($"Blocking=false", _ => Task.FromResult(null))); + + return Task.CompletedTask; } } @@ -115,12 +117,14 @@ private static async Task VerifyRefactoringDisabledAsync() internal sealed class StubRefactoring : CodeRefactoringProvider { - public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create( nameof(StubRefactoring), - async cancellationToken => context.Document, + cancellationToken => Task.FromResult(context.Document), equivalenceKey: nameof(StubRefactoring))); + + return Task.CompletedTask; } } @@ -291,7 +295,7 @@ internal abstract class AbstractNonSourceFileRefactoring : CodeRefactoringProvid protected AbstractNonSourceFileRefactoring(string title) => Title = title; - public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create(Title, createChangedSolution: async ct => @@ -303,6 +307,8 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte return document.Project.Solution.WithAdditionalDocumentText(document.Id, newText); return document.Project.Solution.WithAnalyzerConfigDocumentText(document.Id, newText); })); + + return Task.CompletedTask; } } diff --git a/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs b/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs index 243a47677dde1..fc3e35d1c6a9d 100644 --- a/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs +++ b/src/EditorFeatures/Test/Completion/CompletionServiceTests.cs @@ -116,14 +116,14 @@ public override async Task ProvideCompletionsAsync(CompletionContext context) context.CompletionListSpan = await GetTextChangeSpanAsync(context.Document, context.CompletionListSpan, context.CancellationToken).ConfigureAwait(false); } - public override async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + public override Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { - return CompletionDescription.FromText(nameof(DebugAssertTestCompletionProvider)); + return Task.FromResult(CompletionDescription.FromText(nameof(DebugAssertTestCompletionProvider))); } - public override async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public override Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { - return CompletionChange.Create(new TextChange(item.Span, nameof(DebugAssertTestCompletionProvider))); + return Task.FromResult(CompletionChange.Create(new TextChange(item.Span, nameof(DebugAssertTestCompletionProvider)))); } private static async Task GetTextChangeSpanAsync(Document document, TextSpan startSpan, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs index fd4c976a14a2e..463403f829658 100644 --- a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs @@ -1012,9 +1012,10 @@ private sealed class LeakDocumentAnalyzer : DocumentDiagnosticAnalyzer public override ImmutableArray SupportedDiagnostics => [s_syntaxRule]; - public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) + public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) { - return [Diagnostic.Create(s_syntaxRule, tree.GetRoot(cancellationToken).GetLocation())]; + return Task.FromResult>( + [Diagnostic.Create(s_syntaxRule, tree.GetRoot(cancellationToken).GetLocation())]); } } diff --git a/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs b/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs index fdcd9784c5594..3a6a31da9eb4c 100644 --- a/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs +++ b/src/EditorFeatures/Test/FindReferences/FindReferencesCommandHandlerTests.cs @@ -30,12 +30,14 @@ private sealed class MockFindUsagesContext : FindUsagesContext { public readonly List Result = []; - public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public override ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (Result) { Result.Add(definition); } + + return default; } } diff --git a/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs b/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs index 34e57f5b49388..71152e7aec433 100644 --- a/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs +++ b/src/EditorFeatures/Test/LanguageServer/VSTypeScriptHandlerTests.cs @@ -178,12 +178,12 @@ internal sealed class TypeScriptHandler : AbstractVSTypeScriptRequestHandler HandleRequestAsync(TSRequest request, TypeScriptRequestContext context, CancellationToken cancellationToken) + protected override Task HandleRequestAsync(TSRequest request, TypeScriptRequestContext context, CancellationToken cancellationToken) { Assert.NotNull(context.Solution); AssertEx.NotNull(context.Document); Assert.Equal(context.Document.GetURI(), request.Document); - return Response; + return Task.FromResult(Response); } } } diff --git a/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs b/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs index da16387f07081..bb3881d8e3662 100644 --- a/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs +++ b/src/EditorFeatures/Test/LinkedFiles/LinkedFileDiffMergingEditorTests.cs @@ -108,7 +108,7 @@ public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContex .WithDocumentText(document.Id, (await document.GetTextAsync()).Replace(textString.IndexOf("public"), "public".Length, "internal")) .WithDocumentText(linkedDocument.Id, sourceText.Replace(textString.LastIndexOf("public"), "public".Length, "private")); - context.RegisterRefactoring(CodeAction.Create("Description", async _ => newSolution), context.Span); + context.RegisterRefactoring(CodeAction.Create("Description", _ => Task.FromResult(newSolution)), context.Span); } } } diff --git a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs index 48effdc3bf745..b9b19dcf47696 100644 --- a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs +++ b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.cs @@ -23,7 +23,7 @@ public abstract partial class AbstractMetadataAsSourceTests : IAsyncLifetime { protected static readonly string ICSharpCodeDecompilerVersion = "9.1.0.7988"; - public virtual async Task InitializeAsync() + public virtual Task InitializeAsync() { AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.MscorlibRef_v46, "mscorlib.v4_6_1038_0.dll", ImmutableArray.Create(Net461.ReferenceInfos.mscorlib.ImageBytes)); AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.SystemRef_v46, "System.v4_6_1038_0.dll", ImmutableArray.Create(Net461.ReferenceInfos.System.ImageBytes)); @@ -33,11 +33,15 @@ public virtual async Task InitializeAsync() AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.MsvbRef, "Microsoft.VisualBasic.dll", ImmutableArray.Create(Net461.Resources.MicrosoftVisualBasic)); AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.SystemXmlRef, "System.Xml.v4_0_30319.dll", ImmutableArray.Create(Net461.Resources.SystemXml)); AssemblyResolver.TestAccessor.AddInMemoryImage(TestBase.SystemXmlLinqRef, "System.Xml.Linq.v4_0_30319.dll", ImmutableArray.Create(Net461.Resources.SystemXmlLinq)); + + return Task.CompletedTask; } - public virtual async Task DisposeAsync() + public virtual Task DisposeAsync() { AssemblyResolver.TestAccessor.ClearInMemoryImages(); + + return Task.CompletedTask; } internal static async Task GenerateAndVerifySourceAsync( diff --git a/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs b/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs index f535dcc81506f..1c6b693d9d5f4 100644 --- a/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs +++ b/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs @@ -259,11 +259,13 @@ protected override TaggerDelay EventChangeDelay protected override ITaggerEventSource CreateEventSource(ITextView? textView, ITextBuffer subjectBuffer) => eventSource; - protected override async Task ProduceTagsAsync( + protected override Task ProduceTagsAsync( TaggerContext context, DocumentSnapshotSpan snapshotSpan, int? caretPosition, CancellationToken cancellationToken) { foreach (var tag in callback(context, snapshotSpan)) context.AddTag(tag); + + return Task.CompletedTask; } protected override bool TagEquals(TextMarkerTag tag1, TextMarkerTag tag2) diff --git a/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs b/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs index 50c85c6bd6441..2fef5def6bc4f 100644 --- a/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs +++ b/src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.cs @@ -213,10 +213,10 @@ public Task> GetProjectReferencesAsync(string proj throw new System.NotImplementedException(); } - public async Task TryUpdateReferenceAsync(string projectPath, ReferenceUpdate referenceUpdate, CancellationToken cancellationToken) + public Task TryUpdateReferenceAsync(string projectPath, ReferenceUpdate referenceUpdate, CancellationToken cancellationToken) { _appliedUpdates.Add(referenceUpdate); - return true; + return Task.FromResult(true); } } } diff --git a/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs b/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs index 8b12bcd43deb6..f35726022c7c6 100644 --- a/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs +++ b/src/EditorFeatures/TestUtilities/FindUsages/FindUsagesTestContext.cs @@ -25,12 +25,14 @@ public bool ShouldShow(DefinitionItem definition) return definition.DisplayIfNoReferences; } - public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public override ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { Definitions.Add(definition); } + + return default; } public override async ValueTask OnReferencesFoundAsync(IAsyncEnumerable references, CancellationToken cancellationToken) diff --git a/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs b/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs index 0f77a07078140..67ddac8523f42 100644 --- a/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs +++ b/src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs @@ -262,7 +262,7 @@ public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] protected sealed class TestWorkspaceNavigateToSearchHostService() : IWorkspaceNavigateToSearcherHostService { - public async ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) - => true; + public ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) + => new(true); } } diff --git a/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs b/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs index 5ed3727438d98..6958c6eefd15a 100644 --- a/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs +++ b/src/EditorFeatures/TestUtilities/Workspaces/NoCompilationDocumentDiagnosticAnalyzer.cs @@ -20,9 +20,9 @@ internal sealed class NoCompilationDocumentDiagnosticAnalyzer : DocumentDiagnost public override ImmutableArray SupportedDiagnostics => [Descriptor]; - public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) + public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree tree, CancellationToken cancellationToken) { - return ImmutableArray.Create( - Diagnostic.Create(Descriptor, Location.Create(document.FilePath, default, default))); + return Task.FromResult(ImmutableArray.Create( + Diagnostic.Create(Descriptor, Location.Create(document.FilePath, default, default)))); } } diff --git a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs index 03f545b781379..839ef19d05b14 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/EnableNullable/EnableNullableCodeRefactoringProvider.FixAllProvider.cs @@ -30,10 +30,10 @@ private RefactorAllProvider() public override IEnumerable GetSupportedRefactorAllScopes() => [RefactorAllScope.Solution]; - public override async Task GetRefactoringAsync(RefactorAllContext fixAllContext) + public override Task GetRefactoringAsync(RefactorAllContext fixAllContext) { Debug.Assert(fixAllContext.Scope == RefactorAllScope.Solution); - return new FixAllCodeAction(EnableNullableReferenceTypesInSolutionAsync); + return Task.FromResult(new FixAllCodeAction(EnableNullableReferenceTypesInSolutionAsync)); async Task EnableNullableReferenceTypesInSolutionAsync( CodeActionPurpose purpose, IProgress progress, CancellationToken cancellationToken) diff --git a/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs index d5bbe6f0f664c..8567987595b96 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs @@ -32,8 +32,9 @@ protected override TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel protected override TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, CSharpSimplifierOptions options, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(typeName, semanticModel, options, cancellationToken); - protected override async Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) + protected override Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) { UseImplicitTypeCodeFixProvider.ReplaceTypeWithVar(editor, type); + return Task.CompletedTask; } } diff --git a/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs index 82627f28ab148..ca1c863dbf3ac 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/UseRecursivePatterns/UseRecursivePatternsCodeRefactoringProvider.cs @@ -65,7 +65,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte context.RegisterRefactoring( CodeAction.Create( CSharpFeaturesResources.Use_recursive_patterns, - async _ => document.WithSyntaxRoot(replacementFunc(root)), + _ => Task.FromResult(document.WithSyntaxRoot(replacementFunc(root))), nameof(CSharpFeaturesResources.Use_recursive_patterns))); } diff --git a/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs b/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs index b0507828f831c..dc1efe67c8b1b 100644 --- a/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs +++ b/src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs @@ -68,7 +68,7 @@ internal override CompletionRules GetRules(CompletionOptions options) return newRules; } - internal override async ValueTask IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) + internal override async Task IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) { var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs index ebd313850f93b..e525d687a4d53 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs @@ -243,8 +243,8 @@ private static IEnumerable GetAttributeNamedParameters( return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } - protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) - => GetTextChange(selectedItem, ch); + protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + => Task.FromResult(GetTextChange(selectedItem, ch)); private static TextChange? GetTextChange(CompletionItem selectedItem, char? ch) { diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs index 50f65ccd6d3d3..3281aeda172f5 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/CrefCompletionProvider.cs @@ -365,14 +365,14 @@ private static CompletionItemRules GetRules(string displayText) } } - protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { if (!SymbolCompletionItem.TryGetInsertionText(selectedItem, out var insertionText)) { insertionText = selectedItem.DisplayText; } - return new TextChange(selectedItem.Span, insertionText); + return Task.FromResult(new TextChange(selectedItem.Span, insertionText)); } internal TestAccessor GetTestAccessor() diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs index e7cf6c02234cf..65a62f5b1d49b 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs @@ -61,14 +61,14 @@ public override async Task ProvideCompletionsAsync(CompletionContext context) } } - protected override async Task> GetSymbolsAsync( + protected override Task> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, CompletionOptions options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) - return []; + return SpecializedTasks.EmptyImmutableArray(); var potentialTypeNode = targetToken.Parent; if (targetToken.IsKind(SyntaxKind.GreaterThanToken) && potentialTypeNode is TypeArgumentListSyntax typeArgumentList) @@ -89,17 +89,17 @@ protected override async Task> GetSymbols } if (typeNode == null) - return []; + return SpecializedTasks.EmptyImmutableArray(); // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) - return []; + return SpecializedTasks.EmptyImmutableArray(); var typeDeclaration = typeNode.GetAncestor(); if (typeDeclaration == null) - return []; + return SpecializedTasks.EmptyImmutableArray(); // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); @@ -115,7 +115,7 @@ protected override async Task> GetSymbols interfaceSet.AddRange(directInterface.AllInterfaces); } - return interfaceSet.SelectAsArray(t => new SymbolAndSelectionInfo(Symbol: t, Preselect: false)); + return Task.FromResult(interfaceSet.SelectAsArray(t => new SymbolAndSelectionInfo(Symbol: t, Preselect: false))); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs index e665f235033e8..85b8c0c52f911 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/ExtensionMemberImportCompletionProvider.cs @@ -46,7 +46,7 @@ protected override bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, Sy }; } - protected override async Task ShouldProvideParenthesisCompletionAsync( + protected override Task ShouldProvideParenthesisCompletionAsync( Document document, CompletionItem item, char? commitKey, @@ -57,7 +57,7 @@ protected override async Task ShouldProvideParenthesisCompletionAsync( // it can only be used as like: bar.ToInt(); // Func x = bar.ToInt or Func x = bar.ToInt is illegal. It can't be assign to delegate. // Therefore at here we always assume the user always wants to add parenthesis. - => commitKey is ';' or '.'; + => Task.FromResult(commitKey is ';' or '.'); protected override (ITypeSymbol? receiverTypeSymbol, bool isStatic) TryGetReceiverTypeSymbol( SemanticModel semanticModel, diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs index 4a423e7237ec5..ea2d30a4250d0 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.cs @@ -277,12 +277,12 @@ bool IEqualityComparer.Equals(IParameterSymbol? x, IParameterS int IEqualityComparer.GetHashCode(IParameterSymbol obj) => obj.Name.GetHashCode(); - protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { - return new TextChange( + return Task.FromResult(new TextChange( selectedItem.Span, // Insert extra colon if committing with '(' only: "method(parameter:(" is preferred to "method(parameter(". // In all other cases, do not add extra colon. Note that colon is already added if committing with ':'. - ch == '(' ? selectedItem.GetEntireDisplayText() : selectedItem.DisplayText); + ch == '(' ? selectedItem.GetEntireDisplayText() : selectedItem.DisplayText)); } } diff --git a/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs b/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs index 7e8eb091f0b62..9a6d275f073a8 100644 --- a/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs +++ b/src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.cs @@ -113,11 +113,11 @@ private static void AddItems(ImmutableArray inferredTypes, int } } - protected override async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + protected override Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { - return new TextChange( + return Task.FromResult(new TextChange( selectedItem.Span, - selectedItem.DisplayText); + selectedItem.DisplayText)); } public override ImmutableHashSet TriggerCharacters => []; diff --git a/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs b/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs index aed957642f6c3..678c1d7046b04 100644 --- a/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs +++ b/src/Features/CSharp/Portable/Completion/Providers/DefaultArgumentProvider.cs @@ -22,7 +22,7 @@ public DefaultArgumentProvider() { } - public override async Task ProvideArgumentAsync(ArgumentContext context) + public override Task ProvideArgumentAsync(ArgumentContext context) { if (context.PreviousValue is { }) { @@ -52,5 +52,7 @@ public override async Task ProvideArgumentAsync(ArgumentContext context) _ => "default", }; } + + return Task.CompletedTask; } } diff --git a/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs b/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs index 1075a6e961e0b..00cf305a680e5 100644 --- a/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs +++ b/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs @@ -24,18 +24,18 @@ public OutVariableArgumentProvider() { } - public override async Task ProvideArgumentAsync(ArgumentContext context) + public override Task ProvideArgumentAsync(ArgumentContext context) { if (context.PreviousValue is not null) { // This argument provider does not attempt to replace arguments already in code. - return; + return Task.CompletedTask; } if (context.Parameter.RefKind != RefKind.Out) { // This argument provider only considers 'out' parameters. - return; + return Task.CompletedTask; } // Since tihs provider runs after ContextVariableArgumentProvider, we know there is no suitable target in @@ -60,5 +60,6 @@ public override async Task ProvideArgumentAsync(ArgumentContext context) [])))); context.DefaultValue = syntax.NormalizeWhitespace().ToFullString(); + return Task.CompletedTask; } } diff --git a/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs b/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs index a5beb9785fa38..aaee437c94516 100644 --- a/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs +++ b/src/Features/CSharp/Portable/Copilot/CSharpCopilotCodeFixProvider.DismissChangesCodeAction.cs @@ -22,11 +22,12 @@ private sealed class CopilotDismissChangesCodeAction(SyntaxNode originalMethodNo { public override string Title => FeaturesResources.Dismiss; - protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) - => null!; + protected override Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) + => Task.FromResult>(null!); - protected override async Task> ComputeOperationsAsync(CancellationToken cancellationToken) - => [new TriggerDismissalCodeActionOperation(originalMethodNode, diagnostic)]; + protected override Task> ComputeOperationsAsync(CancellationToken cancellationToken) + => Task.FromResult>( + [new TriggerDismissalCodeActionOperation(originalMethodNode, diagnostic)]); private sealed class TriggerDismissalCodeActionOperation(SyntaxNode originalMethodNode, Diagnostic diagnostic) : CodeActionOperation { diff --git a/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs b/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs index a08bdb4e4294d..d8ff380709b28 100644 --- a/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs +++ b/src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs @@ -31,7 +31,7 @@ internal sealed class CSharpDocumentHighlightsService( CSharpSyntaxKinds.Instance, services) { - protected override async ValueTask> GetAdditionalReferencesAsync( + protected override async Task> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { // The FindRefs engine won't find references through 'var' for performance reasons. diff --git a/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs b/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs index 6fdd8560c3cbe..36b10c8df0b20 100644 --- a/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs +++ b/src/Features/CSharp/Portable/ExtractInterface/CSharpExtractInterfaceService.cs @@ -63,7 +63,7 @@ internal override bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode) return typeDeclaration.Modifiers.Any(m => SyntaxFacts.IsAccessibilityModifier(m.Kind())); } - protected override async Task UpdateMembersWithExplicitImplementationsAsync( + protected override Task UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList documentIds, INamedTypeSymbol extractedInterface, INamedTypeSymbol typeToExtractFrom, IEnumerable includedMembers, ImmutableDictionary symbolToDeclarationMap, @@ -72,6 +72,6 @@ protected override async Task UpdateMembersWithExplicitImplementations // In C#, member implementations do not always need // to be explicitly added. It's safe enough to return // the passed in solution - return unformattedSolution; + return Task.FromResult(unformattedSolution); } } diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs index ac9232df581a6..842a16f5c4305 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs @@ -83,10 +83,10 @@ protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite() protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() => this.SelectionResult.GetLastStatementUnderContainer(); - protected override async Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) + protected override Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) { var statement = GetStatementContainingInvocationToExtractedMethodWorker(); - return statement.WithAdditionalAnnotations(CallSiteAnnotation); + return Task.FromResult(statement.WithAdditionalAnnotations(CallSiteAnnotation)); } } } diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs index cadfe83c8c745..befaafb31ffc3 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs @@ -44,10 +44,10 @@ protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() return this.SelectionResult.GetFirstStatement(); } - protected override async Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) + protected override Task GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) { var statement = GetStatementContainingInvocationToExtractedMethodWorker(); - return statement.WithAdditionalAnnotations(CallSiteAnnotation); + return Task.FromResult(statement.WithAdditionalAnnotations(CallSiteAnnotation)); } } } diff --git a/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs b/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs index a0b5f2f03af54..af747c6470b09 100644 --- a/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs +++ b/src/Features/CSharp/Portable/GoToDefinition/CSharpGoToDefinitionSymbolService.cs @@ -22,8 +22,8 @@ namespace Microsoft.CodeAnalysis.CSharp.GoToDefinition; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class CSharpGoToDefinitionSymbolService() : AbstractGoToDefinitionSymbolService { - protected override async Task FindRelatedExplicitlyDeclaredSymbolAsync(Project project, ISymbol symbol, CancellationToken cancellationToken) - => symbol; + protected override Task FindRelatedExplicitlyDeclaredSymbolAsync(Project project, ISymbol symbol, CancellationToken cancellationToken) + => Task.FromResult(symbol); protected override int? GetTargetPositionIfControlFlow(SemanticModel semanticModel, SyntaxToken token) { diff --git a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs index e63edc15a02ab..3a051264177cf 100644 --- a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs +++ b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs @@ -22,7 +22,7 @@ namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable; internal sealed partial class CSharpIntroduceVariableService { - protected override async Task IntroduceFieldAsync( + protected override Task IntroduceFieldAsync( SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, @@ -68,7 +68,7 @@ protected override async Task IntroduceFieldAsync( var finalTypeDeclaration = InsertMember(newTypeDeclaration, newFieldDeclaration, insertionIndex); var newRoot = document.Root.ReplaceNode(oldTypeDeclaration, finalTypeDeclaration); - return document.Document.WithSyntaxRoot(newRoot); + return Task.FromResult(document.Document.WithSyntaxRoot(newRoot)); } else { @@ -81,7 +81,7 @@ protected override async Task IntroduceFieldAsync( : DetermineFieldInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members); var newRoot = newCompilationUnit.WithMembers(newCompilationUnit.Members.Insert(insertionIndex, newFieldDeclaration)); - return document.Document.WithSyntaxRoot(newRoot); + return Task.FromResult(document.Document.WithSyntaxRoot(newRoot)); } } diff --git a/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs b/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs index 71e5dd9c5b902..7d26c03d7f728 100644 --- a/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs +++ b/src/Features/CSharp/Portable/LanguageServices/CSharpSymbolDisplayService.SymbolDescriptionBuilder.cs @@ -92,24 +92,24 @@ protected override void AddEnumUnderlyingTypeSeparator() Space()); } - protected override async Task> GetInitializerSourcePartsAsync( + protected override Task> GetInitializerSourcePartsAsync( ISymbol symbol) { // Actually check for C# symbol types here. if (symbol is IParameterSymbol parameter) { - return await GetInitializerSourcePartsAsync(parameter).ConfigureAwait(false); + return GetInitializerSourcePartsAsync(parameter); } else if (symbol is ILocalSymbol local) { - return await GetInitializerSourcePartsAsync(local).ConfigureAwait(false); + return GetInitializerSourcePartsAsync(local); } else if (symbol is IFieldSymbol field) { - return await GetInitializerSourcePartsAsync(field).ConfigureAwait(false); + return GetInitializerSourcePartsAsync(field); } - return []; + return SpecializedTasks.EmptyImmutableArray(); } protected override ImmutableArray ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format) diff --git a/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs b/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs index eaecc0fa61d38..c13f4d3f7e28b 100644 --- a/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs +++ b/src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs @@ -38,13 +38,13 @@ await GetQuickinfoForPragmaWarningAsync(document, token, cancellationToken).Conf await GetQuickInfoForSuppressMessageAttributeAsync(document, token, cancellationToken).ConfigureAwait(false); } - protected override async Task BuildQuickInfoAsync( + protected override Task BuildQuickInfoAsync( CommonQuickInfoContext context, SyntaxToken token) { // TODO: This provider currently needs access to Document/Project to compute applicable analyzers // and provide quick info, which is not available in CommonQuickInfoContext. - return null; + return Task.FromResult(null); } private static async Task GetQuickinfoForPragmaWarningAsync( diff --git a/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs b/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs index f34c4994ae03c..4a8c56fd6b141 100644 --- a/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs +++ b/src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs @@ -23,15 +23,15 @@ namespace Microsoft.CodeAnalysis.CSharp.QuickInfo; [method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] internal sealed class CSharpSyntacticQuickInfoProvider() : CommonQuickInfoProvider { - protected override async Task BuildQuickInfoAsync( + protected override Task BuildQuickInfoAsync( QuickInfoContext context, SyntaxToken token) - => BuildQuickInfo(token, context.CancellationToken); + => Task.FromResult(BuildQuickInfo(token, context.CancellationToken)); - protected override async Task BuildQuickInfoAsync( + protected override Task BuildQuickInfoAsync( CommonQuickInfoContext context, SyntaxToken token) - => BuildQuickInfo(token, context.CancellationToken); + => Task.FromResult(BuildQuickInfo(token, context.CancellationToken)); private static QuickInfoItem? BuildQuickInfo(SyntaxToken token, CancellationToken cancellationToken) { diff --git a/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs b/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs index d89891c0fd99d..5b2a83eecbef4 100644 --- a/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs +++ b/src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.cs @@ -17,7 +17,7 @@ namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp; internal abstract partial class InvocationExpressionSignatureHelpProviderBase { - internal virtual async Task<(ImmutableArray items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync( + internal virtual Task<(ImmutableArray items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync( ImmutableArray accessibleMethods, Document document, InvocationExpressionSyntax invocationExpression, @@ -29,7 +29,7 @@ internal abstract partial class InvocationExpressionSignatureHelpProviderBase var items = accessibleMethods.SelectAsArray(method => ConvertMethodGroupMethod( document, method, invocationExpression.SpanStart, semanticModel)); var selectedItemIndex = TryGetSelectedIndex(accessibleMethods, currentSymbol); - return (items, selectedItemIndex); + return Task.FromResult((items, selectedItemIndex)); } private static ImmutableArray GetAccessibleMethods( diff --git a/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs index dbd917f054aab..3068e293019c9 100644 --- a/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/AbstractCSharpAutoPropertySnippetProvider.cs @@ -75,16 +75,16 @@ protected override async Task GenerateSnippetSyntaxAs protected override int GetTargetCaretPosition(PropertyDeclarationSyntax propertyDeclaration, SourceText sourceText) => propertyDeclaration.AccessorList!.CloseBraceToken.Span.End; - protected override async ValueTask> GetPlaceHolderLocationsListAsync( + protected override ValueTask> GetPlaceHolderLocationsListAsync( Document document, PropertyDeclarationSyntax propertyDeclaration, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var identifier = propertyDeclaration.Identifier; var type = propertyDeclaration.Type; - return [ + return new([ new SnippetPlaceholder(type.ToString(), type.SpanStart), new SnippetPlaceholder(identifier.ValueText, identifier.SpanStart), - ]; + ]); } protected override PropertyDeclarationSyntax? FindAddedSnippetSyntaxNode(SyntaxNode root, int position) diff --git a/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs index f02eacb351808..489b8af6abeb4 100644 --- a/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/AbstractCSharpForLoopSnippetProvider.cs @@ -45,14 +45,14 @@ internal abstract class AbstractCSharpForLoopSnippetProvider : AbstractForLoopSn protected override bool CanInsertStatementAfterToken(SyntaxToken token) => token.IsBeginningOfStatementContext() || token.IsBeginningOfGlobalStatementContext(); - protected override async ValueTask AdjustSnippetExpressionAsync( + protected override ValueTask AdjustSnippetExpressionAsync( Document document, ForStatementSyntax snippetExpressionNode, CancellationToken cancellationToken) { var editor = new SyntaxEditor(snippetExpressionNode, document.Project.Solution.Services); foreach (var node in snippetExpressionNode.Declaration!.DescendantNodesAndSelf().Reverse()) editor.ReplaceNode(node, (node, _) => node.WithAdditionalAnnotations(Simplifier.Annotation)); - return (ForStatementSyntax)editor.GetChangedRoot(); + return new((ForStatementSyntax)editor.GetChangedRoot()); } protected override ForStatementSyntax GenerateStatement( @@ -108,7 +108,7 @@ protected override ForStatementSyntax GenerateStatement( } } - protected override async ValueTask> GetPlaceHolderLocationsListAsync( + protected override ValueTask> GetPlaceHolderLocationsListAsync( Document document, ForStatementSyntax forStatement, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { using var _ = ArrayBuilder.GetInstance(out var result); @@ -133,7 +133,7 @@ protected override async ValueTask> GetPlaceH foreach (var (key, value) in placeholderBuilder) result.Add(new(key, [.. value])); - return result.ToImmutableAndClear(); + return new(result.ToImmutableAndClear()); } protected override int GetTargetCaretPosition(ForStatementSyntax forStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs index 867c740ee82fc..a720e79571b8d 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpElseSnippetProvider.cs @@ -54,10 +54,10 @@ protected override bool IsValidSnippetLocationCore(SnippetContext context, Cance return isAfterIfStatement && base.IsValidSnippetLocationCore(context, cancellationToken); } - protected override async Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) + protected override Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) { var elseClause = SyntaxFactory.ElseClause(SyntaxFactory.Block()); - return new TextChange(TextSpan.FromBounds(position, position), elseClause.ToFullString()); + return Task.FromResult(new TextChange(TextSpan.FromBounds(position, position), elseClause.ToFullString())); } protected override int GetTargetCaretPosition(ElseClauseSyntax elseClause, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs index 259a436d11a8c..fa3e97345f88c 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs @@ -111,7 +111,7 @@ protected override ForEachStatementSyntax GenerateStatement( /// Goes through each piece of the foreach statement and extracts the identifiers /// as well as their locations to create SnippetPlaceholder's of each. /// - protected override async ValueTask> GetPlaceHolderLocationsListAsync( + protected override ValueTask> GetPlaceHolderLocationsListAsync( Document document, ForEachStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { using var _ = ArrayBuilder.GetInstance(out var arrayBuilder); @@ -120,7 +120,7 @@ protected override async ValueTask> GetPlaceH if (!ConstructedFromInlineExpression) arrayBuilder.Add(new SnippetPlaceholder(node.Expression.ToString(), node.Expression.SpanStart)); - return arrayBuilder.ToImmutableAndClear(); + return new(arrayBuilder.ToImmutableAndClear()); } protected override int GetTargetCaretPosition(ForEachStatementSyntax forEachStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs index eb433a3aa0ae9..10a6b9d6620cc 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpLockSnippetProvider.cs @@ -25,11 +25,11 @@ internal sealed class CSharpLockSnippetProvider() : AbstractLockSnippetProvider< public override string Description => CSharpFeaturesResources.lock_statement; - protected override async ValueTask> GetPlaceHolderLocationsListAsync( + protected override ValueTask> GetPlaceHolderLocationsListAsync( Document document, LockStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var expression = node.Expression; - return [new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]; + return new([new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]); } protected override int GetTargetCaretPosition(LockStatementSyntax lockStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs index 1cb0ae592b30c..43f6e9f7a3ee1 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpUsingSnippetProvider.cs @@ -25,11 +25,11 @@ internal sealed class CSharpUsingSnippetProvider() : AbstractUsingSnippetProvide public override string Description => CSharpFeaturesResources.using_statement; - protected override async ValueTask> GetPlaceHolderLocationsListAsync( + protected override ValueTask> GetPlaceHolderLocationsListAsync( Document document, UsingStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var expression = node.Expression!; - return [new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]; + return new([new SnippetPlaceholder(expression.ToString(), expression.SpanStart)]); } protected override int GetTargetCaretPosition(UsingStatementSyntax usingStatement, SourceText sourceText) diff --git a/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs b/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs index 26c700c5a46a9..7c224bfc4c712 100644 --- a/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs @@ -27,9 +27,10 @@ internal sealed partial class CSharpIsAndCastCheckWithoutNameCodeFixProvider() public override ImmutableArray FixableDiagnosticIds => [IDEDiagnosticIds.InlineIsTypeWithoutNameCheckDiagnosticsId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, CSharpAnalyzersResources.Use_pattern_matching, nameof(CSharpAnalyzersResources.Use_pattern_matching), CodeActionPriority.Low); + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs index 8b3718486997a..0d937ea4b9e77 100644 --- a/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs +++ b/src/Features/CSharpTest/Copilot/CSharpImplementNotImplementedExceptionFixProviderTests.cs @@ -568,7 +568,7 @@ private sealed class CustomCompositionCSharpTest : VerifyCS.Test private TestWorkspace? _testWorkspace; private Action? _copilotServiceSetupAction; - protected override async Task CreateWorkspaceImplAsync() + protected override Task CreateWorkspaceImplAsync() { _testComposition = FeaturesTestCompositions.Features .AddParts([typeof(TestCopilotOptionsService), typeof(TestCopilotCodeAnalysisService)]); @@ -576,7 +576,7 @@ protected override async Task CreateWorkspaceImplAsync() // Trigger the action if it's set _copilotServiceSetupAction?.Invoke(GetCopilotService(_testWorkspace)); - return _testWorkspace; + return Task.FromResult(_testWorkspace); } public CustomCompositionCSharpTest WithMockCopilotService(Action setup) @@ -608,20 +608,20 @@ private sealed class TestCopilotOptionsService : ICopilotOptionsService [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestCopilotOptionsService() { } - public async Task IsRefineOptionEnabledAsync() - => true; + public Task IsRefineOptionEnabledAsync() + => Task.FromResult(true); - public async Task IsCodeAnalysisOptionEnabledAsync() - => true; + public Task IsCodeAnalysisOptionEnabledAsync() + => Task.FromResult(true); - public async Task IsOnTheFlyDocsOptionEnabledAsync() - => true; + public Task IsOnTheFlyDocsOptionEnabledAsync() + => Task.FromResult(true); - public async Task IsGenerateDocumentationCommentOptionEnabledAsync() - => true; + public Task IsGenerateDocumentationCommentOptionEnabledAsync() + => Task.FromResult(true); - public async Task IsImplementNotImplementedExceptionEnabledAsync() - => true; + public Task IsImplementNotImplementedExceptionEnabledAsync() + => Task.FromResult(true); } [ExportLanguageService(typeof(ICopilotCodeAnalysisService), LanguageNames.CSharp), Shared, PartNotDiscoverable] @@ -649,8 +649,8 @@ public Task> GetCachedDocumentDiagnosticsAsync(Docume public Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken) => throw new NotImplementedException(); - public async Task IsAvailableAsync(CancellationToken cancellationToken) - => true; + public Task IsAvailableAsync(CancellationToken cancellationToken) + => Task.FromResult(true); public Task IsFileExcludedAsync(string filePath, CancellationToken cancellationToken) => throw new NotImplementedException(); @@ -661,22 +661,22 @@ public Task StartRefinementSessionAsync(Document oldDocument, Document newDocume Task<(Dictionary? responseDictionary, bool isQuotaExceeded)> ICopilotCodeAnalysisService.GetDocumentationCommentAsync(DocumentationCommentProposal proposal, CancellationToken cancellationToken) => throw new NotImplementedException(); - public async Task> ImplementNotImplementedExceptionsAsync( + public Task> ImplementNotImplementedExceptionsAsync( Document document, ImmutableDictionary> methodOrProperties, CancellationToken cancellationToken) { if (SetupFixAll != null) { - return SetupFixAll.Invoke(document, methodOrProperties, cancellationToken); + return Task.FromResult(SetupFixAll.Invoke(document, methodOrProperties, cancellationToken)); } if (PrepareUsingSingleFakeResult != null) { - return CreateSingleNodeResult(methodOrProperties, PrepareUsingSingleFakeResult); + return Task.FromResult(CreateSingleNodeResult(methodOrProperties, PrepareUsingSingleFakeResult)); } - return ImmutableDictionary.Empty; + return Task.FromResult(ImmutableDictionary.Empty); } private static ImmutableDictionary CreateSingleNodeResult( @@ -692,9 +692,9 @@ private static ImmutableDictionary CreateSing return resultsBuilder.ToImmutable(); } - public async Task IsImplementNotImplementedExceptionsAvailableAsync(CancellationToken cancellationToken) + public Task IsImplementNotImplementedExceptionsAvailableAsync(CancellationToken cancellationToken) { - return true; + return Task.FromResult(true); } public Task GetOnTheFlyDocsPromptAsync(OnTheFlyDocsInfo onTheFlyDocsInfo, CancellationToken cancellationToken) diff --git a/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs b/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs index 97d7a938fcb34..7ca3b8ac3e7c9 100644 --- a/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs +++ b/src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs @@ -46,11 +46,11 @@ protected override IEnumerable GetCodeRefactoringProvid return [new CSharpExtractClassCodeRefactoringProvider(service)]; } - protected override async Task CreateWorkspaceImplAsync() + protected override Task CreateWorkspaceImplAsync() { var unusedCompilationOptions = new CSharpCompilationOptions(OutputKind.NetModule); var unusedParseOptions = new CSharpParseOptions(LanguageVersion.CSharp1); - return TestWorkspace.Create(WorkspaceKind, LanguageNames.CSharp, unusedCompilationOptions, unusedParseOptions); + return Task.FromResult(TestWorkspace.Create(WorkspaceKind, LanguageNames.CSharp, unusedCompilationOptions, unusedParseOptions)); } } diff --git a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs index 2676ce6666df3..1403c022fbd82 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/AssemblyReferenceCodeAction.cs @@ -78,14 +78,14 @@ public override void Apply(Workspace workspace, CancellationToken cancellationTo operation.Apply(workspace, cancellationToken); } - internal override async Task TryApplyAsync( + internal override Task TryApplyAsync( Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) { var operation = GetApplyChangesOperation(workspace); if (operation is null) - return false; + return SpecializedTasks.False; - return await operation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken).ConfigureAwait(false); + return operation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken); } private ApplyChangesOperation? GetApplyChangesOperation(Workspace workspace) diff --git a/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs index 04fa3b484b4c4..9d1f04f95a08d 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.cs @@ -22,11 +22,11 @@ private sealed class InstallWithPackageManagerCodeAction( public override string Title => FeaturesResources.Install_with_package_manager; - protected override async Task> ComputeOperationsAsync( + protected override Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { - return ImmutableArray.Create( - new InstallWithPackageManagerCodeActionOperation(_installerService, _packageName)); + return Task.FromResult(ImmutableArray.Create( + new InstallWithPackageManagerCodeActionOperation(_installerService, _packageName))); } private sealed class InstallWithPackageManagerCodeActionOperation( diff --git a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs index 1e77a938c9a3a..e2e3601ee0b2c 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/MetadataSymbolReferenceCodeAction.cs @@ -24,14 +24,14 @@ public MetadataSymbolReferenceCodeAction(Document originalDocument, AddImportFix Contract.ThrowIfFalse(fixData.Kind == AddImportFixKind.MetadataSymbol); } - protected override async Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) + protected override Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { var projectWithReference = project.Solution.GetRequiredProject(FixData.PortableExecutableReferenceProjectId); var reference = projectWithReference.MetadataReferences .OfType() .First(pe => pe.FilePath == FixData.PortableExecutableReferenceFilePathToAdd); - return new ApplyChangesOperation(project.AddMetadataReference(reference).Solution); + return Task.FromResult(new ApplyChangesOperation(project.AddMetadataReference(reference).Solution)); } } } diff --git a/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs b/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs index fff46496e5f09..30318b4a371b2 100644 --- a/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs @@ -37,19 +37,19 @@ public ProjectSymbolReferenceCodeAction( private static bool ShouldAddProjectReference(Document originalDocument, AddImportFixData fixData) => fixData.ProjectReferenceToAdd != null && fixData.ProjectReferenceToAdd != originalDocument.Project.Id; - protected override async Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) + protected override Task UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { if (!ShouldAddProjectReference(this.OriginalDocument, this.FixData)) - return null; + return SpecializedTasks.Null(); var projectWithAddedReference = project.AddProjectReference(new ProjectReference(FixData.ProjectReferenceToAdd)); var applyOperation = new ApplyChangesOperation(projectWithAddedReference.Solution); if (isPreview) { - return applyOperation; + return Task.FromResult(applyOperation); } - return new AddProjectReferenceCodeActionOperation(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, applyOperation); + return Task.FromResult(new AddProjectReferenceCodeActionOperation(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, applyOperation)); } private sealed class AddProjectReferenceCodeActionOperation(ProjectId referencingProject, ProjectId referencedProject, ApplyChangesOperation applyOperation) : CodeActionOperation @@ -68,13 +68,13 @@ public override void Apply(Workspace workspace, CancellationToken cancellationTo _applyOperation.Apply(workspace, cancellationToken); } - internal override async Task TryApplyAsync( + internal override Task TryApplyAsync( Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) { if (!CanApply(workspace)) - return false; + return SpecializedTasks.False; - return await _applyOperation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken).ConfigureAwait(false); + return _applyOperation.TryApplyAsync(workspace, originalSolution, progressTracker, cancellationToken); } private bool CanApply(Workspace workspace) diff --git a/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs b/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs index 2f2bbaea89636..d3662d9de4712 100644 --- a/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs +++ b/src/Features/Core/Portable/AddMissingReference/AddMissingReferenceCodeAction.cs @@ -70,22 +70,22 @@ public static async Task CreateAsync(Project project, AssemblyIdenti return new AddMissingReferenceCodeAction(project, description, null, missingAssemblyIdentity); } - protected override async Task> ComputeOperationsAsync( + protected override Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { // If we have a project reference to add, then add it if (_projectReferenceToAdd != null) { // note: no need to post process since we are just adding a project reference and not making any code changes. - return ImmutableArray.Create( - new ApplyChangesOperation(_project.AddProjectReference(_projectReferenceToAdd).Solution)); + return Task.FromResult(ImmutableArray.Create( + new ApplyChangesOperation(_project.AddProjectReference(_projectReferenceToAdd).Solution))); } else { // We didn't have any project, so we need to try adding a metadata reference var factoryService = _project.Solution.Services.GetRequiredService(); var operation = factoryService.CreateAddMetadataReferenceOperation(_project.Id, _missingAssemblyIdentity); - return ImmutableArray.Create(operation); + return Task.FromResult(ImmutableArray.Create(operation)); } } } diff --git a/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs b/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs index 036aa84ba4bb1..3489f4c596dc1 100644 --- a/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs +++ b/src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs @@ -30,6 +30,6 @@ internal sealed class InstallPackageDirectlyCodeAction( ? string.Format(FeaturesResources.Use_local_version_0, versionOpt) : string.Format(FeaturesResources.Install_version_0, versionOpt); - protected override async Task> ComputeOperationsAsync(IProgress progress, CancellationToken cancellationToken) - => ImmutableArray.Create(_installPackageOperation); + protected override Task> ComputeOperationsAsync(IProgress progress, CancellationToken cancellationToken) + => Task.FromResult(ImmutableArray.Create(_installPackageOperation)); } diff --git a/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs b/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs index 5309ff40e418b..9bdda9c841eea 100644 --- a/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs +++ b/src/Features/Core/Portable/AddPackage/InstallWithPackageManagerCodeAction.cs @@ -19,11 +19,11 @@ internal sealed class InstallWithPackageManagerCodeAction( public override string Title => FeaturesResources.Install_with_package_manager; - protected override async Task> ComputeOperationsAsync( + protected override Task> ComputeOperationsAsync( IProgress progress, CancellationToken cancellationToken) { - return ImmutableArray.Create( - new InstallWithPackageManagerCodeActionOperation(this)); + return Task.FromResult(ImmutableArray.Create( + new InstallWithPackageManagerCodeActionOperation(this))); } private sealed class InstallWithPackageManagerCodeActionOperation( diff --git a/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs b/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs index 32dd9baa90412..b467249f4a070 100644 --- a/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs +++ b/src/Features/Core/Portable/BraceCompletion/AbstractBraceCompletionService.cs @@ -38,19 +38,19 @@ internal abstract class AbstractBraceCompletionService : IBraceCompletionService public abstract bool AllowOverType(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); - public async ValueTask HasBraceCompletionAsync(BraceCompletionContext context, Document document, CancellationToken cancellationToken) + public ValueTask HasBraceCompletionAsync(BraceCompletionContext context, Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!context.HasCompletionForOpeningBrace(OpeningBrace)) - return false; + return ValueTask.FromResult(false); var openingToken = context.GetOpeningToken(); if (!NeedsSemantics) - return IsValidOpenBraceTokenAtPosition(context.Document.Text, openingToken, context.OpeningPoint); + return ValueTask.FromResult(IsValidOpenBraceTokenAtPosition(context.Document.Text, openingToken, context.OpeningPoint)); // Pass along a document with frozen partial semantics. Brace completion is a highly latency sensitive // operation. We don't want to wait on things like source generators to figure things out. - return await IsValidOpenBraceTokenAtPositionAsync(document.WithFrozenPartialSemantics(cancellationToken), openingToken, context.OpeningPoint, cancellationToken).ConfigureAwait(false); + return IsValidOpenBraceTokenAtPositionAsync(document.WithFrozenPartialSemantics(cancellationToken), openingToken, context.OpeningPoint, cancellationToken); } public BraceCompletionResult GetBraceCompletion(BraceCompletionContext context) diff --git a/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs b/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs index 7c89b81cbd770..832571f7667e0 100644 --- a/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs +++ b/src/Features/Core/Portable/ChangeSignature/DelegateInvokeMethodReferenceFinder.cs @@ -64,7 +64,7 @@ protected override async ValueTask> DetermineCascadedSym return result.ToImmutableAndClear(); } - protected override async Task DetermineDocumentsToSearchAsync( + protected override Task DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet? globalAliases, Project project, @@ -76,6 +76,8 @@ protected override async Task DetermineDocumentsToSearchAsync( { foreach (var document in project.Documents) processResult(document, processResultData); + + return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs b/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs index 249f4e6c6a875..a5d813b79a1f4 100644 --- a/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs +++ b/src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; diff --git a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs index f8a3c696bdf63..836235535dff4 100644 --- a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureCodeStyle/ConfigureCodeStyleOptionCodeFixProvider.cs @@ -52,11 +52,11 @@ public bool IsFixableDiagnostic(Diagnostic diagnostic) public FixAllProvider? GetFixAllProvider() => null; - public async Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) - => GetConfigurations(document.Project, diagnostics); + public Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) + => Task.FromResult(GetConfigurations(document.Project, diagnostics)); - public async Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) - => GetConfigurations(project, diagnostics); + public Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) + => Task.FromResult(GetConfigurations(project, diagnostics)); private static ImmutableArray GetConfigurations(Project project, IEnumerable diagnostics) { diff --git a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs index 74c7d6c3074c4..3a3d88501982b 100644 --- a/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.cs @@ -44,11 +44,11 @@ public bool IsFixableDiagnostic(Diagnostic diagnostic) public FixAllProvider? GetFixAllProvider() => null; - public async Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) - => GetConfigurations(document.Project, diagnostics, cancellationToken); + public Task> GetFixesAsync(TextDocument document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) + => Task.FromResult(GetConfigurations(document.Project, diagnostics, cancellationToken)); - public async Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) - => GetConfigurations(project, diagnostics, cancellationToken); + public Task> GetFixesAsync(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) + => Task.FromResult(GetConfigurations(project, diagnostics, cancellationToken)); private static ImmutableArray GetConfigurations(Project project, IEnumerable diagnostics, CancellationToken cancellationToken) { diff --git a/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs b/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs index bc6c93c86add6..90190f331627c 100644 --- a/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Service/CodeFixService.FixAllPredefinedDiagnosticProvider.cs @@ -19,13 +19,13 @@ private sealed class FixAllPredefinedDiagnosticProvider : FixAllContext.Diagnost public FixAllPredefinedDiagnosticProvider(ImmutableArray diagnostics) => _diagnostics = diagnostics; - public override async Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) - => _diagnostics; + public override Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) + => Task.FromResult>(_diagnostics); - public override async Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) - => _diagnostics; + public override Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) + => Task.FromResult>(_diagnostics); - public override async Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) - => []; + public override Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) + => SpecializedTasks.EmptyEnumerable(); } } diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs index d8d0e75811b5c..1aa81ab578563 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionBatchFixAllProvider.cs @@ -196,11 +196,12 @@ private static Action> GetRegisterCodeFix }; } - protected virtual async Task AddProjectFixesAsync( + protected virtual Task AddProjectFixesAsync( Project project, ImmutableArray diagnostics, ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes, FixAllState fixAllState, CancellationToken cancellationToken) { + return Task.CompletedTask; } public virtual async Task TryGetMergedFixAsync( @@ -215,7 +216,7 @@ protected virtual async Task AddProjectFixesAsync( if (newSolution != null && newSolution != solution) { var title = FixAllHelper.GetDefaultFixAllTitle(fixAllState.Scope, title: fixAllState.DiagnosticIds.First(), fixAllState.Document!, fixAllState.Project); - return CodeAction.SolutionChangeAction.Create(title, async _ => newSolution, title); + return CodeAction.SolutionChangeAction.Create(title, _ => Task.FromResult(newSolution), title); } return null; diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs index d2b64e7d0c591..d32c1f1e9e1df 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageFixAllCodeAction.cs @@ -57,10 +57,10 @@ private sealed class GlobalSuppressionSolutionChangeAction( Func, CancellationToken, Task> createChangedSolution, string equivalenceKey) : SolutionChangeAction(title, createChangedSolution, equivalenceKey, CodeActionPriority.Default, CodeActionCleanup.Default) { - protected override async Task PostProcessChangesAsync(Document document, CancellationToken cancellationToken) + protected override Task PostProcessChangesAsync(Document document, CancellationToken cancellationToken) { // PERF: We don't to formatting on the entire global suppressions document, but instead do it for each attribute individual in the fixer. - return document; + return Task.FromResult(document); } } diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs index 6ea562e6e40ec..ec1584616a016 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.cs @@ -146,7 +146,7 @@ public override async Task TryGetMergedFixAsync( var batchAttributeRemoveFix = CodeAction.Create( attributeRemoveFixes.First().Title, - createChangedSolution: async ct => currentSolution, + createChangedSolution: ct => Task.FromResult(currentSolution), equivalenceKey: fixAllState.CodeActionEquivalenceKey); newBatchOfFixes.Insert(0, (diagnostic: null, batchAttributeRemoveFix)); diff --git a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs index a726c631255ea..e5e5b8521de94 100644 --- a/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs @@ -138,13 +138,13 @@ private SyntaxToken GetAdjustedTokenForPragmaRestore(SyntaxToken token, SyntaxNo return token; } - public async Task> GetFixesAsync( + public Task> GetFixesAsync( TextDocument textDocument, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) { if (textDocument is not Document document) - return ImmutableArray.Empty; + return Task.FromResult(ImmutableArray.Empty); - return await GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken).ConfigureAwait(false); + return GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken); } internal async Task> GetPragmaSuppressionsAsync(Document document, TextSpan span, IEnumerable diagnostics, CancellationToken cancellationToken) diff --git a/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs b/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs index 1d33c509c2e16..1eea7eaac7c52 100644 --- a/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs +++ b/src/Features/Core/Portable/CodeLens/CodeLensReferencesService.cs @@ -91,11 +91,11 @@ public async ValueTask GetProjectCodeLensVersionAsync(Solution sol { var projectVersion = await GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false); return await FindAsync(solution, documentId, syntaxNode, - async progress => new ReferenceCount( + progress => Task.FromResult(new ReferenceCount( progress.SearchCap > 0 ? Math.Min(progress.ReferencesCount, progress.SearchCap) - : progress.ReferencesCount, progress.SearchCapReached, projectVersion.ToString()), - async progress => new ReferenceCount(progress.SearchCap, IsCapped: true, projectVersion.ToString()), + : progress.ReferencesCount, progress.SearchCapReached, projectVersion.ToString())), + progress => Task.FromResult(new ReferenceCount(progress.SearchCap, IsCapped: true, projectVersion.ToString())), maxSearchResults, cancellationToken).ConfigureAwait(false); } diff --git a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs index 7b0de443d6fe9..73607e6b9e236 100644 --- a/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs +++ b/src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs @@ -28,7 +28,8 @@ public override async Task> GetOperationsAsy return [new ApplyChangesOperation(newSolution)]; } - public override async Task GetModifiedSolutionAsync() - => SemanticDocument.Project.Solution.WithDocumentName(SemanticDocument.Document.Id, FileName); + public override Task GetModifiedSolutionAsync() + => Task.FromResult( + SemanticDocument.Project.Solution.WithDocumentName(SemanticDocument.Document.Id, FileName)); } } diff --git a/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs b/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs index 0cd16958e722c..be2eabb3e952e 100644 --- a/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/CommonCompletionProvider.cs @@ -117,8 +117,8 @@ public override async Task GetChangeAsync(Document document, C public virtual Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => GetTextChangeAsync(selectedItem, ch, cancellationToken); - protected virtual async Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) - => null; + protected virtual Task GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + => SpecializedTasks.Default(); protected static CompletionItem CreateSuggestionModeItem(string? displayText, string? description) { diff --git a/src/Features/Core/Portable/Completion/CompletionProvider.cs b/src/Features/Core/Portable/Completion/CompletionProvider.cs index 975380a6b9c94..c16459cb06398 100644 --- a/src/Features/Core/Portable/Completion/CompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/CompletionProvider.cs @@ -60,8 +60,8 @@ internal virtual async Task IsSyntacticTriggerCharacterAsync(Document docu /// /// Gets the description of the specified item. /// - public virtual async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) - => CompletionDescription.Empty; + public virtual Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + => Task.FromResult(CompletionDescription.Empty); internal virtual Task GetDescriptionAsync(Document document, CompletionItem item, CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) #pragma warning disable RS0030 // Do not used banned APIs @@ -74,8 +74,8 @@ internal virtual async Task IsSyntacticTriggerCharacterAsync(Document docu /// The current document. /// The item to be committed. /// The optional key character that caused the commit. - public virtual async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) - => CompletionChange.Create(new TextChange(item.Span, item.DisplayText)); + public virtual Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + => Task.FromResult(CompletionChange.Create(new TextChange(item.Span, item.DisplayText))); /// /// True if the provider produces snippet items. diff --git a/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs b/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs index d49fd9bbf6a7e..72ec826ec8b1c 100644 --- a/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs +++ b/src/Features/Core/Portable/Completion/CompletionService.ProviderManager.cs @@ -81,7 +81,7 @@ private IReadOnlyList> GetL return _lazyImportedProviders; } - private async ValueTask ProcessBatchAsync(ImmutableSegmentedList> referencesList, CancellationToken cancellationToken) + private ValueTask ProcessBatchAsync(ImmutableSegmentedList> referencesList, CancellationToken cancellationToken) { foreach (var references in referencesList) { @@ -90,6 +90,8 @@ private async ValueTask ProcessBatchAsync(ImmutableSegmentedList GetCachedProjectCompletionProvidersOrQueueLoadInBackground(Project? project, CompletionOptions options) diff --git a/src/Features/Core/Portable/Completion/CompletionService.cs b/src/Features/Core/Portable/Completion/CompletionService.cs index 6d2195ce377ba..c880d896d33f9 100644 --- a/src/Features/Core/Portable/Completion/CompletionService.cs +++ b/src/Features/Core/Portable/Completion/CompletionService.cs @@ -375,9 +375,9 @@ internal static bool IsAllPunctuation(string filterText) return true; } - internal virtual async ValueTask IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) + internal virtual Task IsSpeculativeTypeParameterContextAsync(Document document, int position, CancellationToken cancellationToken) { - return false; + return SpecializedTasks.False; } /// diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs index 39136c307568d..2c44eb5daa37e 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractKeywordCompletionProvider.cs @@ -72,6 +72,6 @@ private async Task> RecommendKeywordsAsync( return result.ToImmutableAndClear(); } - public sealed override async Task GetTextChangeAsync(Document document, CompletionItem item, char? ch, CancellationToken cancellationToken) - => (TextChange?)new TextChange(item.Span, item.DisplayText); + public sealed override Task GetTextChangeAsync(Document document, CompletionItem item, char? ch, CancellationToken cancellationToken) + => Task.FromResult((TextChange?)new TextChange(item.Span, item.DisplayText)); } diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs index 9f754edc28a87..94e1170f2e2f9 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractObjectCreationCompletionProvider.cs @@ -44,12 +44,12 @@ protected override CompletionItem CreateItem( supportedPlatforms: supportedPlatformData); } - protected override async Task> GetSymbolsAsync( + protected override Task> GetSymbolsAsync( CompletionContext? completionContext, TSyntaxContext context, int position, CompletionOptions options, CancellationToken cancellationToken) { var newExpression = GetObjectCreationNewExpression(context.SyntaxTree, position, cancellationToken); if (newExpression == null) - return []; + return SpecializedTasks.EmptyImmutableArray(); var typeInferenceService = context.GetRequiredLanguageService(); var type = typeInferenceService.InferType( @@ -62,20 +62,20 @@ protected override async Task> GetSymbols type = arrayType.ElementType; if (type == null) - return []; + return SpecializedTasks.EmptyImmutableArray(); // Unwrap nullable if (type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) type = type.GetTypeArguments().Single(); if (type.SpecialType == SpecialType.System_Void) - return []; + return SpecializedTasks.EmptyImmutableArray(); if (type.ContainsAnonymousType()) - return []; + return SpecializedTasks.EmptyImmutableArray(); if (!type.CanBeReferencedByName) - return []; + return SpecializedTasks.EmptyImmutableArray(); // Normally the user can't say things like "new IList". Except for "IList[] x = new |". // In this case we do want to allow them to preselect certain types in the completion @@ -85,18 +85,18 @@ protected override async Task> GetSymbols if (type.TypeKind is TypeKind.Interface or TypeKind.Pointer or TypeKind.Dynamic || type.IsAbstract) { - return []; + return SpecializedTasks.EmptyImmutableArray(); } if (type is ITypeParameterSymbol typeParameter && !typeParameter.HasConstructorConstraint) - return []; + return SpecializedTasks.EmptyImmutableArray(); } if (!type.IsEditorBrowsable(options.MemberDisplayOptions.HideAdvancedMembers, context.SemanticModel.Compilation)) - return []; + return SpecializedTasks.EmptyImmutableArray(); // In the case of array creation, we don't offer a preselected/hard-selected item because // the user may want an implicitly-typed array creation - return ImmutableArray.Create(new SymbolAndSelectionInfo(Symbol: type, Preselect: !isArray)); + return Task.FromResult(ImmutableArray.Create(new SymbolAndSelectionInfo(Symbol: type, Preselect: !isArray))); } } diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs index 54fdc40b7a468..01fac320c09b8 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs @@ -110,9 +110,9 @@ private static bool NotNewDeclaredMember(INamedTypeSymbol symbol, TSyntaxContext internal override Task GetDescriptionWorkerAsync(Document document, CompletionItem item, CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, displayOptions, cancellationToken); - public override async Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + public override Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { var insertionText = SymbolCompletionItem.GetInsertionText(selectedItem); - return new TextChange(selectedItem.Span, insertionText); + return Task.FromResult(new TextChange(selectedItem.Span, insertionText)); } } diff --git a/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs index 9fe46ca17d807..1a11cdd1da824 100644 --- a/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.cs @@ -379,8 +379,8 @@ private async Task> GetItemsAsync( protected virtual bool IsExclusive() => false; - protected virtual async Task IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) - => true; + protected virtual Task IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) + => SpecializedTasks.True; private static Dictionary UnionSymbols( ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray symbols)> linkedContextSymbolLists) @@ -466,8 +466,8 @@ private static Dictionary> FindSymbolsMissingIn return missingSymbols; } - public sealed override async Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) - => new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch)); + public sealed override Task GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) + => Task.FromResult(new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch))); private string GetInsertionText(CompletionItem item, char? ch) { diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs index 0168eb4651f89..d42f558318a47 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs @@ -25,9 +25,10 @@ internal abstract class AbstractImportCompletionProvider : LSPCompletionProvider protected abstract Task ShouldProvideParenthesisCompletionAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken); protected abstract void LogCommit(); - public async Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { LogCommit(); + return Task.CompletedTask; } internal override bool IsExpandItemProvider => true; diff --git a/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs b/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs index deaa61c5bce4f..385012c4d2d87 100644 --- a/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs +++ b/src/Features/Core/Portable/ConvertLinq/AbstractConvertLinqQueryToForEachProvider.cs @@ -46,7 +46,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte context.RegisterRefactoring( CodeAction.Create( Title, - async c => document.WithSyntaxRoot(documentUpdateInfo.UpdateRoot(root)), + c => Task.FromResult(document.WithSyntaxRoot(documentUpdateInfo.UpdateRoot(root))), Title), queryExpression.Span); } diff --git a/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs b/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs index b7fbd35741236..994a2a9d97799 100644 --- a/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs +++ b/src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConvertForEachToLinqQueryProvider.cs @@ -142,7 +142,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte } } - private async Task ApplyConversionAsync( + private Task ApplyConversionAsync( IConverter converter, Document document, bool convertToQuery, @@ -152,7 +152,7 @@ private async Task ApplyConversionAsync( converter.Convert(editor, convertToQuery, cancellationToken); var newRoot = editor.GetChangedRoot(); var rootWithLinqUsing = AddLinqUsing(converter, converter.ForEachInfo.SemanticModel, newRoot); - return document.WithSyntaxRoot(rootWithLinqUsing); + return Task.FromResult(document.WithSyntaxRoot(rootWithLinqUsing)); } /// diff --git a/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs b/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs index c2e890257774f..4bcc920a74e59 100644 --- a/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertNumericLiteral/AbstractConvertNumericLiteralCodeRefactoringProvider.cs @@ -119,13 +119,13 @@ static string AddSeparators(string numericText, int interval) return result[0] == '_' ? result[1..] : result; } - static async Task ReplaceTokenAsync(Document document, SyntaxNode root, SyntaxToken numericToken, long value, string text, string suffix) + static Task ReplaceTokenAsync(Document document, SyntaxNode root, SyntaxToken numericToken, long value, string text, string suffix) { var generator = SyntaxGenerator.GetGenerator(document); var updatedToken = generator.NumericLiteralToken(text + suffix, (ulong)value) .WithTriviaFrom(numericToken); var updatedRoot = root.ReplaceToken(numericToken, updatedToken); - return document.WithSyntaxRoot(updatedRoot); + return Task.FromResult(document.WithSyntaxRoot(updatedRoot)); } (string prefix, string number, string suffix) GetNumericLiteralParts(string numericText) diff --git a/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs b/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs index 1244fadf004d5..db0e91296f327 100644 --- a/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs +++ b/src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.cs @@ -103,13 +103,13 @@ private static SyntaxNode CreateInterpolatedString(Document document, SyntaxNode generator.CreateInterpolatedStringEndToken()).WithTriviaFrom(literalExpression); } - private static async Task UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxToken token) + private static Task UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxToken token) { var syntaxFacts = document.GetRequiredLanguageService(); var literalExpression = token.GetRequiredParent(); - return document.WithSyntaxRoot( + return Task.FromResult(document.WithSyntaxRoot( root.ReplaceNode( literalExpression, - CreateInterpolatedString(document, literalExpression, syntaxFacts.IsVerbatimStringLiteral(token)))); + CreateInterpolatedString(document, literalExpression, syntaxFacts.IsVerbatimStringLiteral(token))))); } } diff --git a/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs b/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs index 52b94e08b9c56..57c6616b4b9e0 100644 --- a/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs +++ b/src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs @@ -46,7 +46,7 @@ private sealed class Portable(MetadataReaderProvider pdbReaderProvider) : DebugI public override EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader() => EditAndContinueMethodDebugInfoReader.Create(_pdbReaderProvider.GetMetadataReader()); - public override async ValueTask CopyContentToAsync(Stream stream, CancellationToken cancellationToken) + public override ValueTask CopyContentToAsync(Stream stream, CancellationToken cancellationToken) { var reader = _pdbReaderProvider.GetMetadataReader(); unsafe @@ -54,6 +54,8 @@ public override async ValueTask CopyContentToAsync(Stream stream, CancellationTo using var metadataStream = new UnmanagedMemoryStream(reader.MetadataPointer, reader.MetadataLength); metadataStream.CopyTo(stream); } + + return ValueTask.CompletedTask; } public override void Dispose() diff --git a/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs b/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs index 44ab3a135cd52..0c3ed361576ef 100644 --- a/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs +++ b/src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.cs @@ -197,10 +197,10 @@ private async Task> FilterAndCreateSpansAsync documentsToSearch, cancellationToken).ConfigureAwait(false); } - protected virtual async ValueTask> GetAdditionalReferencesAsync( + protected virtual Task> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { - return []; + return SpecializedTasks.EmptyImmutableArray(); } private static async Task> CreateSpansAsync( diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs index 5ba173cc9947b..f87762dd30276 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs @@ -207,7 +207,7 @@ public ValueTask> GetDocumentDiagnosticsAsync(Documen cancellationToken); } - public async ValueTask EmitSolutionUpdateAsync( + public ValueTask EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ImmutableDictionary runningProjects, @@ -217,10 +217,10 @@ public async ValueTask EmitSolutionUpdateAsync( var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { - return EmitSolutionUpdateResults.Empty; + return ValueTask.FromResult(EmitSolutionUpdateResults.Empty); } - return await debuggingSession.EmitSolutionUpdateAsync(solution, runningProjects, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); + return debuggingSession.EmitSolutionUpdateAsync(solution, runningProjects, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId) @@ -239,7 +239,7 @@ public void DiscardSolutionUpdate(DebuggingSessionId sessionId) debuggingSession.DiscardSolutionUpdate(); } - public async ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) + public ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) @@ -247,18 +247,18 @@ public async ValueTask>> GetB return default; } - return await debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken).ConfigureAwait(false); + return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } - public async ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + public ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { - return ImmutableArray.Empty; + return ValueTask.FromResult(ImmutableArray.Empty); } - return await debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); + return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } internal TestAccessor GetTestAccessor() diff --git a/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs b/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs index d65ff0e616248..35f21c48e4adf 100644 --- a/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs +++ b/src/Features/Core/Portable/EditAndContinue/IPdbMatchingSourceTextProvider.cs @@ -24,6 +24,6 @@ private NullPdbMatchingSourceTextProvider() { } - public async ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) - => null; + public ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) + => ValueTask.FromResult(null); } diff --git a/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs b/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs index 6e182ad2bd3ec..9f89c0e96515a 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedCompletionProvider.cs @@ -212,7 +212,7 @@ private static void ProvideCustomFormats(EmbeddedCompletionContext context) context.AddCustom("/", FeaturesResources.date_separator, FeaturesResources.date_separator_description); } - public override async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public override Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { // These values have always been added by us. var startString = item.GetProperty(StartKey); @@ -223,16 +223,16 @@ public override async Task GetChangeAsync(Document document, C Contract.ThrowIfNull(lengthString); Contract.ThrowIfNull(newText); - return CompletionChange.Create( - new TextChange(new TextSpan(int.Parse(startString), int.Parse(lengthString)), newText)); + return Task.FromResult(CompletionChange.Create( + new TextChange(new TextSpan(int.Parse(startString), int.Parse(lengthString)), newText))); } - public override async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + public override Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { if (!item.TryGetProperty(DescriptionKey, out var description)) - return null; + return SpecializedTasks.Null(); - return (CompletionDescription?)CompletionDescription.Create( - [new TaggedText(TextTags.Text, description)]); + return Task.FromResult((CompletionDescription?)CompletionDescription.Create( + [new TaggedText(TextTags.Text, description)])); } } diff --git a/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs b/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs index b9ae7ce4dc6d9..a0416c4bb3e3e 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/Json/LanguageServices/AbstractJsonDetectionCodeFixProvider.cs @@ -32,9 +32,10 @@ protected AbstractJsonDetectionCodeFixProvider( public override ImmutableArray FixableDiagnosticIds => [AbstractJsonDetectionAnalyzer.DiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, FeaturesResources.Enable_all_JSON_editor_features, nameof(FeaturesResources.Enable_all_JSON_editor_features)); + return Task.CompletedTask; } public void Fix(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken) @@ -49,11 +50,13 @@ public void Fix(SyntaxEditor editor, Diagnostic diagnostic, CancellationToken ca this.AddComment(editor, stringLiteral, commentContents); } - protected override async Task FixAllAsync( + protected override Task FixAllAsync( Document document, ImmutableArray diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) Fix(editor, diagnostic, cancellationToken); + + return Task.CompletedTask; } } diff --git a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs index e5d37962ef1bc..262367f29eecd 100644 --- a/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs +++ b/src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedCompletionProvider.cs @@ -442,7 +442,7 @@ bool IsInCharacterClassWorker(RegexNode parent, bool inCharacterClass) } } - public override async Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) + public override Task GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { // These values have always been added by us. var startString = item.GetProperty(StartKey); @@ -452,19 +452,19 @@ public override async Task GetChangeAsync(Document document, C // This value is optionally added in some cases and may not always be there. item.TryGetProperty(NewPositionKey, out var newPositionString); - return CompletionChange.Create( + return Task.FromResult(CompletionChange.Create( new TextChange(new TextSpan(int.Parse(startString), int.Parse(lengthString)), newText), - newPositionString == null ? null : int.Parse(newPositionString)); + newPositionString == null ? null : int.Parse(newPositionString))); } - public override async Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) + public override Task GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { if (!item.TryGetProperty(DescriptionKey, out var description)) { - return null; + return SpecializedTasks.Null(); } - return CompletionDescription.Create( - [new TaggedText(TextTags.Text, description)]); + return Task.FromResult(CompletionDescription.Create( + [new TaggedText(TextTags.Text, description)])); } } diff --git a/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs b/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs index 916692a3d8c54..bbbbdb6ce1450 100644 --- a/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs +++ b/src/Features/Core/Portable/Extensions/ExtensionMessageHandlerService.cs @@ -70,7 +70,7 @@ private void ClearCachedHandlers_WhileUnderLock() _cachedHandlers_useOnlyUnderLock.document.Clear(); } - private async ValueTask RegisterExtensionInCurrentProcessAsync(string assemblyFilePath) + private ValueTask RegisterExtensionInCurrentProcessAsync(string assemblyFilePath) { // Note: This method executes no extension code. And, as such, does not try to catch exceptions to // translate them accordingly to a failure that we send back to the client as part of the response. @@ -89,11 +89,11 @@ private async ValueTask RegisterExtensionInCurrentProcessAsync(string assemblyFi assemblyFolderPath => new ExtensionFolder(this, assemblyFolderPath)); extensionFolder.RegisterAssembly(assemblyFilePath); - return; + return default; } } - private async ValueTask UnregisterExtensionInCurrentProcessAsync(string assemblyFilePath) + private ValueTask UnregisterExtensionInCurrentProcessAsync(string assemblyFilePath) { // Note: This method executes no extension code. And, as such, does not try to catch exceptions to // translate them accordingly to a failure that we send back to the client as part of the response. @@ -104,7 +104,7 @@ private async ValueTask UnregisterExtensionInCurrentProcessAsync(string assembly // to unload all ALCs needed to load it and the extensions within. Unloading will happen once the // runtime/gc determine the ALC is finally collectible. folderToUnload?.Unload(); - return; + return default; ExtensionFolder? Unregister() { @@ -144,7 +144,7 @@ private async ValueTask UnregisterExtensionInCurrentProcessAsync(string assembly } } - private async ValueTask ResetInCurrentProcessAsync() + private ValueTask ResetInCurrentProcessAsync() { // Note: This method executes no extension code. And, as such, does not try to catch exceptions to // translate them accordingly to a failure that we send back to the client as part of the response. @@ -161,6 +161,8 @@ private async ValueTask ResetInCurrentProcessAsync() foreach (var (_, folderToUnload) in oldFolderPathToExtensionFolder) folderToUnload.Unload(); + + return default; } private async ValueTask GetExtensionMessageNamesInCurrentProcessAsync( diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs index 50a7d6aceee73..98ff20b113e32 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/NewUnitTestingIncrementalAnalyzer.cs @@ -36,9 +36,10 @@ public Task AnalyzeProjectAsync( cancellationToken); } - public async Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) + public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { _implementation.RemoveDocument(documentId); + return Task.CompletedTask; } } } diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs index ec482cd1e5459..15c0db217f5c1 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.cs @@ -19,14 +19,14 @@ private sealed class DebuggerService(ImmutableArray capabilities) : IMan { private readonly ImmutableArray _capabilities = capabilities; - public async ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); - public async ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) - => new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available); + public ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) + => ValueTask.FromResult(new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available)); - public async ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) - => _capabilities; + public ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) + => ValueTask.FromResult(_capabilities); public ValueTask PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => ValueTask.CompletedTask; @@ -49,7 +49,7 @@ public readonly struct Update( } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = - async (_, _, _) => ImmutableArray.Empty; + (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); private readonly IEditAndContinueService _encService = services.GetRequiredService().Service; private DebuggingSessionId _sessionId; diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs index c55f42fc2a8ba..27045155dbabf 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/LegacySolutionEvents/UnitTestingLegacySolutionEventsListener.cs @@ -45,9 +45,10 @@ public bool ShouldReportChanges(SolutionServices services) return service.HasRegisteredAnalyzerProviders; } - public async ValueTask OnWorkspaceChangedAsync(WorkspaceChangeEventArgs args, CancellationToken cancellationToken) + public ValueTask OnWorkspaceChangedAsync(WorkspaceChangeEventArgs args, CancellationToken cancellationToken) { var coordinator = GetCoordinator(args.NewSolution); coordinator?.OnWorkspaceChanged(args); + return ValueTask.CompletedTask; } } diff --git a/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs index e021b9b6f8bf4..7f767cb6c8737 100644 --- a/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs +++ b/src/Features/Core/Portable/ExternalAccess/UnitTesting/Notification/AbstractGlobalOperationNotificationService.cs @@ -45,13 +45,15 @@ protected AbstractGlobalOperationNotificationService( } } - private async ValueTask ProcessEventsAsync(ImmutableSegmentedList list, CancellationToken cancellationToken) + private ValueTask ProcessEventsAsync(ImmutableSegmentedList list, CancellationToken cancellationToken) { foreach (var value in list) { var eventHandler = value ? Started : Stopped; eventHandler?.Invoke(this, EventArgs.Empty); } + + return ValueTask.CompletedTask; } public IDisposable Start(string operation) diff --git a/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs b/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs index ac0a89f5d327a..dfa94995ac4e3 100644 --- a/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs +++ b/src/Features/Core/Portable/FindUsages/DefaultExternalDefinitionItemProvider.cs @@ -20,6 +20,6 @@ internal sealed class DefaultExternalDefinitionItemProvider() : IExternalDefinit /// Provides an extension point that allows for other workspace layers to add additional /// results to the results found by the FindReferences engine. /// - public async ValueTask GetThirdPartyDefinitionItemAsync(Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) - => null; + public Task GetThirdPartyDefinitionItemAsync(Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) + => SpecializedTasks.Null(); } diff --git a/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs b/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs index 932f1c3ca41a1..bfab728b62a21 100644 --- a/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs +++ b/src/Features/Core/Portable/FindUsages/IExternalDefinitionItemProvider.cs @@ -10,6 +10,6 @@ namespace Microsoft.CodeAnalysis.FindUsages; internal interface IExternalDefinitionItemProvider : IWorkspaceService { - ValueTask GetThirdPartyDefinitionItemAsync( + Task GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken); } diff --git a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs index 7eb8ba507080c..947ae6b37ea81 100644 --- a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs +++ b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs @@ -46,12 +46,12 @@ internal abstract partial class AbstractInitializeMemberFromParameterCodeRefacto protected abstract Accessibility DetermineDefaultPropertyAccessibility(); protected abstract SyntaxNode RemoveThrowNotImplemented(SyntaxNode propertySyntax); - protected sealed override async Task> GetRefactoringsForAllParametersAsync( + protected sealed override Task> GetRefactoringsForAllParametersAsync( Document document, SyntaxNode functionDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray listOfParameterNodes, TextSpan parameterSpan, CancellationToken cancellationToken) { - return []; + return SpecializedTasks.EmptyImmutableArray(); } protected sealed override async Task> GetRefactoringsForSingleParameterAsync( diff --git a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs index 5e077232d7b6c..04c51af3abbf4 100644 --- a/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs +++ b/src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs @@ -18,13 +18,13 @@ internal abstract partial class AbstractSymbolDisplayService(LanguageServices se protected abstract AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(SemanticModel semanticModel, int position, SymbolDescriptionOptions options, CancellationToken cancellationToken); - public async Task> ToDescriptionPartsAsync(SemanticModel semanticModel, int position, ImmutableArray symbols, SymbolDescriptionOptions options, SymbolDescriptionGroups groups, CancellationToken cancellationToken) + public Task> ToDescriptionPartsAsync(SemanticModel semanticModel, int position, ImmutableArray symbols, SymbolDescriptionOptions options, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { if (symbols.Length == 0) - return []; + return SpecializedTasks.EmptyImmutableArray(); var builder = CreateDescriptionBuilder(semanticModel, position, options, cancellationToken); - return await builder.BuildDescriptionAsync(symbols, groups).ConfigureAwait(false); + return builder.BuildDescriptionAsync(symbols, groups); } public async Task>> ToDescriptionGroupsAsync( diff --git a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs index 31a28e8d7070a..fdffff0191d32 100644 --- a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs +++ b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs @@ -167,18 +167,18 @@ private static int GetNamespaceInSpineCount(SyntaxNode node) private static bool ContainsMultipleTypesInSpine(SyntaxNode node) => node.AncestorsAndSelf().OfType().Count() > 1; - public async Task MoveToNamespaceAsync( + public Task MoveToNamespaceAsync( MoveToNamespaceAnalysisResult analysisResult, string targetNamespace, CancellationToken cancellationToken) { if (!analysisResult.CanPerform) - return MoveToNamespaceResult.Failed; + return Task.FromResult(MoveToNamespaceResult.Failed); return analysisResult.Container switch { - MoveToNamespaceAnalysisResult.ContainerType.Namespace => await MoveItemsInNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken).ConfigureAwait(false), - MoveToNamespaceAnalysisResult.ContainerType.NamedType => await MoveTypeToNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken).ConfigureAwait(false), + MoveToNamespaceAnalysisResult.ContainerType.Namespace => MoveItemsInNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken), + MoveToNamespaceAnalysisResult.ContainerType.NamedType => MoveTypeToNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken), _ => throw new InvalidOperationException(), }; } diff --git a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs index ec8df45129b0d..d5b37c9fa304b 100644 --- a/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs +++ b/src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.CachedDocumentSearch.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.Remote; +using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Threading; using Roslyn.Utilities; @@ -156,18 +157,18 @@ await Parallel.ForEachAsync( } } - private static async ValueTask GetIndexAsync( + private static Task GetIndexAsync( IChecksummedPersistentStorageService storageService, DocumentKey documentKey, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) - return null; + return SpecializedTasks.Null(); // Retrieve the string table we use to dedupe strings. If we can't get it, that means the solution has // fully loaded and we've switched over to normal navto lookup. if (!ShouldSearchCachedDocuments(out var cachedIndexMap, out var stringTable)) - return null; + return SpecializedTasks.Null(); // Add the async lazy to compute the index for this document. Or, return the existing cached one if already // present. This ensures that subsequent searches that are run while the solution is still loading are fast @@ -180,6 +181,6 @@ await Parallel.ForEachAsync( static t => AsyncLazy.Create(static (t, c) => TopLevelSyntaxTreeIndex.LoadAsync(t.service, t.documentKey, checksum: null, t.stringTable, c), arg: t)); - return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); + return asyncLazy.GetValueAsync(cancellationToken); } } diff --git a/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs b/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs index d27eedd9e5ced..4db3bc8000888 100644 --- a/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs +++ b/src/Features/Core/Portable/NavigateTo/NavigateToSearcher.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; +using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; @@ -195,22 +196,22 @@ await service.SearchDocumentAsync( cancellationToken).ConfigureAwait(false); } - private async Task SearchCurrentProjectAsync( + private Task SearchCurrentProjectAsync( NavigateToDocumentSupport documentSupport, CancellationToken cancellationToken) { if (_activeDocument == null) - return; + return Task.CompletedTask; var activeProject = _activeDocument.Project; - await SearchSpecificProjectsAsync( + return SearchSpecificProjectsAsync( // Because we're only searching the current project, it's fine to bring that project fully up to date before // searching it. We only do the work to search cached files when doing the initial load of something huge // (the full solution). isFullyLoaded: true, documentSupport, [[activeProject]], - cancellationToken).ConfigureAwait(false); + cancellationToken); } private INavigateToSearchService GetNavigateToSearchService(Project project) diff --git a/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs b/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs index b6fb06cecd542..d119541fd91d4 100644 --- a/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs +++ b/src/Features/Core/Portable/Navigation/DefaultSymbolNavigationService.cs @@ -12,12 +12,12 @@ namespace Microsoft.CodeAnalysis.Navigation; internal sealed class DefaultSymbolNavigationService : ISymbolNavigationService { - public async Task GetNavigableLocationAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) - => null; + public Task GetNavigableLocationAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task TrySymbolNavigationNotifyAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) - => false; + public Task TrySymbolNavigationNotifyAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task<(string filePath, LinePosition linePosition)?> GetExternalNavigationSymbolLocationAsync(DefinitionItem definitionItem, CancellationToken cancellationToken) - => null; + public Task<(string filePath, LinePosition linePosition)?> GetExternalNavigationSymbolLocationAsync(DefinitionItem definitionItem, CancellationToken cancellationToken) + => Task.FromResult<(string filePath, LinePosition linePosition)?>(null); } diff --git a/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs b/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs index 503e1fc3153a9..006506a55e49c 100644 --- a/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs +++ b/src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs @@ -30,14 +30,14 @@ internal interface IDocumentNavigationService : IWorkspaceService internal abstract class AbstractDocumentNavigationService : IDocumentNavigationService { - public virtual async Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => false; + public virtual Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => SpecializedTasks.False; public virtual Task CanNavigateToPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) => CanNavigateToSpanAsync(workspace, documentId, new TextSpan(position, 0), allowInvalidSpan: allowInvalidPosition, cancellationToken); - public virtual async Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => null; + public virtual Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => SpecializedTasks.Null(); public virtual Task GetLocationForPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) => GetLocationForSpanAsync(workspace, documentId, new TextSpan(position, 0), allowInvalidSpan: allowInvalidPosition, cancellationToken); diff --git a/src/Features/Core/Portable/Navigation/INavigableLocation.cs b/src/Features/Core/Portable/Navigation/INavigableLocation.cs index d71f6b623a551..84eee62f5d52c 100644 --- a/src/Features/Core/Portable/Navigation/INavigableLocation.cs +++ b/src/Features/Core/Portable/Navigation/INavigableLocation.cs @@ -33,10 +33,11 @@ public Task NavigateToAsync(NavigationOptions options, CancellationToken c public static class TestAccessor { #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods - public static async Task Create(bool value) + public static Task Create(bool value) #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods { - return new NavigableLocation(async (_, _) => value); + return Task.FromResult( + new NavigableLocation((_, _) => value ? SpecializedTasks.True : SpecializedTasks.False)); } } } diff --git a/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs b/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs index af84d4e22a275..026aafeb92c19 100644 --- a/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/OrganizeImports/OrganizeImportsCodeRefactoringProvider.cs @@ -88,7 +88,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte context.RegisterRefactoring(CodeAction.Create( document.GetRequiredLanguageService().SortImportsDisplayStringWithoutAccelerator, - async cancellationToken => document.WithSyntaxRoot(newRoot)), + cancellationToken => Task.FromResult(document.WithSyntaxRoot(newRoot))), applicableToSpan: imports.GetContainedSpan()); } } diff --git a/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs b/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs index 2e8b4b7f87f53..416ee5dc0c44b 100644 --- a/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs +++ b/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs @@ -23,13 +23,15 @@ internal sealed class PreferFrameworkTypeCodeFixProvider() : SyntaxEditorBasedCo public sealed override ImmutableArray FixableDiagnosticIds { get; } = [IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId]; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; if (diagnostic.Properties.ContainsKey(PreferFrameworkTypeConstants.PreferFrameworkType)) { RegisterCodeFix(context, FeaturesResources.Use_framework_type, nameof(FeaturesResources.Use_framework_type)); } + + return Task.CompletedTask; } protected override async Task FixAllAsync( diff --git a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs index 5d2f29b895f1a..5a55c3ae91af3 100644 --- a/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs +++ b/src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.cs @@ -185,8 +185,8 @@ protected static Task CreateContentAsync( protected abstract bool GetBindableNodeForTokenIndicatingPossibleIndexerAccess(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found); protected abstract bool GetBindableNodeForTokenIndicatingMemberAccess(SyntaxToken token, out SyntaxToken found); - protected virtual async Task GetOnTheFlyDocsInfoAsync(QuickInfoContext context, CancellationToken cancellationToken) - => null; + protected virtual Task GetOnTheFlyDocsInfoAsync(QuickInfoContext context, CancellationToken cancellationToken) + => Task.FromResult(null); protected virtual string? GetNullabilityAnalysis(SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => null; diff --git a/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs b/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs index 95c1fcec88326..816669d75b6a7 100644 --- a/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs +++ b/src/Features/Core/Portable/QuickInfo/QuickInfoService.cs @@ -40,12 +40,12 @@ internal QuickInfoService() return GetQuickInfoAsync(document, position, SymbolDescriptionOptions.Default, cancellationToken); } - internal virtual async Task GetQuickInfoAsync( + internal virtual Task GetQuickInfoAsync( Document document, int position, SymbolDescriptionOptions options, CancellationToken cancellationToken) { - return null; + return SpecializedTasks.Null(); } } diff --git a/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs b/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs index 14f1a1e579ae3..cc0ab05fae1a8 100644 --- a/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs +++ b/src/Features/Core/Portable/SemanticSearch/SearchCompilationFailureDefinitionItem.cs @@ -33,7 +33,7 @@ internal sealed class SearchCompilationFailureDefinitionItem(QueryCompilationErr { internal override bool IsExternal => false; - public override async Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) - => null; + public override Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) + => Task.FromResult(null); } diff --git a/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs b/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs index ecff91bc9059c..927ec6da8ae43 100644 --- a/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs +++ b/src/Features/Core/Portable/SemanticSearch/SearchExceptionDefinitionItem.cs @@ -37,7 +37,7 @@ .. stackTrace { internal override bool IsExternal => false; - public override async Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) - => null; + public override Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) + => Task.FromResult(null); } diff --git a/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs b/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs index 9413925b75df2..1f99311067ec3 100644 --- a/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs +++ b/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeCodeFixProvider.cs @@ -27,9 +27,10 @@ internal abstract partial class AbstractSimplifyThisOrMeCodeFixProvider FixableDiagnosticIds { get; } = [IDEDiagnosticIds.RemoveThisOrMeQualificationDiagnosticId]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { RegisterCodeFix(context, GetTitle(), IDEDiagnosticIds.RemoveThisOrMeQualificationDiagnosticId); + return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs index 8e5f1c24c6418..a94185d9ffbd7 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractConditionalBlockSnippetProvider.cs @@ -21,13 +21,13 @@ internal abstract class AbstractConditionalBlockSnippetProvider type.SpecialType == SpecialType.System_Boolean; - protected sealed override async ValueTask> GetPlaceHolderLocationsListAsync( + protected sealed override ValueTask> GetPlaceHolderLocationsListAsync( Document document, TStatementSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { if (ConstructedFromInlineExpression) - return []; + return new([]); var condition = GetCondition(node); - return [new SnippetPlaceholder(condition.ToString(), condition.SpanStart)]; + return new([new SnippetPlaceholder(condition.ToString(), condition.SpanStart)]); } } diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs index 85a0ec8cee204..006fc5a0318dd 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractLockSnippetProvider.cs @@ -12,10 +12,10 @@ namespace Microsoft.CodeAnalysis.Snippets.SnippetProviders; internal abstract class AbstractLockSnippetProvider : AbstractStatementSnippetProvider where TLockStatementSyntax : SyntaxNode { - protected sealed override async Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) + protected sealed override Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var statement = generator.LockStatement(generator.ThisExpression(), statements: []); - return new TextChange(TextSpan.FromBounds(position, position), statement.NormalizeWhitespace().ToFullString()); + return Task.FromResult(new TextChange(TextSpan.FromBounds(position, position), statement.NormalizeWhitespace().ToFullString())); } } diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs index 39285b9772b4a..b6f9b706a11a9 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractMainMethodSnippetProvider.cs @@ -19,7 +19,7 @@ internal abstract class AbstractMainMethodSnippetProvider GenerateInnerStatements(SyntaxGenerator generator); - protected sealed override async Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) + protected sealed override Task GenerateSnippetTextChangeAsync(Document document, int position, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var method = generator.MethodDeclaration( @@ -31,6 +31,6 @@ protected sealed override async Task GenerateSnippetTextChangeAsync( modifiers: DeclarationModifiers.Static, statements: GenerateInnerStatements(generator)); - return new TextChange(TextSpan.FromBounds(position, position), method.NormalizeWhitespace().ToFullString()); + return Task.FromResult(new TextChange(TextSpan.FromBounds(position, position), method.NormalizeWhitespace().ToFullString())); } } diff --git a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs index 035819b9fe535..2e7531c518669 100644 --- a/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs +++ b/src/Features/Core/Portable/Snippets/SnippetProviders/AbstractSnippetProvider.cs @@ -48,9 +48,9 @@ internal abstract class AbstractSnippetProvider : ISnippetProvid /// /// Method to find the locations that must be renamed and where tab stops must be inserted into the snippet. /// - protected virtual async ValueTask> GetPlaceHolderLocationsListAsync( + protected virtual ValueTask> GetPlaceHolderLocationsListAsync( Document document, TSnippetSyntax node, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) - => []; + => new([]); public bool IsValidSnippetLocation(SnippetContext context, CancellationToken cancellationToken) { @@ -222,8 +222,8 @@ private async Task AnnotateNodesToReformatAsync( reformatSnippetNode.WithAdditionalAnnotations(FindSnippetAnnotation, Simplifier.Annotation, Formatter.Annotation)); } - protected virtual async ValueTask AdjustSnippetExpressionAsync(Document document, TSnippetSyntax snippetExpressionNode, CancellationToken cancellationToken) - => snippetExpressionNode; + protected virtual ValueTask AdjustSnippetExpressionAsync(Document document, TSnippetSyntax snippetExpressionNode, CancellationToken cancellationToken) + => new(snippetExpressionNode); protected virtual TSnippetSyntax? FindAddedSnippetSyntaxNode(SyntaxNode root, int position) => root.FindNode(TextSpan.FromBounds(position, position), getInnermostNodeForTie: true) as TSnippetSyntax; @@ -244,6 +244,6 @@ private async Task AddIndentationToDocumentAsync(Document document, Ca return await AddIndentationToDocumentAsync(document, snippet, cancellationToken).ConfigureAwait(false); } - protected virtual async Task AddIndentationToDocumentAsync(Document document, TSnippetSyntax snippet, CancellationToken cancellationToken) - => document; + protected virtual Task AddIndentationToDocumentAsync(Document document, TSnippetSyntax snippet, CancellationToken cancellationToken) + => Task.FromResult(document); } diff --git a/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs b/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs index f8fb871877d99..fdcf3a12e5173 100644 --- a/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs @@ -22,7 +22,7 @@ internal abstract class AbstractSplitIfStatementCodeRefactoringProvider : CodeRe protected abstract CodeAction CreateCodeAction(Func> createChangedDocument, string ifKeywordText); - protected abstract ValueTask GetChangedRootAsync( + protected abstract Task GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, diff --git a/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs b/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs index bb00eccfedf33..49e37866eaad9 100644 --- a/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs @@ -50,7 +50,7 @@ protected sealed override CodeAction CreateCodeAction(Func GetChangedRootAsync( + protected sealed override async Task GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, diff --git a/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs b/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs index 0f3655e8ac56b..cedc4f34f2a5a 100644 --- a/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/SplitOrMergeIfStatements/Nested/AbstractSplitIntoNestedIfStatementsCodeRefactoringProvider.cs @@ -37,7 +37,7 @@ protected sealed override CodeAction CreateCodeAction(Func GetChangedRootAsync( + protected sealed override Task GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, @@ -53,6 +53,7 @@ protected sealed override async ValueTask GetChangedRootAsync( var innerIfStatement = ifGenerator.WithCondition(ifGenerator.ToIfStatement(ifOrElseIf), rightCondition); var outerIfOrElseIf = ifGenerator.WithCondition(ifGenerator.WithStatementInBlock(ifOrElseIf, innerIfStatement), leftCondition); - return root.ReplaceNode(ifOrElseIf, outerIfOrElseIf.WithAdditionalAnnotations(Formatter.Annotation)); + return Task.FromResult( + root.ReplaceNode(ifOrElseIf, outerIfOrElseIf.WithAdditionalAnnotations(Formatter.Annotation))); } } diff --git a/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs b/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs index f8bbad417b95b..877911305c84e 100644 --- a/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs +++ b/src/Features/Core/Portable/StackTraceExplorer/StackFrameMethodSymbolResolver.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.StackTraceExplorer; internal sealed class StackFrameMethodSymbolResolver : AbstractStackTraceSymbolResolver { - public override async Task TryGetBestMatchAsync( + public override Task TryGetBestMatchAsync( Project project, INamedTypeSymbol type, StackFrameSimpleNameNode methodNode, @@ -27,6 +27,6 @@ internal sealed class StackFrameMethodSymbolResolver : AbstractStackTraceSymbolR .Where(m => m.Name == methodName); var match = TryGetBestMatch(candidateMethods, methodTypeArguments, methodArguments); - return match; + return Task.FromResult(match); } } diff --git a/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs b/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs index 6346902a87777..e3198d3e6fa29 100644 --- a/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs +++ b/src/Features/Core/Portable/StackTraceExplorer/StackTraceAnalyzer.cs @@ -23,10 +23,10 @@ internal static class StackTraceAnalyzer /// private static readonly ImmutableArray s_parsers = [new DotnetStackFrameParser(), new VSDebugCallstackParser(), new DefaultStackParser()]; - public static async Task AnalyzeAsync(string callstack, CancellationToken cancellationToken) + public static Task AnalyzeAsync(string callstack, CancellationToken cancellationToken) { var result = new StackTraceAnalysisResult(callstack, Parse(callstack, cancellationToken)); - return result; + return Task.FromResult(result); } private static ImmutableArray Parse(string callstack, CancellationToken cancellationToken) diff --git a/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs b/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs index 7c7da96a65d28..94c39c7355c19 100644 --- a/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs +++ b/src/Features/Core/Portable/SymbolMapping/SymbolMappingServiceFactory.cs @@ -33,6 +33,6 @@ public async Task MapSymbolAsync(Document document, SymbolK return null; } - public async Task MapSymbolAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) - => new SymbolMappingResult(document.Project, symbol); + public Task MapSymbolAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) + => Task.FromResult(new SymbolMappingResult(document.Project, symbol)); } diff --git a/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs b/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs index 1ba86fb8f3f80..eef3b039283ec 100644 --- a/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs +++ b/src/Features/Core/Portable/SymbolSearch/SymbolSearchUpdateNoOpEngine.cs @@ -18,14 +18,14 @@ public void Dispose() // Nothing to do for the no-op version. } - public async ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); - public async ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); - public async ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); public ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, CancellationToken cancellationToken) => default; diff --git a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs index 389c9eb84d4ba..3cdbe883397d3 100644 --- a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs +++ b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.Update.cs @@ -62,7 +62,7 @@ internal sealed partial class SymbolSearchUpdateEngine /// Currently used only in tests so we can shutdown gracefully. In normal VS+OOP scenarios /// we don't care about this and we just get torn down when the OOP process goes down. /// - public async ValueTask UpdateContinuouslyAsync(string source, string localSettingsDirectory, CancellationToken cancellationToken) + public ValueTask UpdateContinuouslyAsync(string source, string localSettingsDirectory, CancellationToken cancellationToken) { // Only the first thread to try to update this source should succeed // and cause us to actually begin the update loop. @@ -72,12 +72,12 @@ public async ValueTask UpdateContinuouslyAsync(string source, string localSettin if (ourSentinel != currentSentinel) { // We already have an update loop for this source. Nothing for us to do. - return; + return default; } // We were the first ones to try to update this source. Spawn off a task to do // the updating. - await new Updater(this, source, localSettingsDirectory).UpdateInBackgroundAsync(cancellationToken).ConfigureAwait(false); + return new Updater(this, source, localSettingsDirectory).UpdateInBackgroundAsync(cancellationToken); } private static void LogInfo(string text) diff --git a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs index 64b9608db3c11..42d372b04cb1f 100644 --- a/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs +++ b/src/Features/Core/Portable/SymbolSearch/Windows/SymbolSearchUpdateEngine.cs @@ -111,7 +111,7 @@ public ValueTask> FindReferenceAssemblie cancellationToken); } - public async ValueTask> FindPackageOrReferenceAssembliesAsync( + public ValueTask> FindPackageOrReferenceAssembliesAsync( string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, @@ -121,7 +121,7 @@ public async ValueTask> FindPackageOrReferenceAssemblies { // Check if we don't have a database to search. if (!_sourceToDatabase.TryGetValue(source, out var databaseWrapper)) - return ImmutableArray.Empty; + return ValueTask.FromResult(ImmutableArray.Empty); var database = databaseWrapper.Database; @@ -129,7 +129,7 @@ public async ValueTask> FindPackageOrReferenceAssemblies // never find anything named 'var'. if (searchName == "var") - return ImmutableArray.Empty; + return ValueTask.FromResult(ImmutableArray.Empty); var query = new MemberQuery(searchName, isFullSuffix: true, isFullNamespace: false); var symbols = new PartialArray(100); @@ -146,7 +146,7 @@ public async ValueTask> FindPackageOrReferenceAssemblies } } - return results.ToImmutableAndClear(); + return ValueTask.FromResult(results.ToImmutableAndClear()); static IEnumerable FilterToViableSymbols( PartialArray symbols, NamespaceQuery namespaceQuery) @@ -173,13 +173,13 @@ static IEnumerable FilterToViableSymbols( } } - public async ValueTask> FindPackagesWithAssemblyAsync( + public ValueTask> FindPackagesWithAssemblyAsync( string source, string assemblyName, CancellationToken cancellationToken) { if (!_sourceToDatabase.TryGetValue(source, out var databaseWrapper)) { // Don't have a database to search. - return ImmutableArray.Empty; + return ValueTask.FromResult(ImmutableArray.Empty); } using var _ = ArrayBuilder.GetInstance(out var result); @@ -211,7 +211,7 @@ public async ValueTask> FindPackagesWi } } - return result.ToImmutableAndClear(); + return ValueTask.FromResult(result.ToImmutableAndClear()); } private static int GetRank(Symbol symbol) diff --git a/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs b/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs index cf3711d1d0a18..3a9ab3951b7be 100644 --- a/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/UseNamedArguments/AbstractUseNamedArgumentsCodeRefactoringProvider.cs @@ -132,7 +132,7 @@ public async Task ComputeRefactoringsAsync( } } - private async Task AddNamedArgumentsAsync( + private Task AddNamedArgumentsAsync( SyntaxNode root, Document document, TSimpleArgumentSyntax firstArgument, @@ -143,7 +143,7 @@ private async Task AddNamedArgumentsAsync( var argumentList = (TArgumentListSyntax)firstArgument.Parent!; var newArgumentList = GetOrSynthesizeNamedArguments(parameters, argumentList, index, includingTrailingArguments); var newRoot = root.ReplaceNode(argumentList, newArgumentList); - return document.WithSyntaxRoot(newRoot); + return Task.FromResult(document.WithSyntaxRoot(newRoot)); } private TArgumentListSyntax GetOrSynthesizeNamedArguments( diff --git a/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs b/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs index c24c630bb9e7d..61d32f16b98b0 100644 --- a/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs +++ b/src/Features/Core/Portable/ValueTracking/ValueTracker.OperationCollector.cs @@ -108,7 +108,7 @@ private async Task VisitInvocationAsync(IInvocationOperation invocationOperation await TrackArgumentsAsync(invocationOperation.Arguments, cancellationToken).ConfigureAwait(false); } - private async Task VisitReferenceAsync(IOperation operation, CancellationToken cancellationToken) + private Task VisitReferenceAsync(IOperation operation, CancellationToken cancellationToken) { Debug.Assert(operation is ILocalReferenceOperation or @@ -122,22 +122,23 @@ IFieldReferenceOperation or { // Always add ref or out parameters to track as assignments since the values count as // assignments across method calls for the purposes of value tracking. - await AddOperationAsync(operation, argumentOperation.Parameter, cancellationToken).ConfigureAwait(false); - } - else - { - // If the parameter is not a ref or out param, track the reference assignments that count - // as input to the argument being passed to the method. - await AddReferenceAsync(operation, cancellationToken).ConfigureAwait(false); + return AddOperationAsync(operation, argumentOperation.Parameter, cancellationToken); } + + // If the parameter is not a ref or out param, track the reference assignments that count + // as input to the argument being passed to the method. + return AddReferenceAsync(operation, cancellationToken); } - else if (IsContainedIn(operation) || IsContainedIn(operation)) + + if (IsContainedIn(operation) || IsContainedIn(operation)) { // If the reference is part of a return operation or assignment operation we want to track where the values come from // since they contribute to the "output" of the method/assignment and are relavent for value tracking. - await AddReferenceAsync(operation, cancellationToken).ConfigureAwait(false); + return AddReferenceAsync(operation, cancellationToken); } + return Task.CompletedTask; + Task AddReferenceAsync(IOperation operation, CancellationToken cancellationToken) => operation switch { @@ -149,24 +150,24 @@ Task AddReferenceAsync(IOperation operation, CancellationToken cancellationToken }; } - private async Task VisitLiteralAsync(ILiteralOperation literalOperation, CancellationToken cancellationToken) + private Task VisitLiteralAsync(ILiteralOperation literalOperation, CancellationToken cancellationToken) { if (literalOperation.Type is null) { - return; + return Task.CompletedTask; } - await AddOperationAsync(literalOperation, literalOperation.Type, cancellationToken).ConfigureAwait(false); + return AddOperationAsync(literalOperation, literalOperation.Type, cancellationToken); } - private async Task VisitReturnAsync(IReturnOperation returnOperation, CancellationToken cancellationToken) + private Task VisitReturnAsync(IReturnOperation returnOperation, CancellationToken cancellationToken) { if (returnOperation.ReturnedValue is null) { - return; + return Task.CompletedTask; } - await VisitAsync(returnOperation.ReturnedValue, cancellationToken).ConfigureAwait(false); + return VisitAsync(returnOperation.ReturnedValue, cancellationToken); } private async Task AddOperationAsync(IOperation operation, ISymbol symbol, CancellationToken cancellationToken) diff --git a/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs b/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs index a8c8c73534ab0..02caaf4eeca29 100644 --- a/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs +++ b/src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs @@ -157,7 +157,7 @@ protected async Task GetIndentationAfterAsync( // Store the root so we don't just end up creating this code action again. _seenDocumentRoots.Add(formattedRoot); - return new WrapItemsAction(title, parentTitle, async (_, _) => formattedDocument); + return new WrapItemsAction(title, parentTitle, (_, _) => Task.FromResult(formattedDocument)); } private async Task FormatDocumentAsync( diff --git a/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs b/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs index 920982571935a..0473efa36bac4 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActions/CSharpCodeRefactoringVerifier`1+Test.cs @@ -119,14 +119,14 @@ protected override CompilationOptions CreateCompilationOptions() private static readonly TestComposition s_editorFeaturesOOPComposition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess); - protected override async Task CreateWorkspaceImplAsync() + protected override Task CreateWorkspaceImplAsync() { if (TestHost == TestHost.InProcess) - return await base.CreateWorkspaceImplAsync().ConfigureAwait(false); + return base.CreateWorkspaceImplAsync(); var hostServices = s_editorFeaturesOOPComposition.GetHostServices(); var workspace = new AdhocWorkspace(hostServices); - return workspace; + return Task.FromResult(workspace); } #endif } diff --git a/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs b/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs index a49946d0db1af..e6a00a6496828 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1+Test.cs @@ -106,14 +106,14 @@ protected override ParseOptions CreateParseOptions() private static readonly TestComposition s_editorFeaturesOOPComposition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess); - protected override async Task CreateWorkspaceImplAsync() + protected override Task CreateWorkspaceImplAsync() { if (TestHost == TestHost.InProcess) - return await base.CreateWorkspaceImplAsync().ConfigureAwait(false); + return base.CreateWorkspaceImplAsync(); var hostServices = s_editorFeaturesOOPComposition.GetHostServices(); var workspace = new AdhocWorkspace(hostServices); - return workspace; + return Task.FromResult(workspace); } #endif diff --git a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs index ece9bc416c87d..07690dcae04ce 100644 --- a/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs +++ b/src/Features/DiagnosticsTestUtilities/CodeActionsLegacy/AbstractCodeActionTest_NoEditor.cs @@ -97,8 +97,8 @@ private static async Task GetFixAllFixAsync( return await refactorAllProvider.GetRefactoringAsync(refactorAllContext).ConfigureAwait(false); } - protected override async Task> GetDiagnosticsWorkerAsync(TTestWorkspace workspace, TestParameters parameters) - => []; + protected override Task> GetDiagnosticsWorkerAsync(TTestWorkspace workspace, TestParameters parameters) + => SpecializedTasks.EmptyImmutableArray(); internal override async Task GetCodeRefactoringAsync( TTestWorkspace workspace, TestParameters parameters) diff --git a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs index fdb081db59a53..ae44dadd08e08 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs @@ -166,9 +166,9 @@ public async Task> GetCachedDocumentDiagnosticsAsync( return diagnostics.ToImmutable(); } - protected virtual async Task> GetDiagnosticsIntersectWithSpanAsync(Document document, IReadOnlyList diagnostics, TextSpan span, CancellationToken cancellationToken) + protected virtual Task> GetDiagnosticsIntersectWithSpanAsync(Document document, IReadOnlyList diagnostics, TextSpan span, CancellationToken cancellationToken) { - return diagnostics.WhereAsArray(static (diagnostic, span) => diagnostic.Location.SourceSpan.IntersectsWith(span), span); + return Task.FromResult(diagnostics.WhereAsArray(static (diagnostic, span) => diagnostic.Location.SourceSpan.IntersectsWith(span), span)); } public async Task StartRefinementSessionAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken) diff --git a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs index 81e03e7dfded4..ac005eb0be0e0 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs @@ -59,58 +59,60 @@ IDiagnosticsRefresher diagnosticsRefresher GenerateImplementationService = externalCSharpCopilotGenerateImplementationService; } - protected override async Task> AnalyzeDocumentCoreAsync(Document document, TextSpan? span, string promptTitle, CancellationToken cancellationToken) + protected override Task> AnalyzeDocumentCoreAsync(Document document, TextSpan? span, string promptTitle, CancellationToken cancellationToken) { if (AnalysisService is not null) - return await AnalysisService.AnalyzeDocumentAsync(document, span, promptTitle, cancellationToken).ConfigureAwait(false); + return AnalysisService.AnalyzeDocumentAsync(document, span, promptTitle, cancellationToken); - return ImmutableArray.Empty; + return Task.FromResult(ImmutableArray.Empty); } - protected override async Task> GetAvailablePromptTitlesCoreAsync(Document document, CancellationToken cancellationToken) + protected override Task> GetAvailablePromptTitlesCoreAsync(Document document, CancellationToken cancellationToken) { if (AnalysisService is not null) - return await AnalysisService.GetAvailablePromptTitlesAsync(document, cancellationToken).ConfigureAwait(false); + return AnalysisService.GetAvailablePromptTitlesAsync(document, cancellationToken); - return ImmutableArray.Empty; + return Task.FromResult(ImmutableArray.Empty); } - protected override async Task> GetCachedDiagnosticsCoreAsync(Document document, string promptTitle, CancellationToken cancellationToken) + protected override Task> GetCachedDiagnosticsCoreAsync(Document document, string promptTitle, CancellationToken cancellationToken) { if (AnalysisService is not null) - return await AnalysisService.GetCachedDiagnosticsAsync(document, promptTitle, cancellationToken).ConfigureAwait(false); + return AnalysisService.GetCachedDiagnosticsAsync(document, promptTitle, cancellationToken); - return ImmutableArray.Empty; + return Task.FromResult(ImmutableArray.Empty); } - protected override async Task IsAvailableCoreAsync(CancellationToken cancellationToken) + protected override Task IsAvailableCoreAsync(CancellationToken cancellationToken) { if (AnalysisService is not null) - return await AnalysisService.IsAvailableAsync(cancellationToken).ConfigureAwait(false); + return AnalysisService.IsAvailableAsync(cancellationToken); - return false; + return Task.FromResult(false); } - protected override async Task StartRefinementSessionCoreAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken) + protected override Task StartRefinementSessionCoreAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken) { if (AnalysisService is not null) - await AnalysisService.StartRefinementSessionAsync(oldDocument, newDocument, primaryDiagnostic, cancellationToken).ConfigureAwait(false); + return AnalysisService.StartRefinementSessionAsync(oldDocument, newDocument, primaryDiagnostic, cancellationToken); + + return Task.CompletedTask; } - protected override async Task GetOnTheFlyDocsPromptCoreAsync(OnTheFlyDocsInfo onTheFlyDocsInfo, CancellationToken cancellationToken) + protected override Task GetOnTheFlyDocsPromptCoreAsync(OnTheFlyDocsInfo onTheFlyDocsInfo, CancellationToken cancellationToken) { if (OnTheFlyDocsService is not null) - return await OnTheFlyDocsService.GetOnTheFlyDocsPromptAsync(new CopilotOnTheFlyDocsInfoWrapper(onTheFlyDocsInfo), cancellationToken).ConfigureAwait(false); + return OnTheFlyDocsService.GetOnTheFlyDocsPromptAsync(new CopilotOnTheFlyDocsInfoWrapper(onTheFlyDocsInfo), cancellationToken); - return string.Empty; + return Task.FromResult(string.Empty); } - protected override async Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsResponseCoreAsync(string prompt, CancellationToken cancellationToken) + protected override Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsResponseCoreAsync(string prompt, CancellationToken cancellationToken) { if (OnTheFlyDocsService is not null) - return await OnTheFlyDocsService.GetOnTheFlyDocsResponseAsync(prompt, cancellationToken).ConfigureAwait(false); + return OnTheFlyDocsService.GetOnTheFlyDocsResponseAsync(prompt, cancellationToken); - return (string.Empty, false); + return Task.FromResult((string.Empty, false)); } protected override async Task> GetDiagnosticsIntersectWithSpanAsync( @@ -133,20 +135,20 @@ protected override async Task> GetDiagnosticsIntersec return filteredDiagnostics.ToImmutable(); } - protected override async Task IsFileExcludedCoreAsync(string filePath, CancellationToken cancellationToken) + protected override Task IsFileExcludedCoreAsync(string filePath, CancellationToken cancellationToken) { if (AnalysisService is not null) - return await AnalysisService.IsFileExcludedAsync(filePath, cancellationToken).ConfigureAwait(false); + return AnalysisService.IsFileExcludedAsync(filePath, cancellationToken); - return false; + return Task.FromResult(false); } - protected override async Task<(Dictionary? responseDictionary, bool isQuotaExceeded)> GetDocumentationCommentCoreAsync(DocumentationCommentProposal proposal, CancellationToken cancellationToken) + protected override Task<(Dictionary? responseDictionary, bool isQuotaExceeded)> GetDocumentationCommentCoreAsync(DocumentationCommentProposal proposal, CancellationToken cancellationToken) { if (GenerateDocumentationService is not null) - return await GenerateDocumentationService.GetDocumentationCommentAsync(new CopilotDocumentationCommentProposalWrapper(proposal), cancellationToken).ConfigureAwait(false); + return GenerateDocumentationService.GetDocumentationCommentAsync(new CopilotDocumentationCommentProposalWrapper(proposal), cancellationToken); - return (null, false); + return Task.FromResult<(Dictionary?, bool)>((null, false)); } protected override bool IsImplementNotImplementedExceptionsAvailableCore() diff --git a/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs b/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs index d00004a66d1ac..5915edf57088a 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/Completion/CSharpContextProviderService.cs @@ -27,10 +27,12 @@ public IAsyncEnumerable GetContextItemsAsync(Document document, in static async (provider, callback, args, cancellationToken) => await provider.ProvideContextItemsAsync( args.document, args.position, args.activeExperiments, - async (items, cancellationToken) => + (items, cancellationToken) => { foreach (var item in items) callback(item); + + return default; }, cancellationToken).ConfigureAwait(false), args: (document, position, activeExperiments), cancellationToken); diff --git a/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs b/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs index 48c9fe2e44ed1..429e9bb145610 100644 --- a/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs +++ b/src/Features/ExternalAccess/Copilot/Internal/SemanticSearch/CopilotSemanticSearchQueryExecutor.cs @@ -34,8 +34,8 @@ private sealed class ResultsObserver(CancellationTokenSource cancellationSource, /// /// We only use symbol display names, classification is not relevant. /// - public async ValueTask GetClassificationOptionsAsync(LanguageServices language, CancellationToken cancellationToken) - => ClassificationOptions.Default; + public ValueTask GetClassificationOptionsAsync(LanguageServices language, CancellationToken cancellationToken) + => new(ClassificationOptions.Default); public ValueTask AddItemsAsync(int itemCount, CancellationToken cancellationToken) => ValueTask.CompletedTask; @@ -43,13 +43,14 @@ public ValueTask AddItemsAsync(int itemCount, CancellationToken cancellationToke public ValueTask ItemsCompletedAsync(int itemCount, CancellationToken cancellationToken) => ValueTask.CompletedTask; - public async ValueTask OnUserCodeExceptionAsync(UserCodeExceptionInfo exception, CancellationToken cancellationToken) + public ValueTask OnUserCodeExceptionAsync(UserCodeExceptionInfo exception, CancellationToken cancellationToken) { RuntimeException ??= $"{exception.TypeName.ToVisibleDisplayString(includeLeftToRightMarker: false)}: {exception.Message}{Environment.NewLine}{exception.StackTrace.ToVisibleDisplayString(includeLeftToRightMarker: false)}"; cancellationSource.Cancel(); + return ValueTask.CompletedTask; } - public async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { if (!ImmutableInterlocked.Update(ref _results, list => list.Count == resultCountLimit ? list : list.Add(definition.NameDisplayParts.ToVisibleDisplayString(includeLeftToRightMarker: false)))) @@ -57,6 +58,8 @@ public async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, Cancell LimitReached = true; cancellationSource.Cancel(); } + + return ValueTask.CompletedTask; } public ValueTask OnDocumentUpdatedAsync(DocumentId documentId, ImmutableArray changes, CancellationToken cancellationToken) diff --git a/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs b/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs index 0e4219cb63f18..81ff0b2f59772 100644 --- a/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs +++ b/src/Features/ExternalAccess/Copilot/SemanticSearch/CopilotSemanticSearchUtilities.cs @@ -55,10 +55,12 @@ private sealed class Progress(Action callback) : IStreamingFi public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) => ValueTask.CompletedTask; - public async ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) + public ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) { foreach (var (_, _, location) in references) callback(location); + + return ValueTask.CompletedTask; } public IStreamingProgressTracker ProgressTracker diff --git a/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs b/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs index ba0885b6b4859..da8d623383977 100644 --- a/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs +++ b/src/Features/ExternalAccess/HotReload/Api/HotReloadService.cs @@ -18,11 +18,11 @@ internal sealed class HotReloadService(SolutionServices services, Func>> capabilitiesProvider) : IManagedHotReloadService { - public async ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); - public async ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) - => new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available); + public ValueTask GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) + => ValueTask.FromResult(new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.Available)); public ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) => capabilitiesProvider(); @@ -129,14 +129,14 @@ public readonly struct Updates } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = - async (_, _, _) => ImmutableArray.Empty; + (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); private readonly IEditAndContinueService _encService = services.GetRequiredService().Service; private DebuggingSessionId _sessionId; public HotReloadService(HostWorkspaceServices services, ImmutableArray capabilities) - : this(services.SolutionServices, async () => AddImplicitDotNetCapabilities(capabilities)) + : this(services.SolutionServices, () => ValueTask.FromResult(AddImplicitDotNetCapabilities(capabilities))) { } diff --git a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs index 92948008cf2eb..61914cfd87225 100644 --- a/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs +++ b/src/Features/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs @@ -2654,7 +2654,7 @@ public async Task Project_Add_BinaryAlreadyLoaded() var trackedActiveSpans = ImmutableArray.Create( new ActiveStatementSpan(new ActiveStatementId(0), activeLineSpanB1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.LeafFrame)); - var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, async (_, _, _) => trackedActiveSpans, CancellationToken.None); + var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, (_, _, _) => new(trackedActiveSpans), CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/79423 // AssertEx.Equal(trackedActiveSpans, currentSpans); Assert.Empty(currentSpans); @@ -4590,7 +4590,7 @@ public async Task ActiveStatements() var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); - var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, async (_, _, _) => trackedActiveSpans1, CancellationToken.None); + var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); // change the source (valid edit): @@ -4602,7 +4602,7 @@ public async Task ActiveStatements() var activeStatementSpan22 = new ActiveStatementSpan(new ActiveStatementId(1), activeLineSpan22, ActiveStatementFlags.LeafFrame); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); - currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, async (_, _, _) => trackedActiveSpans2, CancellationToken.None); + currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal([adjustedActiveLineSpan1, adjustedActiveLineSpan2], currentSpans.Select(s => s.LineSpan)); } @@ -4666,7 +4666,7 @@ public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSy var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: - var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, async (_, _, _) => baseSpans, CancellationToken.None); + var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTask.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal([activeLineSpan11, activeLineSpan12], currentSpans.Select(s => s.LineSpan)); } diff --git a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs index 219e5807487e8..dd97b08c68add 100644 --- a/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs +++ b/src/Features/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs @@ -113,11 +113,11 @@ await localWorkspace.ChangeSolutionAsync(localWorkspace.CurrentSolution var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(new ActiveStatementId(0), new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.NonLeafFrame, documentId)); - var activeStatementSpanProvider = new ActiveStatementSpanProvider(async (documentId, path, cancellationToken) => + var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => { Assert.Equal(documentId, documentId); Assert.Equal("test.cs", path); - return activeSpans1; + return new(activeSpans1); }); var diagnosticDescriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired); diff --git a/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs b/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs index b5006c3a395e2..aa12537213bfb 100644 --- a/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs +++ b/src/Features/TestUtilities/BrokeredServices/MockServiceBroker.cs @@ -22,6 +22,6 @@ internal sealed class MockServiceBroker : IServiceBroker public ValueTask GetPipeAsync(ServiceMoniker serviceMoniker, ServiceActivationOptions options = default, CancellationToken cancellationToken = default) => throw new NotImplementedException(); - public async ValueTask GetProxyAsync(ServiceRpcDescriptor serviceDescriptor, ServiceActivationOptions options = default, CancellationToken cancellationToken = default) where T : class - => (T?)(CreateService ?? throw new NotImplementedException()).Invoke(typeof(T)); + public ValueTask GetProxyAsync(ServiceRpcDescriptor serviceDescriptor, ServiceActivationOptions options = default, CancellationToken cancellationToken = default) where T : class + => ValueTask.FromResult((T?)(CreateService ?? throw new NotImplementedException()).Invoke(typeof(T))); } diff --git a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs index c76816b4d1544..12904badeb6c6 100644 --- a/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs +++ b/src/Features/TestUtilities/EditAndContinue/EditAndContinueWorkspaceTestBase.cs @@ -38,7 +38,7 @@ public abstract class EditAndContinueWorkspaceTestBase : TestBase, IDisposable private protected static readonly Regex s_timePropertiesRegex = new("[|](EmitDifferenceMilliseconds|TotalAnalysisMilliseconds)=[0-9]+"); private protected static readonly ActiveStatementSpanProvider s_noActiveSpans = - async (_, _, _) => []; + (_, _, _) => new([]); private protected const TargetFramework DefaultTargetFramework = TargetFramework.NetLatest; diff --git a/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs b/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs index d28c4fe771abc..9060ea835fbb8 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockActiveStatementSpanProvider.cs @@ -14,9 +14,9 @@ internal sealed class MockActiveStatementSpanProvider : IActiveStatementSpanFact public Func, ImmutableArray>>? GetBaseActiveStatementSpansImpl; public Func>? GetAdjustedActiveStatementSpansImpl; - public async ValueTask>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) - => (GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds); + public ValueTask>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) + => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); - public async ValueTask> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => (GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider); + public ValueTask> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); } diff --git a/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs b/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs index cd85df62e01c5..b585a1f4cd11c 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockEditAndContinueService.cs @@ -39,20 +39,20 @@ public void CommitSolutionUpdate(DebuggingSessionId sessionId) public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); - public async ValueTask EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ImmutableDictionary runningProjects, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => (EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, runningProjects, activeStatementSpanProvider); + public ValueTask EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ImmutableDictionary runningProjects, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, runningProjects, activeStatementSpanProvider)); public void EndDebuggingSession(DebuggingSessionId sessionId) => EndDebuggingSessionImpl?.Invoke(); - public async ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) - => (GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds); + public ValueTask>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray documentIds, CancellationToken cancellationToken) + => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); - public async ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => (GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider); + public ValueTask> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); - public async ValueTask> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) - => (GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider); + public ValueTask> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) + => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); diff --git a/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs b/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs index aff02e6e57c57..207fa76880dde 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs @@ -19,26 +19,26 @@ internal sealed class MockManagedEditAndContinueDebuggerService : IManagedHotRel public Func>? GetActiveStatementsImpl; public Func>? GetCapabilitiesImpl; - public async ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) - => GetActiveStatementsImpl?.Invoke() ?? []; + public ValueTask> GetActiveStatementsAsync(CancellationToken cancellationToken) + => ValueTask.FromResult(GetActiveStatementsImpl?.Invoke() ?? []); - public async ValueTask GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) + public ValueTask GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) { if (IsEditAndContinueAvailable != null) { - return IsEditAndContinueAvailable(mvid); + return ValueTask.FromResult(IsEditAndContinueAvailable(mvid)); } if (LoadedModules != null) { - return LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.ModuleNotLoaded); + return ValueTask.FromResult(LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedHotReloadAvailability(ManagedHotReloadAvailabilityStatus.ModuleNotLoaded)); } throw new NotImplementedException(); } - public async ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) - => GetCapabilitiesImpl?.Invoke() ?? ["Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"]; + public ValueTask> GetCapabilitiesAsync(CancellationToken cancellationToken) + => ValueTask.FromResult(GetCapabilitiesImpl?.Invoke() ?? ["Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"]); public ValueTask PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken) => ValueTask.CompletedTask; diff --git a/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs b/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs index fd90c731b2d0a..c40e896847a2f 100644 --- a/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs +++ b/src/Features/TestUtilities/EditAndContinue/MockPdbMatchingSourceTextProvider.cs @@ -15,6 +15,6 @@ internal sealed class MockPdbMatchingSourceTextProvider : IPdbMatchingSourceText { public Func, SourceHashAlgorithm, string?>? TryGetMatchingSourceTextImpl { get; set; } - public async ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) - => TryGetMatchingSourceTextImpl?.Invoke(filePath, requiredChecksum, checksumAlgorithm); + public ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) + => ValueTask.FromResult(TryGetMatchingSourceTextImpl?.Invoke(filePath, requiredChecksum, checksumAlgorithm)); } diff --git a/src/Features/TestUtilities/Options/TestOptionsProvider.cs b/src/Features/TestUtilities/Options/TestOptionsProvider.cs index 3851691431333..f93921b093aa5 100644 --- a/src/Features/TestUtilities/Options/TestOptionsProvider.cs +++ b/src/Features/TestUtilities/Options/TestOptionsProvider.cs @@ -13,8 +13,8 @@ internal static class TestOptionsProvider { internal sealed class Provider(TOptions options) : OptionsProvider { - public async ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => options; + public ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) + => ValueTask.FromResult(options); } public static OptionsProvider Create(TOptions options) diff --git a/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs b/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs index bcd4c4934979f..d2e7cc11cf33a 100644 --- a/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs +++ b/src/LanguageServer/ExternalAccess/VisualDiagnostics/Internal/VisualDiagnosticsServiceFactory.cs @@ -58,10 +58,11 @@ public void Dispose() (_visualDiagnosticsLanguageService as IDisposable)?.Dispose(); } - public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _taskCompletionSource.TrySetResult(true); + return Task.CompletedTask; } public void OnServiceBrokerInitialized(IServiceBroker serviceBroker) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs index 4f35f5c488218..6d0590087b5fc 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer.UnitTests/LspFileChangeWatcherTests.cs @@ -118,17 +118,21 @@ private sealed class DynamicCapabilitiesRpcTarget public readonly ConcurrentDictionary Registrations = new(); [JsonRpcMethod("client/registerCapability", UseSingleObjectParameterDeserialization = true)] - public async Task RegisterCapabilityAsync(RegistrationParams registrationParams, CancellationToken _) + public Task RegisterCapabilityAsync(RegistrationParams registrationParams, CancellationToken _) { foreach (var registration in registrationParams.Registrations) Assert.True(Registrations.TryAdd(registration.Id, registration)); + + return Task.CompletedTask; } [JsonRpcMethod("client/unregisterCapability", UseSingleObjectParameterDeserialization = true)] - public async Task UnregisterCapabilityAsync(UnregistrationParams unregistrationParams, CancellationToken _) + public Task UnregisterCapabilityAsync(UnregistrationParams unregistrationParams, CancellationToken _) { foreach (var unregistration in unregistrationParams.Unregistrations) Assert.True(Registrations.TryRemove(unregistration.Id, out var _)); + + return Task.CompletedTask; } } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs index 33898cc63fad4..088d183bc6701 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/BrokeredServiceContainer.cs @@ -42,7 +42,7 @@ internal static async Task CreateAsync(ExportProvider container.ProfferIntrinsicService( FrameworkServices.Authorization, new ServiceRegistration(VisualStudio.Shell.ServiceBroker.ServiceAudience.Local, null, allowGuestClients: true), - async (moniker, options, serviceBroker, cancellationToken) => new NoOpAuthorizationService()); + (moniker, options, serviceBroker, cancellationToken) => new(new NoOpAuthorizationService())); var mefServiceBroker = exportProvider.GetExportedValue(); mefServiceBroker.SetContainer(container); @@ -62,14 +62,14 @@ private class NoOpAuthorizationService : IAuthorizationService public event EventHandler? AuthorizationChanged; - public async ValueTask CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) + public ValueTask CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { - return true; + return new(true); } - public async ValueTask> GetCredentialsAsync(CancellationToken cancellationToken = default) + public ValueTask> GetCredentialsAsync(CancellationToken cancellationToken = default) { - return ImmutableDictionary.Empty; + return new(ImmutableDictionary.Empty); } protected virtual void OnCredentialsChanged(EventArgs args) => this.CredentialsChanged?.Invoke(this, args); diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs index 593541ec74342..4c65e7361beab 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/BrokeredServices/Services/BrokeredServiceBridgeManifest/BrokeredServiceBridgeManifestService.cs @@ -38,7 +38,7 @@ public BrokeredServiceBridgeManifest(ServiceBrokerFactory serviceBrokerFactory, /// /// Returns a subset of services registered to Microsoft.VisualStudio.Code.Server container that are proferred by the Language Server process. /// - public async ValueTask> GetAvailableServicesAsync(CancellationToken cancellationToken) + public ValueTask> GetAvailableServicesAsync(CancellationToken cancellationToken) { var services = (IReadOnlyCollection)[.. _serviceBrokerFactory.GetRequiredServiceBrokerContainer().GetRegisteredServices() .Select(s => s.Key) @@ -46,11 +46,12 @@ public async ValueTask> GetAvailableServices s.Name.StartsWith("Microsoft.VisualStudio.LanguageServer.", StringComparison.Ordinal) || s.Name.StartsWith("Microsoft.VisualStudio.LanguageServices.", StringComparison.Ordinal))]; _logger.LogDebug($"Proffered services: {string.Join(',', services.Select(s => s.ToString()))}"); - return services; + return ValueTask.FromResult(services); } - public async Task InitializeAsync(CancellationToken cancellationToken) + public Task InitializeAsync(CancellationToken cancellationToken) { + return Task.CompletedTask; } } #pragma warning restore RS0030 // Do not used banned APIs diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs index 1dc74897b658f..1e77769b8b924 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/CanonicalMiscFilesProjectLoader.cs @@ -276,9 +276,10 @@ private TextDocument CreatePrimordialProjectAndAddDocument_NoLock(string documen }; } - protected override async ValueTask OnProjectUnloadedAsync(string projectFilePath) + protected override ValueTask OnProjectUnloadedAsync(string projectFilePath) { // Nothing special to do on unload for canonical project + return ValueTask.CompletedTask; } protected override async ValueTask TransitionPrimordialProjectToLoaded_NoLockAsync( diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs index 62815a6276f4a..afa8e5e4dde15 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/FileBasedPrograms/FileBasedProgramsProjectSystem.cs @@ -222,8 +222,9 @@ public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri }; } - protected override async ValueTask OnProjectUnloadedAsync(string projectFilePath) + protected override ValueTask OnProjectUnloadedAsync(string projectFilePath) { + return ValueTask.CompletedTask; } protected override async ValueTask TransitionPrimordialProjectToLoaded_NoLockAsync( diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs index a7b49ced2e38b..5c41b30e837d2 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/FileWatching/LspDidChangeWatchedFilesHandler.cs @@ -23,9 +23,10 @@ public LspDidChangeWatchedFilesHandler() public bool MutatesSolutionState => false; public bool RequiresLSPSolution => false; - async Task INotificationHandler.HandleNotificationAsync(DidChangeWatchedFilesParams request, RequestContext requestContext, CancellationToken cancellationToken) + Task INotificationHandler.HandleNotificationAsync(DidChangeWatchedFilesParams request, RequestContext requestContext, CancellationToken cancellationToken) { NotificationRaised?.Invoke(this, request); + return Task.CompletedTask; } public event EventHandler? NotificationRaised; diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs index 9a467a701e6ae..a7b83343ac0fa 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/LanguageServerProjectSystem.cs @@ -102,9 +102,10 @@ public async Task OpenProjectsAsync(ImmutableArray projectFilePaths) }; } - protected override async ValueTask OnProjectUnloadedAsync(string projectFilePath) + protected override ValueTask OnProjectUnloadedAsync(string projectFilePath) { // Nothing else to unload for ordinary projects. + return ValueTask.CompletedTask; } protected override async ValueTask TransitionPrimordialProjectToLoaded_NoLockAsync( diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs index 1cdbc88fbdf24..6773f0c322a8f 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/Razor/RazorInitializer.cs @@ -17,13 +17,13 @@ namespace Microsoft.CodeAnalysis.LanguageServer.HostWorkspace.Razor; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class RazorInitializer(Lazy workspaceFactory, [Import(AllowDefault = true)] ITelemetryReporter? telemetryReporter) : ILspService, IOnInitialized { - public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { var razorInitializerService = context.GetService(); if (razorInitializerService is null) { // No initializer service registered, nothing to do. - return; + return Task.CompletedTask; } razorInitializerService.Initialize(workspaceFactory.Value.HostWorkspace); @@ -33,5 +33,7 @@ public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, Requ { razorTelemetryReporter.Initialize(new TelemetryReporterWrapper(telemetryReporter)); } + + return Task.CompletedTask; } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs index 8e8cae416cead..267e4a7006e69 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/HostWorkspace/WorkspaceProjectFactoryService.cs @@ -65,10 +65,10 @@ public async Task CreateAndAddProjectAsync(WorkspaceProjectCr } } - public async Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken _) + public Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken _) { // TODO: implement - return []; + return Task.FromResult((IReadOnlyCollection)[]); } } #pragma warning restore RS0030 // Do not used banned APIs diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs index ddb95da49281b..4fe27fcea7d64 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/DebugConfiguration/WorkspaceDebugConfigurationHandler.cs @@ -28,7 +28,7 @@ public WorkspaceDebugConfigurationHandler(ProjectTargetFrameworkManager targetFr public bool RequiresLSPSolution => true; - public async Task HandleRequestAsync(WorkspaceDebugConfigurationParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(WorkspaceDebugConfigurationParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution, nameof(context.Solution)); @@ -36,7 +36,7 @@ public async Task HandleRequestAsync(WorkspaceDebug .Where(p => p.FilePath != null && p.OutputFilePath != null) .Where(p => IsProjectInWorkspace(request.WorkspacePath, p)) .Select(GetProjectDebugConfiguration).ToArray(); - return projects; + return Task.FromResult(projects); } private static bool IsProjectInWorkspace(DocumentUri workspacePath, Project project) diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs index 6ad1868b95059..b8651a80df060 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Logging/UpdateLogLevelHandler.cs @@ -22,10 +22,11 @@ internal sealed class UpdateLogLevelHandler(ServerConfiguration serverConfigurat public bool RequiresLSPSolution => false; - public async Task HandleNotificationAsync(UpdateLogLevelParams request, RequestContext requestContext, CancellationToken cancellationToken) + public Task HandleNotificationAsync(UpdateLogLevelParams request, RequestContext requestContext, CancellationToken cancellationToken) { var level = Enum.Parse(request.LogLevelValue); serverConfiguration.LogConfiguration.UpdateLogLevel(level); + return Task.CompletedTask; } } diff --git a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs index f0427ed9930d6..dff2f53aa8ce6 100644 --- a/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs +++ b/src/LanguageServer/Microsoft.CodeAnalysis.LanguageServer/LanguageServer/Handler/Restore/RestorableProjectsHandler.cs @@ -25,7 +25,7 @@ internal sealed class RestorableProjectsHandler(ProjectTargetFrameworkManager pr public bool RequiresLSPSolution => true; - public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); @@ -43,6 +43,6 @@ public async Task HandleRequestAsync(RequestContext context, Cancellat } } - return projects.ToArray(); + return Task.FromResult(projects.ToArray()); } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs index 606762c26aa8f..4b9ba38ab475f 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.Example/ExampleRequestContextFactory.cs @@ -16,12 +16,12 @@ public ExampleRequestContextFactory(ILspServices lspServices) _lspServices = lspServices; } - public override async Task CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) + public override Task CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) { var logger = _lspServices.GetRequiredService(); var requestContext = new ExampleRequestContext(_lspServices, logger); - return requestContext; + return Task.FromResult(requestContext); } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs index 229fc9543cd90..2e0fbad7fa649 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/Mocks/TestRequestContext.cs @@ -13,7 +13,7 @@ internal sealed class Factory : AbstractRequestContextFactory CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) - => new TestRequestContext(); + public override Task CreateRequestContextAsync(IQueueItem queueItem, IMethodHandler methodHandler, TRequestParam requestParam, CancellationToken cancellationToken) + => Task.FromResult(new TestRequestContext()); } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs index a09f06b3dcd1c..8cb327686f775 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework.UnitTests/TestExampleLanguageServer.cs @@ -60,14 +60,16 @@ public TestLifeCycleManager(TaskCompletionSource shuttingDownSource, TaskCo _exitingSource = exitingSource; } - public async Task ExitAsync() + public Task ExitAsync() { _exitingSource.SetResult(0); + return Task.CompletedTask; } - public async Task ShutdownAsync(string message = "Shutting down") + public Task ShutdownAsync(string message = "Shutting down") { _shuttingDownSource.SetResult(0); + return Task.CompletedTask; } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs index f10cec2138dce..2552058e13c5b 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializeHandler.cs @@ -23,12 +23,12 @@ public InitializeHandler(IInitializeManager capabilitiesMan public bool MutatesSolutionState => true; - public async Task HandleRequestAsync(TRequest request, TRequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TRequest request, TRequestContext context, CancellationToken cancellationToken) { _capabilitiesManager.SetInitializeParams(request); var serverCapabilities = _capabilitiesManager.GetInitializeResult(); - return serverCapabilities; + return Task.FromResult(serverCapabilities); } } diff --git a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs index 2e8da373ae885..30e014534168f 100644 --- a/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs +++ b/src/LanguageServer/Microsoft.CommonLanguageServerProtocol.Framework/Handlers/InitializedHandler.cs @@ -18,7 +18,7 @@ internal sealed class InitializedHandler : INotificat public bool MutatesSolutionState => true; - public async Task HandleNotificationAsync(TRequest request, TRequestContext requestContext, CancellationToken cancellationToken) + public Task HandleNotificationAsync(TRequest request, TRequestContext requestContext, CancellationToken cancellationToken) { if (HasBeenInitialized) { @@ -26,5 +26,7 @@ public async Task HandleNotificationAsync(TRequest request, TRequestContext requ } HasBeenInitialized = true; + + return Task.CompletedTask; } } diff --git a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs index f9167c06be2df..ad45e29418c17 100644 --- a/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs +++ b/src/LanguageServer/Protocol.TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs @@ -78,7 +78,7 @@ internal sealed class TestSpanMapper : ISpanMappingService /// public bool SupportsMappingImportDirectives => true; - public async Task> MapSpansAsync(Document document, IEnumerable spans, CancellationToken cancellationToken) + public Task> MapSpansAsync(Document document, IEnumerable spans, CancellationToken cancellationToken) { ImmutableArray mappedResult = default; if (document.Name == GeneratedFileName) @@ -86,7 +86,7 @@ public async Task> MapSpansAsync(Document docum mappedResult = [.. spans.Select(span => new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5)))]; } - return mappedResult; + return Task.FromResult(mappedResult); } public Task> GetMappedTextChangesAsync( @@ -103,7 +103,7 @@ private protected sealed class OrderLocations : Comparer public override int Compare(LSP.Location? x, LSP.Location? y) => CompareLocations(x, y); } - protected virtual async ValueTask CreateExportProviderAsync() => Composition.ExportProviderFactory.CreateExportProvider(); + protected virtual ValueTask CreateExportProviderAsync() => ValueTask.FromResult(Composition.ExportProviderFactory.CreateExportProvider()); protected virtual TestComposition Composition => FeaturesLspComposition; private protected virtual TestAnalyzerReferenceByLanguage CreateTestAnalyzersReference() diff --git a/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs b/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs index 70c54361f1883..025e30f45eba0 100644 --- a/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs +++ b/src/LanguageServer/Protocol.TestUtilities/Workspaces/LspTestWorkspace.cs @@ -36,10 +36,11 @@ internal LspTestWorkspace( bool ILspWorkspace.SupportsMutation => _supportsLspMutation; - async ValueTask ILspWorkspace.UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) + ValueTask ILspWorkspace.UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_supportsLspMutation); OnDocumentTextChanged(documentId, sourceText, PreservationMode.PreserveIdentity, requireDocumentPresent: false); + return ValueTask.CompletedTask; } internal override ValueTask TryOnDocumentClosedAsync(DocumentId documentId, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs b/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs index f038fb3b9b395..da70d86cc57ee 100644 --- a/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs +++ b/src/LanguageServer/Protocol/Features/DecompiledSource/AssemblyResolver.cs @@ -48,14 +48,14 @@ void BuildReferenceCache() } } - public async Task ResolveAsync(IAssemblyReference name) + public Task ResolveAsync(IAssemblyReference name) { - return Resolve(name); + return Task.FromResult(Resolve(name)); } - public async Task ResolveModuleAsync(MetadataFile mainModule, string moduleName) + public Task ResolveModuleAsync(MetadataFile mainModule, string moduleName) { - return ResolveModule(mainModule, moduleName); + return Task.FromResult(ResolveModule(mainModule, moduleName)); } [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Could be non-static if instance data is accessed")] diff --git a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs index 9151ccc849200..db886e9f5f633 100644 --- a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs +++ b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_OpenDocument.cs @@ -49,7 +49,7 @@ public override async Task> GetDiagnosticsAsync(R var activeStatementSpanProvider = spanLocator != null ? new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => spanLocator.GetSpansAsync(compileTimeSolution, documentId, filePath, cancellationToken)) - : static async (_, _, _) => ImmutableArray.Empty; + : static (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); var rudeEditDiagnostics = await proxy.GetDocumentDiagnosticsAsync(compileTimeDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); diff --git a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs index 8242e49a91481..9069b39d0e3fc 100644 --- a/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs +++ b/src/LanguageServer/Protocol/Features/EditAndContinue/EditAndContinueDiagnosticSource_Workspace.cs @@ -20,15 +20,15 @@ internal static partial class EditAndContinueDiagnosticSource private sealed class ProjectSource(Project project, ImmutableArray diagnostics) : AbstractProjectDiagnosticSource(project) { - public override async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) - => diagnostics; + public override Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + => Task.FromResult(diagnostics); } private sealed class ClosedDocumentSource(TextDocument document, ImmutableArray diagnostics) : AbstractWorkspaceDocumentDiagnosticSource(document) { - public override async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) - => diagnostics; + public override Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + => Task.FromResult(diagnostics); } public static async ValueTask> CreateWorkspaceDiagnosticSourcesAsync(Solution solution, Func isDocumentOpen, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs b/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs index 11c1473dd6c17..1b192d32ff53a 100644 --- a/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs +++ b/src/LanguageServer/Protocol/Features/FindUsages/SimpleFindUsagesContext.cs @@ -28,14 +28,16 @@ internal sealed class SimpleFindUsagesContext : FindUsagesContext public string Message { get; private set; } public string SearchTitle { get; private set; } - public override async ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) + public override ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) { Message = message; + return default; } - public override async ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) + public override ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) { SearchTitle = title; + return default; } public ImmutableArray GetDefinitions() @@ -54,12 +56,14 @@ public ImmutableArray GetReferences() } } - public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) + public override ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitionItems.Add(definition); } + + return default; } public override async ValueTask OnReferencesFoundAsync(IAsyncEnumerable references, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs b/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs index be7649213ec92..436a66f1f83f6 100644 --- a/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs +++ b/src/LanguageServer/Protocol/Handler/AbstractRefreshQueue.cs @@ -50,9 +50,10 @@ public AbstractRefreshQueue( _notificationManager = notificationManager; } - public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { Initialize(clientCapabilities); + return Task.CompletedTask; } public void Initialize(ClientCapabilities clientCapabilities) @@ -103,7 +104,7 @@ protected void EnqueueRefreshNotification(DocumentUri? documentUri) } } - private async ValueTask FilterLspTrackedDocumentsAsync( + private ValueTask FilterLspTrackedDocumentsAsync( LspWorkspaceManager lspWorkspaceManager, IClientLanguageServerManager notificationManager, ImmutableSegmentedList documentUris, @@ -116,7 +117,7 @@ private async ValueTask FilterLspTrackedDocumentsAsync( { try { - await notificationManager.SendRequestAsync(GetWorkspaceRefreshName(), cancellationToken).ConfigureAwait(false); + return notificationManager.SendRequestAsync(GetWorkspaceRefreshName(), cancellationToken); } catch (Exception ex) when (ex is ObjectDisposedException or ConnectionLostException) { @@ -127,6 +128,7 @@ private async ValueTask FilterLspTrackedDocumentsAsync( } // LSP is already tracking all changed documents so we don't need to send a refresh request. + return ValueTask.CompletedTask; } public virtual void Dispose() diff --git a/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs b/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs index 7e0b42b94c06b..43b9ed45e3b73 100644 --- a/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs +++ b/src/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHelper.cs @@ -211,7 +211,7 @@ await AddTextDocumentEditsAsync( return new LSP.WorkspaceEdit { DocumentChanges = textDocumentEdits.ToArray() }; - async Task AddTextDocumentDeletionsAsync( + Task AddTextDocumentDeletionsAsync( IEnumerable removedDocuments, Func getOldDocument) where TTextDocument : TextDocument @@ -223,6 +223,8 @@ async Task AddTextDocumentDeletionsAsync( textDocumentEdits.Add(new DeleteFile { DocumentUri = oldTextDoc.GetURI() }); } + + return Task.CompletedTask; } async Task AddTextDocumentAdditionsAsync( diff --git a/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs b/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs index 944dc39f497eb..b683cde8c423a 100644 --- a/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Completion/CompletionResolveHandler.cs @@ -44,7 +44,7 @@ public CompletionResolveHandler(IGlobalOptionService globalOptions) public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionItem request) => GetTextDocumentCacheEntry(request); - public async Task HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken) { var completionListCache = context.GetRequiredLspService(); @@ -52,17 +52,17 @@ public CompletionResolveHandler(IGlobalOptionService globalOptions) { // Don't have a cache associated with this completion item, cannot resolve. context.TraceWarning("No cache entry found for the provided completion item at resolve time."); - return completionItem; + return Task.FromResult(completionItem); } var document = context.GetRequiredDocument(); var capabilityHelper = new CompletionCapabilityHelper(context.GetRequiredClientCapabilities()); - return await ResolveCompletionItemAsync( - completionItem, cacheEntry.CompletionList, document, _globalOptions, capabilityHelper, cancellationToken).ConfigureAwait(false); + return ResolveCompletionItemAsync( + completionItem, cacheEntry.CompletionList, document, _globalOptions, capabilityHelper, cancellationToken); } - public static async Task ResolveCompletionItemAsync( + public static Task ResolveCompletionItemAsync( LSP.CompletionItem completionItem, Document document, IGlobalOptionService globalOptions, @@ -73,11 +73,11 @@ public CompletionResolveHandler(IGlobalOptionService globalOptions) if (!completionListCache.TryGetCompletionListCacheEntry(completionItem, out var cacheEntry)) { // Don't have a cache associated with this completion item, cannot resolve. - return completionItem; + return Task.FromResult(completionItem); } - return await ResolveCompletionItemAsync( - completionItem, cacheEntry.CompletionList, document, globalOptions, capabilityHelper, cancellationToken).ConfigureAwait(false); + return ResolveCompletionItemAsync( + completionItem, cacheEntry.CompletionList, document, globalOptions, capabilityHelper, cancellationToken); } private static async Task ResolveCompletionItemAsync( diff --git a/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs b/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs index 39ca0567950e2..c6499a9cf4f6a 100644 --- a/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs @@ -35,16 +35,16 @@ public AbstractGoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSour public abstract Task HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken); - protected async Task GetDefinitionAsync(LSP.TextDocumentPositionParams request, bool forSymbolType, RequestContext context, CancellationToken cancellationToken) + protected Task GetDefinitionAsync(LSP.TextDocumentPositionParams request, bool forSymbolType, RequestContext context, CancellationToken cancellationToken) { var workspace = context.Workspace; var document = context.Document; if (workspace is null || document is null) - return null; + return SpecializedTasks.Null(); var linePosition = ProtocolConversions.PositionToLinePosition(request.Position); - return await GetDefinitionsAsync(_globalOptions, _metadataAsSourceFileService, workspace, document, forSymbolType, linePosition, cancellationToken).ConfigureAwait(false); + return GetDefinitionsAsync(_globalOptions, _metadataAsSourceFileService, workspace, document, forSymbolType, linePosition, cancellationToken); } internal static async Task GetDefinitionsAsync(IGlobalOptionService globalOptions, IMetadataAsSourceFileService? metadataAsSourceFileService, Workspace workspace, Document document, bool forSymbolType, LinePosition linePosition, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs index c61ea8b330837..aa35b95813701 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractDocumentPullDiagnosticHandler.cs @@ -26,7 +26,7 @@ internal abstract class AbstractDocumentPullDiagnosticHandler> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) + protected override ValueTask> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) { // Note: context.Document may be null in the case where the client is asking about a document that we have // since removed from the workspace. In this case, we don't really have anything to process. @@ -38,15 +38,15 @@ protected override async ValueTask> GetOrdered if (identifier is null || context.TextDocument is null) { context.TraceDebug("Ignoring diagnostics request because no text document was provided"); - return []; + return new([]); } if (!context.IsTracking(identifier.DocumentUri)) { context.TraceWarning($"Ignoring diagnostics request for untracked document: {identifier.DocumentUri}"); - return []; + return new([]); } - return await DiagnosticSourceManager.CreateDocumentDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken).ConfigureAwait(false); + return DiagnosticSourceManager.CreateDocumentDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken); } } diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs index 5d858f2452d5d..b1490635f95ef 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs @@ -92,8 +92,9 @@ protected abstract ValueTask> GetOrderedDiagno /// Used by public workspace pull diagnostics to allow it to keep the connection open until /// changes occur to avoid the client spamming the server with requests. /// - protected virtual async Task WaitForChangesAsync(string? category, RequestContext context, CancellationToken cancellationToken) + protected virtual Task WaitForChangesAsync(string? category, RequestContext context, CancellationToken cancellationToken) { + return Task.CompletedTask; } public async Task HandleRequestAsync( diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs index 00d487b59e98c..2ba8cae14e540 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/AbstractWorkspacePullDiagnosticsHandler.cs @@ -59,17 +59,17 @@ public void Dispose() _workspaceRegistrationService.LspSolutionChanged -= OnLspSolutionChanged; } - protected override async ValueTask> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) + protected override ValueTask> GetOrderedDiagnosticSourcesAsync(TDiagnosticsParams diagnosticsParams, string? requestDiagnosticCategory, RequestContext context, CancellationToken cancellationToken) { if (context.ServerKind == WellKnownLspServerKinds.RazorLspServer) { // If we're being called from razor, we do not support WorkspaceDiagnostics at all. For razor, workspace // diagnostics will be handled by razor itself, which will operate by calling into Roslyn and asking for // document-diagnostics instead. - return []; + return new([]); } - return await DiagnosticSourceManager.CreateWorkspaceDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken).ConfigureAwait(false); + return DiagnosticSourceManager.CreateWorkspaceDiagnosticSourcesAsync(context, requestDiagnosticCategory, cancellationToken); } private void OnLspSolutionChanged(object? sender, WorkspaceChangeEventArgs e) diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs index 4cd7ef82b419d..e7be797f951aa 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSourceProviders/DocumentSyntaxAndSemanticDiagnosticSourceProvider.cs @@ -22,9 +22,9 @@ internal abstract class AbstractDocumentSyntaxAndSemanticDiagnosticSourceProvide public bool IsEnabled(ClientCapabilities clientCapabilities) => true; - public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return [new DocumentDiagnosticSource(kind, context.GetRequiredDocument())]; + return new([new DocumentDiagnosticSource(kind, context.GetRequiredDocument())]); } [Export(typeof(IDiagnosticSourceProvider)), Shared] diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs index 600d07c6189d1..fd3cd71ac1f8d 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractProjectDiagnosticSource.cs @@ -59,7 +59,7 @@ public override async Task> GetDiagnosticsAsync( private sealed class CodeAnalysisDiagnosticSource(Project project, ICodeAnalysisDiagnosticAnalyzerService codeAnalysisService) : AbstractProjectDiagnosticSource(project) { - public override async Task> GetDiagnosticsAsync( + public override Task> GetDiagnosticsAsync( RequestContext context, CancellationToken cancellationToken) { @@ -69,7 +69,7 @@ public override async Task> GetDiagnosticsAsync( // user. As such, it is definitely not "live" data, and it should be overridden by any subsequent fresh data // that has been produced. diagnostics = ProtocolConversions.AddBuildTagIfNotPresent(diagnostics); - return diagnostics; + return Task.FromResult(diagnostics); } } } diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs index 495d795dfcbac..ec1ac69524218 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/DiagnosticSources/AbstractWorkspaceDocumentDiagnosticSource.cs @@ -94,7 +94,7 @@ AsyncLazy> GetLazyDiagnostics() private sealed class CodeAnalysisDiagnosticSource(TextDocument document, ICodeAnalysisDiagnosticAnalyzerService codeAnalysisService) : AbstractWorkspaceDocumentDiagnosticSource(document) { - public override async Task> GetDiagnosticsAsync( + public override Task> GetDiagnosticsAsync( RequestContext context, CancellationToken cancellationToken) { @@ -104,7 +104,7 @@ public override async Task> GetDiagnosticsAsync( // user. As such, it is definitely not "live" data, and it should be overridden by any subsequent fresh data // that has been produced. diagnostics = ProtocolConversions.AddBuildTagIfNotPresent(diagnostics); - return diagnostics; + return Task.FromResult(diagnostics); } } } diff --git a/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs index 7eeb89d32eb26..aac612e5d8fe8 100644 --- a/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Diagnostics/Public/PublicDocumentNonLocalDiagnosticSourceProvider.cs @@ -28,15 +28,15 @@ internal sealed class PublicDocumentNonLocalDiagnosticSourceProvider( public bool IsEnabled(ClientCapabilities clientCapabilities) => true; - public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { // Non-local document diagnostics are reported only when full solution analysis is enabled for analyzer execution. if (globalOptions.GetBackgroundAnalysisScope(context.GetRequiredDocument().Project.Language) == BackgroundAnalysisScope.FullSolution) { // NOTE: Compiler does not report any non-local diagnostics, so we only ask to run non-compiler-analyzers. - return [new NonLocalDocumentDiagnosticSource(context.GetRequiredDocument(), AnalyzerFilter.NonCompilerAnalyzer)]; + return new([new NonLocalDocumentDiagnosticSource(context.GetRequiredDocument(), AnalyzerFilter.NonCompilerAnalyzer)]); } - return []; + return new([]); } } diff --git a/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs b/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs index 83b5b619afe6d..f20d2f7712411 100644 --- a/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs +++ b/src/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs @@ -26,7 +26,7 @@ internal class DidChangeHandler() : ILspServiceDocumentRequestHandler request.TextDocument; - public async Task HandleRequestAsync(DidChangeTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(DidChangeTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) { var text = context.GetTrackedDocumentInfo(request.TextDocument.DocumentUri).SourceText; @@ -34,7 +34,7 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(DidChangeTextDocumentPar context.UpdateTrackedDocument(request.TextDocument.DocumentUri, text, request.TextDocument.Version); - return null; + return SpecializedTasks.Default(); } internal static bool AreChangesInReverseOrder(TextDocumentContentChangeEvent[] contentChanges) diff --git a/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs index 3f3e35237d313..a7a223a8e77c4 100644 --- a/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/EditAndContinue/DocumentEditAndContinueDiagnosticSourceProvider.cs @@ -23,8 +23,8 @@ internal sealed class DocumentEditAndContinueDiagnosticSourceProvider() : IDiagn public bool IsEnabled(ClientCapabilities capabilities) => true; - public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return [EditAndContinueDiagnosticSource.CreateOpenDocumentSource(context.GetRequiredDocument())]; + return new([EditAndContinueDiagnosticSource.CreateOpenDocumentSource(context.GetRequiredDocument())]); } } diff --git a/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs b/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs index 729d9cd707de9..1c34bd1f636f5 100644 --- a/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs +++ b/src/LanguageServer/Protocol/Handler/EditAndContinue/RegisterSolutionSnapshotHandler.cs @@ -30,10 +30,10 @@ public RegisterSolutionSnapshotHandler(ISolutionSnapshotRegistry registry) public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; - public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); var id = _registry.RegisterSolutionSnapshot(context.Solution); - return new LspSolutionSnapshotId(id.Id); + return Task.FromResult(new LspSolutionSnapshotId(id.Id)); } } diff --git a/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs b/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs index b6c46e6ce6b88..946363b844c3f 100644 --- a/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs +++ b/src/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs @@ -36,14 +36,14 @@ public FoldingRangesHandler(IGlobalOptionService globalOptions) public TextDocumentIdentifier GetTextDocumentIdentifier(FoldingRangeParams request) => request.TextDocument; - public async Task HandleRequestAsync(FoldingRangeParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(FoldingRangeParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document is null) - return null; + return SpecializedTasks.Null(); var lineFoldingOnly = context.GetRequiredClientCapabilities().TextDocument?.FoldingRange?.LineFoldingOnly == true; - return await SpecializedTasks.AsNullable(GetFoldingRangesAsync(_globalOptions, document, lineFoldingOnly, cancellationToken)).ConfigureAwait(false); + return SpecializedTasks.AsNullable(GetFoldingRangesAsync(_globalOptions, document, lineFoldingOnly, cancellationToken)); } internal static Task GetFoldingRangesAsync( diff --git a/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs b/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs index e8e929fe0b4c1..ae1aabe0d4d52 100644 --- a/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs +++ b/src/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs @@ -40,14 +40,14 @@ public DocumentHighlightsHandler(IHighlightingService highlightingService, IGlob public TextDocumentIdentifier GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument; - public async Task HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) - return null; + return SpecializedTasks.Null(); var position = ProtocolConversions.PositionToLinePosition(request.Position); - return await GetHighlightsAsync(_globalOptions, _highlightingService, document, position, cancellationToken).ConfigureAwait(false); + return GetHighlightsAsync(_globalOptions, _highlightingService, document, position, cancellationToken); } internal static async Task GetHighlightsAsync(IGlobalOptionService globalOptions, IHighlightingService highlightingService, Document document, LinePosition linePosition, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs b/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs index de7eedf1ebfec..cd9014d3bc9af 100644 --- a/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs +++ b/src/LanguageServer/Protocol/Handler/OnAutoInsert/OnAutoInsertHandler.cs @@ -42,18 +42,18 @@ internal sealed class OnAutoInsertHandler( public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(LSP.VSInternalDocumentOnAutoInsertParams request) => request.TextDocument; - public async Task HandleRequestAsync( + public Task HandleRequestAsync( LSP.VSInternalDocumentOnAutoInsertParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) - return null; + return SpecializedTasks.Null(); var onAutoInsertEnabled = _globalOptions.GetOption(LspOptionsStorage.LspEnableAutoInsert, document.Project.Language); if (!onAutoInsertEnabled) - return null; + return SpecializedTasks.Null(); var servicesForDocument = _braceCompletionServices.SelectAsArray(s => s.Metadata.Language == document.Project.Language, s => s.Value); var isRazorRequest = context.ServerKind == WellKnownLspServerKinds.RazorLspServer; @@ -63,7 +63,7 @@ internal sealed class OnAutoInsertHandler( // We want adjust the braces after enter for razor and non-VS clients. // We don't do this via on type formatting as it does not support snippets. var includeNewLineBraceFormatting = isRazorRequest || !supportsVSExtensions; - return await GetOnAutoInsertResponseAsync(_globalOptions, servicesForDocument, document, position, request.Character, request.Options, includeNewLineBraceFormatting, cancellationToken).ConfigureAwait(false); + return GetOnAutoInsertResponseAsync(_globalOptions, servicesForDocument, document, position, request.Character, request.Options, includeNewLineBraceFormatting, cancellationToken); } internal static async Task GetOnAutoInsertResponseAsync( diff --git a/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs b/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs index a7905f5abca7c..62fb88c976829 100644 --- a/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs +++ b/src/LanguageServer/Protocol/Handler/ProjectContext/GetTextDocumentWithContextHandler.cs @@ -26,7 +26,7 @@ internal class GetTextDocumentWithContextHandler() : ILspServiceDocumentRequestH public TextDocumentIdentifier GetTextDocumentIdentifier(VSGetProjectContextsParams request) => new() { DocumentUri = request.TextDocument.DocumentUri }; - public async Task HandleRequestAsync(VSGetProjectContextsParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(VSGetProjectContextsParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Workspace); Contract.ThrowIfNull(context.Solution); @@ -37,7 +37,7 @@ internal class GetTextDocumentWithContextHandler() : ILspServiceDocumentRequestH if (!documentIds.Any()) { - return null; + return SpecializedTasks.Null(); } var contexts = new List(); @@ -57,10 +57,10 @@ internal class GetTextDocumentWithContextHandler() : ILspServiceDocumentRequestH var openDocumentId = documentIds.First(); var currentContextDocumentId = context.Workspace.GetDocumentIdInCurrentContext(openDocumentId); - return new VSProjectContextList + return Task.FromResult(new VSProjectContextList { ProjectContexts = [.. contexts], DefaultIndex = documentIds.IndexOf(d => d == currentContextDocumentId) - }; + }); } } diff --git a/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs b/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs index 08861caab5e33..4255fdb8221e4 100644 --- a/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs +++ b/src/LanguageServer/Protocol/Handler/References/FindUsagesLSPContext.cs @@ -372,9 +372,10 @@ private static ClassifiedTextRun[] GetClassifiedTextRuns( return classifiedTextRuns.ToArray(); } - private async ValueTask ReportReferencesAsync(ImmutableSegmentedList> referencesToReport, CancellationToken cancellationToken) + private ValueTask ReportReferencesAsync(ImmutableSegmentedList> referencesToReport, CancellationToken cancellationToken) { // We can report outside of the lock here since _progress is thread-safe. _progress.Report([.. referencesToReport]); + return ValueTask.CompletedTask; } } diff --git a/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs b/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs index 387923e812a5e..e09c98d46bbca 100644 --- a/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs +++ b/src/LanguageServer/Protocol/Handler/ServerLifetime/InitializeHandler.cs @@ -21,7 +21,7 @@ public InitializeHandler() public bool MutatesSolutionState => true; public bool RequiresLSPSolution => false; - public async Task HandleRequestAsync(InitializeParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(InitializeParams request, RequestContext context, CancellationToken cancellationToken) { var clientCapabilitiesManager = context.GetRequiredLspService(); var clientCapabilities = clientCapabilitiesManager.TryGetClientCapabilities(); @@ -44,9 +44,9 @@ public async Task HandleRequestAsync(InitializeParams request, m["capabilities"] = JsonSerializer.Serialize(serverCapabilities, ProtocolConversions.LspJsonSerializerOptions); })); - return new InitializeResult + return Task.FromResult(new InitializeResult { Capabilities = serverCapabilities, - }; + }); } } diff --git a/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs b/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs index 0c224504a535b..e8bec0292d0fe 100644 --- a/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs +++ b/src/LanguageServer/Protocol/Handler/ServerLifetime/LspServiceLifeCycleManager.cs @@ -68,7 +68,9 @@ public async Task ShutdownAsync(string message = "Shutting down") } } - public async Task ExitAsync() + public Task ExitAsync() { + // We don't need any custom logic to run on exit. + return Task.CompletedTask; } } diff --git a/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs b/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs index 196e036f82817..21f56aebf4574 100644 --- a/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs +++ b/src/LanguageServer/Protocol/Handler/SignatureHelp/SignatureHelpHandler.cs @@ -29,15 +29,15 @@ internal sealed class SignatureHelpHandler(SignatureHelpService signatureHelpSer public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(LSP.TextDocumentPositionParams request) => request.TextDocument; - public async Task HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) - return null; + return SpecializedTasks.Null(); var supportsVisualStudioExtensions = context.GetRequiredClientCapabilities().HasVisualStudioLspCapability(); var linePosition = ProtocolConversions.PositionToLinePosition(request.Position); - return await GetSignatureHelpAsync(signatureHelpService, document, linePosition, supportsVisualStudioExtensions, cancellationToken).ConfigureAwait(false); + return GetSignatureHelpAsync(signatureHelpService, document, linePosition, supportsVisualStudioExtensions, cancellationToken); } internal static async Task GetSignatureHelpAsync(SignatureHelpService signatureHelpService, Document document, LinePosition linePosition, bool supportsVisualStudioExtensions, CancellationToken cancellationToken) diff --git a/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs b/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs index cbfad43eaac30..3658140436c78 100644 --- a/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs +++ b/src/LanguageServer/Protocol/Handler/SourceGenerators/SourceGeneratorRefreshQueue.cs @@ -50,16 +50,17 @@ public SourceGeneratorRefreshQueue( _disposalTokenSource.Token); } - public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { if (clientCapabilities.HasVisualStudioLspCapability()) { // VS source generated document content is not provided by LSP. - return; + return Task.CompletedTask; } // After we have initialized we can start listening for workspace changes. _lspWorkspaceRegistrationService.LspSolutionChanged += OnLspSolutionChanged; + return Task.CompletedTask; } private void OnLspSolutionChanged(object? sender, WorkspaceChangeEventArgs e) @@ -119,25 +120,27 @@ await newProject.GetDependentVersionAsync(_disposalTokenSource.Token).ConfigureA } } - private async ValueTask RefreshSourceGeneratedDocumentsAsync( + private ValueTask RefreshSourceGeneratedDocumentsAsync( CancellationToken cancellationToken) { var hasOpenSourceGeneratedDocuments = _lspWorkspaceManager.GetTrackedLspText().Keys.Any(uri => uri.ParsedUri?.Scheme == SourceGeneratedDocumentUri.Scheme); if (!hasOpenSourceGeneratedDocuments) { // There are no opened source generated documents - we don't need to bother asking the client to refresh anything. - return; + return ValueTask.CompletedTask; } try { - await _notificationManager.SendNotificationAsync(RefreshSourceGeneratedDocumentName, cancellationToken).ConfigureAwait(false); + return _notificationManager.SendNotificationAsync(RefreshSourceGeneratedDocumentName, cancellationToken); } catch (Exception ex) when (ex is ObjectDisposedException or ConnectionLostException) { // It is entirely possible that we're shutting down and the connection is lost while we're trying to send a notification // as this runs outside of the guaranteed ordering in the queue. We can safely ignore this exception. } + + return ValueTask.CompletedTask; } public void Dispose() diff --git a/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs index 39feacef3b39a..09804a1157f42 100644 --- a/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Tasks/DocumentTaskDiagnosticSourceProvider.cs @@ -23,9 +23,9 @@ internal sealed class DocumentTaskDiagnosticSourceProvider([Import] IGlobalOptio public bool IsEnabled(ClientCapabilities capabilities) => capabilities.HasVisualStudioLspCapability(); - public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return [new TaskListDiagnosticSource(context.GetRequiredDocument(), globalOptions)]; + return new([new TaskListDiagnosticSource(context.GetRequiredDocument(), globalOptions)]); } } diff --git a/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs b/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs index 29bf846470714..7b341125f4ec0 100644 --- a/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs +++ b/src/LanguageServer/Protocol/Handler/Tasks/WorkspaceTaskDiagnosticSourceProvider.cs @@ -25,7 +25,7 @@ internal sealed class WorkspaceTaskDiagnosticSourceProvider([Import] IGlobalOpti public bool IsEnabled(ClientCapabilities capabilities) => capabilities.HasVisualStudioLspCapability(); - public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); @@ -42,9 +42,9 @@ public async ValueTask> CreateDiagnosticSource } } - return result.ToImmutableAndClear(); + return new(result.ToImmutableAndClear()); } - return []; + return new([]); } } diff --git a/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs b/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs index 7d2fd3cfedf0e..84fe68cc65bfe 100644 --- a/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs +++ b/src/LanguageServer/Protocol/Handler/WorkDoneProgress/WorkDoneProgressCancelledHandler.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -21,10 +21,11 @@ internal sealed class WorkDoneProgressCancelledHandler() : ILspServiceNotificati public bool RequiresLSPSolution => false; - public async Task HandleNotificationAsync(WorkDoneProgressCancelParams request, RequestContext requestContext, CancellationToken cancellationToken) + public Task HandleNotificationAsync(WorkDoneProgressCancelParams request, RequestContext requestContext, CancellationToken cancellationToken) { var manager = requestContext.GetRequiredLspService(); // We always create guid tokens, so use the string sumtype directly. manager.CancelWorkDoneProgress(request.Token.Second); + return Task.CompletedTask; } } diff --git a/src/LanguageServer/Protocol/RoslynLanguageServer.cs b/src/LanguageServer/Protocol/RoslynLanguageServer.cs index f3fae36b579f5..ca575808b15f9 100644 --- a/src/LanguageServer/Protocol/RoslynLanguageServer.cs +++ b/src/LanguageServer/Protocol/RoslynLanguageServer.cs @@ -157,9 +157,10 @@ void AddBaseService(BaseService baseService) } } - public async Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) + public Task OnInitializedAsync(ClientCapabilities clientCapabilities, RequestContext context, CancellationToken cancellationToken) { OnInitialized(); + return Task.CompletedTask; } public override bool TryGetLanguageForRequest(string methodName, object? serializedParameters, [NotNullWhen(true)] out string? language) diff --git a/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs b/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs index 5342371a4db87..e479423f1e139 100644 --- a/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs +++ b/src/LanguageServer/Protocol/Workspaces/LspMiscellaneousFilesWorkspaceProvider.cs @@ -30,10 +30,10 @@ internal sealed class LspMiscellaneousFilesWorkspaceProvider(ILspServices lspSer { public bool SupportsMutation => true; - public async ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, CancellationToken cancellationToken) + public ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument document, CancellationToken cancellationToken) { // In this case, the only documents ever created live in the Miscellaneous Files workspace (which is this object directly), so we can just compare to 'this'. - return document.Project.Solution.Workspace == this; + return ValueTask.FromResult(document.Project.Solution.Workspace == this); } /// @@ -42,8 +42,8 @@ public async ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument docu /// Calls to this method and are made /// from LSP text sync request handling which do not run concurrently. /// - public async ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) - => AddMiscellaneousDocument(uri, documentText, languageId, logger); + public ValueTask AddMiscellaneousDocumentAsync(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) + => ValueTask.FromResult(AddMiscellaneousDocument(uri, documentText, languageId, logger)); private TextDocument? AddMiscellaneousDocument(DocumentUri uri, SourceText documentText, string languageId, ILspLogger logger) { @@ -83,7 +83,7 @@ public async ValueTask IsMiscellaneousFilesDocumentAsync(TextDocument docu /// Calls to this method and are made /// from LSP text sync request handling which do not run concurrently. /// - public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri) + public ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri) { // We'll only ever have a single document matching this URI in the misc solution. var matchingDocument = CurrentSolution.GetDocumentIds(uri).SingleOrDefault(); @@ -103,15 +103,16 @@ public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri var project = CurrentSolution.GetRequiredProject(matchingDocument.ProjectId); OnProjectRemoved(project.Id); - return true; + return ValueTask.FromResult(true); } - return false; + return ValueTask.FromResult(false); } - public async ValueTask UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) + public ValueTask UpdateTextIfPresentAsync(DocumentId documentId, SourceText sourceText, CancellationToken cancellationToken) { this.OnDocumentTextChanged(documentId, sourceText, PreservationMode.PreserveIdentity, requireDocumentPresent: false); + return ValueTask.CompletedTask; } private sealed class StaticSourceTextContainer(SourceText text) : SourceTextContainer diff --git a/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs b/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs index c0009a60454b3..e585ee4c76743 100644 --- a/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs +++ b/src/LanguageServer/Protocol/Workspaces/SourceTextLoader.cs @@ -23,6 +23,6 @@ internal override string? FilePath => _fileUri; // TODO (https://github.com/dotnet/roslyn/issues/63583): Use options.ChecksumAlgorithm - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => TextAndVersion.Create(_sourceText, VersionStamp.Create(), _fileUri); + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(TextAndVersion.Create(_sourceText, VersionStamp.Create(), _fileUri)); } diff --git a/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs b/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs index ac2e470b71ac4..6595db73e8c26 100644 --- a/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Commands/ExecuteWorkspaceCommandTests.cs @@ -67,9 +67,9 @@ public override TextDocumentIdentifier GetTextDocumentIdentifier(ExecuteCommandP return JsonSerializer.Deserialize((JsonElement)request.Arguments!.First(), ProtocolConversions.LspJsonSerializerOptions)!; } - public override async Task HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken) + public override Task HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken) { - return true; + return Task.FromResult(true); } } } diff --git a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs index dcbd3a4e7e054..c60c51ae06e2c 100644 --- a/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs @@ -505,15 +505,15 @@ public TestCaretOutOfScopeCompletionService(SolutionServices services) : base(se public override string Language => LanguageNames.CSharp; - internal override async Task GetCompletionsAsync(Document document, + internal override Task GetCompletionsAsync(Document document, int caretPosition, CodeAnalysis.Completion.CompletionOptions options, OptionSet passThroughOptions, CompletionTrigger trigger = default, ImmutableHashSet roles = null, - CancellationToken cancellationToken = default) => CodeAnalysis.Completion.CompletionList.Empty; + CancellationToken cancellationToken = default) => Task.FromResult(CodeAnalysis.Completion.CompletionList.Empty); - public override async Task GetChangeAsync( + public override Task GetChangeAsync( Document document, CodeAnalysis.Completion.CompletionItem item, char? commitCharacter = null, @@ -526,7 +526,7 @@ public override void M() } """); - return CompletionChange.Create(textChange, newPosition: 0); + return Task.FromResult(CompletionChange.Create(textChange, newPosition: 0)); } internal override bool ShouldTriggerCompletion(Project project, LanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, CodeAnalysis.Completion.CompletionOptions options, OptionSet passthroughOptions, ImmutableHashSet roles = null) @@ -535,7 +535,7 @@ internal override bool ShouldTriggerCompletion(Project project, LanguageServices internal override CompletionRules GetRules(CodeAnalysis.Completion.CompletionOptions options) => CompletionRules.Default; - internal override async Task GetDescriptionAsync(Document document, CodeAnalysis.Completion.CompletionItem item, CodeAnalysis.Completion.CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken = default) - => CompletionDescription.Empty; + internal override Task GetDescriptionAsync(Document document, CodeAnalysis.Completion.CompletionItem item, CodeAnalysis.Completion.CompletionOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken = default) + => Task.FromResult(CompletionDescription.Empty); } } diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs index e3356c4ef825c..3d2cbbff7391e 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AbstractPullDiagnosticTestsBase.cs @@ -372,10 +372,10 @@ private sealed class MockTypescriptDiagnosticAnalyzer : DocumentDiagnosticAnalyz public override ImmutableArray SupportedDiagnostics => [Descriptor]; - public override async Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) + public override Task> AnalyzeSyntaxAsync(TextDocument document, SyntaxTree? tree, CancellationToken cancellationToken) { - return ImmutableArray.Create( - Diagnostic.Create(Descriptor, Location.Create(document.FilePath!, default, default))); + return Task.FromResult(ImmutableArray.Create( + Diagnostic.Create(Descriptor, Location.Create(document.FilePath!, default, default)))); } } } diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs index bb99dc823bda6..548f54f2ef519 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/AdditionalFileDiagnosticsTests.cs @@ -227,23 +227,23 @@ internal sealed class TestAdditionalFileDocumentSourceProvider() : IDiagnosticSo bool IDiagnosticSourceProvider.IsEnabled(LSP.ClientCapabilities clientCapabilities) => true; - async ValueTask> IDiagnosticSourceProvider.CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + ValueTask> IDiagnosticSourceProvider.CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { if (context.TextDocument is not null && context.TextDocument is not Document) { - return [new TestAdditionalFileDocumentSource(context.TextDocument)]; + return new([new TestAdditionalFileDocumentSource(context.TextDocument)]); } - return []; + return new([]); } private class TestAdditionalFileDocumentSource(TextDocument textDocument) : IDiagnosticSource { - public async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + public Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) { var diagnostic = Diagnostic.Create(MockAdditionalFileDiagnosticAnalyzer.Descriptor, location: Location.Create(context.TextDocument!.FilePath!, Text.TextSpan.FromBounds(0, 0), new Text.LinePositionSpan(new Text.LinePosition(0, 0), new Text.LinePosition(0, 0))), "args"); - return [DiagnosticData.Create(diagnostic, context.TextDocument.Project)]; + return Task.FromResult>([DiagnosticData.Create(diagnostic, context.TextDocument.Project)]); } public LSP.TextDocumentIdentifier? GetDocumentIdentifier() => new() diff --git a/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs b/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs index 0625038497254..ab67bd1e23670 100644 --- a/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Diagnostics/DiagnosticsPullCacheTests.cs @@ -118,12 +118,12 @@ private sealed class TestDiagnosticSource(Document document, TestDiagnosticSourc { public const string Id = "Id"; - public override async Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) + public override Task> GetDiagnosticsAsync(RequestContext context, CancellationToken cancellationToken) { Interlocked.Increment(ref provider.DiagnosticsRequestedCount); - return [new DiagnosticData(Id, category: "category", context.Document!.Name, DiagnosticSeverity.Error, DiagnosticSeverity.Error, + return Task.FromResult>([new DiagnosticData(Id, category: "category", context.Document!.Name, DiagnosticSeverity.Error, DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, [], ImmutableDictionary.Empty,context.Document!.Project.Id, - new DiagnosticDataLocation(new FileLinePositionSpan(context.Document!.FilePath!, new Text.LinePosition(0, 0), new Text.LinePosition(0, 0))))]; + new DiagnosticDataLocation(new FileLinePositionSpan(context.Document!.FilePath!, new Text.LinePosition(0, 0), new Text.LinePosition(0, 0))))]); } } @@ -138,9 +138,9 @@ private sealed class TestDiagnosticSourceProvider() : IDiagnosticSourceProvider public int DiagnosticsRequestedCount = 0; - public async ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) + public ValueTask> CreateDiagnosticSourcesAsync(RequestContext context, CancellationToken cancellationToken) { - return [new TestDiagnosticSource(context.Document!, this)]; + return new ValueTask>([new TestDiagnosticSource(context.Document!, this)]); } public bool IsEnabled(LSP.ClientCapabilities clientCapabilities) diff --git a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs index 76678098035d3..edb76dd49fa16 100644 --- a/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.cs @@ -494,11 +494,11 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TextDocumentIdentifier r return request; } - public async Task HandleRequestAsync(TextDocumentIdentifier request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TextDocumentIdentifier request, RequestContext context, CancellationToken cancellationToken) { var trackedDocumentInfo = context.GetTrackedDocumentInfo(request.DocumentUri); - return new TestVersionResponse(trackedDocumentInfo.LspVersion); + return Task.FromResult(new TestVersionResponse(trackedDocumentInfo.LspVersion)); } } } diff --git a/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs b/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs index 3ec74706852c7..a117815191a4d 100644 --- a/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/HandlerTests.cs @@ -316,9 +316,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeOne reque return request.TextDocumentIdentifier; } - public async Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { - return this.GetType().Name; + return Task.FromResult(this.GetType().Name); } } @@ -338,9 +338,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeOne reque return request.TextDocumentIdentifier; } - public async Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { - return this.GetType().Name; + return Task.FromResult(this.GetType().Name); } } @@ -355,9 +355,9 @@ internal sealed class TestRequestHandlerWithNoParams() : ILspServiceRequestHandl public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { - return this.GetType().Name; + return Task.FromResult(this.GetType().Name); } } @@ -370,9 +370,10 @@ internal sealed class TestNotificationHandler() : ILspServiceNotificationHandler public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public async Task HandleNotificationAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public Task HandleNotificationAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { ResultSource.SetResult(this.GetType().Name); + return Task.CompletedTask; } } @@ -399,9 +400,10 @@ internal sealed class TestNotificationWithoutParamsHandler() : ILspServiceNotifi public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public async Task HandleNotificationAsync(RequestContext context, CancellationToken cancellationToken) + public Task HandleNotificationAsync(RequestContext context, CancellationToken cancellationToken) { ResultSource.SetResult(this.GetType().Name); + return Task.CompletedTask; } } @@ -436,9 +438,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeOne reque return request.TextDocumentIdentifier; } - public async Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TestRequestTypeOne request, RequestContext context, CancellationToken cancellationToken) { - return this.GetType().Name; + return Task.FromResult(this.GetType().Name); } } @@ -460,9 +462,9 @@ public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequestTypeTwo reque return request.TextDocumentIdentifier; } - public async Task HandleRequestAsync(TestRequestTypeTwo request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TestRequestTypeTwo request, RequestContext context, CancellationToken cancellationToken) { - return this.GetType().Name; + return Task.FromResult(this.GetType().Name); } } @@ -479,9 +481,9 @@ internal sealed class TestDuplicateLanguageSpecificHandler() : ILspServiceReques public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public async Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(RequestContext context, CancellationToken cancellationToken) { - return this.GetType().Name; + return Task.FromResult(this.GetType().Name); } } } diff --git a/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs b/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs index f18286f314ffb..c96b532168aa4 100644 --- a/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Initialize/LocaleTests.cs @@ -93,9 +93,9 @@ public LocaleTestHandler() public bool MutatesSolutionState => true; public bool RequiresLSPSolution => true; - public async Task HandleRequestAsync(Request request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(Request request, RequestContext context, CancellationToken cancellationToken) { - return new Response(CultureInfo.CurrentUICulture.Name); + return Task.FromResult(new Response(CultureInfo.CurrentUICulture.Name)); } } diff --git a/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs b/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs index 2ffac1bb8b198..d5afa895b3871 100644 --- a/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs +++ b/src/LanguageServer/ProtocolUnitTests/Ordering/LongRunningNonMutatingRequestHandler.cs @@ -28,13 +28,13 @@ public LongRunningNonMutatingRequestHandler() public bool RequiresLSPSolution => true; - public async Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { do { if (cancellationToken.IsCancellationRequested) { - return new TestResponse(); + return Task.FromResult(new TestResponse()); } Thread.Sleep(100); diff --git a/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs b/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs index aff916af644b2..38c122a1bdaaa 100644 --- a/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs +++ b/src/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs @@ -27,10 +27,10 @@ public NonLSPSolutionRequestHandler() public bool MutatesSolutionState => false; public bool RequiresLSPSolution => false; - public async Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { Assert.Null(context.Solution); - return new TestResponse(); + return Task.FromResult(new TestResponse()); } } diff --git a/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs b/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs index 2504b2e663ec2..c6fefb8c008d7 100644 --- a/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Rename/WillRenameTests.cs @@ -152,9 +152,9 @@ private class TestWillRenameListener1() : ILspWillRenameListener { public WorkspaceEdit Result { get; set; } - public async Task HandleWillRenameAsync(RenameFilesParams renameParams, RequestContext context, CancellationToken cancellationToken) + public Task HandleWillRenameAsync(RenameFilesParams renameParams, RequestContext context, CancellationToken cancellationToken) { - return Result; + return Task.FromResult(Result); } } diff --git a/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs b/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs index 329885f80e6e4..213721f2f4ea1 100644 --- a/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/Symbols/WorkspaceSymbolsTests.cs @@ -261,7 +261,7 @@ private static string GetContainerName(Solution solution, string? containingSymb [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] protected sealed class TestWorkspaceNavigateToSearchHostService() : IWorkspaceNavigateToSearcherHostService { - public async ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) - => true; + public ValueTask IsFullyLoadedAsync(CancellationToken cancellationToken) + => new(true); } } diff --git a/src/LanguageServer/ProtocolUnitTests/UriTests.cs b/src/LanguageServer/ProtocolUnitTests/UriTests.cs index 9bf3c82952be9..020f9db691c8e 100644 --- a/src/LanguageServer/ProtocolUnitTests/UriTests.cs +++ b/src/LanguageServer/ProtocolUnitTests/UriTests.cs @@ -383,9 +383,9 @@ private sealed class CustomResolveHandler() : ILspServiceDocumentRequestHandler< public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public LSP.TextDocumentIdentifier GetTextDocumentIdentifier(CustomResolveParams request) => request.TextDocument; - public async Task HandleRequestAsync(CustomResolveParams request, RequestContext context, CancellationToken cancellationToken) + public Task HandleRequestAsync(CustomResolveParams request, RequestContext context, CancellationToken cancellationToken) { - return new ResolvedDocumentInfo(context.Workspace!.Kind!, context.GetRequiredDocument().Project.Language); + return Task.FromResult(new ResolvedDocumentInfo(context.Workspace!.Kind!, context.GetRequiredDocument().Project.Language)); } } } diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs index e0ab97d63dc41..25ec18d52c2e1 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs @@ -45,7 +45,7 @@ public sealed partial class AnalyzerReleaseTrackingFix() : CodeFixProvider public override FixAllProvider GetFixAllProvider() => new ReleaseTrackingFixAllProvider(); - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -98,13 +98,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix(codeAction, diagnostic); } } + + return Task.CompletedTask; } - private static async Task AddAnalyzerReleaseTrackingFilesAsync(Project project) + private static Task AddAnalyzerReleaseTrackingFilesAsync(Project project) { project = AddAdditionalDocument(project, ReleaseTrackingHelper.ShippedFileName, ShippedAnalyzerReleaseTrackingFileDefaultContent); project = AddAdditionalDocument(project, ReleaseTrackingHelper.UnshippedFileName, UnshippedAnalyzerReleaseTrackingFileDefaultContent); - return project.Solution; + return Task.FromResult(project.Solution); // Local functions. static Project AddAdditionalDocument(Project project, string name, string fileContent) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs index 38156a2aa8967..1cb707aa50379 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ApplyDiagnosticAnalyzerAttributeFix.cs @@ -59,7 +59,7 @@ private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root context.RegisterCodeFix(fix, context.Diagnostics); } - private async Task GetFixAsync(Document document, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages) + private Task GetFixAsync(Document document, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages) { var languageNamesFullName = typeof(LanguageNames).FullName; var arguments = new SyntaxNode[languages.Length]; @@ -75,7 +75,7 @@ private async Task GetFixAsync(Document document, SyntaxNode root, Syn var attribute = generator.Attribute(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzerAttribute, arguments); var newClassDecl = generator.AddAttributes(classDecl, attribute); var newRoot = root.ReplaceNode(classDecl, newClassDecl); - return document.WithSyntaxRoot(newRoot); + return Task.FromResult(document.WithSyntaxRoot(newRoot)); } public sealed override FixAllProvider GetFixAllProvider() diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs index d5634c9d5df41..829ec829b11cf 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/CompareSymbolsCorrectlyFix.cs @@ -31,7 +31,7 @@ public abstract class CompareSymbolsCorrectlyFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -58,6 +58,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) } } } + + return Task.CompletedTask; } private async Task ConvertToEqualsAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs index 00ddf3a4d3561..fb253eb9fc60c 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs @@ -25,7 +25,7 @@ public abstract class ConfigureGeneratedCodeAnalysisFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -36,6 +36,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(ConfigureGeneratedCodeAnalysisFix)), diagnostic); } + + return Task.CompletedTask; } private async Task ConfigureGeneratedCodeAnalysisAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs index 4aab9a921dc48..bd56a0fd5dade 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/EnableConcurrentExecutionFix.cs @@ -24,7 +24,7 @@ public abstract class EnableConcurrentExecutionFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -35,6 +35,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(EnableConcurrentExecutionFix)), diagnostic); } + + return Task.CompletedTask; } private async Task EnableConcurrentExecutionAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs index 5a6fd58f66573..f9c870e37760c 100644 --- a/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs +++ b/src/RoslynAnalyzers/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/PreferIsKindFix.cs @@ -19,7 +19,7 @@ public abstract class PreferIsKindFix : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -30,6 +30,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(PreferIsKindFix)), diagnostic); } + + return Task.CompletedTask; } private async Task ConvertKindToIsKindAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs index 05c14b65317c6..66b30fdd3cdf6 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/AnnotatePublicApiFix.cs @@ -32,7 +32,7 @@ public sealed class AnnotatePublicApiFix() : CodeFixProvider public sealed override FixAllProvider GetFixAllProvider() => new PublicSurfaceAreaFixAllProvider(); - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Project project = context.Document.Project; @@ -66,7 +66,7 @@ publicSymbolNameWithNullability is null || } } - return; + return Task.CompletedTask; static async Task GetFixAsync(TextDocument publicSurfaceAreaDocument, string oldSymbolName, string newSymbolName, CancellationToken cancellationToken) { diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs index dff68fccd840a..2a9a44ebefc03 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs @@ -33,7 +33,7 @@ public sealed override FixAllProvider GetFixAllProvider() return new PublicSurfaceAreaFixAllProvider(); } - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var project = context.Document.Project; @@ -63,6 +63,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) diagnostic); } } + + return Task.CompletedTask; } private static IEnumerable GetUnshippedPublicApiFiles(Project project, bool isPublic) diff --git a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs index a709b2c043b91..121ad21a71cd2 100644 --- a/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs +++ b/src/RoslynAnalyzers/PublicApiAnalyzers/Core/CodeFixes/NullableEnablePublicApiFix.cs @@ -29,7 +29,7 @@ public sealed class NullableEnablePublicApiFix() : CodeFixProvider public sealed override FixAllProvider GetFixAllProvider() => new PublicSurfaceAreaFixAllProvider(); - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Project project = context.Document.Project; @@ -49,6 +49,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) diagnostic); } } + + return Task.CompletedTask; } private static async Task GetFixAsync(TextDocument surfaceAreaDocument, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs index 3987368d5fd83..a57e1c259ac68 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/CSharp/PreferNullLiteralCodeFixProvider.cs @@ -30,7 +30,7 @@ public class PreferNullLiteralCodeFixProvider() : CodeFixProvider public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -41,6 +41,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(PreferNullLiteralCodeFixProvider)), diagnostic); } + + return Task.CompletedTask; } private static async Task ReplaceWithNullLiteralAsync(Document document, Location location, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs index 885752b34de0a..3cb4590ffc788 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/DoNotMixAttributesFromDifferentVersionsOfMEF.Fixer.cs @@ -21,9 +21,11 @@ public sealed override FixAllProvider GetFixAllProvider() return WellKnownFixAllProviders.BatchFixer; } - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { // Fixer not yet implemented. + return Task.CompletedTask; + } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs index c4982b7976841..b642602f35feb 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructorCodeFixProvider.cs @@ -32,7 +32,7 @@ public class ExportedPartsShouldHaveImportingConstructorCodeFixProvider() : Code public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -72,6 +72,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: scenario), diagnostic); } + + return Task.CompletedTask; } private static async Task AddExplicitImportingConstructorAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs index 09108f1e6d9c5..d4a449d92b89d 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs @@ -29,7 +29,7 @@ public abstract class AbstractImportingConstructorShouldBeObsoleteCodeFixProvide public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -78,6 +78,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: scenario), diagnostic); } + + return Task.CompletedTask; } private async Task AddObsoleteAttributeAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs index 90b84571c7af5..ba2a682a7b2c2 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.Fixer.cs @@ -58,11 +58,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) private static bool TryGetDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) => (declaration = node.FirstAncestorOrSelf()) is not null; - private static async Task AddSharedAttributeAsync(Document document, SyntaxNode root, SyntaxNode declaration) + private static Task AddSharedAttributeAsync(Document document, SyntaxNode root, SyntaxNode declaration) { var generator = SyntaxGenerator.GetGenerator(document); var newDeclaration = generator.AddAttributes(declaration, generator.Attribute(typeof(SharedAttribute).FullName)); - return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration)); + return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(declaration, newDeclaration))); } } } diff --git a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs index 011e07cbe1fac..f596347c9cee0 100644 --- a/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs +++ b/src/RoslynAnalyzers/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverableCodeFixProvider.cs @@ -32,7 +32,7 @@ public class TestExportsShouldNotBeDiscoverableCodeFixProvider() : CodeFixProvid public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -43,6 +43,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: nameof(TestExportsShouldNotBeDiscoverable)), diagnostic); } + + return Task.CompletedTask; } private static async Task AddPartNotDiscoverableAttributeAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) diff --git a/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs b/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs index 55731d7985b2b..554fa6a98f8ac 100644 --- a/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs +++ b/src/RoslynAnalyzers/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.Fixer.cs @@ -21,9 +21,11 @@ public sealed override FixAllProvider GetFixAllProvider() return WellKnownFixAllProviders.BatchFixer; } - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { // Fixer not yet implemented. + return Task.CompletedTask; + } } } diff --git a/src/VisualStudio/CSharp/Impl/CSharpPackage.cs b/src/VisualStudio/CSharp/Impl/CSharpPackage.cs index c12fedcdbe6d1..d085fa72391ec 100644 --- a/src/VisualStudio/CSharp/Impl/CSharpPackage.cs +++ b/src/VisualStudio/CSharp/Impl/CSharpPackage.cs @@ -67,7 +67,7 @@ protected override void RegisterInitializeAsyncWork(PackageLoadTasks packageInit packageInitializationTasks.AddTask(isMainThreadTask: false, task: PackageInitializationBackgroundThreadAsync); } - private async Task PackageInitializationBackgroundThreadAsync(PackageLoadTasks packageInitializationTasks, CancellationToken cancellationToken) + private Task PackageInitializationBackgroundThreadAsync(PackageLoadTasks packageInitializationTasks, CancellationToken cancellationToken) { try { @@ -90,6 +90,8 @@ private async Task PackageInitializationBackgroundThreadAsync(PackageLoadTasks p catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, ErrorSeverity.General)) { } + + return Task.CompletedTask; } protected override void RegisterObjectBrowserLibraryManager() diff --git a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs index 814c27ffb1a02..61559fa4ec6a4 100644 --- a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs +++ b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProvider.cs @@ -33,7 +33,7 @@ public CSharpCodeStyleSettingsProvider( Update(); } - protected override async Task UpdateOptionsAsync( + protected override Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var varSettings = GetVarCodeStyleOptions(options, SettingsUpdater); @@ -65,6 +65,8 @@ protected override async Task UpdateOptionsAsync( var unusedValueSettings = GetUnusedValueCodeStyleOptions(options, SettingsUpdater); AddRange(unusedValueSettings); + + return Task.CompletedTask; } private static IEnumerable GetVarCodeStyleOptions(TieredAnalyzerConfigOptions options, OptionUpdater updater) diff --git a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs index 104fbf0424e1e..5b1dec17cb78c 100644 --- a/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs +++ b/src/VisualStudio/CSharp/Impl/EditorConfigSettings/DataProvider/Whitespace/CSharpWhitespaceSettingsProvider.cs @@ -28,7 +28,7 @@ public CSharpWhitespaceSettingsProvider(IThreadingContext threadingContext, stri Update(); } - protected override async Task UpdateOptionsAsync( + protected override Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var spacingOptions = GetSpacingOptions(options, SettingsUpdater); @@ -39,6 +39,8 @@ protected override async Task UpdateOptionsAsync( AddRange(indentationOptions.ToImmutableArray()); var wrappingOptions = GetWrappingOptions(options, SettingsUpdater); AddRange(wrappingOptions.ToImmutableArray()); + + return Task.CompletedTask; } private static IEnumerable GetSpacingOptions(TieredAnalyzerConfigOptions options, OptionUpdater updaterService) diff --git a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs index bfa22be013cf0..44adda02940ba 100644 --- a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs +++ b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchDocumentNavigationService.cs @@ -22,14 +22,14 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp; internal sealed class SemanticSearchDocumentNavigationService(SemanticSearchToolWindowImpl window) : AbstractDocumentNavigationService { - public override async Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) - => true; + public override Task CanNavigateToSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + => SpecializedTasks.True; - public override async Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) + public override Task GetLocationForSpanAsync(Workspace workspace, DocumentId documentId, TextSpan textSpan, bool allowInvalidSpan, CancellationToken cancellationToken) { Debug.Assert(workspace is SemanticSearchWorkspace); Debug.Assert(documentId == window.SemanticSearchService.GetQueryDocumentId(workspace.CurrentSolution)); - return window.GetNavigableLocation(textSpan); + return Task.FromResult(window.GetNavigableLocation(textSpan)); } } diff --git a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs index 722533b98ac37..3a26ad85af2c7 100644 --- a/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs +++ b/src/VisualStudio/CSharp/Impl/SemanticSearch/SemanticSearchQueryExecutor.cs @@ -32,8 +32,8 @@ private sealed class ResultsObserver(IFindUsagesContext presenterContext, IOptio private readonly Lazy changes)>> _lazyDocumentUpdates = new(); private readonly Lazy> _lazyTextFileUpdates = new(); - public async ValueTask GetClassificationOptionsAsync(Microsoft.CodeAnalysis.Host.LanguageServices language, CancellationToken cancellationToken) - => options.GetClassificationOptions(language.Language); + public ValueTask GetClassificationOptionsAsync(Microsoft.CodeAnalysis.Host.LanguageServices language, CancellationToken cancellationToken) + => new(options.GetClassificationOptions(language.Language)); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) => presenterContext.OnDefinitionFoundAsync(definition, cancellationToken); @@ -48,14 +48,16 @@ public ValueTask OnUserCodeExceptionAsync(UserCodeExceptionInfo exception, Cance => presenterContext.OnDefinitionFoundAsync( new SearchExceptionDefinitionItem(exception.Message, exception.TypeName, exception.StackTrace, (queryDocument != null) ? new DocumentSpan(queryDocument, exception.Span) : default), cancellationToken); - public async ValueTask OnLogMessageAsync(string message, CancellationToken cancellationToken) + public ValueTask OnLogMessageAsync(string message, CancellationToken cancellationToken) { logMessage(message); + return ValueTask.CompletedTask; } - public async ValueTask OnDocumentUpdatedAsync(DocumentId documentId, ImmutableArray changes, CancellationToken cancellationToken) + public ValueTask OnDocumentUpdatedAsync(DocumentId documentId, ImmutableArray changes, CancellationToken cancellationToken) { _lazyDocumentUpdates.Value.Push((documentId, changes)); + return ValueTask.CompletedTask; } private ImmutableArray<(DocumentId documentId, ImmutableArray changes)> GetDocumentUpdates() @@ -92,9 +94,10 @@ public async ValueTask GetUpdatedSolutionAsync(Solution oldSolution, C public ImmutableArray<(string filePath, string? newContent)> GetFileUpdates() => _lazyTextFileUpdates.IsValueCreated ? _lazyTextFileUpdates.Value.SelectAsArray(static entry => (entry.Key, entry.Value)) : []; - public async ValueTask OnTextFileUpdatedAsync(string filePath, string? newContent, CancellationToken cancellationToken) + public ValueTask OnTextFileUpdatedAsync(string filePath, string? newContent, CancellationToken cancellationToken) { _lazyTextFileUpdates.Value.TryAdd(filePath, newContent); + return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs b/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs index 106809d623bef..4053e232c7efb 100644 --- a/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs +++ b/src/VisualStudio/CSharp/Test/EditorConfigSettings/DataProvider/DataProviderTests.MockAnalyzerReference.cs @@ -60,10 +60,11 @@ public sealed class MockFixer : CodeFixProvider public sealed override ImmutableArray FixableDiagnosticIds => [Id]; - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; ContextDiagnosticsCount = context.Diagnostics.Length; + return Task.CompletedTask; } } diff --git a/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs b/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs index 0ae05af549bb4..f5f66d2d47e1a 100644 --- a/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs +++ b/src/VisualStudio/CSharp/Test/Interactive/Commands/TestResetInteractive.cs @@ -58,10 +58,10 @@ protected override void CancelBuildProject() CancelBuildProjectCount++; } - protected override async Task BuildProjectAsync() + protected override Task BuildProjectAsync() { BuildProjectCount++; - return _buildSucceeds; + return Task.FromResult(_buildSucceeds); } protected override bool GetProjectProperties( @@ -86,8 +86,8 @@ protected override IUIThreadOperationExecutor GetUIThreadOperationExecutor() return _uiThreadOperationExecutor; } - protected override async Task> GetNamespacesToImportAsync(IEnumerable namespacesToImport, IInteractiveWindow interactiveWindow) + protected override Task> GetNamespacesToImportAsync(IEnumerable namespacesToImport, IInteractiveWindow interactiveWindow) { - return (IEnumerable)NamespacesToImport; + return Task.FromResult((IEnumerable)NamespacesToImport); } } diff --git a/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs b/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs index 6ea2d516987fc..79e88ecdc01a8 100644 --- a/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs +++ b/src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs @@ -23,19 +23,19 @@ public void Dispose() { } - public async Task InitializeAsync() - => ExecutionResult.Success; + public Task InitializeAsync() + => Task.FromResult(ExecutionResult.Success); - public async Task ResetAsync(bool initialize = true) - => ExecutionResult.Success; + public Task ResetAsync(bool initialize = true) + => Task.FromResult(ExecutionResult.Success); public bool CanExecuteCode(string text) => true; - public async Task ExecuteCodeAsync(string text) + public Task ExecuteCodeAsync(string text) { OnExecute?.Invoke(this, text); - return ExecutionResult.Success; + return Task.FromResult(ExecutionResult.Success); } public string FormatClipboard() diff --git a/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs b/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs index ca8ec5fe83a30..a6d07c92f40a3 100644 --- a/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs +++ b/src/VisualStudio/CodeLens/ReferenceCodeLensProvider.cs @@ -62,20 +62,20 @@ public void Dispose() _cancellationTokenSource.Cancel(); } - public async Task CanCreateDataPointAsync( + public Task CanCreateDataPointAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken) { if (descriptorContext != null && descriptorContext.ApplicableSpan.HasValue) { // we allow all reference points. // engine will call this for all points our roslyn code lens (reference) tagger tagged. - return true; + return SpecializedTasks.True; } - return false; + return SpecializedTasks.False; } - public async Task CreateDataPointAsync( + public Task CreateDataPointAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken) { var dataPoint = new DataPoint( @@ -84,7 +84,7 @@ public async Task CreateDataPointAsync( descriptor); AddDataPoint(dataPoint); - return dataPoint; + return Task.FromResult(dataPoint); } // The current CodeLens OOP design does not allow us to register an event handler for WorkspaceChanged events diff --git a/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs b/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs index e35b9a87b5fa8..80d620c98b01b 100644 --- a/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs +++ b/src/VisualStudio/Core/Def/CodeCleanup/AbstractCodeCleanUpFixer.cs @@ -136,23 +136,23 @@ private async Task FixHierarchyContentAsync(IVsHierarchyCodeCleanupScope h return false; } - private async Task FixTextBufferAsync(TextBufferCodeCleanUpScope textBufferScope, ICodeCleanUpExecutionContext context) + private Task FixTextBufferAsync(TextBufferCodeCleanUpScope textBufferScope, ICodeCleanUpExecutionContext context) { var buffer = textBufferScope.SubjectBuffer; // Let LSP handle code cleanup in the cloud scenario if (buffer.IsInLspEditorContext()) - return false; + return SpecializedTasks.False; var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) - return false; + return SpecializedTasks.False; var workspace = buffer.GetWorkspace(); if (workspace is not VisualStudioWorkspace visualStudioWorkspace) - return false; + return SpecializedTasks.False; - return await FixAsync(visualStudioWorkspace, ApplyFixAsync, context).ConfigureAwait(false); + return FixAsync(visualStudioWorkspace, ApplyFixAsync, context); // Local function async Task ApplyFixAsync(IProgress progress, CancellationToken cancellationToken) diff --git a/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs b/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs index 73ba63b7daec3..19186ff2d2b4e 100644 --- a/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs +++ b/src/VisualStudio/Core/Def/DesignerAttribute/VisualStudioDesignerAttributeService.cs @@ -311,9 +311,10 @@ private static async Task NotifyCpsProjectSystemAsync( /// /// Callback from the OOP service back into us. /// - public async ValueTask ReportDesignerAttributeDataAsync(ImmutableArray data, CancellationToken cancellationToken) + public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray data, CancellationToken cancellationToken) { Contract.ThrowIfNull(_projectSystemNotificationQueue); _projectSystemNotificationQueue.AddWork(data.AsSpan()); + return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs index 7d21208d1d50e..2852da33b13b2 100644 --- a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs +++ b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsProvider.cs @@ -29,7 +29,7 @@ public CommonCodeStyleSettingsProvider( Update(); } - protected override async Task UpdateOptionsAsync( + protected override Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var qualifySettings = GetQualifyCodeStyleOptions(options, SettingsUpdater); @@ -60,6 +60,8 @@ protected override async Task UpdateOptionsAsync( var experimentalSettings = GetExperimentalCodeStyleOptions(options, SettingsUpdater); AddRange(experimentalSettings); + + return Task.CompletedTask; } private static IEnumerable GetQualifyCodeStyleOptions(TieredAnalyzerConfigOptions options, OptionUpdater updater) diff --git a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs index 78c6ba5e89f40..24e48ecd29ad2 100644 --- a/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs +++ b/src/VisualStudio/Core/Def/EditorConfigSettings/DataProvider/Whitespace/CommonWhitespaceSettingsProvider.cs @@ -29,11 +29,13 @@ public CommonWhitespaceSettingsProvider( Update(); } - protected override async Task UpdateOptionsAsync( + protected override Task UpdateOptionsAsync( TieredAnalyzerConfigOptions options, ImmutableArray projectsInScope, CancellationToken cancellationToken) { var defaultOptions = GetDefaultOptions(options, SettingsUpdater); AddRange(defaultOptions); + + return Task.CompletedTask; } private static IEnumerable GetDefaultOptions(TieredAnalyzerConfigOptions options, OptionUpdater updater) diff --git a/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs b/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs index 6e01e15b6e529..c04271ba7a0ed 100644 --- a/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs +++ b/src/VisualStudio/Core/Def/FindReferences/Contexts/AbstractTableDataSourceFindUsagesContext.cs @@ -170,9 +170,10 @@ protected AbstractTableDataSourceFindUsagesContext( // results). To limit the amount of work we do, we'll only update the window every 250ms. _notifyQueue = new AsyncBatchingWorkQueue( DelayTimeSpan.Short, - async cancellationToken => + cancellationToken => { _tableDataSink.FactorySnapshotChanged(this); + return ValueTask.CompletedTask; }, presenter._asyncListener, CancellationTokenSource.Token); @@ -345,10 +346,11 @@ public IDisposable Subscribe(ITableDataSink sink) #region FindUsagesContext overrides. - public sealed override async ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) + public sealed override ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) { // Note: IFindAllReferenceWindow.Title is safe to set from any thread. _findReferencesWindow.Title = title; + return default; } public sealed override async ValueTask OnCompletedAsync(CancellationToken cancellationToken) @@ -526,12 +528,14 @@ protected RoslynDefinitionBucket GetOrCreateDefinitionBucket(DefinitionItem defi } } - public sealed override async ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) + public sealed override ValueTask ReportNoResultsAsync(string message, CancellationToken cancellationToken) { lock (Gate) { NoDefinitionsFoundMessage = message; } + + return ValueTask.CompletedTask; } public sealed override async ValueTask ReportMessageAsync(string message, NotificationSeverity severity, CancellationToken cancellationToken) @@ -539,12 +543,13 @@ public sealed override async ValueTask ReportMessageAsync(string message, Notifi await this.Presenter.ReportMessageAsync(message, severity, cancellationToken).ConfigureAwait(false); } - protected sealed override async ValueTask ReportProgressAsync(int current, int maximum, CancellationToken cancellationToken) + protected sealed override ValueTask ReportProgressAsync(int current, int maximum, CancellationToken cancellationToken) { _progressQueue.AddWork((current, maximum)); + return default; } - private async ValueTask UpdateTableProgressAsync(ImmutableSegmentedList<(int current, int maximum)> nextBatch, CancellationToken _) + private ValueTask UpdateTableProgressAsync(ImmutableSegmentedList<(int current, int maximum)> nextBatch, CancellationToken _) { if (!nextBatch.IsEmpty) { @@ -563,6 +568,8 @@ private async ValueTask UpdateTableProgressAsync(ImmutableSegmentedList<(int cur if (current > 0) _findReferencesWindow.SetProgress(current, maximum); } + + return ValueTask.CompletedTask; } protected static DefinitionItem CreateNoResultsDefinitionItem(string message) diff --git a/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs b/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs index 8454642f154fa..3265dc00db67a 100644 --- a/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs +++ b/src/VisualStudio/Core/Def/FindReferences/Entries/SimpleMessageEntry.cs @@ -27,13 +27,13 @@ private SimpleMessageEntry( _message = message; } - public static async Task CreateAsync( + public static Task CreateAsync( RoslynDefinitionBucket definitionBucket, RoslynDefinitionBucket? navigationBucket, string message) { var referenceEntry = new SimpleMessageEntry(definitionBucket, navigationBucket, message); - return referenceEntry; + return Task.FromResult(referenceEntry); } protected override object? GetValueWorker(string keyName) diff --git a/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs b/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs index bfcf4b7c7458e..a87b2b42ce545 100644 --- a/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs +++ b/src/VisualStudio/Core/Def/FindReferences/VisualStudioDefinitionsAndReferencesFactory.cs @@ -28,7 +28,7 @@ internal sealed class VisualStudioDefinitionsAndReferencesFactory( SVsServiceProvider serviceProvider, IThreadingContext threadingContext) : IExternalDefinitionItemProvider { - public async ValueTask GetThirdPartyDefinitionItemAsync( + public async Task GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) { var symbolNavigationService = solution.Services.GetRequiredService(); @@ -89,13 +89,13 @@ private sealed class ExternalDefinitionItem( { internal override bool IsExternal => true; - public override async Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) + public override Task GetNavigableLocationAsync(Workspace workspace, CancellationToken cancellationToken) { - return new NavigableLocation(async (options, cancellationToken) => + return Task.FromResult(new NavigableLocation(async (options, cancellationToken) => { await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return TryOpenFile() && TryNavigateToPosition(); - }); + })); } private bool TryOpenFile() diff --git a/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs b/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs index c084a223528f2..73912910b0280 100644 --- a/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs +++ b/src/VisualStudio/Core/Def/Library/AbstractObjectList.cs @@ -62,8 +62,8 @@ protected virtual bool TryGetContextMenu(uint index, out Guid menuGuid, out int return false; } - protected virtual async Task<(bool success, object pvar)> TryGetPropertyAsync(uint index, _VSOBJLISTELEMPROPID propertyId, CancellationToken cancellationToken) - => default((bool success, object pvar)); + protected virtual Task<(bool success, object pvar)> TryGetPropertyAsync(uint index, _VSOBJLISTELEMPROPID propertyId, CancellationToken cancellationToken) + => SpecializedTasks.Default<(bool success, object pvar)>(); protected virtual bool TryCountSourceItems(uint index, out IVsHierarchy hierarchy, out uint itemid, out uint items) { @@ -73,16 +73,16 @@ protected virtual bool TryCountSourceItems(uint index, out IVsHierarchy hierarch return false; } - protected virtual async Task GetBrowseObjectAsync(uint index, CancellationToken cancellationToken) - => null; + protected virtual Task GetBrowseObjectAsync(uint index, CancellationToken cancellationToken) + => SpecializedTasks.Null(); protected virtual bool SupportsNavInfo { get { return false; } } - protected virtual async Task GetNavInfoAsync(uint index, CancellationToken cancellationToken) - => null; + protected virtual Task GetNavInfoAsync(uint index, CancellationToken cancellationToken) + => SpecializedTasks.Null(); protected virtual IVsNavInfoNode GetNavInfoNode(uint index) => null; @@ -98,8 +98,8 @@ protected virtual bool SupportsDescription get { return false; } } - protected virtual async Task TryFillDescriptionAsync(uint index, _VSOBJDESCOPTIONS options, IVsObjectBrowserDescription3 description, CancellationToken cancellationToken) - => false; + protected virtual Task TryFillDescriptionAsync(uint index, _VSOBJDESCOPTIONS options, IVsObjectBrowserDescription3 description, CancellationToken cancellationToken) + => SpecializedTasks.False; int IVsSimpleObjectList2.CanDelete(uint index, out int pfOK) { diff --git a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs index e83ee7bbfbd1e..535834ed445cc 100644 --- a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs +++ b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultPreviewPanel.cs @@ -34,8 +34,8 @@ public RoslynSearchResultPreviewPanel( UserInterface = new CodeEditorModel( nameof(RoslynSearchResultPreviewPanel), - new VisualStudio.Threading.AsyncLazy(async () => - new TextDocumentLocation(uri, projectGuid, span), + new VisualStudio.Threading.AsyncLazy(() => + Task.FromResult(new TextDocumentLocation(uri, projectGuid, span)), provider._threadingContext.JoinableTaskFactory), isEditable: true); } diff --git a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs index b96e6cae4ec5b..93cb5c7e78da9 100644 --- a/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs +++ b/src/VisualStudio/Core/Def/NavigateTo/RoslynSearchResultViewFactory.cs @@ -42,8 +42,8 @@ [.. searchResult.NameMatchSpans.NullToEmpty().Select(m => m.ToSpan())]), primaryIcon: searchResult.NavigableItem.Glyph.GetImageId()); } - public async Task> GetPreviewPanelsAsync(SearchResult result, SearchResultViewBase searchResultView) - => GetPreviewPanels(result, searchResultView) ?? []; + public Task> GetPreviewPanelsAsync(SearchResult result, SearchResultViewBase searchResultView) + => Task.FromResult(GetPreviewPanels(result, searchResultView) ?? []); private IReadOnlyList? GetPreviewPanels(SearchResult result, SearchResultViewBase searchResultView) { diff --git a/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs b/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs index ed8884cf6391f..ff484050603e9 100644 --- a/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs +++ b/src/VisualStudio/Core/Def/Options/VisualStudioOptionStorage.cs @@ -107,9 +107,10 @@ public FeatureFlagStorage(string flagName) FlagName = flagName; } - public async Task PersistAsync(FeatureFlagPersister persister, object? value) + public Task PersistAsync(FeatureFlagPersister persister, object? value) { persister.Persist(FlagName, value); + return Task.CompletedTask; } public bool TryFetch(FeatureFlagPersister persister, OptionKey2 optionKey, out object? value) @@ -121,9 +122,10 @@ internal sealed class LocalUserProfileStorage(string path, string key) : VisualS public string Path => path; public string Key => key; - public async Task PersistAsync(LocalUserRegistryOptionPersister persister, OptionKey2 optionKey, object? value) + public Task PersistAsync(LocalUserRegistryOptionPersister persister, OptionKey2 optionKey, object? value) { persister.Persist(optionKey, path, key, value); + return Task.CompletedTask; } public bool TryFetch(LocalUserRegistryOptionPersister persister, OptionKey2 optionKey, out object? value) diff --git a/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs b/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs index 5fedc87541e58..80621591e11b1 100644 --- a/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs +++ b/src/VisualStudio/Core/Def/Options/VisualStudioSettingsOptionPersister.cs @@ -40,11 +40,12 @@ public VisualStudioSettingsOptionPersister( settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } - private async Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) + private Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { Contract.ThrowIfNull(this.SettingsManager); RefreshIfTracked(args.PropertyName); + return Task.CompletedTask; } public override bool TryFetch(OptionKey2 optionKey, string storageKey, out object? value) diff --git a/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs b/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs index ccb8b50bdd35f..78ee53c51950a 100644 --- a/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs +++ b/src/VisualStudio/Core/Def/Options/VisualStudioUnifiedSettingsOptionPersister.cs @@ -50,7 +50,7 @@ private static void CheckStorageKeyAndType(string storageKey, [NotNull] Type? st optionKey.Option.Definition.Serializer.TryParse(stringValue, out var value) ? new(value) : default; } - public override async Task PersistAsync(OptionKey2 optionKey, string storageKey, object? value) + public override Task PersistAsync(OptionKey2 optionKey, string storageKey, object? value) { var storageType = value?.GetType(); CheckStorageKeyAndType(storageKey, storageType); @@ -65,5 +65,7 @@ public override async Task PersistAsync(OptionKey2 optionKey, string storageKey, // ignoreCase: true, out result)` writer.EnqueueChange(storageKey, optionKey.Option.Definition.Serializer.Serialize(value).ToLowerInvariant()); writer.RequestCommit(nameof(VisualStudioUnifiedSettingsOptionPersister)); + + return Task.CompletedTask; } } diff --git a/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs b/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs index edb29c3e9778e..de3f3b67b6b30 100644 --- a/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs +++ b/src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs @@ -453,7 +453,7 @@ private void OnWorkspaceChanged(WorkspaceChangeEventArgs e) _workQueue.AddWork((solutionChanged, changedProject)); } - private async ValueTask ProcessWorkQueueAsync( + private ValueTask ProcessWorkQueueAsync( ImmutableSegmentedList<(bool solutionChanged, ProjectId? changedProject)> workQueue, CancellationToken cancellationToken) { // ThisCanBeCalledOnAnyThread(); @@ -462,9 +462,9 @@ private async ValueTask ProcessWorkQueueAsync( // If we've been disconnected, then there's no point proceeding. if (Workspace == null || !IsEnabled) - return; + return ValueTask.CompletedTask; - await ProcessWorkQueueWorkerAsync(workQueue, cancellationToken).ConfigureAwait(false); + return ProcessWorkQueueWorkerAsync(workQueue, cancellationToken); } [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs b/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs index 59f68767ae082..52c0c30ceae6b 100644 --- a/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs +++ b/src/VisualStudio/Core/Def/Preview/PreviewUpdater.PreviewDialogWorkspace.cs @@ -47,8 +47,8 @@ private sealed class PreviewTextLoader : TextLoader internal PreviewTextLoader(SourceText documentText) => _text = documentText; - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => LoadTextAndVersionSynchronously(options, cancellationToken); + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(LoadTextAndVersionSynchronously(options, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(LoadTextOptions options, CancellationToken cancellationToken) => TextAndVersion.Create(_text, VersionStamp.Create()); diff --git a/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs b/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs index 792d49bff8b0d..60076ab449d24 100644 --- a/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs +++ b/src/VisualStudio/Core/Def/Progression/GraphNodeCreation.cs @@ -14,10 +14,10 @@ namespace Microsoft.VisualStudio.LanguageServices.Progression; public static class GraphNodeCreation { [Obsolete("This method is not implemented and always returns an empty GraphNodeId.", error: true)] - public static async Task CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) - => GraphNodeId.Empty; + public static Task CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) + => Task.FromResult(GraphNodeId.Empty); [Obsolete("This method is not implemented and always returns an empty GraphNode.", error: true)] - public static async Task CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken) - => graph.Nodes.GetOrCreate(GraphNodeId.Empty); + public static Task CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken) + => Task.FromResult(graph.Nodes.GetOrCreate(GraphNodeId.Empty)); } diff --git a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs index aa7379ad6001f..c87c7e3861576 100644 --- a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs +++ b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProject.cs @@ -163,19 +163,22 @@ public async Task SetBuildSystemPropertiesAsync(IReadOnlyDictionary arguments, CancellationToken cancellationToken) + public Task SetCommandLineArgumentsAsync(IReadOnlyList arguments, CancellationToken cancellationToken) { _project.SetOptions([.. arguments]); + return Task.CompletedTask; } - public async Task SetDisplayNameAsync(string displayName, CancellationToken cancellationToken) + public Task SetDisplayNameAsync(string displayName, CancellationToken cancellationToken) { _project.DisplayName = displayName; + return Task.CompletedTask; } - public async Task SetProjectHasAllInformationAsync(bool hasAllInformation, CancellationToken cancellationToken) + public Task SetProjectHasAllInformationAsync(bool hasAllInformation, CancellationToken cancellationToken) { _project.LastDesignTimeBuildSucceeded = hasAllInformation; + return Task.CompletedTask; } public async Task StartBatchAsync(CancellationToken cancellationToken) diff --git a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs index c3058230d6a86..57744b19a71e8 100644 --- a/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs +++ b/src/VisualStudio/Core/Def/ProjectSystem/BrokeredService/WorkspaceProjectFactoryService.cs @@ -34,9 +34,9 @@ public async Task CreateAndAddProjectAsync(WorkspaceProjectCr return new WorkspaceProject(project); } - public async Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken cancellationToken) + public Task> GetSupportedBuildSystemPropertiesAsync(CancellationToken cancellationToken) { - return (IReadOnlyCollection)_workspaceProjectContextFactory.EvaluationItemNames; + return Task.FromResult((IReadOnlyCollection)_workspaceProjectContextFactory.EvaluationItemNames); } private sealed class EvaluationDataShim : EvaluationData diff --git a/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs b/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs index 60f09078ded3a..0816942fef4c1 100644 --- a/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs +++ b/src/VisualStudio/Core/Def/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs @@ -205,20 +205,24 @@ public void OnUnhandledException(Exception exception) { } - public async ValueTask OnBeforeOpenSolutionAsync(BeforeOpenSolutionArgs args, CancellationToken cancellationToken) + public ValueTask OnBeforeOpenSolutionAsync(BeforeOpenSolutionArgs args, CancellationToken cancellationToken) { + return ValueTask.CompletedTask; } - public async ValueTask OnBeforeCloseSolutionAsync(BeforeCloseSolutionArgs args, CancellationToken cancellationToken) + public ValueTask OnBeforeCloseSolutionAsync(BeforeCloseSolutionArgs args, CancellationToken cancellationToken) { + return ValueTask.CompletedTask; } - public async ValueTask OnAfterCloseSolutionAsync(AfterCloseSolutionArgs args, CancellationToken cancellationToken) + public ValueTask OnAfterCloseSolutionAsync(AfterCloseSolutionArgs args, CancellationToken cancellationToken) { + return ValueTask.CompletedTask; } - public async ValueTask OnAfterRenameSolutionAsync(AfterRenameSolutionArgs args, CancellationToken cancellationToken) + public ValueTask OnAfterRenameSolutionAsync(AfterRenameSolutionArgs args, CancellationToken cancellationToken) { + return ValueTask.CompletedTask; } #endregion diff --git a/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs b/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs index 2b7535c58d492..7635e1501ad77 100644 --- a/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs +++ b/src/VisualStudio/Core/Def/Remote/DefaultRemoteHostClientProvider.cs @@ -14,8 +14,8 @@ namespace Microsoft.VisualStudio.LanguageServices.Remote; [method: Obsolete(MefConstruction.FactoryMethodMessage, error: true)] internal sealed class DefaultRemoteHostClientProvider() : IRemoteHostClientProvider { - public async Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) - => null; + public Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) + => SpecializedTasks.Null(); public Task WaitForClientCreationAsync(CancellationToken cancellationToken) => Task.CompletedTask; diff --git a/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs b/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs index 4cea589e1061d..0eddc78a8298e 100644 --- a/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs +++ b/src/VisualStudio/Core/Def/Remote/VisualStudioRemoteHostClientProvider.cs @@ -139,7 +139,7 @@ private VisualStudioRemoteHostClientProvider( var client = await ServiceHubRemoteHostClient.CreateAsync(Services, configuration, localSettingsDirectory, _listenerProvider, serviceBroker, _callbackDispatchers, _threadingContext.DisposalToken).ConfigureAwait(false); // proffer in-proc brokered services: - _ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, async (_, _, _, _) => new SolutionAssetProvider(Services)); + _ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, (_, _, _, _) => ValueTask.FromResult(new SolutionAssetProvider(Services))); return client; } diff --git a/src/VisualStudio/Core/Def/RoslynPackage.cs b/src/VisualStudio/Core/Def/RoslynPackage.cs index 66bc4d81a3dc5..8c26bfde24b1b 100644 --- a/src/VisualStudio/Core/Def/RoslynPackage.cs +++ b/src/VisualStudio/Core/Def/RoslynPackage.cs @@ -86,10 +86,12 @@ protected override void RegisterOnAfterPackageLoadedAsyncWork(PackageLoadTasks a return; - async Task OnAfterPackageLoadedMainThreadAsync(PackageLoadTasks afterPackageLoadedTasks, CancellationToken cancellationToken) + Task OnAfterPackageLoadedMainThreadAsync(PackageLoadTasks afterPackageLoadedTasks, CancellationToken cancellationToken) { // load some services that have to be loaded in UI thread LoadComponentsInUIContextOnceSolutionFullyLoadedAsync(cancellationToken).Forget(); + + return Task.CompletedTask; } } @@ -100,12 +102,12 @@ private async Task ProfferServiceBrokerServicesAsync(CancellationToken cancellat serviceBrokerContainer.Proffer( WorkspaceProjectFactoryServiceDescriptor.ServiceDescriptor, - async (_, _, _, _) => new WorkspaceProjectFactoryService(this.ComponentModel.GetService())); + (_, _, _, _) => ValueTask.FromResult(new WorkspaceProjectFactoryService(this.ComponentModel.GetService()))); // Must be profferred before any C#/VB projects are loaded and the corresponding UI context activated. serviceBrokerContainer.Proffer( ManagedHotReloadLanguageServiceDescriptor.Descriptor, - async (_, _, _, _) => new ManagedEditAndContinueLanguageServiceBridge(this.ComponentModel.GetService())); + (_, _, _, _) => ValueTask.FromResult(new ManagedEditAndContinueLanguageServiceBridge(this.ComponentModel.GetService()))); } protected override async Task LoadComponentsAsync(CancellationToken cancellationToken) @@ -146,8 +148,8 @@ public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWin protected override string GetToolWindowTitle(Type toolWindowType, int id) => base.GetToolWindowTitle(toolWindowType, id); - protected override async Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) - => (object?)null; + protected override Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) + => Task.FromResult((object?)null); private async Task LoadComponentsBackgroundAsync(CancellationToken cancellationToken) { diff --git a/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs b/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs index 46cb0b4f3f452..2a23e190ab946 100644 --- a/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs +++ b/src/VisualStudio/Core/Def/Snippets/SnippetFunctions/AbstractSnippetFunction.cs @@ -35,9 +35,9 @@ private int GetDefaultValue(CancellationToken cancellationToken, out string valu return exitCode; } - protected virtual async Task<(int ExitCode, string Value, int HasDefaultValue)> GetDefaultValueAsync(CancellationToken cancellationToken) + protected virtual Task<(int ExitCode, string Value, int HasDefaultValue)> GetDefaultValueAsync(CancellationToken cancellationToken) { - return (ExitCode: VSConstants.S_OK, Value: string.Empty, HasDefaultValue: 0); + return Task.FromResult((ExitCode: VSConstants.S_OK, Value: string.Empty, HasDefaultValue: 0)); } private int GetCurrentValue(CancellationToken cancellationToken, out string value, out int hasCurrentValue) @@ -46,9 +46,9 @@ private int GetCurrentValue(CancellationToken cancellationToken, out string valu return exitCode; } - protected virtual async Task<(int ExitCode, string Value, int HasCurrentValue)> GetCurrentValueAsync(CancellationToken cancellationToken) + protected virtual Task<(int ExitCode, string Value, int HasCurrentValue)> GetCurrentValueAsync(CancellationToken cancellationToken) { - return (ExitCode: VSConstants.S_OK, Value: string.Empty, HasCurrentValue: 0); + return Task.FromResult((ExitCode: VSConstants.S_OK, Value: string.Empty, HasDefaultValue: 0)); } protected virtual int FieldChanged(string field, out int requeryFunction) diff --git a/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs b/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs index 9fca096e7f9eb..8be4ed4130e4d 100644 --- a/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs +++ b/src/VisualStudio/Core/Def/Telemetry/FileLogger.cs @@ -93,7 +93,7 @@ public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int unique private void LogBlockEvent(FunctionId functionId, LogMessage logMessage, int uniquePairId, string blockEvent) => Log(functionId, $"[{blockEvent} - {uniquePairId}] {logMessage.GetMessage()}"); - private async ValueTask ProcessWorkQueueAsync( + private ValueTask ProcessWorkQueueAsync( ImmutableSegmentedList<(FunctionId functionId, string message)> list, CancellationToken cancellationToken) { using var _ = PooledStringBuilder.GetInstance(out var buffer); @@ -109,5 +109,7 @@ private async ValueTask ProcessWorkQueueAsync( File.AppendAllText(_logFilePath, buffer.ToString()); }); + + return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs b/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs index 6f7ace14ca6f1..d3f2763c361c1 100644 --- a/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs +++ b/src/VisualStudio/Core/Def/Utilities/VisualStudioNavigateToLinkService.cs @@ -13,25 +13,30 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; -[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host), Shared] -[method: ImportingConstructor] -[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] -internal sealed class VisualStudioNavigateToLinkService() : INavigateToLinkService +[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)] +[Shared] +internal sealed class VisualStudioNavigateToLinkService : INavigateToLinkService { - public async Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public VisualStudioNavigateToLinkService() + { + } + + public Task TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { - return false; + return SpecializedTasks.False; } if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) { - return false; + return SpecializedTasks.False; } StartBrowser(uri); - return true; + return SpecializedTasks.True; } public static void StartBrowser(string uri) diff --git a/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs b/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs index 5cf6d459f1bef..016b4abbb7254 100644 --- a/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs +++ b/src/VisualStudio/Core/Def/Workspace/VisualStudioDocumentNavigationService.cs @@ -104,7 +104,7 @@ public async Task CanNavigateToPositionAsync( return await GetNavigableLocationAsync(workspace, documentId, - async _ => textSpan, + _ => Task.FromResult(textSpan), text => GetVsTextSpan(text, textSpan, allowInvalidSpan), (text, span) => GetVsTextSpan(text, span, allowInvalidSpan), cancellationToken).ConfigureAwait(false); diff --git a/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs b/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs index a8b3732cb9817..a8f92c1f8fcba 100644 --- a/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs +++ b/src/VisualStudio/Core/Impl/SolutionExplorer/Search/RoslynSolutionExplorerSearchProvider.cs @@ -80,7 +80,7 @@ public void Done(bool isFullyLoaded) { } public void ReportIncomplete() { } public void ReportProgress(int current, int maximum) { } - public async Task AddResultsAsync( + public Task AddResultsAsync( ImmutableArray results, Document? activeDocument, CancellationToken cancellationToken) @@ -92,6 +92,8 @@ public async Task AddResultsAsync( var imageMoniker = result.NavigableItem.Glyph.GetImageMoniker(); resultAccumulator(new SolutionExplorerSearchResult(provider, result, name, imageMoniker)); } + + return Task.CompletedTask; } } diff --git a/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs b/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs index 11a57f570272d..a8297d3514aa7 100644 --- a/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs +++ b/src/VisualStudio/Core/Test.Next/Options/VisualStudioSettingsOptionPersisterTests.cs @@ -48,9 +48,10 @@ public GetValueResult TryGetValue(string name, out T value) return result; } - public async Task SetValueAsync(string name, object? value, bool isMachineLocal) + public Task SetValueAsync(string name, object? value, bool isMachineLocal) { SetValueImpl?.Invoke(name, value); + return Task.CompletedTask; } public ISettingsList GetOrCreateList(string name, bool isMachineLocal) diff --git a/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs b/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs index dad61ba775c3e..2cd8b39d186c6 100644 --- a/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs +++ b/src/VisualStudio/Core/Test.Next/Services/AssetProviderTests.cs @@ -187,7 +187,7 @@ private sealed class OrderedAssetSource( ISerializerService serializerService, IReadOnlyDictionary map) : IAssetSource { - public async ValueTask GetAssetsAsync( + public ValueTask GetAssetsAsync( Checksum solutionChecksum, AssetPath assetPath, ReadOnlyMemory checksums, @@ -213,6 +213,8 @@ public async ValueTask GetAssetsAsync( callback(checksum, (T)deserialized, arg); } } + + return ValueTask.CompletedTask; } } } diff --git a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs index c97ca0f6a6bea..65dd675cd3f83 100644 --- a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs +++ b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests.cs @@ -224,9 +224,10 @@ private sealed class DesignerAttributeComputerCallback : IDesignerAttributeDisco public Task> Infos => _infosSource.Task; - public async ValueTask ReportDesignerAttributeDataAsync(ImmutableArray infos, CancellationToken cancellationToken) + public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray infos, CancellationToken cancellationToken) { _infosSource.SetResult(infos); + return ValueTask.CompletedTask; } } diff --git a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs index 670dfe8ef80bb..2e8e396f7225a 100644 --- a/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs +++ b/src/VisualStudio/Core/Test.Next/Services/ServiceHubServicesTests_ExtensionMessageHandler.cs @@ -787,8 +787,8 @@ private sealed class TestHandler( string name, Func? executeCallback = null) : IExtensionMessageHandlerWrapper { - public async Task ExecuteAsync(object? message, TArgument argument, CancellationToken cancellationToken) - => executeCallback!(message, argument, cancellationToken); + public Task ExecuteAsync(object? message, TArgument argument, CancellationToken cancellationToken) + => Task.FromResult(executeCallback!(message, argument, cancellationToken)); public Type MessageType => typeof(int); diff --git a/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs b/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs index 49a43ea764e3b..d7cf5e8a4d05a 100644 --- a/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs +++ b/src/VisualStudio/ExternalAccess/FSharp/Internal/Classification/FSharpClassificationService.cs @@ -81,7 +81,8 @@ public void AddSyntacticClassifications(SolutionServices services, SyntaxNode? r return new(); } - public async Task AddEmbeddedLanguageClassificationsAsync(Document document, ImmutableArray textSpans, ClassificationOptions options, SegmentedList result, CancellationToken cancellationToken) + public Task AddEmbeddedLanguageClassificationsAsync(Document document, ImmutableArray textSpans, ClassificationOptions options, SegmentedList result, CancellationToken cancellationToken) { + return Task.CompletedTask; } } diff --git a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs index 637d8582f4b42..7af59bf296a18 100644 --- a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs +++ b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs @@ -202,9 +202,9 @@ public FSharpEditorInlineRenameService( public bool IsEnabled => true; - public async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return ImmutableDictionary>.Empty; + return Task.FromResult(ImmutableDictionary>.Empty); } public async Task GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) diff --git a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs index 431ca25879a71..caa330436d993 100644 --- a/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs +++ b/src/VisualStudio/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesContext.cs @@ -37,8 +37,9 @@ public Task ReportMessageAsync(string message) return _context.ReportNoResultsAsync(message, CancellationToken).AsTask(); } - public async Task ReportProgressAsync(int current, int maximum) + public Task ReportProgressAsync(int current, int maximum) { + return Task.CompletedTask; } public Task SetSearchTitleAsync(string title) diff --git a/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs b/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs index f2ad0c2ed6c58..2474517cbcb80 100644 --- a/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs +++ b/src/VisualStudio/LiveShare/Impl/Client/Projects/WorkspaceFileTextLoaderNoException.cs @@ -25,13 +25,13 @@ public WorkspaceFileTextLoaderNoException(SolutionServices services, string path { } - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) { if (!File.Exists(Path)) { - return TextAndVersion.Create(SourceText.From("", encoding: null, options.ChecksumAlgorithm), VersionStamp.Create()); + return Task.FromResult(TextAndVersion.Create(SourceText.From("", encoding: null, options.ChecksumAlgorithm), VersionStamp.Create())); } - return await base.LoadTextAndVersionAsync(options, cancellationToken).ConfigureAwait(false); + return base.LoadTextAndVersionAsync(options, cancellationToken); } } diff --git a/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs b/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs index a4e41d96669cc..dbb29ef7281df 100644 --- a/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs +++ b/src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs @@ -26,7 +26,7 @@ internal abstract class AbstractLspClientServiceFactory : ICollaborationServiceF public LS.ILanguageServerClient ActiveLanguageServerClient { get; private set; } - public async Task CreateServiceAsync(CollaborationSession collaborationSession, CancellationToken cancellationToken) + public Task CreateServiceAsync(CollaborationSession collaborationSession, CancellationToken cancellationToken) { var languageServerGuestService = (LS.ILanguageServerGuestService)collaborationSession.GetService(typeof(LS.ILanguageServerGuestService)); @@ -90,7 +90,7 @@ public async Task CreateServiceAsync(CollaborationSession ActiveLanguageServerClient = null; }; - return lifeTimeService; + return Task.FromResult(lifeTimeService); } protected abstract class RoslynLSPClientLifeTimeService : ICollaborationService, IDisposable diff --git a/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs b/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs index 520242cc504e8..23fb0dc7e581e 100644 --- a/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs +++ b/src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs @@ -28,13 +28,13 @@ public LSPSDKInitializeHandler() { } - public async Task HandleAsync(LSP.InitializeParams request, RequestContext requestContext, CancellationToken cancellationToken) + public Task HandleAsync(LSP.InitializeParams request, RequestContext requestContext, CancellationToken cancellationToken) { var result = new LSP.InitializeResult { Capabilities = new LSP.ServerCapabilities() }; - return result; + return Task.FromResult(result); } } diff --git a/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs b/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs index ebfabf67cddc6..73780d3c8b3f5 100644 --- a/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs +++ b/src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs @@ -25,8 +25,8 @@ internal class LiveShareInitializeHandler : ILspRequestHandler HandleAsync(InitializeParams param, RequestContext requestContext, CancellationToken cancellationToken) - => s_initializeResult; + public Task HandleAsync(InitializeParams param, RequestContext requestContext, CancellationToken cancellationToken) + => Task.FromResult(s_initializeResult); } [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, Methods.InitializeName)] diff --git a/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs b/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs index f9c51df21e6a1..a78e33358c98b 100644 --- a/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs +++ b/src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs @@ -20,8 +20,8 @@ namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests; [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class MockDocumentNavigationService() : AbstractDocumentNavigationService { - public override async Task CanNavigateToPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) - => true; + public override Task CanNavigateToPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) + => SpecializedTasks.True; public override Task GetLocationForPositionAsync(Workspace workspace, DocumentId documentId, int position, int virtualSpace, bool allowInvalidPosition, CancellationToken cancellationToken) => NavigableLocation.TestAccessor.Create(true); diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs index 1202455fe078f..720f866972587 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.cs @@ -111,8 +111,8 @@ protected override string GetToolWindowTitle(Type toolWindowType, int id) return null; } - protected override async Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) + protected override Task InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) { - return new object(); + return Task.FromResult(new object()); } } diff --git a/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs b/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs index 09ae6dbfccf24..6890bcc6c0d57 100644 --- a/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs +++ b/src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs @@ -40,7 +40,7 @@ public override FixAllProvider GetFixAllProvider() return null; } - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( CodeAction.Create( @@ -48,6 +48,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) c => RemoveUnnecessaryImportsAsync(context.Document, c), nameof(Resources.RemoveUnnecessaryNamespaces)), context.Diagnostics); + return Task.CompletedTask; } private static async Task RemoveUnnecessaryImportsAsync( diff --git a/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs b/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs index a82ad035e0047..05afdafdff8ca 100644 --- a/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs +++ b/src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.cs @@ -32,9 +32,9 @@ public XamlEditorInlineRenameService(IXamlRenameInfoService renameService) public bool IsEnabled => true; - public async Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) + public Task>> GetRenameContextAsync(IInlineRenameInfo inlineRenameInfo, IInlineRenameLocationSet inlineRenameLocationSet, CancellationToken cancellationToken) { - return ImmutableDictionary>.Empty; + return Task.FromResult(ImmutableDictionary>.Empty); } public async Task GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) diff --git a/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs b/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs index 343bd759a0530..d0bed3f4f5309 100644 --- a/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs +++ b/src/Workspaces/Core/Portable/CodeActions/CodeAction.cs @@ -752,8 +752,8 @@ public static NoChangeAction Create( CodeActionPriority priority = CodeActionPriority.Default) => new(title, equivalenceKey, priority, createdFromFactoryMethod: true); - protected sealed override async Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) - => null; + protected sealed override Task GetChangedSolutionAsync(IProgress progress, CancellationToken cancellationToken) + => SpecializedTasks.Null(); } #endregion diff --git a/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs b/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs index a482e4ee9c882..0f8c3b5471b5c 100644 --- a/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs +++ b/src/Workspaces/Core/Portable/CodeActions/CodeActionWithOptions.cs @@ -63,8 +63,8 @@ private protected sealed override async Task /// /// An object instance returned from a call to . /// A cancellation token. - protected virtual async Task> ComputeOperationsAsync(object options, CancellationToken cancellationToken) - => []; + protected virtual Task> ComputeOperationsAsync(object options, CancellationToken cancellationToken) + => SpecializedTasks.EmptyEnumerable(); /// /// Override this method to compute the operations that implement this . Prefer @@ -74,6 +74,6 @@ protected virtual async Task> ComputeOperations protected virtual Task> ComputeOperationsAsync(object options, IProgress progress, CancellationToken cancellationToken) => ComputeOperationsAsync(options, cancellationToken); - protected override async Task> ComputeOperationsAsync(CancellationToken cancellationToken) - => []; + protected override Task> ComputeOperationsAsync(CancellationToken cancellationToken) + => SpecializedTasks.EmptyEnumerable(); } diff --git a/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs b/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs index 59473aa8c9e9c..472c72ec61d23 100644 --- a/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs +++ b/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs @@ -40,8 +40,8 @@ public sealed class ApplyChangesOperation(Solution changedSolution) : CodeAction public override void Apply(Workspace workspace, CancellationToken cancellationToken) => workspace.TryApplyChanges(ChangedSolution, CodeAnalysisProgress.None); - internal sealed override async Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) - => ApplyOrMergeChanges(workspace, originalSolution, ChangedSolution, progressTracker, cancellationToken); + internal sealed override Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) + => Task.FromResult(ApplyOrMergeChanges(workspace, originalSolution, ChangedSolution, progressTracker, cancellationToken)); internal static bool ApplyOrMergeChanges( Workspace workspace, diff --git a/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs b/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs index cd751e5107a06..1b42c22b424e9 100644 --- a/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs +++ b/src/Workspaces/Core/Portable/CodeActions/Operations/CodeActionOperation.cs @@ -31,12 +31,12 @@ public virtual void Apply(Workspace workspace, CancellationToken cancellationTok /// Called by the host environment to apply the effect of the operation. /// This method is guaranteed to be called on the UI thread. /// - internal virtual async Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) + internal virtual Task TryApplyAsync(Workspace workspace, Solution originalSolution, IProgress progressTracker, CancellationToken cancellationToken) { // It is a requirement that this method be called on the UI thread. So it's safe for us to call // into .Apply without any threading operations here. this.Apply(workspace, cancellationToken); - return true; + return SpecializedTasks.True; } /// diff --git a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs index b2b376f1839ff..ea4943c2ef085 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs @@ -19,9 +19,9 @@ internal sealed class SimplificationCodeCleanupProvider : ICodeCleanupProvider public Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) => Simplifier.ReduceAsync(document, spans, options.SimplifierOptions, cancellationToken); - public async Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) + public Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) { // Simplifier doesn't work without semantic information - return root; + return Task.FromResult(root); } } diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs index af06f65d38d4f..d300d1999f1eb 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllState.FixMultipleDiagnosticProvider.cs @@ -33,7 +33,7 @@ public FixMultipleDiagnosticProvider(ImmutableDictionary>.Empty; } - public override async Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) + public override Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) { var allDiagnosticsBuilder = ArrayBuilder.GetInstance(); ImmutableArray diagnostics; @@ -53,27 +53,27 @@ public override async Task> GetAllDiagnosticsAsync(Proje allDiagnosticsBuilder.AddRange(diagnostics); } - return allDiagnosticsBuilder.ToImmutableAndFree(); + return Task.FromResult>(allDiagnosticsBuilder.ToImmutableAndFree()); } - public override async Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) + public override Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) { if (DocumentDiagnosticsMap.TryGetValue(document, out var diagnostics)) { - return diagnostics; + return Task.FromResult>(diagnostics); } - return []; + return SpecializedTasks.EmptyEnumerable(); } - public override async Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) + public override Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) { if (ProjectDiagnosticsMap.TryGetValue(project, out var diagnostics)) { - return diagnostics; + return Task.FromResult>(diagnostics); } - return []; + return SpecializedTasks.EmptyEnumerable(); } } } diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs index 48536883db552..34003ef3452e4 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/NoOpFixAllProvider.cs @@ -22,6 +22,6 @@ private NoOpFixAllProvider() { } - public override async Task GetFixAsync(FixAllContext fixAllContext) - => null; + public override Task GetFixAsync(FixAllContext fixAllContext) + => Task.FromResult(null); } diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs index e7ce2878139e0..bd3b899996941 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/DefaultFixAllProviderHelpers.cs @@ -44,7 +44,7 @@ FixAllScope.Document or FixAllScope.ContainingMember or FixAllScope.ContainingTy return null; return CodeAction.Create( - title, async (_, _) => solution, equivalenceKey: null, CodeActionPriority.Default, fixAllContext.State.FixAllProvider.Cleanup); + title, (_, _) => Task.FromResult(solution), equivalenceKey: null, CodeActionPriority.Default, fixAllContext.State.FixAllProvider.Cleanup); } private static Task GetDocumentFixesAsync( diff --git a/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs b/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs index 72d29750941b4..9cb666d29f30f 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs @@ -16,11 +16,11 @@ internal abstract class DocumentDiagnosticAnalyzer : DiagnosticAnalyzer { public const int DefaultPriority = 50; - public virtual async Task> AnalyzeSyntaxAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) - => []; + public virtual Task> AnalyzeSyntaxAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) + => SpecializedTasks.EmptyImmutableArray(); - public virtual async Task> AnalyzeSemanticsAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) - => []; + public virtual Task> AnalyzeSemanticsAsync(TextDocument textDocument, SyntaxTree? tree, CancellationToken cancellationToken) + => SpecializedTasks.EmptyImmutableArray(); /// /// it is not allowed one to implement both DocumentDiagnosticAnalyzer and DiagnosticAnalyzer diff --git a/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs b/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs index d5297107104b9..cbd469cb79047 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs @@ -349,10 +349,10 @@ public static ImmutableArray Filter( /// This checksum is also affected by the for this project. /// As such, it is not usable across different sessions of a particular host. /// - public static async Task GetDiagnosticChecksumAsync(this Project? project, CancellationToken cancellationToken) + public static Task GetDiagnosticChecksumAsync(this Project? project, CancellationToken cancellationToken) { if (project is null) - return default(Checksum); + return SpecializedTasks.Default(); var lazyChecksum = s_projectToDiagnosticChecksum.GetValue( project, @@ -360,7 +360,7 @@ public static async Task GetDiagnosticChecksumAsync(this Project? proj static (project, cancellationToken) => ComputeDiagnosticChecksumAsync(project, cancellationToken), project)); - return await lazyChecksum.GetValueAsync(cancellationToken).ConfigureAwait(false); + return lazyChecksum.GetValueAsync(cancellationToken); static async Task ComputeDiagnosticChecksumAsync(Project project, CancellationToken cancellationToken) { diff --git a/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs b/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs index 9ca9c86b72177..3fc98f00b8f0b 100644 --- a/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs +++ b/src/Workspaces/Core/Portable/Editing/SymbolEditor.cs @@ -260,9 +260,10 @@ public Task EditOneDeclarationAsync( { return this.EditOneDeclarationAsync( symbol, - async (e, d, c) => + (e, d, c) => { editAction(e, d); + return Task.CompletedTask; }, cancellationToken); } @@ -350,9 +351,10 @@ public Task EditOneDeclarationAsync( return this.EditOneDeclarationAsync( symbol, location, - async (e, d, c) => + (e, d, c) => { editAction(e, d); + return Task.CompletedTask; }, cancellationToken); } @@ -432,9 +434,10 @@ public Task EditOneDeclarationAsync( return this.EditOneDeclarationAsync( symbol, member, - async (e, d, c) => + (e, d, c) => { editAction(e, d); + return Task.CompletedTask; }, cancellationToken); } @@ -512,9 +515,10 @@ public Task EditAllDeclarationsAsync( { return this.EditAllDeclarationsAsync( symbol, - async (e, d, c) => + (e, d, c) => { editAction(e, d); + return Task.CompletedTask; }, cancellationToken); } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs index 1c6e4e1d355b1..0d14dd1197a7d 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedClasses.cs @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.FindSymbols; internal static partial class DependentTypeFinder { - private static async Task> FindDerivedClassesInCurrentProcessAsync( + private static Task> FindDerivedClassesInCurrentProcessAsync( INamedTypeSymbol type, Solution solution, IImmutableSet? projects, @@ -24,13 +24,13 @@ private static async Task> FindDerivedClassesIn static bool TypeMatches(INamedTypeSymbol type, HashSet set) => TypeHasBaseTypeInSet(type, set); - return await DescendInheritanceTreeAsync(type, solution, projects, + return DescendInheritanceTreeAsync(type, solution, projects, typeMatches: TypeMatches, shouldContinueSearching: s_isNonSealedClass, transitive: transitive, - cancellationToken: cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken); } - return []; + return SpecializedTasks.EmptyImmutableArray(); } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs index eb62c6c38c171..40e155a7d09b2 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_DerivedInterfaces.cs @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.FindSymbols; internal static partial class DependentTypeFinder { - private static async Task> FindDerivedInterfacesInCurrentProcessAsync( + private static Task> FindDerivedInterfacesInCurrentProcessAsync( INamedTypeSymbol type, Solution solution, IImmutableSet? projects, @@ -25,13 +25,13 @@ private static async Task> FindDerivedInterface static bool TypeMatches(INamedTypeSymbol type, HashSet set) => s_isInterface(type) && TypeHasInterfaceInSet(type, set); - return await DescendInheritanceTreeAsync(type, solution, projects, + return DescendInheritanceTreeAsync(type, solution, projects, typeMatches: TypeMatches, shouldContinueSearching: s_isInterface, transitive: transitive, - cancellationToken: cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken); } - return []; + return SpecializedTasks.EmptyImmutableArray(); } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs index 051f3e148c990..90189a63e9875 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs @@ -21,10 +21,11 @@ private sealed class NonCascadingSymbolSet(FindReferencesSearchEngine engine, Me public override ImmutableArray GetAllSymbols() => _symbols; - public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken) + public override Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken) { // Nothing to do here. We're in a non-cascading scenario, so even as we encounter a new project we // don't have to figure out what new symbols may be found. + return Task.CompletedTask; } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs index 2c02f5b714830..9fda34d3981d9 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs @@ -301,7 +301,7 @@ private async ValueTask ProcessDocumentAsync( await Parallel.ForEachAsync( symbolsToSearchFor, GetParallelOptions(cancellationToken), - async (kvp, cancellationToken) => + (kvp, cancellationToken) => { var (symbolToSearchFor, symbolGroup) = kvp; @@ -311,6 +311,7 @@ await Parallel.ForEachAsync( cache, TryGet(symbolToGlobalAliases, symbolToSearchFor)); ProcessDocument(symbolToSearchFor, symbolGroup, state, onReferenceFound); + return ValueTask.CompletedTask; }).ConfigureAwait(false); return; diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs index 12a3dd0c7f171..28bdfeecea888 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine_FindReferencesInDocuments.cs @@ -134,7 +134,7 @@ async ValueTask DirectSymbolSearchAsync(ISymbol symbol, SymbolGroup group, FindR { await ProducerConsumer.RunAsync( ProducerConsumerOptions.SingleReaderWriterOptions, - static async (callback, args, cancellationToken) => + static (callback, args, cancellationToken) => { var (@this, symbol, group, state) = args; @@ -148,6 +148,8 @@ static async (callback, args, cancellationToken) => static (finderLocation, callback) => callback(finderLocation), callback, @this._options, cancellationToken); } + + return Task.CompletedTask; }, consumeItems: static async (values, args, cancellationToken) => { diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs index cdddde2c58f9e..1c194904c1ca4 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs @@ -24,7 +24,7 @@ protected abstract bool TokensMatch( protected sealed override bool CanFind(TSymbol symbol) => true; - protected sealed override async Task DetermineDocumentsToSearchAsync( + protected sealed override Task DetermineDocumentsToSearchAsync( TSymbol symbol, HashSet? globalAliases, Project project, @@ -36,16 +36,17 @@ protected sealed override async Task DetermineDocumentsToSearchAsync( { var location = symbol.Locations.FirstOrDefault(); if (location == null || !location.IsInSource) - return; + return Task.CompletedTask; var document = project.GetDocument(location.SourceTree); if (document == null) - return; + return Task.CompletedTask; if (documents != null && !documents.Contains(document)) - return; + return Task.CompletedTask; processResult(document, processResultData); + return Task.CompletedTask; } protected sealed override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs index 87619f7d9a253..fcc624121fa30 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder.cs @@ -144,7 +144,7 @@ protected static Task FindDocumentsWithGlobalSuppressMessageAttributeAsync index.ContainsGlobalSuppressMessageAttribute, processResult, processResultData, cancellationToken); } - protected static async Task FindDocumentsAsync( + protected static Task FindDocumentsAsync( Project project, IImmutableSet? documents, PredefinedType predefinedType, @@ -153,10 +153,10 @@ protected static async Task FindDocumentsAsync( CancellationToken cancellationToken) { if (predefinedType == PredefinedType.None) - return; + return Task.CompletedTask; - await FindDocumentsWithPredicateAsync( - project, documents, static (index, predefinedType) => index.ContainsPredefinedType(predefinedType), predefinedType, processResult, processResultData, cancellationToken).ConfigureAwait(false); + return FindDocumentsWithPredicateAsync( + project, documents, static (index, predefinedType) => index.ContainsPredefinedType(predefinedType), predefinedType, processResult, processResultData, cancellationToken); } protected static bool IdentifiersMatch(ISyntaxFactsService syntaxFacts, string name, SyntaxToken token) @@ -666,10 +666,10 @@ protected abstract void FindReferencesInDocument( Action processResult, TData processResultData, FindReferencesSearchOptions options, CancellationToken cancellationToken); - protected virtual async Task> DetermineGlobalAliasesAsync( + protected virtual Task> DetermineGlobalAliasesAsync( TSymbol symbol, Project project, CancellationToken cancellationToken) { - return []; + return SpecializedTasks.EmptyImmutableArray(); } public sealed override Task> DetermineGlobalAliasesAsync( @@ -680,13 +680,15 @@ public sealed override Task> DetermineGlobalAliasesAsync( : SpecializedTasks.EmptyImmutableArray(); } - public sealed override async Task DetermineDocumentsToSearchAsync( + public sealed override Task DetermineDocumentsToSearchAsync( ISymbol symbol, HashSet? globalAliases, Project project, IImmutableSet? documents, Action processResult, TData processResultData, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (symbol is TSymbol typedSymbol && CanFind(typedSymbol)) - await DetermineDocumentsToSearchAsync(typedSymbol, globalAliases, project, documents, processResult, processResultData, options, cancellationToken).ConfigureAwait(false); + return DetermineDocumentsToSearchAsync(typedSymbol, globalAliases, project, documents, processResult, processResultData, options, cancellationToken); + + return Task.CompletedTask; } public sealed override void FindReferencesInDocument( @@ -696,23 +698,23 @@ public sealed override void FindReferencesInDocument( FindReferencesInDocument(typedSymbol, state, processResult, processResultData, options, cancellationToken); } - public sealed override async ValueTask> DetermineCascadedSymbolsAsync( + public sealed override ValueTask> DetermineCascadedSymbolsAsync( ISymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (options.Cascade && symbol is TSymbol typedSymbol && CanFind(typedSymbol)) { - return await DetermineCascadedSymbolsAsync(typedSymbol, solution, options, cancellationToken).ConfigureAwait(false); + return DetermineCascadedSymbolsAsync(typedSymbol, solution, options, cancellationToken); } - return []; + return new([]); } - protected virtual async ValueTask> DetermineCascadedSymbolsAsync( + protected virtual ValueTask> DetermineCascadedSymbolsAsync( TSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { - return []; + return new([]); } protected static void FindReferencesInDocumentUsingSymbolName( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs index 201318e2717e8..5acaa790afd3d 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AliasSymbolReferenceFinder.cs @@ -21,7 +21,7 @@ private AliasSymbolReferenceFinder() protected override bool CanFind(IAliasSymbol symbol) => true; - protected override async Task DetermineDocumentsToSearchAsync( + protected override Task DetermineDocumentsToSearchAsync( IAliasSymbol symbol, HashSet? globalAliases, Project project, @@ -37,6 +37,8 @@ protected override async Task DetermineDocumentsToSearchAsync( if (document?.Project == project) processResult(document, processResultData); } + + return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs index 349e83213f182..574fdca8ab760 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorSymbolReferenceFinder.cs @@ -25,12 +25,12 @@ private ConstructorSymbolReferenceFinder() protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind is MethodKind.Constructor or MethodKind.StaticConstructor; - protected override async ValueTask> DetermineCascadedSymbolsAsync(IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) + protected override ValueTask> DetermineCascadedSymbolsAsync(IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (symbol.MethodKind is MethodKind.Constructor) - return GetOtherPartsOfPartial(symbol); + return new(GetOtherPartsOfPartial(symbol)); - return []; + return new([]); } private static ImmutableArray GetOtherPartsOfPartial(IMethodSymbol symbol) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs index 56e2b563e08b9..da5c9354a7339 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/CrefTypeParameterSymbolReferenceFinder.cs @@ -24,7 +24,7 @@ private CrefTypeParameterSymbolReferenceFinder() protected override bool CanFind(ITypeParameterSymbol symbol) => symbol.TypeParameterKind == TypeParameterKind.Cref; - protected override async Task DetermineDocumentsToSearchAsync( + protected override Task DetermineDocumentsToSearchAsync( ITypeParameterSymbol symbol, HashSet? globalAliases, Project project, @@ -40,6 +40,8 @@ protected override async Task DetermineDocumentsToSearchAsync( if (document != null) processResult(document, processResultData); } + + return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs index 953b3ac880336..35741d81ce547 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/DestructorSymbolReferenceFinder.cs @@ -15,7 +15,7 @@ internal sealed class DestructorSymbolReferenceFinder : AbstractReferenceFinder< protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.Destructor; - protected override async Task DetermineDocumentsToSearchAsync( + protected override Task DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet? globalAliases, Project project, @@ -25,6 +25,7 @@ protected override async Task DetermineDocumentsToSearchAsync( FindReferencesSearchOptions options, CancellationToken cancellationToken) { + return Task.CompletedTask; } protected override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs index 2c511322fe574..611c8a6476e0b 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs @@ -17,7 +17,7 @@ internal sealed class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEve protected override bool CanFind(IEventSymbol symbol) => true; - protected sealed override async ValueTask> DetermineCascadedSymbolsAsync( + protected sealed override ValueTask> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -32,7 +32,7 @@ protected sealed override async ValueTask> DetermineCasc .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray(); - return [.. GetOtherPartsOfPartial(symbol), .. backingFields, .. associatedNamedTypes]; + return new([.. GetOtherPartsOfPartial(symbol), .. backingFields, .. associatedNamedTypes]); } private static ImmutableArray GetOtherPartsOfPartial(IEventSymbol symbol) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs index d8e14c0435b7f..888729ebfd1a7 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs @@ -15,7 +15,7 @@ internal sealed class ExplicitInterfaceMethodReferenceFinder : AbstractReference protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.ExplicitInterfaceImplementation; - protected sealed override async Task DetermineDocumentsToSearchAsync( + protected sealed override Task DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet? globalAliases, Project project, @@ -26,6 +26,7 @@ protected sealed override async Task DetermineDocumentsToSearchAsync( CancellationToken cancellationToken) { // An explicit method can't be referenced anywhere. + return Task.CompletedTask; } protected sealed override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs index eb22c3ce7316c..f929bc1c580d6 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs @@ -23,7 +23,7 @@ private MethodTypeParameterSymbolReferenceFinder() protected override bool CanFind(ITypeParameterSymbol symbol) => symbol.TypeParameterKind == TypeParameterKind.Method; - protected override async ValueTask> DetermineCascadedSymbolsAsync( + protected override ValueTask> DetermineCascadedSymbolsAsync( ITypeParameterSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -35,13 +35,13 @@ protected override async ValueTask> DetermineCascadedSym if (ordinal >= 0) { if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.TypeParameters.Length) - return [method.PartialDefinitionPart.TypeParameters[ordinal]]; + return new([method.PartialDefinitionPart.TypeParameters[ordinal]]); if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.TypeParameters.Length) - return [method.PartialImplementationPart.TypeParameters[ordinal]]; + return new([method.PartialImplementationPart.TypeParameters[ordinal]]); } - return []; + return new([]); } protected sealed override Task DetermineDocumentsToSearchAsync( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs index b68b2fd47e894..e94f628cce45d 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamedTypeSymbolReferenceFinder.cs @@ -25,7 +25,7 @@ protected override Task> DetermineGlobalAliasesAsync(INam return GetAllMatchingGlobalAliasNamesAsync(project, symbol.Name, symbol.Arity, cancellationToken); } - protected override async ValueTask> DetermineCascadedSymbolsAsync( + protected override ValueTask> DetermineCascadedSymbolsAsync( INamedTypeSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -42,7 +42,7 @@ protected override async ValueTask> DetermineCascadedSym // cascade to destructor Add(result, symbol.GetMembers(WellKnownMemberNames.DestructorName)); - return result.ToImmutable(); + return new(result.ToImmutable()); } private static void Add(ArrayBuilder result, ImmutableArray enumerable) where TSymbol : ISymbol diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs index 41c8a1721779c..a7ec78f9f8280 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs @@ -33,7 +33,7 @@ protected sealed override async Task DetermineDocumentsToSearchAsync( await FindDocumentsWithGlobalSuppressMessageAttributeAsync(project, documents, processResult, processResultData, cancellationToken).ConfigureAwait(false); } - private static async Task FindDocumentsAsync( + private static Task FindDocumentsAsync( Project project, IImmutableSet? documents, PredefinedOperator op, @@ -42,10 +42,10 @@ private static async Task FindDocumentsAsync( CancellationToken cancellationToken) { if (op == PredefinedOperator.None) - return; + return Task.CompletedTask; - await FindDocumentsWithPredicateAsync( - project, documents, static (index, op) => index.ContainsPredefinedOperator(op), op, processResult, processResultData, cancellationToken).ConfigureAwait(false); + return FindDocumentsWithPredicateAsync( + project, documents, static (index, op) => index.ContainsPredefinedOperator(op), op, processResult, processResultData, cancellationToken); } protected sealed override void FindReferencesInDocument( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs index 088312654b994..6c65d0a37a15d 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs @@ -21,7 +21,7 @@ MethodKind.DeclareMethod or MethodKind.ReducedExtension or MethodKind.LocalFunction; - protected override async ValueTask> DetermineCascadedSymbolsAsync( + protected override ValueTask> DetermineCascadedSymbolsAsync( IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -30,7 +30,7 @@ protected override async ValueTask> DetermineCascadedSym // If it's a delegate method, then cascade to the type as well. These guys are // practically equivalent for users. if (symbol.ContainingType.TypeKind == TypeKind.Delegate) - return [symbol.ContainingType]; + return new([symbol.ContainingType]); using var _ = ArrayBuilder.GetInstance(out var result); @@ -43,7 +43,7 @@ protected override async ValueTask> DetermineCascadedSym if (symbol.TryGetCorrespondingExtensionBlockMethod() is IMethodSymbol method) result.Add(method); - return result.ToImmutableAndClear(); + return new(result.ToImmutableAndClear()); } private static ImmutableArray GetOtherPartsOfPartial(IMethodSymbol symbol) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs index 7bcc55d8e1cef..3799f7231bfaa 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs @@ -17,7 +17,7 @@ internal sealed class PropertyAccessorSymbolReferenceFinder : AbstractMethodOrPr protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind.IsPropertyAccessor(); - protected override async ValueTask> DetermineCascadedSymbolsAsync( + protected override ValueTask> DetermineCascadedSymbolsAsync( IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -33,7 +33,7 @@ protected override async ValueTask> DetermineCascadedSym // If the given symbol is an extension accessor, cascade to its implementation method result.AddIfNotNull(symbol.AssociatedExtensionImplementation); - return result.ToImmutableAndClear(); + return new(result.ToImmutableAndClear()); } protected override async Task DetermineDocumentsToSearchAsync( diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs index a453c554d724b..1132babf80056 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs @@ -27,7 +27,7 @@ private PropertySymbolReferenceFinder() protected override bool CanFind(IPropertySymbol symbol) => true; - protected override async ValueTask> DetermineCascadedSymbolsAsync( + protected override ValueTask> DetermineCascadedSymbolsAsync( IPropertySymbol symbol, Solution solution, FindReferencesSearchOptions options, @@ -40,7 +40,7 @@ protected override async ValueTask> DetermineCascadedSym CascadeToAccessors(symbol, result); CascadeToPrimaryConstructorParameters(symbol, result, cancellationToken); - return result.ToImmutable(); + return new(result.ToImmutable()); } private static void CascadeToOtherPartOfPartial(IPropertySymbol symbol, ArrayBuilder result) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs index fc5e3c0528103..6e9c6f8336976 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/StreamingFindReferencesProgress.cs @@ -25,23 +25,27 @@ internal sealed class StreamingFindReferencesProgressAdapter : IStreamingFindRef public StreamingFindReferencesProgressAdapter(IFindReferencesProgress progress) { _progress = progress; - ProgressTracker = new StreamingProgressTracker(async (current, max, ct) => + ProgressTracker = new StreamingProgressTracker((current, max, ct) => { _progress.ReportProgress(current, max); + return default; }); } - public async ValueTask OnCompletedAsync(CancellationToken cancellationToken) + public ValueTask OnCompletedAsync(CancellationToken cancellationToken) { _progress.OnCompleted(); + return default; } - public async ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) + public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) { try { foreach (var symbol in group.Symbols) _progress.OnDefinitionFound(symbol); + + return default; } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { @@ -49,14 +53,17 @@ public async ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationTok } } - public async ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) + public ValueTask OnReferencesFoundAsync(ImmutableArray<(SymbolGroup group, ISymbol symbol, ReferenceLocation location)> references, CancellationToken cancellationToken) { foreach (var (_, symbol, location) in references) _progress.OnReferenceFound(symbol, location); + + return ValueTask.CompletedTask; } - public async ValueTask OnStartedAsync(CancellationToken cancellationToken) + public ValueTask OnStartedAsync(CancellationToken cancellationToken) { _progress.OnStarted(); + return default; } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs index 5b1af0e92999b..408f0f9923ce7 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs @@ -183,7 +183,7 @@ static async Task CreateMetadataSymbolTreeInfoAsync( arg.services, arg.solutionKey, arg.checksum, - createAsync: async checksum => new MetadataInfoCreator(checksum, GetMetadataNoThrow(arg.reference)).Create(), + createAsync: checksum => new ValueTask(new MetadataInfoCreator(checksum, GetMetadataNoThrow(arg.reference)).Create()), keySuffix: GetMetadataKeySuffix(arg.reference), cancellationToken), arg: (services, solutionKey, checksum, reference))); diff --git a/src/Workspaces/Core/Portable/Recommendations/Recommender.cs b/src/Workspaces/Core/Portable/Recommendations/Recommender.cs index 7a24a397850f5..fd8919d2a13d1 100644 --- a/src/Workspaces/Core/Portable/Recommendations/Recommender.cs +++ b/src/Workspaces/Core/Portable/Recommendations/Recommender.cs @@ -32,14 +32,14 @@ public static IEnumerable GetRecommendedSymbolsAtPosition( } [Obsolete("Use GetRecommendedSymbolsAtPositionAsync(Document, ...)")] - public static async Task> GetRecommendedSymbolsAtPositionAsync( + public static Task> GetRecommendedSymbolsAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, OptionSet? options = null, CancellationToken cancellationToken = default) { - return GetRecommendedSymbolsAtPosition(semanticModel, position, workspace, options, cancellationToken); + return Task.FromResult(GetRecommendedSymbolsAtPosition(semanticModel, position, workspace, options, cancellationToken)); } public static async Task> GetRecommendedSymbolsAtPositionAsync( diff --git a/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs b/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs index 6f2b4b234fb22..433dca5a99a23 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteHostClient.cs @@ -19,37 +19,37 @@ internal abstract class RemoteHostClient : IDisposable { public abstract void Dispose(); - public static async Task WaitForClientCreationAsync(Workspace workspace, CancellationToken cancellationToken) + public static Task WaitForClientCreationAsync(Workspace workspace, CancellationToken cancellationToken) { var service = workspace.Services.GetService(); if (service == null) - return; + return Task.CompletedTask; - await service.WaitForClientCreationAsync(cancellationToken).ConfigureAwait(false); + return service.WaitForClientCreationAsync(cancellationToken); } - public static async Task TryGetClientAsync(Project project, CancellationToken cancellationToken) + public static Task TryGetClientAsync(Project project, CancellationToken cancellationToken) { if (!RemoteSupportedLanguages.IsSupported(project.Language)) { - return null; + return SpecializedTasks.Null(); } - return await TryGetClientAsync(project.Solution.Services, cancellationToken).ConfigureAwait(false); + return TryGetClientAsync(project.Solution.Services, cancellationToken); } public static Task TryGetClientAsync(Workspace workspace, CancellationToken cancellationToken) => TryGetClientAsync(workspace.Services.SolutionServices, cancellationToken); - public static async Task TryGetClientAsync(SolutionServices services, CancellationToken cancellationToken) + public static Task TryGetClientAsync(SolutionServices services, CancellationToken cancellationToken) { var service = services.GetService(); if (service == null) { - return null; + return SpecializedTasks.Null(); } - return await service.TryGetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); + return service.TryGetRemoteHostClientAsync(cancellationToken); } public abstract RemoteServiceConnection CreateConnection(object? callbackTarget) diff --git a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs index f8637a23e25ec..ed0dfbf53b914 100644 --- a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs +++ b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs @@ -40,16 +40,16 @@ public AsynchronousOperationListener(string featureName, bool enableDiagnosticTo [PerformanceSensitive( "https://github.com/dotnet/roslyn/pull/58646", Constraint = "Cannot use async/await because it produces large numbers of first-chance cancellation exceptions.")] - public async Task Delay(TimeSpan delay, CancellationToken cancellationToken) + public Task Delay(TimeSpan delay, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) - return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); var expeditedDelayCancellationToken = _expeditedDelayCancellationTokenSource.Token; if (expeditedDelayCancellationToken.IsCancellationRequested) { // The operation is already being expedited - return false; + return SpecializedTasks.False; } var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, expeditedDelayCancellationToken); @@ -59,28 +59,28 @@ public async Task Delay(TimeSpan delay, CancellationToken cancellationToke { cancellationTokenSource.Dispose(); if (delayTask.Status == TaskStatus.RanToCompletion) - return true; + return SpecializedTasks.True; else if (cancellationToken.IsCancellationRequested) - return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); else - return false; + return SpecializedTasks.False; } // Handle continuation in a local function to avoid capturing arguments when this path is avoided - return await DelaySlowAsync(delayTask, cancellationTokenSource, cancellationToken).ConfigureAwait(false); + return DelaySlowAsync(delayTask, cancellationTokenSource, cancellationToken); static Task DelaySlowAsync(Task delayTask, CancellationTokenSource cancellationTokenSourceToDispose, CancellationToken cancellationToken) { return delayTask.ContinueWith( - async task => + task => { cancellationTokenSourceToDispose.Dispose(); if (task.Status == TaskStatus.RanToCompletion) - return true; + return SpecializedTasks.True; else if (cancellationToken.IsCancellationRequested) - return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); else - return false; + return SpecializedTasks.False; }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs index d4884dafbad74..c17666916d22d 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs @@ -64,23 +64,23 @@ protected override string GetDatabaseFilePath(string workingFolderPath) return Path.Combine(workingFolderPath, StorageExtension, nameof(v2), PersistentStorageFileName); } - protected override async ValueTask TryOpenDatabaseAsync( + protected override ValueTask TryOpenDatabaseAsync( SolutionKey solutionKey, string workingFolderPath, string databaseFilePath, IPersistentStorageFaultInjector? faultInjector, CancellationToken cancellationToken) { if (!TryInitializeLibraries()) { // SQLite is not supported on the current platform - return null; + return new((IChecksummedPersistentStorage?)null); } if (solutionKey.FilePath == null) - return NoOpPersistentStorage.GetOrThrow(solutionKey, Configuration.ThrowOnFailure); + return new(NoOpPersistentStorage.GetOrThrow(solutionKey, Configuration.ThrowOnFailure)); - return SQLitePersistentStorage.TryCreate( + return new(SQLitePersistentStorage.TryCreate( solutionKey, workingFolderPath, databaseFilePath, asyncListener, - faultInjector); + faultInjector)); } } diff --git a/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs b/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs index 211d88014e0d9..45337f28d766e 100644 --- a/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs +++ b/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs @@ -155,12 +155,12 @@ internal sealed class ReferenceAssemblyResult( [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class DefaultSymbolSearchService() : ISymbolSearchService { - public async ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> FindPackagesAsync(string source, TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); - public async ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); - public async ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) - => ImmutableArray.Empty; + public ValueTask> FindReferenceAssembliesAsync(TypeQuery typeQuery, NamespaceQuery namespaceQuery, CancellationToken cancellationToken) + => ValueTask.FromResult(ImmutableArray.Empty); } diff --git a/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs b/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs index 7c4381c1e6d7d..cc0f48a32e732 100644 --- a/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs +++ b/src/Workspaces/Core/Portable/TemporaryStorage/TrivialTemporaryStorageService.cs @@ -32,9 +32,9 @@ public ITemporaryStorageTextHandle WriteToTemporaryStorage(SourceText text, Canc return new TextStorage(text); } - public async Task WriteToTemporaryStorageAsync(SourceText text, CancellationToken cancellationToken) + public Task WriteToTemporaryStorageAsync(SourceText text, CancellationToken cancellationToken) { - return new TextStorage(text); + return Task.FromResult(new TextStorage(text)); } private sealed class StreamStorage : ITemporaryStorageStreamHandle @@ -74,9 +74,9 @@ public SourceText ReadFromTemporaryStorage(CancellationToken cancellationToken) return _sourceText; } - public async Task ReadFromTemporaryStorageAsync(CancellationToken cancellationToken) + public Task ReadFromTemporaryStorageAsync(CancellationToken cancellationToken) { - return _sourceText; + return Task.FromResult(_sourceText); } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs b/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs index 8497e7a584f49..b409b22a479fc 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/DocumentExcerptHelper.cs @@ -23,20 +23,20 @@ public static bool CanExcerpt(Document document) return document.DocumentServiceProvider.GetService() is not null; } - public static async Task TryExcerptAsync(Document document, TextSpan span, ExcerptMode mode, ClassificationOptions classificationOptions, CancellationToken cancellationToken) + public static Task TryExcerptAsync(Document document, TextSpan span, ExcerptMode mode, ClassificationOptions classificationOptions, CancellationToken cancellationToken) { if (document is SourceGeneratedDocument sourceGeneratedDocument && document.Project.Solution.Services.GetService() is { } sourceGeneratedExcerptService) { - return await sourceGeneratedExcerptService.TryExcerptAsync(sourceGeneratedDocument, span, mode, classificationOptions, cancellationToken).ConfigureAwait(false); + return sourceGeneratedExcerptService.TryExcerptAsync(sourceGeneratedDocument, span, mode, classificationOptions, cancellationToken); } var excerptService = document.DocumentServiceProvider.GetService(); if (excerptService == null) { - return null; + return SpecializedTasks.Default(); } - return await excerptService.TryExcerptAsync(document, span, mode, classificationOptions, cancellationToken).ConfigureAwait(false); + return excerptService.TryExcerptAsync(document, span, mode, classificationOptions, cancellationToken); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs index 123d9bf2315f6..0af8e93ab5b28 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs @@ -20,68 +20,68 @@ public static IChecksummedPersistentStorage GetOrThrow(SolutionKey solutionKey, ? throw new InvalidOperationException("Database was not supported") : new NoOpPersistentStorage(solutionKey); - public async Task ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) - => false; + public Task ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) - => false; + public Task ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) - => false; + public Task ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) - => false; + public Task ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) - => false; + public Task ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task ReadStreamAsync(string name, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(string name, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task ReadStreamAsync(string name, Checksum? checksum, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(string name, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task ReadStreamAsync(Project project, string name, Checksum? checksum, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(Project project, string name, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task ReadStreamAsync(Document document, string name, Checksum? checksum, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(Document document, string name, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task ReadStreamAsync(ProjectKey project, string name, Checksum? checksum, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(ProjectKey project, string name, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task ReadStreamAsync(DocumentKey document, string name, Checksum? checksum, CancellationToken cancellationToken) - => null; + public Task ReadStreamAsync(DocumentKey document, string name, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.Null(); - public async Task WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task WriteStreamAsync(string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task WriteStreamAsync(Project project, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(Project project, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task WriteStreamAsync(Document document, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(Document document, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; - public async Task WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) - => false; + public Task WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken) + => SpecializedTasks.False; public readonly struct TestAccessor { diff --git a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs index 1b14a15cf1c4f..5f5bc076f5df3 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs @@ -22,6 +22,6 @@ public static IChecksummedPersistentStorageService GetOrThrow(IPersistentStorage ? throw new InvalidOperationException("Database was not supported") : Instance; - public async ValueTask GetStorageAsync(SolutionKey solutionKey, CancellationToken cancellationToken) - => NoOpPersistentStorage.GetOrThrow(solutionKey, throwOnFailure: false); + public ValueTask GetStorageAsync(SolutionKey solutionKey, CancellationToken cancellationToken) + => new(NoOpPersistentStorage.GetOrThrow(solutionKey, throwOnFailure: false)); } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs b/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs index 63921d5c1f0fe..02c72cb3e4183 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Status/DefaultWorkspaceStatusService.cs @@ -22,14 +22,15 @@ event EventHandler IWorkspaceStatusService.StatusChanged remove { } } - public async Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) + public Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded + return Task.CompletedTask; } - public async Task IsFullyLoadedAsync(CancellationToken cancellationToken) + public Task IsFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded - return true; + return SpecializedTasks.True; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs index 9a3fc38b5f180..a4e011da48238 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/LegacyTemporaryStorageService.cs @@ -50,9 +50,9 @@ public Stream ReadStream(CancellationToken cancellationToken = default) return new MemoryStream(stream.GetBuffer(), 0, (int)stream.Length, writable: false); } - public async Task ReadStreamAsync(CancellationToken cancellationToken = default) + public Task ReadStreamAsync(CancellationToken cancellationToken = default) { - return ReadStream(cancellationToken); + return Task.FromResult(ReadStream(cancellationToken)); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default) @@ -92,8 +92,8 @@ public void Dispose() public SourceText ReadText(CancellationToken cancellationToken = default) => _sourceText ?? throw new InvalidOperationException(); - public async Task ReadTextAsync(CancellationToken cancellationToken = default) - => ReadText(cancellationToken); + public Task ReadTextAsync(CancellationToken cancellationToken = default) + => Task.FromResult(ReadText(cancellationToken)); public void WriteText(SourceText text, CancellationToken cancellationToken = default) { @@ -107,9 +107,10 @@ public void WriteText(SourceText text, CancellationToken cancellationToken = def } } - public async Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) + public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) { WriteText(text, cancellationToken); + return Task.CompletedTask; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs index 6b6c349c0d6d7..2592d94422eb8 100644 --- a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs +++ b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Core.cs @@ -210,7 +210,7 @@ public static async partial ValueTask> CreateI useAsync, analyzerChecksums, solutionServices, - async () => references, + () => Task.FromResult(references), cancellationToken).ConfigureAwait(false); } diff --git a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs index b4638bdf3a54f..362f448ae8262 100644 --- a/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs +++ b/src/Workspaces/Core/Portable/Workspace/IsolatedAnalyzerReferenceSet.Desktop.cs @@ -21,13 +21,13 @@ namespace Microsoft.CodeAnalysis; /// internal sealed partial class IsolatedAnalyzerReferenceSet { - public static async partial ValueTask> CreateIsolatedAnalyzerReferencesAsync( + public static partial ValueTask> CreateIsolatedAnalyzerReferencesAsync( bool useAsync, ImmutableArray references, SolutionServices solutionServices, CancellationToken cancellationToken) { - return references; + return ValueTask.FromResult(references); } public static async partial ValueTask> CreateIsolatedAnalyzerReferencesAsync( diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs index b41df54f26611..ab75dacee1552 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs @@ -664,8 +664,8 @@ public SourceTextLoader(SourceTextContainer textContainer, string? filePath) _filePath = filePath; } - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath); + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath)); } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs index d2c38a34cb8f1..19d32d984b671 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs @@ -27,8 +27,8 @@ public TextLoader? TextLoader public TextAndVersion GetValue(LoadTextOptions options, CancellationToken cancellationToken) => _value; - public async Task GetValueAsync(LoadTextOptions options, CancellationToken cancellationToken) - => _value; + public Task GetValueAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(_value); public bool TryGetValue(LoadTextOptions options, [MaybeNullWhen(false)] out TextAndVersion value) { @@ -42,6 +42,6 @@ public bool TryGetVersion(LoadTextOptions options, out VersionStamp version) return true; } - public async ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => _value.Version; + public ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => new(_value.Version); } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs index ce4b54061fd2b..7b83ff5fb000d 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs @@ -165,18 +165,18 @@ public bool SupportsSemanticModel /// to or may end up causing computation /// to occur at that point. /// - public async Task GetSyntaxTreeAsync(CancellationToken cancellationToken = default) + public Task GetSyntaxTreeAsync(CancellationToken cancellationToken = default) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { - return null; + return SpecializedTasks.Null(); } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { - return await _syntaxTreeResultTask.ConfigureAwait(false); + return _syntaxTreeResultTask.AsNullable(); } // check to see if we already have the tree before actually going async @@ -185,13 +185,13 @@ public bool SupportsSemanticModel // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. - _ = Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); + Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); - return await _syntaxTreeResultTask.ConfigureAwait(false); + return _syntaxTreeResultTask.AsNullable(); } // do it async for real. - return await DocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + return DocumentState.GetSyntaxTreeAsync(cancellationToken).AsTask().AsNullable(); } internal SyntaxTree? GetSyntaxTreeSynchronously(CancellationToken cancellationToken) diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs index 02c21970b852e..53f5d0dc024c4 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs @@ -58,6 +58,6 @@ public bool TryGetVersion(LoadTextOptions options, out VersionStamp version) return version != default; } - public async ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => _version; + public ValueTask GetVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => new(_version); } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index 764d65bc75496..df6641633fe30 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -251,31 +251,31 @@ private static Project CreateProject(ProjectId projectId, Solution solution) /// /// Gets a document or a source generated document in this solution with the specified document ID. /// - internal async ValueTask GetDocumentAsync(DocumentId? documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) + internal ValueTask GetDocumentAsync(DocumentId? documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) { var project = GetProject(documentId?.ProjectId); if (project == null) { - return null; + return default; } Contract.ThrowIfNull(documentId); - return await project.GetDocumentAsync(documentId, includeSourceGenerated, cancellationToken).ConfigureAwait(false); + return project.GetDocumentAsync(documentId, includeSourceGenerated, cancellationToken); } /// /// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID. /// - internal async ValueTask GetTextDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken = default) + internal ValueTask GetTextDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken = default) { var project = GetProject(documentId?.ProjectId); if (project == null) { - return null; + return default; } Contract.ThrowIfNull(documentId); - return await project.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); + return project.GetTextDocumentAsync(documentId, cancellationToken); } /// @@ -304,17 +304,17 @@ private static Project CreateProject(ProjectId projectId, Solution solution) return null; } - public async ValueTask GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) + public ValueTask GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { var project = GetProject(documentId.ProjectId); if (project == null) { - return null; + return new(result: null); } else { - return await project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); + return project.GetSourceGeneratedDocumentAsync(documentId, cancellationToken); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs index 9f13228131041..7754b7924a122 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.RegularCompilationTracker.cs @@ -213,22 +213,22 @@ public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) } } - public async Task GetCompilationAsync(SolutionCompilationState compilationState, CancellationToken cancellationToken) + public Task GetCompilationAsync(SolutionCompilationState compilationState, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { - return compilation; + return Task.FromResult(compilation); } else if (cancellationToken.IsCancellationRequested) { // Handle early cancellation here to avoid throwing/catching cancellation exceptions in the async // state machines. This helps reduce the total number of First Chance Exceptions occurring in IDE // typing scenarios. - return await Task.FromCanceled(cancellationToken).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } else { - return await GetCompilationSlowAsync(compilationState, cancellationToken).ConfigureAwait(false); + return GetCompilationSlowAsync(compilationState, cancellationToken); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs index 75081bcd871b0..129720b03bd5f 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.SkeletonReferenceCache.cs @@ -208,8 +208,8 @@ public readonly SkeletonReferenceCache Clone() // concurrent requests asynchronously wait for that work to be done. var lazy = s_compilationToSkeletonSet.GetValue(compilation, - compilation => AsyncLazy.Create(static async (arg, cancellationToken) => - CreateSkeletonSet(arg.services, arg.compilation, cancellationToken), + compilation => AsyncLazy.Create(static (arg, cancellationToken) => + Task.FromResult(CreateSkeletonSet(arg.services, arg.compilation, cancellationToken)), arg: (services, compilation))); return await lazy.GetValueAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs index a1b490c502b4a..85c092e64821a 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionCompilationState.TranslationAction_Actions.cs @@ -82,8 +82,8 @@ internal sealed class TouchAdditionalDocumentsAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => oldCompilation; + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => Task.FromResult(oldCompilation); public override TranslationAction? TryMergeWithPrior(TranslationAction priorAction) { @@ -117,10 +117,10 @@ internal sealed class TouchAnalyzerConfigDocumentsAction( /// /// Updating editorconfig document updates . /// - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { RoslynDebug.AssertNotNull(this.NewProjectState.CompilationOptions); - return oldCompilation.WithOptions(this.NewProjectState.CompilationOptions); + return Task.FromResult(oldCompilation.WithOptions(this.NewProjectState.CompilationOptions)); } // Updating the analyzer config optons doesn't require us to reparse trees, so we can use this to update @@ -239,10 +239,10 @@ internal sealed class ProjectCompilationOptionsAction( ProjectState oldProjectState, ProjectState newProjectState) : TranslationAction(oldProjectState, newProjectState) { - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { Contract.ThrowIfNull(this.NewProjectState.CompilationOptions); - return oldCompilation.WithOptions(this.NewProjectState.CompilationOptions); + return Task.FromResult(oldCompilation.WithOptions(this.NewProjectState.CompilationOptions)); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update @@ -262,8 +262,8 @@ internal sealed class ProjectAssemblyNameAction( ProjectState newProjectState) : TranslationAction(oldProjectState, newProjectState) { - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => oldCompilation.WithAssemblyName(NewProjectState.AssemblyName); + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => Task.FromResult(oldCompilation.WithAssemblyName(NewProjectState.AssemblyName)); // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update // compilations with stale generated trees. @@ -285,8 +285,8 @@ internal sealed class AddOrRemoveAnalyzerReferencesAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => oldCompilation; + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => Task.FromResult(oldCompilation); public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver generatorDriver) { @@ -316,8 +316,8 @@ internal sealed class AddAdditionalDocumentsAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => oldCompilation; + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => Task.FromResult(oldCompilation); public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver generatorDriver) { @@ -336,8 +336,8 @@ internal sealed class RemoveAdditionalDocumentsAction( // compilation with stale trees around, answering true is still important. public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => oldCompilation; + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => Task.FromResult(oldCompilation); public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver generatorDriver) { @@ -355,8 +355,8 @@ internal sealed class ReplaceGeneratorDriverAction( // Replacing the generator doesn't change the non-generator compilation. So we can just return the old // compilation as is. - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) - => oldCompilation; + public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) + => Task.FromResult(oldCompilation); public override GeneratorDriver TransformGeneratorDriver(GeneratorDriver _) { diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs index 375de862ad368..ab9bfa465da47 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.cs @@ -178,15 +178,15 @@ private static ITextAndVersionSource CreateTextFromLoader(SolutionServices solut return new RecoverableTextAndVersion(new LoadableTextAndVersionSource(loader, cacheResult: false), solutionServices); } - private async ValueTask GetTextAndVersionAsync(CancellationToken cancellationToken) + private ValueTask GetTextAndVersionAsync(CancellationToken cancellationToken) { if (this.TextAndVersionSource.TryGetValue(LoadTextOptions, out var textAndVersion)) { - return textAndVersion; + return new ValueTask(textAndVersion); } else { - return await TextAndVersionSource.GetValueAsync(LoadTextOptions, cancellationToken).ConfigureAwait(false); + return new ValueTask(TextAndVersionSource.GetValueAsync(LoadTextOptions, cancellationToken)); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs b/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs index 9d3e1654a3ccf..ac00ed9a74486 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.cs @@ -200,8 +200,8 @@ private sealed class TextDocumentLoader : TextLoader internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => _textAndVersion; + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(_textAndVersion); internal override TextAndVersion LoadTextAndVersionSynchronously(LoadTextOptions options, CancellationToken cancellationToken) => _textAndVersion; @@ -223,8 +223,8 @@ internal TextContainerLoader(SourceTextContainer container, VersionStamp version internal override string? FilePath => _filePath; - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => LoadTextAndVersionSynchronously(options, cancellationToken); + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(LoadTextAndVersionSynchronously(options, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(LoadTextOptions options, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace.cs b/src/Workspaces/Core/Portable/Workspace/Workspace.cs index e93a13970638c..4c32aa6986c8a 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace.cs @@ -291,9 +291,7 @@ internal bool SetCurrentSolution( // Doing so under the serialization lock guarantees the same ordering of the events // as the order of the changes made to the solution. var (changeKind, projectId, documentId) = data.changeKind(oldSolution, newSolution); - - // Fire and forget - _ = data.@this.RaiseWorkspaceChangedEventAsync(changeKind, oldSolution, newSolution, projectId, documentId); + data.@this.RaiseWorkspaceChangedEventAsync(changeKind, oldSolution, newSolution, projectId, documentId); }, cancellationToken).ConfigureAwait(false); @@ -643,13 +641,10 @@ private void ClearSolution(bool reportChangeEvent) (oldSolution, _) => this.CreateSolution(oldSolution.Id), mayRaiseEvents: reportChangeEvent, onBeforeUpdate: (_, _, _) => this.ClearSolutionData(), - onAfterUpdate: (oldSolution, newSolution, _1) => + onAfterUpdate: (oldSolution, newSolution, _) => { if (reportChangeEvent) - { - // Fire and forget - _ = this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionCleared, oldSolution, newSolution); - } + this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionCleared, oldSolution, newSolution); }); } @@ -1070,10 +1065,7 @@ protected internal void OnDocumentsAdded(ImmutableArray documentIn // Raise ProjectChanged as the event type here. DocumentAdded is presumed by many callers to have a // DocumentId associated with it, and we don't want to be raising multiple events. foreach (var projectId in data.documentInfos.Select(i => i.Id.ProjectId).Distinct()) - { - // Fire and forget - _ = data.@this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution, projectId); - } + data.@this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution, projectId); }); } @@ -1349,8 +1341,7 @@ private void OnAnyDocumentTextChanged( foreach (var updatedDocumentInfo in data.updatedDocumentIds) { - // Fire and forget - _ = data.@this.RaiseWorkspaceChangedEventAsync( + data.@this.RaiseWorkspaceChangedEventAsync( data.changeKind, oldSolution, newSolution, diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs b/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs index b173dec7be691..a7b74adde521f 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs @@ -325,7 +325,7 @@ protected internal void OnDocumentContextUpdated(DocumentId documentId) } // fire and forget - _ = this.RaiseDocumentActiveContextChangedEventAsync(container, oldActiveContextDocumentId: oldActiveContextDocumentId, newActiveContextDocumentId: documentId); + this.RaiseDocumentActiveContextChangedEventAsync(container, oldActiveContextDocumentId: oldActiveContextDocumentId, newActiveContextDocumentId: documentId); } } @@ -352,9 +352,10 @@ protected void CheckDocumentIsOpen(DocumentId documentId) protected internal void OnDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true) => OnDocumentOpened(documentId, textContainer, isCurrentContext, requireDocumentPresentAndClosed: true); - internal virtual async ValueTask TryOnDocumentOpenedAsync(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, CancellationToken cancellationToken) + internal virtual ValueTask TryOnDocumentOpenedAsync(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, CancellationToken cancellationToken) { OnDocumentOpened(documentId, textContainer, isCurrentContext, requireDocumentPresentAndClosed: false); + return ValueTask.CompletedTask; } internal void OnDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, bool requireDocumentPresentAndClosed) @@ -420,7 +421,7 @@ internal void OnDocumentOpened(DocumentId documentId, SourceTextContainer textCo @this.OnDocumentTextChanged(newDoc); // Fire and forget that the workspace is changing. - _ = @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); + @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // We fire 2 events on source document opened. @this.RaiseDocumentOpenedEventAsync(newDoc); @@ -609,7 +610,7 @@ private void OnAdditionalOrAnalyzerConfigDocumentOpened( data.@this.SignupForTextChanges(documentId, data.textContainer, data.isCurrentContext, data.onDocumentTextChanged); // Fire and forget. - _ = data.@this.RaiseWorkspaceChangedEventAsync(data.workspaceChangeKind, oldSolution, newSolution, documentId: documentId); + data.@this.RaiseWorkspaceChangedEventAsync(data.workspaceChangeKind, oldSolution, newSolution, documentId: documentId); // Fire and forget. var newDoc = newSolution.GetRequiredTextDocument(documentId); @@ -696,8 +697,7 @@ private protected void OnDocumentClosedEx(DocumentId documentId, TextLoader relo var newDoc = newSolution.GetRequiredDocument(documentId); @this.OnDocumentTextChanged(newDoc); - // Fire and forget - _ = @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this + @this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this // We fire and forget 2 events on source document closed. @this.RaiseDocumentClosedEventAsync(newDoc); @@ -786,8 +786,7 @@ private void OnAdditionalOrAnalyzerConfigDocumentClosed( }, onAfterUpdate: static (oldSolution, newSolution, data) => { - // Fire and forget - _ = data.@this.RaiseWorkspaceChangedEventAsync( + data.@this.RaiseWorkspaceChangedEventAsync( data.workspaceChangeKind, oldSolution, newSolution, documentId: data.documentId); // don't wait for this var newDoc = newSolution.GetRequiredTextDocument(data.documentId); diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs b/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs index 2a5b3e4d4b733..a3a47ce9e9ce4 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace_Events.cs @@ -93,13 +93,13 @@ private WorkspaceEventRegistration RegisterHandler(WorkspaceEventTyp #endregion - protected async Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId? projectId = null, DocumentId? documentId = null) + protected Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId? projectId = null, DocumentId? documentId = null) { if (newSolution == null) throw new ArgumentNullException(nameof(newSolution)); if (oldSolution == newSolution) - return; + return Task.CompletedTask; if (projectId == null && documentId != null) projectId = documentId.ProjectId; @@ -117,8 +117,10 @@ protected async Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, S if (handlerSet.HasHandlers) { args ??= new WorkspaceChangeEventArgs(kind, oldSolution, newSolution, projectId, documentId); - await this.ScheduleTask(args, handlerSet).ConfigureAwait(false); + return this.ScheduleTask(args, handlerSet); } + + return Task.CompletedTask; } protected internal virtual void OnWorkspaceFailed(WorkspaceDiagnostic diagnostic) @@ -137,7 +139,7 @@ protected Task RaiseDocumentOpenedEventAsync(Document document) protected Task RaiseTextDocumentOpenedEventAsync(TextDocument document) => RaiseTextDocumentOpenedOrClosedEventAsync(document, new TextDocumentEventArgs(document), WorkspaceEventType.TextDocumentOpened); - private async Task RaiseTextDocumentOpenedOrClosedEventAsync( + private Task RaiseTextDocumentOpenedOrClosedEventAsync( TDocument document, TDocumentEventArgs args, WorkspaceEventType eventType) @@ -146,7 +148,9 @@ private async Task RaiseTextDocumentOpenedOrClosedEventAsync throw new NotImplementedException(); - protected async Task RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) + protected Task RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) { if (sourceTextContainer == null || oldActiveContextDocumentId == null || newActiveContextDocumentId == null) - return; + return Task.CompletedTask; var handlerSet = GetEventHandlers(WorkspaceEventType.DocumentActiveContextChanged); if (handlerSet.HasHandlers) @@ -171,8 +175,10 @@ protected async Task RaiseDocumentActiveContextChangedEventAsync(SourceTextConta var currentSolution = this.CurrentSolution; var args = new DocumentActiveContextChangedEventArgs(currentSolution, sourceTextContainer, oldActiveContextDocumentId, newActiveContextDocumentId); - await this.ScheduleTask(args, handlerSet).ConfigureAwait(false); + return this.ScheduleTask(args, handlerSet); } + + return Task.CompletedTask; } private EventHandlerSet GetEventHandlers(WorkspaceEventType eventType) diff --git a/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs b/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs index 35c0f34534e2e..b43aa84cc4bb6 100644 --- a/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs +++ b/src/Workspaces/CoreTest/BatchFixAllProviderTests.cs @@ -82,7 +82,7 @@ public ReplaceZeroFix(ImmutableArray replacements, bool nested) public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - public override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { @@ -105,6 +105,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix(fix, diagnostic); } } + + return Task.CompletedTask; } private static async Task CreateChangedDocument(Document document, TextSpan sourceSpan, int replacement, CancellationToken cancellationToken) diff --git a/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs b/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs index 507bbce3b9854..0e562bd597b7d 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/CodeCleanupTests.cs @@ -396,10 +396,10 @@ private static async Task VerifyRange(string code, ImmutableArray + CleanupDocumentAsyncImpl = (provider, document, spans, options, cancellationToken) => { provider.ExpectedResult = spans; - return document; + return Task.FromResult(document); } }; diff --git a/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs b/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs index 26680babb2917..0a992ecb57abb 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs @@ -27,6 +27,6 @@ internal sealed class MockCodeCleanupProvider : ICodeCleanupProvider public Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) => (CleanupDocumentAsyncImpl ?? throw new NotImplementedException()).Invoke(this, document, spans, options.FormattingOptions, cancellationToken); - public async Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) - => (CleanupNodeImpl ?? throw new NotImplementedException()).Invoke(root, spans, options, services); + public Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) + => Task.FromResult((CleanupNodeImpl ?? throw new NotImplementedException()).Invoke(root, spans, options, services)); } diff --git a/src/Workspaces/CoreTest/Formatter/FormatterTests.cs b/src/Workspaces/CoreTest/Formatter/FormatterTests.cs index 7178230fe5960..040105af59734 100644 --- a/src/Workspaces/CoreTest/Formatter/FormatterTests.cs +++ b/src/Workspaces/CoreTest/Formatter/FormatterTests.cs @@ -38,8 +38,8 @@ public TestFormattingService() { } - public async Task FormatAsync(Document document, IEnumerable? spans, LineFormattingOptions lineFormattingOptions, SyntaxFormattingOptions? syntaxFormattingOptions, CancellationToken cancellationToken) - => document.WithText(SourceText.From($"Formatted with options: {lineFormattingOptions.ToString().Replace("\r", "\\r").Replace("\n", "\\n")}")); + public Task FormatAsync(Document document, IEnumerable? spans, LineFormattingOptions lineFormattingOptions, SyntaxFormattingOptions? syntaxFormattingOptions, CancellationToken cancellationToken) + => Task.FromResult(document.WithText(SourceText.From($"Formatted with options: {lineFormattingOptions.ToString().Replace("\r", "\\r").Replace("\n", "\\n")}"))); } [Fact] diff --git a/src/Workspaces/CoreTest/SyntaxNodeTests.cs b/src/Workspaces/CoreTest/SyntaxNodeTests.cs index 5eddfd2e26d20..81a812676dd41 100644 --- a/src/Workspaces/CoreTest/SyntaxNodeTests.cs +++ b/src/Workspaces/CoreTest/SyntaxNodeTests.cs @@ -28,10 +28,10 @@ public async Task TestReplaceOneNodeAsync() var root = tree.GetRoot(); var node = root.DescendantNodes().OfType().Single(); - var newRoot = await root.ReplaceNodesAsync([node], async (o, n, c) => + var newRoot = await root.ReplaceNodesAsync([node], (o, n, c) => { var decl = (VariableDeclaratorSyntax)n; - return decl.WithIdentifier(SyntaxFactory.Identifier("Y")); + return Task.FromResult(decl.WithIdentifier(SyntaxFactory.Identifier("Y"))); }, CancellationToken.None); var actual = newRoot.ToString(); @@ -48,22 +48,22 @@ public async Task TestReplaceNestedNodesAsync() var nodes = root.DescendantNodes().Where(n => n is VariableDeclaratorSyntax or ClassDeclarationSyntax).ToList(); var computations = 0; - var newRoot = await root.ReplaceNodesAsync(nodes, async (o, n, c) => + var newRoot = await root.ReplaceNodesAsync(nodes, (o, n, c) => { computations++; if (n is ClassDeclarationSyntax classDecl) { var id = classDecl.Identifier; - return classDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia)); + return Task.FromResult(classDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia))); } if (n is VariableDeclaratorSyntax varDecl) { var id = varDecl.Identifier; - return varDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia)); + return Task.FromResult(varDecl.WithIdentifier(SyntaxFactory.Identifier(id.LeadingTrivia, id.ToString() + "1", id.TrailingTrivia))); } - return n; + return Task.FromResult(n); }, CancellationToken.None); var actual = newRoot.ToString(); diff --git a/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs b/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs index 89431b740e550..1ca298c74e810 100644 --- a/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs +++ b/src/Workspaces/CoreTest/UtilityTest/AsyncLazyTests.cs @@ -22,7 +22,7 @@ public void GetValueAsyncReturnsCompletedTaskIfAsyncComputationCompletesImmediat // Note, this test may pass even if GetValueAsync posted a task to the threadpool, since the // current thread may context switch out and allow the threadpool to complete the task before // we check the state. However, a failure here definitely indicates a bug in AsyncLazy. - var lazy = AsyncLazy.Create(static async c => 5); + var lazy = AsyncLazy.Create(static c => Task.FromResult(5)); var t = lazy.GetValueAsync(CancellationToken.None); Assert.Equal(TaskStatus.RanToCompletion, t.Status); Assert.Equal(5, t.Result); @@ -241,7 +241,7 @@ private static void CancellationDuringInlinedComputationFromGetValueOrGetValueAs }; var lazy = AsyncLazy.Create( - static async (synchronousComputation, c) => synchronousComputation(c), + static (synchronousComputation, c) => Task.FromResult(synchronousComputation(c)), includeSynchronousComputation ? static (synchronousComputation, c) => synchronousComputation(c) : null, arg: synchronousComputation); @@ -263,7 +263,7 @@ static async (synchronousComputation, c) => synchronousComputation(c), [Fact] public void SynchronousRequestShouldCacheValueWithAsynchronousComputeFunction() { - var lazy = AsyncLazy.Create(static async c => new object()); + var lazy = AsyncLazy.Create(static c => Task.FromResult(new object())); var firstRequestResult = lazy.GetValue(CancellationToken.None); var secondRequestResult = lazy.GetValue(CancellationToken.None); @@ -339,7 +339,7 @@ public async Task CancelledAndReranAsynchronousComputationDoesNotBreakSynchronou Assert.Equal(TaskStatus.Canceled, asynchronousRequestToBeCancelled.Status); // Step 3: let's now let an async request run normally, producing a value - asynchronousComputation = async _ => "Returned from asynchronous computation: " + Guid.NewGuid(); + asynchronousComputation = _ => Task.FromResult("Returned from asynchronous computation: " + Guid.NewGuid()); var asynchronousRequest = lazy.GetValueAsync(CancellationToken.None); @@ -369,7 +369,7 @@ public async Task AsynchronousResultThatWasCancelledDoesNotBreakSynchronousReque var asynchronousRequestCancellationToken = new CancellationTokenSource(); var lazy = AsyncLazy.Create( - asynchronousComputeFunction: static async (arg, ct) => + asynchronousComputeFunction: static (arg, ct) => { arg.asynchronousRequestCancellationToken.Cancel(); @@ -381,7 +381,7 @@ public async Task AsynchronousResultThatWasCancelledDoesNotBreakSynchronousReque arg.asynchronousComputationReadyToComplete.Set(); arg.asynchronousComputationShouldCompleteEvent.WaitOne(); - return "Returned from asynchronous computation: " + Guid.NewGuid(); + return Task.FromResult("Returned from asynchronous computation: " + Guid.NewGuid()); }, synchronousComputeFunction: static (arg, _) => { diff --git a/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs b/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs index dd2e4840fcc7a..271ab19c41819 100644 --- a/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs +++ b/src/Workspaces/CoreTestUtilities/Fakes/SimpleAssetSource.cs @@ -17,7 +17,7 @@ namespace Microsoft.CodeAnalysis.Remote.Testing; /// internal sealed class SimpleAssetSource(ISerializerService serializerService, IReadOnlyDictionary map) : IAssetSource { - public async ValueTask GetAssetsAsync( + public ValueTask GetAssetsAsync( Checksum solutionChecksum, AssetPath assetPath, ReadOnlyMemory checksums, ISerializerService deserializerService, Action callback, TArg arg, CancellationToken cancellationToken) { foreach (var checksum in checksums.Span) @@ -37,5 +37,7 @@ public async ValueTask GetAssetsAsync( Contract.ThrowIfNull(asset); callback(checksum, (T)asset, arg); } + + return ValueTask.CompletedTask; } } diff --git a/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs b/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs index df9c1c71a7edd..278245aeb2a8e 100644 --- a/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs +++ b/src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs @@ -118,7 +118,7 @@ public event EventHandler? AvailabilityChanged public ValueTask GetPipeAsync(ServiceMoniker serviceMoniker, ServiceActivationOptions options, CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable(); - public async ValueTask GetProxyAsync(ServiceRpcDescriptor descriptor, ServiceActivationOptions options, CancellationToken cancellationToken) where T : class + public ValueTask GetProxyAsync(ServiceRpcDescriptor descriptor, ServiceActivationOptions options, CancellationToken cancellationToken) where T : class { var pipePair = FullDuplexStream.CreatePipePair(); @@ -145,7 +145,7 @@ public event EventHandler? AvailabilityChanged clientConnection.StartListening(); - return (T?)clientConnection.ConstructRpcClient(); + return ValueTask.FromResult((T?)clientConnection.ConstructRpcClient()); } } diff --git a/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs b/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs index b893e6e3240c1..cae4c5c4b814c 100644 --- a/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs +++ b/src/Workspaces/CoreTestUtilities/Remote/InProcRemoteHostClientProvider.cs @@ -109,8 +109,8 @@ public void Dispose() } } - public async Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) - => _lazyClient.Value; + public Task TryGetRemoteHostClientAsync(CancellationToken cancellationToken) + => Task.FromResult(_lazyClient.Value); public Task WaitForClientCreationAsync(CancellationToken cancellationToken) => _clientCreationSource.Task.WithCancellation(cancellationToken); diff --git a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs index c139e61f22a2b..61a2882c96efa 100644 --- a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs +++ b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesFiles.cs @@ -27,14 +27,14 @@ public TestDynamicFileInfoProviderThatProducesFiles() event EventHandler IDynamicFileInfoProvider.Updated { add { } remove { } } - public async Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) + public Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) { - return new DynamicFileInfo( + return Task.FromResult(new DynamicFileInfo( filePath + ".fromdynamicfile", SourceCodeKind.Regular, new TestTextLoader(GetDynamicFileText(filePath)), designTimeOnly: false, - new TestDocumentServiceProvider()); + new TestDocumentServiceProvider())); } public static string GetDynamicFileText(string filePath) diff --git a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs index bfe3732cf5f09..0c1f47e007511 100644 --- a/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs +++ b/src/Workspaces/CoreTestUtilities/TestDynamicFileInfoProviderThatProducesNoFiles.cs @@ -27,8 +27,8 @@ public TestDynamicFileInfoProviderThatProducesNoFiles() event EventHandler IDynamicFileInfoProvider.Updated { add { } remove { } } - public async Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) - => null; + public Task GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) + => SpecializedTasks.Null(); public Task RemoveDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken) => Task.CompletedTask; diff --git a/src/Workspaces/CoreTestUtilities/TestTextLoader.cs b/src/Workspaces/CoreTestUtilities/TestTextLoader.cs index 90f522f286406..bab25b699b7fe 100644 --- a/src/Workspaces/CoreTestUtilities/TestTextLoader.cs +++ b/src/Workspaces/CoreTestUtilities/TestTextLoader.cs @@ -18,6 +18,6 @@ public TestTextLoader(string text = "test", SourceHashAlgorithm checksumAlgorith _textAndVersion = TextAndVersion.Create(SourceText.From(text, encoding: null, checksumAlgorithm), VersionStamp.Create()); } - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => _textAndVersion; + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(_textAndVersion); } diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs index 632f8eef0814c..4eee565e43341 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestHostDocument.cs @@ -186,8 +186,8 @@ internal TestDocumentLoader(TestHostDocument hostDocument, string text) internal override string? FilePath => _hostDocument.FilePath; - public override async Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => TextAndVersion.Create(SourceText.From(_text, encoding: Encoding.UTF8, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath); + public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) + => Task.FromResult(TextAndVersion.Create(SourceText.From(_text, encoding: Encoding.UTF8, options.ChecksumAlgorithm), VersionStamp.Create(), _hostDocument.FilePath)); } public TextLoader Loader => _loader; diff --git a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs index 6b52acce18858..308073548de5d 100644 --- a/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs +++ b/src/Workspaces/CoreTestUtilities/Workspaces/TestWorkspace`1.cs @@ -468,13 +468,14 @@ internal override void SetDocumentContext(DocumentId documentId) /// Overriding base impl so that when we close a document it goes back to the initial state when the test /// workspace was loaded, throwing away any changes made to the open version. /// - internal override async ValueTask TryOnDocumentClosedAsync(DocumentId documentId, CancellationToken cancellationToken) + internal override ValueTask TryOnDocumentClosedAsync(DocumentId documentId, CancellationToken cancellationToken) { var testDocument = this.GetTestDocument(documentId); Contract.ThrowIfNull(testDocument); Contract.ThrowIfTrue(testDocument.IsSourceGenerated); this.OnDocumentClosedEx(documentId, testDocument.Loader, requireDocumentPresentAndOpen: false); + return ValueTask.CompletedTask; } public override void CloseDocument(DocumentId documentId) diff --git a/src/Workspaces/MSBuild/BuildHost/BuildHost.cs b/src/Workspaces/MSBuild/BuildHost/BuildHost.cs index 2daff24db28a3..ec31e8096e6b8 100644 --- a/src/Workspaces/MSBuild/BuildHost/BuildHost.cs +++ b/src/Workspaces/MSBuild/BuildHost/BuildHost.cs @@ -238,10 +238,12 @@ private int LoadProjectCore(string projectFilePath, string projectContent, strin return _buildManager.TryGetOutputFilePathAsync(projectFilePath, cancellationToken); } - public async Task ShutdownAsync() + public Task ShutdownAsync() { _buildManager?.EndBatchBuild(); _server.Shutdown(); + + return Task.CompletedTask; } } diff --git a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs index f6239c516b3f1..4f92c9fea189b 100644 --- a/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs +++ b/src/Workspaces/MSBuild/Core/MSBuild/MSBuildProjectLoader.Worker.cs @@ -264,7 +264,7 @@ private async Task> LoadProjectInfosFromPathAsync( return results; } - private async Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo, ProjectId projectId, bool addDiscriminator, CancellationToken cancellationToken) + private Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo, ProjectId projectId, bool addDiscriminator, CancellationToken cancellationToken) { var language = projectFileInfo.Language; var projectPath = projectFileInfo.FilePath; @@ -287,7 +287,8 @@ private async Task CreateProjectInfoAsync(ProjectFileInfo projectFi var compilationOptions = GetLanguageService(language) ?.GetDefaultCompilationOptions(); - return ProjectInfo.Create( + return Task.FromResult( + ProjectInfo.Create( new ProjectInfo.ProjectAttributes( projectId, version, @@ -300,10 +301,10 @@ private async Task CreateProjectInfoAsync(ProjectFileInfo projectFi outputRefFilePath: projectFileInfo.OutputRefFilePath, filePath: projectPath), compilationOptions: compilationOptions, - parseOptions: parseOptions); + parseOptions: parseOptions)); } - return await DoOperationAndReportProgressAsync(ProjectLoadOperation.Resolve, projectPath, projectFileInfo.TargetFramework, async () => + return DoOperationAndReportProgressAsync(ProjectLoadOperation.Resolve, projectPath, projectFileInfo.TargetFramework, async () => { var projectDirectory = Path.GetDirectoryName(projectPath); @@ -380,7 +381,7 @@ private async Task CreateProjectInfoAsync(ProjectFileInfo projectFi hostObjectType: null) .WithDefaultNamespace(projectFileInfo.DefaultNamespace) .WithAnalyzerConfigDocuments(analyzerConfigDocuments); - }).ConfigureAwait(false); + }); } private static string GetAssemblyNameFromProjectPath(string? projectFilePath) diff --git a/src/Workspaces/MSBuild/Test/RpcTests.cs b/src/Workspaces/MSBuild/Test/RpcTests.cs index 04ef68a8171ab..a42b14094941b 100644 --- a/src/Workspaces/MSBuild/Test/RpcTests.cs +++ b/src/Workspaces/MSBuild/Test/RpcTests.cs @@ -235,12 +235,12 @@ public async Task RequestThatClosesServerDoesNotThrow() private sealed class ObjectWithVoidMethod { public string? Message; public void SetMessage(string message) { Message = message; } } private sealed class ObjectWithAsyncHelloMethods { - public async Task HelloAsync(string name) { return "Hello " + name; } - public async Task HelloWithCancellationAsync(string name, CancellationToken cancellationToken) + public Task HelloAsync(string name) { return Task.FromResult("Hello " + name); } + public Task HelloWithCancellationAsync(string name, CancellationToken cancellationToken) { // We never expect to be given a cancellable cancellation token over RPC Assert.False(cancellationToken.CanBeCanceled); - return "Hello " + name; + return Task.FromResult("Hello " + name); } } diff --git a/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs b/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs index df628047d59d6..8897519edc0b0 100644 --- a/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs +++ b/src/Workspaces/Remote/Core/EditAndContinue/ManagedHotReloadLanguageService.cs @@ -35,12 +35,12 @@ private sealed class PdbMatchingSourceTextProvider : IPdbMatchingSourceTextProvi public static readonly PdbMatchingSourceTextProvider Instance = new(); // Returning null will check the file on disk: - public async ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) - => null; + public ValueTask TryGetMatchingSourceTextAsync(string filePath, ImmutableArray requiredChecksum, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken) + => ValueTask.FromResult(null); } private static readonly ActiveStatementSpanProvider s_emptyActiveStatementProvider = - async (_, _, _) => ImmutableArray.Empty; + (_, _, _) => ValueTask.FromResult(ImmutableArray.Empty); private readonly ManagedHotReloadServiceProxy _debuggerService = new(serviceBrokerProvider.ServiceBroker); private readonly SolutionSnapshotProviderProxy _solutionSnapshotProvider = new(serviceBrokerProvider.ServiceBroker); @@ -99,11 +99,11 @@ public async ValueTask StartSessionAsync(CancellationToken cancellationToken) } } - private async ValueTask BreakStateOrCapabilitiesChangedAsync(bool? inBreakState, CancellationToken cancellationToken) + private ValueTask BreakStateOrCapabilitiesChangedAsync(bool? inBreakState, CancellationToken cancellationToken) { if (_disabled) { - return; + return ValueTask.CompletedTask; } try @@ -115,6 +115,8 @@ private async ValueTask BreakStateOrCapabilitiesChangedAsync(bool? inBreakState, { Disable(); } + + return ValueTask.CompletedTask; } public ValueTask EnterBreakStateAsync(CancellationToken cancellationToken) @@ -126,11 +128,11 @@ public ValueTask ExitBreakStateAsync(CancellationToken cancellationToken) public ValueTask OnCapabilitiesChangedAsync(CancellationToken cancellationToken) => BreakStateOrCapabilitiesChangedAsync(inBreakState: null, cancellationToken); - public async ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) + public ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { - return; + return ValueTask.CompletedTask; } try @@ -147,17 +149,19 @@ public async ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { Disable(); } + + return ValueTask.CompletedTask; } [Obsolete] public ValueTask UpdateBaselinesAsync(ImmutableArray projectPaths, CancellationToken cancellationToken) => throw new NotImplementedException(); - public async ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) + public ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { - return; + return ValueTask.CompletedTask; } try @@ -171,13 +175,15 @@ public async ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { Disable(); } + + return ValueTask.CompletedTask; } - public async ValueTask EndSessionAsync(CancellationToken cancellationToken) + public ValueTask EndSessionAsync(CancellationToken cancellationToken) { if (_disabled) { - return; + return ValueTask.CompletedTask; } try @@ -194,6 +200,8 @@ public async ValueTask EndSessionAsync(CancellationToken cancellationToken) { Disable(); } + + return ValueTask.CompletedTask; } /// diff --git a/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs b/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs index aaef097cfe118..934c7a12b76fb 100644 --- a/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs +++ b/src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs @@ -33,8 +33,8 @@ internal sealed class CSharpDocumentDifferenceService() : RemoteDocumentDifferen [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] internal sealed class VisualBasicDocumentDifferenceService() : RemoteDocumentDifferenceService; - public async Task GetChangedMemberAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) + public Task GetChangedMemberAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { - return null; + return SpecializedTasks.Null(); } } diff --git a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs index 2fd6afe32773e..f6603fc983db9 100644 --- a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs +++ b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs @@ -58,7 +58,7 @@ await RunWithSolutionAsync( assetProvider, solutionChecksum, updatePrimaryBranch: true, - implementation: static async _ => false, + implementation: static _ => ValueTask.FromResult(false), cancellationToken).ConfigureAwait(false); } @@ -340,7 +340,7 @@ public async ValueTask GetSolutionAsync( CancellationToken cancellationToken) { var (solution, _) = await _remoteWorkspace.RunWithSolutionAsync( - assetProvider, solutionChecksum, updatePrimaryBranch, async _ => false, cancellationToken).ConfigureAwait(false); + assetProvider, solutionChecksum, updatePrimaryBranch, _ => ValueTask.FromResult(false), cancellationToken).ConfigureAwait(false); return solution; } } diff --git a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs index 2625afbdbd48c..48bcac81ede3e 100644 --- a/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs +++ b/src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs @@ -94,7 +94,7 @@ public async ValueTask GetSolutionAsync(ServiceBrokerClient client, Ch var (solution, _) = await workspace.RunWithSolutionAsync( assetProvider, solutionChecksum, - static async _ => false, + static _ => ValueTask.FromResult(false), cancellationToken).ConfigureAwait(false); return solution; diff --git a/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs b/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs index 26bf388a88ef1..d96419e82b0d3 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/AssetSynchronization/RemoteAssetSynchronizationService.cs @@ -46,10 +46,11 @@ public ValueTask SynchronizePrimaryWorkspaceAsync(Checksum solutionChecksum, Can }, cancellationToken); } - public async ValueTask SynchronizeActiveDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken) + public ValueTask SynchronizeActiveDocumentAsync(DocumentId? documentId, CancellationToken cancellationToken) { var documentTrackingService = GetWorkspace().Services.GetRequiredService() as RemoteDocumentTrackingService; documentTrackingService?.SetActiveDocument(documentId); + return ValueTask.CompletedTask; } public ValueTask SynchronizeTextChangesAsync( diff --git a/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs b/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs index c292ddb17447e..e58ac47a6bb35 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/AsynchronousOperationListener/RemoteAsynchronousOperationListenerService.cs @@ -25,21 +25,22 @@ public RemoteAsynchronousOperationListenerService(in ServiceConstructionArgument public ValueTask EnableAsync(bool enable, bool diagnostics, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { AsynchronousOperationListenerProvider.Enable(enable, diagnostics); + return default; }, cancellationToken); } public ValueTask IsCompletedAsync(ImmutableArray featureNames, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { var workspace = GetWorkspace(); var exportProvider = workspace.Services.SolutionServices.ExportProvider; var listenerProvider = exportProvider.GetExports().Single().Value; - return !listenerProvider.HasPendingWaiter([.. featureNames]); + return new ValueTask(!listenerProvider.HasPendingWaiter([.. featureNames])); }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs b/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs index 2f810a4115815..a79cd330b7dd1 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs @@ -44,7 +44,7 @@ protected virtual TService CreateService( object? clientRpcTarget) => CreateService(arguments); - public async Task CreateAsync( + public Task CreateAsync( Stream stream, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, @@ -67,11 +67,11 @@ public async Task CreateAsync( CultureInfo.DefaultThreadCurrentCulture = serviceActivationOptions.ClientCulture; } - return (object)Create( + return Task.FromResult((object)Create( stream.UsePipe(), hostProvidedServices, serviceActivationOptions, - serviceBroker); + serviceBroker)); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { diff --git a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs index c36ad6e040758..f7a9c14a22483 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/RemoteDiagnosticAnalyzerService.cs @@ -121,7 +121,7 @@ public ValueTask> GetSourceGeneratorDiagnosticsAs public ValueTask ReportAnalyzerPerformanceAsync(ImmutableArray snapshot, int unitCount, bool forSpanAnalysis, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { using (RoslynLogger.LogBlock(FunctionId.CodeAnalysisService_ReportAnalyzerPerformance, cancellationToken)) { @@ -130,11 +130,13 @@ public ValueTask ReportAnalyzerPerformanceAsync(ImmutableArray(); if (service == null) { - return; + return default; } service.AddSnapshot(snapshot, unitCount, forSpanAnalysis); } + + return default; }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs b/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs index 0900f79dc119d..a76ae37045002 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs @@ -82,13 +82,13 @@ private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServ /// public ValueTask StartDebuggingSessionAsync(Checksum solutionChecksum, RemoteServiceCallbackId callbackId, bool reportDiagnostics, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, async solution => + return RunServiceAsync(solutionChecksum, solution => { var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId); var sourceTextProvider = new SourceTextProvider(_callback, callbackId); var sessionId = GetService().StartDebuggingSession(solution, debuggerService, sourceTextProvider, reportDiagnostics); - return sessionId; + return ValueTask.FromResult(sessionId); }, cancellationToken); } @@ -97,9 +97,10 @@ public ValueTask StartDebuggingSessionAsync(Checksum solutio /// public ValueTask BreakStateOrCapabilitiesChangedAsync(DebuggingSessionId sessionId, bool? inBreakState, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { GetService().BreakStateOrCapabilitiesChanged(sessionId, inBreakState); + return ValueTask.CompletedTask; }, cancellationToken); } @@ -108,9 +109,10 @@ public ValueTask BreakStateOrCapabilitiesChangedAsync(DebuggingSessionId session /// public ValueTask EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { GetService().EndDebuggingSession(sessionId); + return ValueTask.CompletedTask; }, cancellationToken); } @@ -161,9 +163,10 @@ public ValueTask> GetDocumentDiagnosticsAsync(Che /// public ValueTask CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { GetService().CommitSolutionUpdate(sessionId); + return ValueTask.CompletedTask; }, cancellationToken); } @@ -172,9 +175,10 @@ public ValueTask CommitSolutionUpdateAsync(DebuggingSessionId sessionId, Cancell /// public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { GetService().DiscardSolutionUpdate(sessionId); + return default; }, cancellationToken); } @@ -206,9 +210,10 @@ public ValueTask> GetAdjustedActiveStatement /// public ValueTask SetFileLoggingDirectoryAsync(string? logDirectory, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { GetService().SetFileLoggingDirectory(logDirectory); + return default; }, cancellationToken); } } diff --git a/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs b/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs index 8e0bf1dd7cafd..679501bc4974c 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.cs @@ -61,10 +61,11 @@ public ValueTask> GetUnimported public ValueTask WarmUpCacheAsync(Checksum solutionChecksum, ProjectId projectId, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, async solution => + return RunServiceAsync(solutionChecksum, solution => { var project = solution.GetRequiredProject(projectId); ExtensionMemberImportCompletionHelper.WarmUpCacheInCurrentProcess(project); + return ValueTask.CompletedTask; }, cancellationToken); } } diff --git a/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs b/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs index 07e859ba90e8e..f1be8f34cafab 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/Initialization/RemoteInitializationService.cs @@ -28,12 +28,12 @@ protected override IRemoteInitializationService CreateService(in ServiceConstruc try { - var processId = await RunServiceAsync(async cancellationToken => + var processId = await RunServiceAsync(cancellationToken => { var service = (RemoteWorkspaceConfigurationService)GetWorkspaceServices().GetRequiredService(); service.InitializeOptions(options); - return Process.GetCurrentProcess().Id; + return ValueTask.FromResult(Process.GetCurrentProcess().Id); }, cancellationToken).ConfigureAwait(false); return (processId, errorMessage); diff --git a/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs b/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs index 7d4739b255a24..320060bf361a2 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/LegacySolutionEvents/RemoteLegacySolutionEventsAggregationService.cs @@ -24,11 +24,11 @@ public RemoteLegacySolutionEventsAggregationService(in ServiceConstructionArgume public ValueTask ShouldReportChangesAsync(CancellationToken cancellationToken) { return RunServiceImplAsync( - async cancellationToken => + cancellationToken => { var services = this.GetWorkspaceServices(); var aggregationService = services.GetRequiredService(); - return aggregationService.ShouldReportChanges(services); + return new ValueTask(aggregationService.ShouldReportChanges(services)); }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs index 0d5a5c15b9248..3f4230e85e358 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs @@ -43,10 +43,10 @@ public PerformanceReporter( _diagnosticAnalyzerPerformanceTracker.SnapshotAdded += (_, _) => _workQueue.AddWork(); } - private async ValueTask ProcessWorkAsync(CancellationToken cancellationToken) + private ValueTask ProcessWorkAsync(CancellationToken cancellationToken) { if (!_telemetrySession.IsOptedIn) - return; + return ValueTask.CompletedTask; using (RoslynLogger.LogBlock(FunctionId.Diagnostics_GeneratePerformaceReport, cancellationToken)) { @@ -70,6 +70,8 @@ private async ValueTask ProcessWorkAsync(CancellationToken cancellationToken) } } } + + return ValueTask.CompletedTask; } } } diff --git a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs index ab9572daa9c4c..bb9112646ca6e 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.cs @@ -39,7 +39,7 @@ protected override IRemoteProcessTelemetryService CreateService(in ServiceConstr /// public ValueTask InitializeTelemetrySessionAsync(int hostProcessId, string serializedSession, bool logDelta, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { var services = GetWorkspace().Services; @@ -65,6 +65,8 @@ public ValueTask InitializeTelemetrySessionAsync(int hostProcessId, string seria // We know in the remote layer that this type must exist. _performanceReporter = new PerformanceReporter(telemetrySession, diagnosticAnalyzerPerformanceTracker, _shutdownCancellationSource.Token); } + + return ValueTask.CompletedTask; }, cancellationToken); } @@ -73,7 +75,7 @@ public ValueTask InitializeTelemetrySessionAsync(int hostProcessId, string seria /// public ValueTask EnableLoggingAsync(ImmutableArray loggerTypeNames, ImmutableArray functionIds, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { var functionIdsSet = new HashSet(functionIds); bool logChecker(FunctionId id) => functionIdsSet.Contains(id); @@ -81,6 +83,8 @@ public ValueTask EnableLoggingAsync(ImmutableArray loggerTypeNames, Immu // we only support 2 types of loggers SetRoslynLogger(loggerTypeNames, () => new EtwLogger(logChecker)); SetRoslynLogger(loggerTypeNames, () => new TraceLogger(logChecker)); + + return ValueTask.CompletedTask; }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs b/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs index 96506aa72e8a1..84ea91adddd5d 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/SemanticSearch/RemoteSemanticSearchService.cs @@ -93,13 +93,13 @@ public ValueTask CompileQueryAsync( string referenceAssembliesDir, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { var services = GetWorkspaceServices(); var service = GetRequiredService(); var result = service.CompileQuery(services, query, targetLanguage, referenceAssembliesDir, TraceLogger, cancellationToken); - return result; + return ValueTask.FromResult(result); }, cancellationToken); } @@ -108,10 +108,12 @@ public ValueTask CompileQueryAsync( /// public ValueTask DiscardQueryAsync(CompiledQueryId queryId, CancellationToken cancellationToken) { - return RunServiceAsync(async cancellationToken => + return RunServiceAsync(cancellationToken => { var service = GetRequiredService(); service.DiscardQuery(queryId); + + return default; }, cancellationToken); } diff --git a/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs b/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs index 2a48e1386c70f..ecc5845487b8e 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/SourceGeneration/RemoteSourceGenerationService.cs @@ -153,13 +153,13 @@ public ValueTask> GetSourceGeneratorIden string analyzerReferenceFullPath, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, async solution => + return RunServiceAsync(solutionChecksum, solution => { var project = solution.GetRequiredProject(projectId); var analyzerReference = project.AnalyzerReferences .First(r => r.FullPath == analyzerReferenceFullPath); - return SourceGeneratorIdentity.GetIdentities(analyzerReference, project.Language); + return ValueTask.FromResult(SourceGeneratorIdentity.GetIdentities(analyzerReference, project.Language)); }, cancellationToken); } @@ -169,19 +169,19 @@ public ValueTask HasAnalyzersOrSourceGeneratorsAsync( string analyzerReferenceFullPath, CancellationToken cancellationToken) { - return RunServiceAsync(solutionChecksum, async solution => + return RunServiceAsync(solutionChecksum, solution => { var project = solution.GetRequiredProject(projectId); var analyzerReference = project.AnalyzerReferences .First(r => r.FullPath == analyzerReferenceFullPath); - return analyzerReference.HasAnalyzersOrSourceGenerators(project.Language); + return ValueTask.FromResult(analyzerReference.HasAnalyzersOrSourceGenerators(project.Language)); }, cancellationToken); } - public async ValueTask>> FetchAndClearTelemetryKeyValuePairsAsync(CancellationToken _) + public ValueTask>> FetchAndClearTelemetryKeyValuePairsAsync(CancellationToken _) { var workspaceService = GetWorkspaceServices().GetRequiredService(); - return workspaceService.FetchKeysAndAndClear(); + return ValueTask.FromResult(workspaceService.FetchKeysAndAndClear()); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs index 47c2acd96f004..43cfec9304f24 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy.cs @@ -21,7 +21,7 @@ public static AsyncLazy Create(Func public static AsyncLazy Create(Func synchronousComputeFunction, TArg arg) => Create( - asynchronousComputeFunction: static async (outerArg, cancellationToken) => outerArg.synchronousComputeFunction(outerArg.arg, cancellationToken), + asynchronousComputeFunction: static (outerArg, cancellationToken) => Task.FromResult(outerArg.synchronousComputeFunction(outerArg.arg, cancellationToken)), synchronousComputeFunction: static (outerArg, cancellationToken) => outerArg.synchronousComputeFunction(outerArg.arg, cancellationToken), (synchronousComputeFunction, arg)); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs index 01e5f7a2833ff..895e26313b279 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs @@ -182,16 +182,17 @@ public void Dispose() instanceToDispose?.Dispose(); } - public async ValueTask DisposeAsync() + public ValueTask DisposeAsync() { var instanceToDispose = DisposeImpl(); if (instanceToDispose == null) - return; + return ValueTask.CompletedTask; if (instanceToDispose is IAsyncDisposable asyncDisposable) - await asyncDisposable.DisposeAsync().ConfigureAwait(false); + return asyncDisposable.DisposeAsync(); instanceToDispose.Dispose(); + return ValueTask.CompletedTask; } private T? DisposeImpl() diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs index 424ec08eda861..f612474882770 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Editing/CSharpImportAdder.cs @@ -133,7 +133,7 @@ public async Task AddPotentiallyConflictingImportsAsync(SyntaxNode container, Ha await ProducerConsumer.RunParallelAsync( source: nodes, - produceItems: static async (node, onItemsFound, args, cancellationToken) => + produceItems: static (node, onItemsFound, args, cancellationToken) => { var (self, containsAnonymousMethods, _) = args; if (node is SimpleNameSyntax nameSyntaxNode) @@ -142,6 +142,8 @@ await ProducerConsumer.RunParallelAsync( self.ProduceConflicts(memberAccessExpressionNode, containsAnonymousMethods, onItemsFound, cancellationToken); else throw ExceptionUtilities.Unreachable(); + + return Task.CompletedTask; }, consumeItems: static async (items, args, cancellationToken) => { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs index f334a07d3e652..e8b6f1d6bbe88 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/ForkingSyntaxEditorBasedCodeFixProvider.cs @@ -45,10 +45,11 @@ protected sealed override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnost // Never try to fix the secondary diagnostics that were produced just to fade out code. => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var (title, equivalenceKey) = GetTitleAndEquivalenceKey(context); RegisterCodeFix(context, title, equivalenceKey); + return Task.CompletedTask; } protected sealed override async Task FixAllAsync( diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs index c16a605f8bf08..80d4f64262154 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/MultiProjectSafeFixAllProvider.cs @@ -44,7 +44,7 @@ internal abstract class MultiProjectSafeFixAllProvider : FixAllProvider return CodeAction.Create( fixAllContext.GetDefaultFixAllTitle(), - async (_, _) => updatedSolution, + (_, _) => Task.FromResult(updatedSolution), equivalenceKey: null, CodeActionPriority.Default #if WORKSPACE diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs index f388d23ca2a00..40f6a6abce8d6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs @@ -12,12 +12,12 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions; internal static partial class TextDocumentExtensions { #if !WORKSPACE - public static async ValueTask GetValueTextAsync(this TextDocument document, CancellationToken cancellationToken) + public static ValueTask GetValueTextAsync(this TextDocument document, CancellationToken cancellationToken) { if (document.TryGetText(out var text)) - return text; + return ValueTask.FromResult(text); - return await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + return new ValueTask(document.GetTextAsync(cancellationToken)); } #endif diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs index 79192aaf593cb..acf7fef59183e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Options/OptionsProvider.cs @@ -20,8 +20,8 @@ internal static class OptionsProvider { private sealed class OptionsReaderProvider(IOptionsReader optionsReader, Func reader) : OptionsProvider { - public async ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => reader(optionsReader, languageServices.Language); + public ValueTask GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) + => ValueTask.FromResult(reader(optionsReader, languageServices.Language)); } public static OptionsProvider GetProvider(this IOptionsReader optionsReader, Func reader) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs index 4312b86087ff0..c6cee45a9fc67 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/SymbolFinder/SymbolFinderInternal.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.FindSymbols; internal static class SymbolFinderInternal { /// - internal static async ValueTask FindSourceDefinitionAsync( + internal static ValueTask FindSourceDefinitionAsync( ISymbol? symbol, Solution solution, CancellationToken cancellationToken) { if (symbol != null) @@ -32,11 +32,11 @@ internal static class SymbolFinderInternal case SymbolKind.Property: case SymbolKind.TypeParameter: case SymbolKind.Namespace: - return await FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken).ConfigureAwait(false); + return FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken); } } - return null; + return new ValueTask(result: null); } private static async ValueTask FindSourceDefinitionWorkerAsync( diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs index fbe93246ae201..cc5811efb3aa5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs @@ -14,6 +14,6 @@ internal abstract class AsyncSymbolVisitor : SymbolVisitor Visit(ISymbol? symbol) => symbol?.Accept(this) ?? ValueTask.FromResult(DefaultResult); - public override async ValueTask DefaultVisit(ISymbol symbol) - => DefaultResult; + public override ValueTask DefaultVisit(ISymbol symbol) + => ValueTask.FromResult(DefaultResult); } diff --git a/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs b/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs index 59cabddbb16ce..d2b9df631ad53 100644 --- a/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs +++ b/src/Workspaces/TestAnalyzerReference/NonSourceFileRefactoring.cs @@ -18,7 +18,7 @@ namespace Microsoft.CodeAnalysis.CodeRefactorings; [Shared] public sealed class NonSourceFileRefactoring : CodeRefactoringProvider { - public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { context.RegisterRefactoring(CodeAction.Create(nameof(NonSourceFileRefactoring), createChangedSolution: async ct => @@ -30,6 +30,8 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte return document.Project.Solution.WithAdditionalDocumentText(document.Id, newText); return document.Project.Solution.WithAnalyzerConfigDocumentText(document.Id, newText); })); + + return Task.CompletedTask; } }