diff --git a/pkg/analysis_server/benchmark/perf/dart_analyze.dart b/pkg/analysis_server/benchmark/perf/dart_analyze.dart index 031fafb74b5..3d20f0cb088 100644 --- a/pkg/analysis_server/benchmark/perf/dart_analyze.dart +++ b/pkg/analysis_server/benchmark/perf/dart_analyze.dart @@ -139,18 +139,17 @@ class CmdLineSeveralProjectsBenchmark extends AbstractCmdLineBenchmark { String get workingDir => packageRoot; @override - List analyzeWhat(bool quick) => - quick - ? ['meta'] - : [ - 'analysis_server', - 'analysis_server_client', - 'analyzer', - 'analyzer_cli', - 'analyzer_plugin', - 'analyzer_utilities', - '_fe_analyzer_shared', - ]; + List analyzeWhat(bool quick) => quick + ? ['meta'] + : [ + 'analysis_server', + 'analysis_server_client', + 'analyzer', + 'analyzer_cli', + 'analyzer_plugin', + 'analyzer_utilities', + '_fe_analyzer_shared', + ]; } class CmdLineSmallFileBenchmark extends AbstractCmdLineBenchmark { diff --git a/pkg/analysis_server/integration_test/analysis/get_reachable_sources_test.dart b/pkg/analysis_server/integration_test/analysis/get_reachable_sources_test.dart index 6d63d63c6f3..e6230d7d51b 100644 --- a/pkg/analysis_server/integration_test/analysis/get_reachable_sources_test.dart +++ b/pkg/analysis_server/integration_test/analysis/get_reachable_sources_test.dart @@ -34,8 +34,8 @@ class Bar { await analysisFinished; var result = - // ignore: deprecated_member_use_from_same_package - await sendAnalysisGetReachableSources(pathname); + // ignore: deprecated_member_use_from_same_package + await sendAnalysisGetReachableSources(pathname); var sources = result.sources; var keys = sources.keys.toList(); var url = File(pathname).uri.toString(); diff --git a/pkg/analysis_server/integration_test/analysis/occurrences_test.dart b/pkg/analysis_server/integration_test/analysis/occurrences_test.dart index 506cd156c87..f850771900a 100644 --- a/pkg/analysis_server/integration_test/analysis/occurrences_test.dart +++ b/pkg/analysis_server/integration_test/analysis/occurrences_test.dart @@ -52,10 +52,9 @@ void f() { } void check(String elementName, Iterable expectedOccurrences) { - var expectedOffsets = - expectedOccurrences - .map((String substring) => text.indexOf(substring)) - .toSet(); + var expectedOffsets = expectedOccurrences + .map((String substring) => text.indexOf(substring)) + .toSet(); var foundOffsets = findOffsets(elementName); expect(foundOffsets, equals(expectedOffsets)); } @@ -102,10 +101,9 @@ void f() { } void check(String elementName, Iterable expectedOccurrences) { - var expectedOffsets = - expectedOccurrences - .map((String substring) => text.indexOf(substring)) - .toSet(); + var expectedOffsets = expectedOccurrences + .map((String substring) => text.indexOf(substring)) + .toSet(); var foundOffsets = findOffsets(elementName); expect(foundOffsets, equals(expectedOffsets)); } @@ -156,10 +154,9 @@ void f() { } void check(String elementName, Iterable expectedOccurrences) { - var expectedOffsets = - expectedOccurrences - .map((String substring) => text.indexOf(substring)) - .toSet(); + var expectedOffsets = expectedOccurrences + .map((String substring) => text.indexOf(substring)) + .toSet(); var foundOffsets = findOffsets(elementName); expect(foundOffsets, equals(expectedOffsets)); } @@ -212,10 +209,9 @@ void f() { } void check(String elementName, Iterable expectedOccurrences) { - var expectedOffsets = - expectedOccurrences - .map((String substring) => text.indexOf(substring)) - .toSet(); + var expectedOffsets = expectedOccurrences + .map((String substring) => text.indexOf(substring)) + .toSet(); var foundOffsets = findOffsets(elementName); expect(foundOffsets, equals(expectedOffsets)); } diff --git a/pkg/analysis_server/integration_test/analysis/update_content_list_test.dart b/pkg/analysis_server/integration_test/analysis/update_content_list_test.dart index 982a73051d4..1b7f70e8f32 100644 --- a/pkg/analysis_server/integration_test/analysis/update_content_list_test.dart +++ b/pkg/analysis_server/integration_test/analysis/update_content_list_test.dart @@ -37,11 +37,10 @@ void f() { // order in which they appear in the file. If these edits are applied in // the wrong order, some of the quotation marks will be in the wrong // places, and there will still be errors. - var edits = - '"' - .allMatches(goodText) - .map((Match match) => SourceEdit(match.start, 0, '"')) - .toList(); + var edits = '"' + .allMatches(goodText) + .map((Match match) => SourceEdit(match.start, 0, '"')) + .toList(); await sendAnalysisUpdateContent({pathname: ChangeContentOverlay(edits)}); await analysisFinished; // There should be no errors now, assuming that quotation marks have been diff --git a/pkg/analysis_server/integration_test/coverage_test.dart b/pkg/analysis_server/integration_test/coverage_test.dart index 7b3a5255fff..f9dea1f59f2 100644 --- a/pkg/analysis_server/integration_test/coverage_test.dart +++ b/pkg/analysis_server/integration_test/coverage_test.dart @@ -23,35 +23,29 @@ void main() { var lines = coverageFile.readAsLinesSync(); // ## server domain - var coveredDomains = - lines - .where((line) => line.startsWith('## ') && line.endsWith(' domain')) - .map( - (line) => - line - .substring('##'.length, line.length - 'domain'.length) - .trim(), - ) - .toSet(); + var coveredDomains = lines + .where((line) => line.startsWith('## ') && line.endsWith(' domain')) + .map( + (line) => + line.substring('##'.length, line.length - 'domain'.length).trim(), + ) + .toSet(); // Remove any ' (test failed)' suffixes. - lines = - lines.map((String line) { - var index = line.indexOf('('); - return index != -1 ? line.substring(0, index).trim() : line; - }).toList(); + lines = lines.map((String line) { + var index = line.indexOf('('); + return index != -1 ? line.substring(0, index).trim() : line; + }).toList(); // - [ ] server.getVersion - var allMembers = - lines - .where((line) => line.startsWith('- ')) - .map((line) => line.substring('- [ ]'.length).trim()) - .toSet(); - var coveredMembers = - lines - .where((line) => line.startsWith('- [x]')) - .map((line) => line.substring('- [x]'.length).trim()) - .toSet(); + var allMembers = lines + .where((line) => line.startsWith('- ')) + .map((line) => line.substring('- [ ]'.length).trim()) + .toSet(); + var coveredMembers = lines + .where((line) => line.startsWith('- [x]')) + .map((line) => line.substring('- [x]'.length).trim()) + .toSet(); // generate domain tests for (var domain in api.domains) { @@ -85,10 +79,9 @@ void main() { expect( fileExists, isMarkedAsCovered, - reason: - isMarkedAsCovered - ? '$testName marked as covered but has no test at $testPath' - : '$testName marked as not covered has test at $testPath', + reason: isMarkedAsCovered + ? '$testName marked as covered but has no test at $testPath' + : '$testName marked as not covered has test at $testPath', ); }); } diff --git a/pkg/analysis_server/integration_test/lsp_server/integration_tests.dart b/pkg/analysis_server/integration_test/lsp_server/integration_tests.dart index d6c29df7223..77dea52e8eb 100644 --- a/pkg/analysis_server/integration_test/lsp_server/integration_tests.dart +++ b/pkg/analysis_server/integration_test/lsp_server/integration_tests.dart @@ -139,10 +139,9 @@ abstract class AbstractLspAnalysisServerIntegrationTest @mustCallSuper Future setUp() async { // Set up temporary folder for the test. - projectFolderPath = - Directory.systemTemp - .createTempSync('analysisServer_test_integration_lspProject') - .resolveSymbolicLinksSync(); + projectFolderPath = Directory.systemTemp + .createTempSync('analysisServer_test_integration_lspProject') + .resolveSymbolicLinksSync(); _temporaryFolders.add(projectFolderPath); newFolder(projectFolderPath); newFolder(path.join(projectFolderPath, 'lib')); diff --git a/pkg/analysis_server/integration_test/server/blaze_changes_test.dart b/pkg/analysis_server/integration_test/server/blaze_changes_test.dart index ccbba182c6c..76914677af4 100644 --- a/pkg/analysis_server/integration_test/server/blaze_changes_test.dart +++ b/pkg/analysis_server/integration_test/server/blaze_changes_test.dart @@ -56,12 +56,11 @@ class BlazeChangesTest extends AbstractAnalysisServerIntegrationTest { await super.setUp(); oldSourceDirectory = sourceDirectory; - tmpPath = - Directory( - Directory.systemTemp - .createTempSync('analysisServer_test_integration_blazeProject') - .resolveSymbolicLinksSync(), - ).path; + tmpPath = Directory( + Directory.systemTemp + .createTempSync('analysisServer_test_integration_blazeProject') + .resolveSymbolicLinksSync(), + ).path; _temporaryFolders.add(tmpPath); workspacePath = inTmpDir('workspace_root'); writeFile(inWorkspace(file_paths.blazeWorkspaceMarker), ''); diff --git a/pkg/analysis_server/integration_test/support/integration_test_methods.dart b/pkg/analysis_server/integration_test/support/integration_test_methods.dart index 3d4ed28302e..e941bf98c32 100644 --- a/pkg/analysis_server/integration_test/support/integration_test_methods.dart +++ b/pkg/analysis_server/integration_test/support/integration_test_methods.dart @@ -285,8 +285,8 @@ abstract class IntegrationTest { /// /// The stack trace associated with the generation of the error, used for /// debugging the server. - late final Stream onServerError = - _onServerError.stream.asBroadcastStream(); + late final Stream onServerError = _onServerError.stream + .asBroadcastStream(); /// Stream controller for [onServerError]. final _onServerError = StreamController(sync: true); @@ -314,8 +314,8 @@ abstract class IntegrationTest { /// Parameters /// /// entry: ServerLogEntry - late final Stream onServerLog = - _onServerLog.stream.asBroadcastStream(); + late final Stream onServerLog = _onServerLog.stream + .asBroadcastStream(); /// Stream controller for [onServerLog]. final _onServerLog = StreamController(sync: true); @@ -341,8 +341,8 @@ abstract class IntegrationTest { /// /// Note: this status type is deprecated, and is no longer sent by the /// server. - late final Stream onServerStatus = - _onServerStatus.stream.asBroadcastStream(); + late final Stream onServerStatus = _onServerStatus.stream + .asBroadcastStream(); /// Stream controller for [onServerStatus]. final _onServerStatus = StreamController(sync: true); @@ -973,8 +973,9 @@ abstract class IntegrationTest { /// errors: List /// /// The errors contained in the file. - late final Stream onAnalysisErrors = - _onAnalysisErrors.stream.asBroadcastStream(); + late final Stream onAnalysisErrors = _onAnalysisErrors + .stream + .asBroadcastStream(); /// Stream controller for [onAnalysisErrors]. final _onAnalysisErrors = StreamController(sync: true); @@ -1436,8 +1437,8 @@ abstract class IntegrationTest { /// /// The existing imports in the library. late final Stream - onCompletionExistingImports = - _onCompletionExistingImports.stream.asBroadcastStream(); + onCompletionExistingImports = _onCompletionExistingImports.stream + .asBroadcastStream(); /// Stream controller for [onCompletionExistingImports]. final _onCompletionExistingImports = @@ -1723,8 +1724,9 @@ abstract class IntegrationTest { /// /// True if this is that last set of results that will be returned for the /// indicated search. - late final Stream onSearchResults = - _onSearchResults.stream.asBroadcastStream(); + late final Stream onSearchResults = _onSearchResults + .stream + .asBroadcastStream(); /// Stream controller for [onSearchResults]. final _onSearchResults = StreamController(sync: true); @@ -3014,8 +3016,9 @@ abstract class IntegrationTest { /// outline: FlutterOutline /// /// The outline associated with the file. - late final Stream onFlutterOutline = - _onFlutterOutline.stream.asBroadcastStream(); + late final Stream onFlutterOutline = _onFlutterOutline + .stream + .asBroadcastStream(); /// Stream controller for [onFlutterOutline]. final _onFlutterOutline = StreamController(sync: true); diff --git a/pkg/analysis_server/integration_test/support/integration_tests.dart b/pkg/analysis_server/integration_test/support/integration_tests.dart index 7fb5cc24365..7c6c1b5609c 100644 --- a/pkg/analysis_server/integration_test/support/integration_tests.dart +++ b/pkg/analysis_server/integration_test/support/integration_tests.dart @@ -604,11 +604,9 @@ class Server { ]) { // Provide a default implementation of the reverse request processor that // just throws because there are many tests that don't use reverse-requests. - reverseRequestProcessor ??= - (_) => - throw UnimplementedError( - "A reverse request was received but the test did not provide 'reverseRequestProcessor'", - ); + reverseRequestProcessor ??= (_) => throw UnimplementedError( + "A reverse request was received but the test did not provide 'reverseRequestProcessor'", + ); _process.stdout.transform(utf8.decoder).transform(LineSplitter()).listen(( String line, @@ -620,18 +618,16 @@ class Server { // {"event":"server.connected","params":{...}}The Dart VM service is listening on ... const dartVMServiceMessage = 'The Dart VM service is listening on '; if (trimmedLine.contains(dartVMServiceMessage)) { - trimmedLine = - trimmedLine - .substring(0, trimmedLine.indexOf(dartVMServiceMessage)) - .trim(); + trimmedLine = trimmedLine + .substring(0, trimmedLine.indexOf(dartVMServiceMessage)) + .trim(); } const devtoolsMessage = 'The Dart DevTools debugger and profiler is available at:'; if (trimmedLine.contains(devtoolsMessage)) { - trimmedLine = - trimmedLine - .substring(0, trimmedLine.indexOf(devtoolsMessage)) - .trim(); + trimmedLine = trimmedLine + .substring(0, trimmedLine.indexOf(devtoolsMessage)) + .trim(); } if (trimmedLine.isEmpty) { return; @@ -998,10 +994,9 @@ abstract class _RecursiveMatcher extends Matcher { mismatchDescription = mismatchDescription .add(' (should be ') .addDescriptionOf(matcher); - var subDescription = - matcher - .describeMismatch(item, StringDescription(), subState, false) - .toString(); + var subDescription = matcher + .describeMismatch(item, StringDescription(), subState, false) + .toString(); if (subDescription.isNotEmpty) { mismatchDescription = mismatchDescription .add('; ') @@ -1062,10 +1057,9 @@ abstract class _RecursiveMatcher extends Matcher { void populateMismatches(Object? item, List mismatches); /// Create a [MismatchDescriber] describing a mismatch with a simple string. - MismatchDescriber simpleDescription(String description) => ( - Description mismatchDescription, - ) { - mismatchDescription.add(description); - return mismatchDescription; - }; + MismatchDescriber simpleDescription(String description) => + (Description mismatchDescription) { + mismatchDescription.add(description); + return mismatchDescription; + }; } diff --git a/pkg/analysis_server/lib/plugin/protocol/protocol_dart.dart b/pkg/analysis_server/lib/plugin/protocol/protocol_dart.dart index 65bdfd408bb..e798b8ead92 100644 --- a/pkg/analysis_server/lib/plugin/protocol/protocol_dart.dart +++ b/pkg/analysis_server/lib/plugin/protocol/protocol_dart.dart @@ -257,17 +257,15 @@ int _preferRequiredParams( engine.FormalParameterElement e1, engine.FormalParameterElement e2, ) { - var rank1 = - (e1.isRequiredNamed || e1.metadata.hasRequired) - ? 0 - : !e1.isNamed - ? -1 - : 1; - var rank2 = - (e2.isRequiredNamed || e2.metadata.hasRequired) - ? 0 - : !e2.isNamed - ? -1 - : 1; + var rank1 = (e1.isRequiredNamed || e1.metadata.hasRequired) + ? 0 + : !e1.isNamed + ? -1 + : 1; + var rank2 = (e2.isRequiredNamed || e2.metadata.hasRequired) + ? 0 + : !e2.isNamed + ? -1 + : 1; return rank1 - rank2; } diff --git a/pkg/analysis_server/lib/protocol/protocol_generated.dart b/pkg/analysis_server/lib/protocol/protocol_generated.dart index 81f3a3b5806..991362b26ab 100644 --- a/pkg/analysis_server/lib/protocol/protocol_generated.dart +++ b/pkg/analysis_server/lib/protocol/protocol_generated.dart @@ -75,13 +75,12 @@ class AnalysisAnalyzedFilesParams implements HasToJson { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['directories'] = - directories - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['directories'] = directories + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); return result; } @@ -197,13 +196,12 @@ class AnalysisClosingLabelsParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['labels'] = - labels - .map( - (ClosingLabel value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['labels'] = labels + .map( + (ClosingLabel value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -300,13 +298,12 @@ class AnalysisErrorFixes implements HasToJson { }) { var result = {}; result['error'] = error.toJson(clientUriConverter: clientUriConverter); - result['fixes'] = - fixes - .map( - (SourceChange value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['fixes'] = fixes + .map( + (SourceChange value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -404,13 +401,12 @@ class AnalysisErrorsParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['errors'] = - errors - .map( - (AnalysisError value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['errors'] = errors + .map( + (AnalysisError value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -505,13 +501,12 @@ class AnalysisFlushResultsParams implements HasToJson { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['files'] = - files - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['files'] = files + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); return result; } @@ -613,13 +608,12 @@ class AnalysisFoldingParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['regions'] = - regions - .map( - (FoldingRegion value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['regions'] = regions + .map( + (FoldingRegion value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -796,13 +790,12 @@ class AnalysisGetErrorsResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['errors'] = - errors - .map( - (AnalysisError value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['errors'] = errors + .map( + (AnalysisError value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -992,13 +985,12 @@ class AnalysisGetHoverResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['hovers'] = - hovers - .map( - (HoverInformation value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['hovers'] = hovers + .map( + (HoverInformation value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -1206,13 +1198,12 @@ class AnalysisGetImportedElementsResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['elements'] = - elements - .map( - (ImportedElements value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['elements'] = elements + .map( + (ImportedElements value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -1315,12 +1306,12 @@ class AnalysisGetLibraryDependenciesResult implements ResponseResult { packageMap = jsonDecoder.decodeMap( '$jsonPath.packageMap', json['packageMap'], - valueDecoder: - (String jsonPath, Object? json) => jsonDecoder.decodeMap( + valueDecoder: (String jsonPath, Object? json) => + jsonDecoder.decodeMap( jsonPath, json, - valueDecoder: - (String jsonPath, Object? json) => jsonDecoder.decodeList( + valueDecoder: (String jsonPath, Object? json) => + jsonDecoder.decodeList( jsonPath, json, (String jsonPath, Object? json) => @@ -1361,28 +1352,23 @@ class AnalysisGetLibraryDependenciesResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['libraries'] = - libraries + result['libraries'] = libraries + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); + result['packageMap'] = mapMap( + packageMap, + valueCallback: (Map> value) => mapMap( + value, + valueCallback: (List value) => value .map( (String value) => clientUriConverter?.toClientFilePath(value) ?? value, ) - .toList(); - result['packageMap'] = mapMap( - packageMap, - valueCallback: - (Map> value) => mapMap( - value, - valueCallback: - (List value) => - value - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? - value, - ) - .toList(), - ), + .toList(), + ), ); return result; } @@ -1645,27 +1631,24 @@ class AnalysisGetNavigationResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['files'] = - files - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); - result['targets'] = - targets - .map( - (NavigationTarget value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['regions'] = - regions - .map( - (NavigationRegion value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['files'] = files + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); + result['targets'] = targets + .map( + (NavigationTarget value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['regions'] = regions + .map( + (NavigationRegion value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -1827,12 +1810,8 @@ class AnalysisGetReachableSourcesResult implements ResponseResult { sources = jsonDecoder.decodeMap( '$jsonPath.sources', json['sources'], - valueDecoder: - (String jsonPath, Object? json) => jsonDecoder.decodeList( - jsonPath, - json, - jsonDecoder.decodeString, - ), + valueDecoder: (String jsonPath, Object? json) => + jsonDecoder.decodeList(jsonPath, json, jsonDecoder.decodeString), ); } else { throw jsonDecoder.mismatch(jsonPath, 'sources', json); @@ -2086,13 +2065,12 @@ class AnalysisGetSignatureResult implements ResponseResult { }) { var result = {}; result['name'] = name; - result['parameters'] = - parameters - .map( - (ParameterInfo value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['parameters'] = parameters + .map( + (ParameterInfo value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); var dartdoc = this.dartdoc; if (dartdoc != null) { result['dartdoc'] = dartdoc; @@ -2207,13 +2185,12 @@ class AnalysisHighlightsParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['regions'] = - regions - .map( - (HighlightRegion value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['regions'] = regions + .map( + (HighlightRegion value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -2339,20 +2316,18 @@ class AnalysisImplementedParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['classes'] = - classes - .map( - (ImplementedClass value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['members'] = - members - .map( - (ImplementedMember value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['classes'] = classes + .map( + (ImplementedClass value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['members'] = members + .map( + (ImplementedMember value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -2630,27 +2605,24 @@ class AnalysisNavigationParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['regions'] = - regions - .map( - (NavigationRegion value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['targets'] = - targets - .map( - (NavigationTarget value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['files'] = - files - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['regions'] = regions + .map( + (NavigationRegion value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['targets'] = targets + .map( + (NavigationTarget value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['files'] = files + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); return result; } @@ -2768,13 +2740,12 @@ class AnalysisOccurrencesParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['occurrences'] = - occurrences - .map( - (Occurrences value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['occurrences'] = occurrences + .map( + (Occurrences value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -3217,13 +3188,12 @@ class AnalysisOverridesParams implements HasToJson { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['overrides'] = - overrides - .map( - (Override value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['overrides'] = overrides + .map( + (Override value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -3440,18 +3410,16 @@ class AnalysisSetAnalysisRootsParams implements RequestParams { packageRoots = jsonDecoder.decodeMap( '$jsonPath.packageRoots', json['packageRoots'], - keyDecoder: - (String jsonPath, Object? json) => - clientUriConverter?.fromClientFilePath( - jsonDecoder.decodeString(jsonPath, json), - ) ?? - jsonDecoder.decodeString(jsonPath, json), - valueDecoder: - (String jsonPath, Object? json) => - clientUriConverter?.fromClientFilePath( - jsonDecoder.decodeString(jsonPath, json), - ) ?? - jsonDecoder.decodeString(jsonPath, json), + keyDecoder: (String jsonPath, Object? json) => + clientUriConverter?.fromClientFilePath( + jsonDecoder.decodeString(jsonPath, json), + ) ?? + jsonDecoder.decodeString(jsonPath, json), + valueDecoder: (String jsonPath, Object? json) => + clientUriConverter?.fromClientFilePath( + jsonDecoder.decodeString(jsonPath, json), + ) ?? + jsonDecoder.decodeString(jsonPath, json), ); } return AnalysisSetAnalysisRootsParams( @@ -3485,30 +3453,26 @@ class AnalysisSetAnalysisRootsParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['included'] = - included - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); - result['excluded'] = - excluded - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['included'] = included + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); + result['excluded'] = excluded + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); var packageRoots = this.packageRoots; if (packageRoots != null) { result['packageRoots'] = mapMap( packageRoots, - keyCallback: - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - valueCallback: - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, + keyCallback: (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + valueCallback: (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, ); } return result; @@ -3642,13 +3606,12 @@ class AnalysisSetGeneralSubscriptionsParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['subscriptions'] = - subscriptions - .map( - (GeneralAnalysisService value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['subscriptions'] = subscriptions + .map( + (GeneralAnalysisService value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -3770,13 +3733,12 @@ class AnalysisSetPriorityFilesParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['files'] = - files - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['files'] = files + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); return result; } @@ -3858,15 +3820,15 @@ class AnalysisSetSubscriptionsParams implements RequestParams { subscriptions = jsonDecoder.decodeMap( '$jsonPath.subscriptions', json['subscriptions'], - keyDecoder: - (String jsonPath, Object? json) => AnalysisService.fromJson( + keyDecoder: (String jsonPath, Object? json) => + AnalysisService.fromJson( jsonDecoder, jsonPath, json, clientUriConverter: clientUriConverter, ), - valueDecoder: - (String jsonPath, Object? json) => jsonDecoder.decodeList( + valueDecoder: (String jsonPath, Object? json) => + jsonDecoder.decodeList( jsonPath, json, (String jsonPath, Object? json) => @@ -3908,17 +3870,14 @@ class AnalysisSetSubscriptionsParams implements RequestParams { var result = {}; result['subscriptions'] = mapMap( subscriptions, - keyCallback: - (AnalysisService value) => - value.toJson(clientUriConverter: clientUriConverter), - valueCallback: - (List value) => - value - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(), + keyCallback: (AnalysisService value) => + value.toJson(clientUriConverter: clientUriConverter), + valueCallback: (List value) => value + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(), ); return result; } @@ -4084,40 +4043,35 @@ class AnalysisUpdateContentParams implements RequestParams { files = jsonDecoder.decodeMap( '$jsonPath.files', json['files'], - keyDecoder: - (String jsonPath, Object? json) => - clientUriConverter?.fromClientFilePath( - jsonDecoder.decodeString(jsonPath, json), - ) ?? - jsonDecoder.decodeString(jsonPath, json), - valueDecoder: - (String jsonPath, Object? json) => - jsonDecoder.decodeUnion(jsonPath, json, 'type', { - 'add': - (String jsonPath, Object? json) => - AddContentOverlay.fromJson( - jsonDecoder, - jsonPath, - json, - clientUriConverter: clientUriConverter, - ), - 'change': - (String jsonPath, Object? json) => - ChangeContentOverlay.fromJson( - jsonDecoder, - jsonPath, - json, - clientUriConverter: clientUriConverter, - ), - 'remove': - (String jsonPath, Object? json) => - RemoveContentOverlay.fromJson( - jsonDecoder, - jsonPath, - json, - clientUriConverter: clientUriConverter, - ), - }), + keyDecoder: (String jsonPath, Object? json) => + clientUriConverter?.fromClientFilePath( + jsonDecoder.decodeString(jsonPath, json), + ) ?? + jsonDecoder.decodeString(jsonPath, json), + valueDecoder: (String jsonPath, Object? json) => + jsonDecoder.decodeUnion(jsonPath, json, 'type', { + 'add': (String jsonPath, Object? json) => + AddContentOverlay.fromJson( + jsonDecoder, + jsonPath, + json, + clientUriConverter: clientUriConverter, + ), + 'change': (String jsonPath, Object? json) => + ChangeContentOverlay.fromJson( + jsonDecoder, + jsonPath, + json, + clientUriConverter: clientUriConverter, + ), + 'remove': (String jsonPath, Object? json) => + RemoveContentOverlay.fromJson( + jsonDecoder, + jsonPath, + json, + clientUriConverter: clientUriConverter, + ), + }), ); } else { throw jsonDecoder.mismatch(jsonPath, 'files', json); @@ -4151,9 +4105,8 @@ class AnalysisUpdateContentParams implements RequestParams { var result = {}; result['files'] = mapMap( files, - keyCallback: - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, + keyCallback: (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, valueCallback: (Object value) => (value as dynamic).toJson(), ); return result; @@ -4859,13 +4812,12 @@ class BulkFix implements HasToJson { }) { var result = {}; result['path'] = clientUriConverter?.toClientFilePath(path) ?? path; - result['fixes'] = - fixes - .map( - (BulkFixDetail value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['fixes'] = fixes + .map( + (BulkFixDetail value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -5781,13 +5733,12 @@ class CompletionGetSuggestions2Result implements ResponseResult { var result = {}; result['replacementOffset'] = replacementOffset; result['replacementLength'] = replacementLength; - result['suggestions'] = - suggestions - .map( - (CompletionSuggestion value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['suggestions'] = suggestions + .map( + (CompletionSuggestion value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); result['isIncomplete'] = isIncomplete; return result; } @@ -5931,13 +5882,12 @@ class CompletionRegisterLibraryPathsParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['paths'] = - paths - .map( - (LibraryPathSet value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['paths'] = paths + .map( + (LibraryPathSet value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -6272,13 +6222,12 @@ class DiagnosticGetDiagnosticsResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['contexts'] = - contexts - .map( - (ContextData value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['contexts'] = contexts + .map( + (ContextData value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -6534,13 +6483,12 @@ class EditBulkFixesParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['included'] = - included - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['included'] = included + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); var inTestMode = this.inTestMode; if (inTestMode != null) { result['inTestMode'] = inTestMode; @@ -6687,20 +6635,18 @@ class EditBulkFixesResult implements ResponseResult { }) { var result = {}; result['message'] = message; - result['edits'] = - edits - .map( - (SourceFileEdit value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['details'] = - details - .map( - (BulkFix value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['edits'] = edits + .map( + (SourceFileEdit value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['details'] = details + .map( + (BulkFix value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -6792,13 +6738,12 @@ class EditFormatIfEnabledParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['directories'] = - directories - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['directories'] = directories + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); return result; } @@ -6894,13 +6839,12 @@ class EditFormatIfEnabledResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['edits'] = - edits - .map( - (SourceFileEdit value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['edits'] = edits + .map( + (SourceFileEdit value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -7161,13 +7105,12 @@ class EditFormatResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['edits'] = - edits - .map( - (SourceEdit value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['edits'] = edits + .map( + (SourceEdit value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); result['selectionOffset'] = selectionOffset; result['selectionLength'] = selectionLength; return result; @@ -7371,13 +7314,12 @@ class EditGetAssistsResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['assists'] = - assists - .map( - (SourceChange value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['assists'] = assists + .map( + (SourceChange value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -7584,13 +7526,12 @@ class EditGetAvailableRefactoringsResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['kinds'] = - kinds - .map( - (RefactoringKind value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['kinds'] = kinds + .map( + (RefactoringKind value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -7776,13 +7717,12 @@ class EditGetFixesResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['fixes'] = - fixes - .map( - (AnalysisErrorFixes value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['fixes'] = fixes + .map( + (AnalysisErrorFixes value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -8363,27 +8303,24 @@ class EditGetRefactoringResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['initialProblems'] = - initialProblems - .map( - (RefactoringProblem value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['optionsProblems'] = - optionsProblems - .map( - (RefactoringProblem value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['finalProblems'] = - finalProblems - .map( - (RefactoringProblem value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['initialProblems'] = initialProblems + .map( + (RefactoringProblem value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['optionsProblems'] = optionsProblems + .map( + (RefactoringProblem value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['finalProblems'] = finalProblems + .map( + (RefactoringProblem value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); var feedback = this.feedback; if (feedback != null) { result['feedback'] = feedback.toJson( @@ -8738,13 +8675,12 @@ class EditImportElementsParams implements RequestParams { }) { var result = {}; result['file'] = clientUriConverter?.toClientFilePath(file) ?? file; - result['elements'] = - elements - .map( - (ImportedElements value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['elements'] = elements + .map( + (ImportedElements value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); var offset = this.offset; if (offset != null) { result['offset'] = offset; @@ -9154,13 +9090,12 @@ class EditListPostfixCompletionTemplatesResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['templates'] = - templates - .map( - (PostfixTemplateDescriptor value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['templates'] = templates + .map( + (PostfixTemplateDescriptor value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -10352,22 +10287,20 @@ class ExecutionGetSuggestionsParams implements RequestParams { result['contextFile'] = clientUriConverter?.toClientFilePath(contextFile) ?? contextFile; result['contextOffset'] = contextOffset; - result['variables'] = - variables - .map( - (RuntimeCompletionVariable value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['variables'] = variables + .map( + (RuntimeCompletionVariable value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); var expressions = this.expressions; if (expressions != null) { - result['expressions'] = - expressions - .map( - (RuntimeCompletionExpression value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['expressions'] = expressions + .map( + (RuntimeCompletionExpression value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } return result; } @@ -10515,23 +10448,21 @@ class ExecutionGetSuggestionsResult implements ResponseResult { var result = {}; var suggestions = this.suggestions; if (suggestions != null) { - result['suggestions'] = - suggestions - .map( - (CompletionSuggestion value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['suggestions'] = suggestions + .map( + (CompletionSuggestion value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } var expressions = this.expressions; if (expressions != null) { - result['expressions'] = - expressions - .map( - (RuntimeCompletionExpression value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['expressions'] = expressions + .map( + (RuntimeCompletionExpression value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } return result; } @@ -10669,13 +10600,12 @@ class ExecutionLaunchDataParams implements HasToJson { } var referencedFiles = this.referencedFiles; if (referencedFiles != null) { - result['referencedFiles'] = - referencedFiles - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['referencedFiles'] = referencedFiles + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); } return result; } @@ -11011,13 +10941,12 @@ class ExecutionSetSubscriptionsParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['subscriptions'] = - subscriptions - .map( - (ExecutionService value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['subscriptions'] = subscriptions + .map( + (ExecutionService value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -11216,13 +11145,12 @@ class ExistingImports implements HasToJson { result['elements'] = elements.toJson( clientUriConverter: clientUriConverter, ); - result['imports'] = - imports - .map( - (ExistingImport value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['imports'] = imports + .map( + (ExistingImport value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -11666,13 +11594,12 @@ class ExtractMethodFeedback extends RefactoringFeedback { result['returnType'] = returnType; result['names'] = names; result['canCreateGetter'] = canCreateGetter; - result['parameters'] = - parameters - .map( - (RefactoringMethodParameter value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['parameters'] = parameters + .map( + (RefactoringMethodParameter value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); result['offsets'] = offsets; result['lengths'] = lengths; return result; @@ -11851,13 +11778,12 @@ class ExtractMethodOptions extends RefactoringOptions { result['returnType'] = returnType; result['createGetter'] = createGetter; result['name'] = name; - result['parameters'] = - parameters - .map( - (RefactoringMethodParameter value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['parameters'] = parameters + .map( + (RefactoringMethodParameter value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); result['extractAll'] = extractAll; return result; } @@ -12209,13 +12135,12 @@ class FlutterGetWidgetDescriptionResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['properties'] = - properties - .map( - (FlutterWidgetProperty value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['properties'] = properties + .map( + (FlutterWidgetProperty value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -12477,13 +12402,12 @@ class FlutterOutline implements HasToJson { } var attributes = this.attributes; if (attributes != null) { - result['attributes'] = - attributes - .map( - (FlutterOutlineAttribute value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['attributes'] = attributes + .map( + (FlutterOutlineAttribute value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } var className = this.className; if (className != null) { @@ -12499,13 +12423,12 @@ class FlutterOutline implements HasToJson { } var children = this.children; if (children != null) { - result['children'] = - children - .map( - (FlutterOutline value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['children'] = children + .map( + (FlutterOutline value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } return result; } @@ -12958,15 +12881,15 @@ class FlutterSetSubscriptionsParams implements RequestParams { subscriptions = jsonDecoder.decodeMap( '$jsonPath.subscriptions', json['subscriptions'], - keyDecoder: - (String jsonPath, Object? json) => FlutterService.fromJson( + keyDecoder: (String jsonPath, Object? json) => + FlutterService.fromJson( jsonDecoder, jsonPath, json, clientUriConverter: clientUriConverter, ), - valueDecoder: - (String jsonPath, Object? json) => jsonDecoder.decodeList( + valueDecoder: (String jsonPath, Object? json) => + jsonDecoder.decodeList( jsonPath, json, (String jsonPath, Object? json) => @@ -13008,17 +12931,14 @@ class FlutterSetSubscriptionsParams implements RequestParams { var result = {}; result['subscriptions'] = mapMap( subscriptions, - keyCallback: - (FlutterService value) => - value.toJson(clientUriConverter: clientUriConverter), - valueCallback: - (List value) => - value - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(), + keyCallback: (FlutterService value) => + value.toJson(clientUriConverter: clientUriConverter), + valueCallback: (List value) => value + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(), ); return result; } @@ -13468,13 +13388,12 @@ class FlutterWidgetProperty implements HasToJson { result['name'] = name; var children = this.children; if (children != null) { - result['children'] = - children - .map( - (FlutterWidgetProperty value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['children'] = children + .map( + (FlutterWidgetProperty value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } var editor = this.editor; if (editor != null) { @@ -13586,13 +13505,12 @@ class FlutterWidgetPropertyEditor implements HasToJson { result['kind'] = kind.toJson(clientUriConverter: clientUriConverter); var enumItems = this.enumItems; if (enumItems != null) { - result['enumItems'] = - enumItems - .map( - (FlutterWidgetPropertyValueEnumItem value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['enumItems'] = enumItems + .map( + (FlutterWidgetPropertyValueEnumItem value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } return result; } @@ -14948,13 +14866,12 @@ class LibraryPathSet implements HasToJson { }) { var result = {}; result['scope'] = clientUriConverter?.toClientFilePath(scope) ?? scope; - result['libraryPaths'] = - libraryPaths - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['libraryPaths'] = libraryPaths + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); return result; } @@ -15581,13 +15498,12 @@ class Override implements HasToJson { } var interfaceMembers = this.interfaceMembers; if (interfaceMembers != null) { - result['interfaceMembers'] = - interfaceMembers - .map( - (OverriddenMember value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['interfaceMembers'] = interfaceMembers + .map( + (OverriddenMember value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } return result; } @@ -16582,13 +16498,12 @@ class RuntimeCompletionExpressionType implements HasToJson { } var typeArguments = this.typeArguments; if (typeArguments != null) { - result['typeArguments'] = - typeArguments - .map( - (RuntimeCompletionExpressionType value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['typeArguments'] = typeArguments + .map( + (RuntimeCompletionExpressionType value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } var returnType = this.returnType; if (returnType != null) { @@ -16598,13 +16513,12 @@ class RuntimeCompletionExpressionType implements HasToJson { } var parameterTypes = this.parameterTypes; if (parameterTypes != null) { - result['parameterTypes'] = - parameterTypes - .map( - (RuntimeCompletionExpressionType value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['parameterTypes'] = parameterTypes + .map( + (RuntimeCompletionExpressionType value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } var parameterNames = this.parameterNames; if (parameterNames != null) { @@ -17722,20 +17636,18 @@ class SearchGetElementDeclarationsResult implements ResponseResult { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['declarations'] = - declarations - .map( - (ElementDeclaration value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); - result['files'] = - files - .map( - (String value) => - clientUriConverter?.toClientFilePath(value) ?? value, - ) - .toList(); + result['declarations'] = declarations + .map( + (ElementDeclaration value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); + result['files'] = files + .map( + (String value) => + clientUriConverter?.toClientFilePath(value) ?? value, + ) + .toList(); return result; } @@ -17958,13 +17870,12 @@ class SearchGetTypeHierarchyResult implements ResponseResult { var result = {}; var hierarchyItems = this.hierarchyItems; if (hierarchyItems != null) { - result['hierarchyItems'] = - hierarchyItems - .map( - (TypeHierarchyItem value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['hierarchyItems'] = hierarchyItems + .map( + (TypeHierarchyItem value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); } return result; } @@ -18096,13 +18007,12 @@ class SearchResult implements HasToJson { ); result['kind'] = kind.toJson(clientUriConverter: clientUriConverter); result['isPotential'] = isPotential; - result['path'] = - path - .map( - (Element value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['path'] = path + .map( + (Element value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -18264,13 +18174,12 @@ class SearchResultsParams implements HasToJson { }) { var result = {}; result['id'] = id; - result['results'] = - results - .map( - (SearchResult value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['results'] = results + .map( + (SearchResult value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); result['isLast'] = isLast; return result; } @@ -19420,13 +19329,12 @@ class ServerSetSubscriptionsParams implements RequestParams { required ClientUriConverter? clientUriConverter, }) { var result = {}; - result['subscriptions'] = - subscriptions - .map( - (ServerService value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['subscriptions'] = subscriptions + .map( + (ServerService value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } @@ -19578,13 +19486,12 @@ class ServerShowMessageRequestParams implements RequestParams { var result = {}; result['type'] = type.toJson(clientUriConverter: clientUriConverter); result['message'] = message; - result['actions'] = - actions - .map( - (MessageAction value) => - value.toJson(clientUriConverter: clientUriConverter), - ) - .toList(); + result['actions'] = actions + .map( + (MessageAction value) => + value.toJson(clientUriConverter: clientUriConverter), + ) + .toList(); return result; } diff --git a/pkg/analysis_server/lib/src/analysis_server.dart b/pkg/analysis_server/lib/src/analysis_server.dart index e39cfcee23f..1ac6ea3c757 100644 --- a/pkg/analysis_server/lib/src/analysis_server.dart +++ b/pkg/analysis_server/lib/src/analysis_server.dart @@ -319,14 +319,13 @@ abstract class AnalysisServer { } var disablePubCommandVariable = Platform.environment[PubCommand.disablePubCommandEnvironmentKey]; - var pubCommand = - processRunner != null && disablePubCommandVariable == null - ? PubCommand( - instrumentationService, - resourceProvider.pathContext, - processRunner, - ) - : null; + var pubCommand = processRunner != null && disablePubCommandVariable == null + ? PubCommand( + instrumentationService, + resourceProvider.pathContext, + processRunner, + ) + : null; pubPackageService = PubPackageService( instrumentationService, @@ -336,14 +335,13 @@ abstract class AnalysisServer { ); performance = performanceDuringStartup; - this.pluginManager = - pluginManager ??= PluginManager( - resourceProvider, - resourceProvider.byteStorePath, - sdkManager.defaultSdkDirectory, - notificationManager, - instrumentationService, - ); + this.pluginManager = pluginManager ??= PluginManager( + resourceProvider, + resourceProvider.byteStorePath, + sdkManager.defaultSdkDirectory, + notificationManager, + instrumentationService, + ); var pluginWatcher = PluginWatcher(resourceProvider, pluginManager); var logName = options.newAnalysisDriverLog; @@ -601,10 +599,9 @@ abstract class AnalysisServer { if (resourceProvider is PhysicalResourceProvider) { var stateLocation = resourceProvider.getStateLocation('.analysis-driver'); if (stateLocation != null) { - var timingByteStore = - _timingByteStore = TimingByteStore( - EvictingFileByteStore(stateLocation.path, G), - ); + var timingByteStore = _timingByteStore = TimingByteStore( + EvictingFileByteStore(stateLocation.path, G), + ); return MemoryCachingByteStore(timingByteStore, memoryCacheSize); } } @@ -840,10 +837,9 @@ abstract class AnalysisServer { // This is FutureOr<> because for the legacy server it's never a future, so // we can skip the await. var initializedLspHandler = lspInitialized; - var handler = - initializedLspHandler is lsp.InitializedStateMessageHandler - ? initializedLspHandler - : await initializedLspHandler; + var handler = initializedLspHandler is lsp.InitializedStateMessageHandler + ? initializedLspHandler + : await initializedLspHandler; return handler.handleMessage( message, diff --git a/pkg/analysis_server/lib/src/analytics/analytics_manager.dart b/pkg/analysis_server/lib/src/analytics/analytics_manager.dart index 5653e085f2a..0280db85eeb 100644 --- a/pkg/analysis_server/lib/src/analytics/analytics_manager.dart +++ b/pkg/analysis_server/lib/src/analytics/analytics_manager.dart @@ -516,10 +516,10 @@ class AnalyticsManager { transitiveFileUniqueCount: contextStructure.transitiveFileUniqueCount, transitiveFileUniqueLineCount: contextStructure.transitiveFileUniqueLineCount, - libraryCycleLibraryCounts: - contextStructure.libraryCycleLibraryCounts.toAnalyticsString(), - libraryCycleLineCounts: - contextStructure.libraryCycleLineCounts.toAnalyticsString(), + libraryCycleLibraryCounts: contextStructure.libraryCycleLibraryCounts + .toAnalyticsString(), + libraryCycleLineCounts: contextStructure.libraryCycleLineCounts + .toAnalyticsString(), ), ); } @@ -598,16 +598,16 @@ class AnalyticsManager { method: data.method, duration: data.responseTimes.toAnalyticsString(), added: data.additionalPercentiles[addedKey]?.toAnalyticsString(), - excluded: - data.additionalPercentiles[excludedKey]?.toAnalyticsString(), + excluded: data.additionalPercentiles[excludedKey] + ?.toAnalyticsString(), files: data.additionalPercentiles[filesKey]?.toAnalyticsString(), - included: - data.additionalPercentiles[includedKey]?.toAnalyticsString(), - openWorkspacePaths: - data.additionalPercentiles[openWorkspacePathsKey] - ?.toAnalyticsString(), - removed: - data.additionalPercentiles[removedKey]?.toAnalyticsString(), + included: data.additionalPercentiles[includedKey] + ?.toAnalyticsString(), + openWorkspacePaths: data + .additionalPercentiles[openWorkspacePathsKey] + ?.toAnalyticsString(), + removed: data.additionalPercentiles[removedKey] + ?.toAnalyticsString(), ), ); var commandMap = data.additionalEnumCounts[commandEnumKey]; diff --git a/pkg/analysis_server/lib/src/analytics/percentile_calculator.dart b/pkg/analysis_server/lib/src/analytics/percentile_calculator.dart index dcce05b4afe..cb49e9de015 100644 --- a/pkg/analysis_server/lib/src/analytics/percentile_calculator.dart +++ b/pkg/analysis_server/lib/src/analytics/percentile_calculator.dart @@ -48,9 +48,8 @@ class PercentileCalculator { return 0; } var targetIndex = _valueCount * percentile / 100; - var entries = - _counts.entries.toList() - ..sort((first, second) => first.key.compareTo(second.key)); + var entries = _counts.entries.toList() + ..sort((first, second) => first.key.compareTo(second.key)); // The number of values represented by walking the counts. var accumulation = 0; for (var i = 0; i < entries.length; i++) { diff --git a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart b/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart index d558a921051..9c96d863fcc 100644 --- a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart +++ b/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart @@ -25,26 +25,23 @@ class ByteStreamClientChannel implements ClientCommunicationChannel { Stream notificationStream; factory ByteStreamClientChannel(Stream> input, IOSink output) { - var jsonStream = - input - .transform(const Utf8Decoder()) - .transform(LineSplitter()) - .transform(JsonStreamDecoder()) - .where((json) => json is Map) - .cast>() - .asBroadcastStream(); - var responseStream = - jsonStream - .where((json) => json[Notification.EVENT] == null) - .transform(ResponseConverter()) - .where((response) => response != null) - .cast() - .asBroadcastStream(); - var notificationStream = - jsonStream - .where((json) => json[Notification.EVENT] != null) - .transform(NotificationConverter()) - .asBroadcastStream(); + var jsonStream = input + .transform(const Utf8Decoder()) + .transform(LineSplitter()) + .transform(JsonStreamDecoder()) + .where((json) => json is Map) + .cast>() + .asBroadcastStream(); + var responseStream = jsonStream + .where((json) => json[Notification.EVENT] == null) + .transform(ResponseConverter()) + .where((response) => response != null) + .cast() + .asBroadcastStream(); + var notificationStream = jsonStream + .where((json) => json[Notification.EVENT] != null) + .transform(NotificationConverter()) + .asBroadcastStream(); return ByteStreamClientChannel._( output, responseStream, diff --git a/pkg/analysis_server/lib/src/cider/completion.dart b/pkg/analysis_server/lib/src/cider/completion.dart index 4179b88a3f6..82aa3740392 100644 --- a/pkg/analysis_server/lib/src/cider/completion.dart +++ b/pkg/analysis_server/lib/src/cider/completion.dart @@ -170,12 +170,11 @@ class CiderCompletionComputer { required OperationPerformanceImpl performance, }) { var suggestionBuilders = []; - var importedLibraries = - target.withEnclosing2 - .expand((fragment) => fragment.libraryImports) - .map((import) => import.importedLibrary) - .nonNulls - .toSet(); + var importedLibraries = target.withEnclosing2 + .expand((fragment) => fragment.libraryImports) + .map((import) => import.importedLibrary) + .nonNulls + .toSet(); for (var importedLibrary in importedLibraries) { var importedSuggestions = _importedLibrarySuggestions( element: importedLibrary, diff --git a/pkg/analysis_server/lib/src/cider/document_symbols.dart b/pkg/analysis_server/lib/src/cider/document_symbols.dart index 8f2e6210bc5..afa1dc1e32c 100644 --- a/pkg/analysis_server/lib/src/cider/document_symbols.dart +++ b/pkg/analysis_server/lib/src/cider/document_symbols.dart @@ -47,10 +47,9 @@ class CiderDocumentSymbolsComputer { ) { var codeRange = toRange(lineInfo, outline.codeOffset, outline.codeLength); var nameLocation = outline.element.location; - var nameRange = - nameLocation != null - ? toRange(lineInfo, nameLocation.offset, nameLocation.length) - : null; + var nameRange = nameLocation != null + ? toRange(lineInfo, nameLocation.offset, nameLocation.length) + : null; return DocumentSymbol( name: toElementName(outline.element), detail: outline.element.parameters, @@ -58,12 +57,9 @@ class CiderDocumentSymbolsComputer { deprecated: outline.element.isDeprecated, range: codeRange, selectionRange: nameRange ?? codeRange, - children: - outline.children - ?.map( - (child) => _asDocumentSymbol(supportedKinds, lineInfo, child), - ) - .toList(), + children: outline.children + ?.map((child) => _asDocumentSymbol(supportedKinds, lineInfo, child)) + .toList(), ); } } diff --git a/pkg/analysis_server/lib/src/cider/local_library_contributor.dart b/pkg/analysis_server/lib/src/cider/local_library_contributor.dart index b085617d5b3..1218cc1709f 100644 --- a/pkg/analysis_server/lib/src/cider/local_library_contributor.dart +++ b/pkg/analysis_server/lib/src/cider/local_library_contributor.dart @@ -37,10 +37,9 @@ class LibraryElementSuggestionBuilder String? prefix, ]) { var opType = request.opType; - var kind = - request.target.isFunctionalArgument() - ? CompletionSuggestionKind.IDENTIFIER - : opType.suggestKind; + var kind = request.target.isFunctionalArgument() + ? CompletionSuggestionKind.IDENTIFIER + : opType.suggestKind; return LibraryElementSuggestionBuilder._( request, builder, diff --git a/pkg/analysis_server/lib/src/cider/rename.dart b/pkg/analysis_server/lib/src/cider/rename.dart index d15a18b90b4..d492bd76551 100644 --- a/pkg/analysis_server/lib/src/cider/rename.dart +++ b/pkg/analysis_server/lib/src/cider/rename.dart @@ -316,23 +316,22 @@ class CheckNameResponse { } catch (_) { match.add(CiderSearchMatch(sourcePath, [searchInfo])); } - var replacements = - match - .map( - (m) => CiderReplaceMatch( - m.path, - m.references - .map( - (p) => ReplaceInfo( - stateName, - p.startPosition, - stateClass.name!.length, - ), - ) - .toList(), - ), - ) - .toList(); + var replacements = match + .map( + (m) => CiderReplaceMatch( + m.path, + m.references + .map( + (p) => ReplaceInfo( + stateName, + p.startPosition, + stateClass.name!.length, + ), + ) + .toList(), + ), + ) + .toList(); return FlutterWidgetRename(stateName, match, replacements); } diff --git a/pkg/analysis_server/lib/src/computer/computer_call_hierarchy.dart b/pkg/analysis_server/lib/src/computer/computer_call_hierarchy.dart index 9585c7f9473..db11cd5e171 100644 --- a/pkg/analysis_server/lib/src/computer/computer_call_hierarchy.dart +++ b/pkg/analysis_server/lib/src/computer/computer_call_hierarchy.dart @@ -110,8 +110,9 @@ class CallHierarchyItem { var enclosingElement = element.enclosingElement ?? element.firstFragment.enclosingFragment?.element; - var container = - enclosingElement != null ? _getContainer(enclosingElement) : null; + var container = enclosingElement != null + ? _getContainer(enclosingElement) + : null; containerName = container != null ? _getDisplayName(container) : null; } diff --git a/pkg/analysis_server/lib/src/computer/computer_color.dart b/pkg/analysis_server/lib/src/computer/computer_color.dart index e752a751bca..b3cfef35f6d 100644 --- a/pkg/analysis_server/lib/src/computer/computer_color.dart +++ b/pkg/analysis_server/lib/src/computer/computer_color.dart @@ -106,12 +106,11 @@ class ColorComputer { double? alpha, red, green, blue; for (var arg in args.whereType()) { var expression = arg.expression; - var value = - expression is DoubleLiteral - ? expression.value - : expression is IntegerLiteral - ? expression.value?.toDouble() - : null; + var value = expression is DoubleLiteral + ? expression.value + : expression is IntegerLiteral + ? expression.value?.toDouble() + : null; switch (arg.name.label.name) { case 'alpha': alpha = value; @@ -154,12 +153,11 @@ class ColorComputer { var red = arg0 is IntegerLiteral ? arg0.value : null; var green = arg1 is IntegerLiteral ? arg1.value : null; var blue = arg2 is IntegerLiteral ? arg2.value : null; - var opacity = - arg3 is IntegerLiteral - ? arg3.value - : arg3 is DoubleLiteral - ? arg3.value - : null; + var opacity = arg3 is IntegerLiteral + ? arg3.value + : arg3 is DoubleLiteral + ? arg3.value + : null; var alpha = opacity != null ? (opacity * 255).toInt() : null; return alpha != null && red != null && green != null && blue != null @@ -175,9 +173,9 @@ class ColorComputer { String? name, List args, ) => - // MaterialAccentColor is a subclass of SwatchColor and has the same - // constructor. - _getFlutterSwatchColor(name, args); + // MaterialAccentColor is a subclass of SwatchColor and has the same + // constructor. + _getFlutterSwatchColor(name, args); /// Extracts the color information from Flutter ColorSwatch constructor args. ColorInformation? _getFlutterSwatchColor( @@ -270,11 +268,11 @@ class ColorComputer { }) { return alpha != null && red != null && green != null && blue != null ? ColorInformation( - (alpha * 255.0).round() & 0xff, - (red * 255.0).round() & 0xff, - (green * 255.0).round() & 0xff, - (blue * 255.0).round() & 0xff, - ) + (alpha * 255.0).round() & 0xff, + (red * 255.0).round() & 0xff, + (green * 255.0).round() & 0xff, + (blue * 255.0).round() & 0xff, + ) : null; } @@ -283,11 +281,11 @@ class ColorComputer { static ColorInformation? getColorForInt(int? value) { return value != null ? ColorInformation( - (value >> 24) & 0xff, - (value >> 16) & 0xff, - (value >> 8) & 0xff, - value & 0xff, - ) + (value >> 24) & 0xff, + (value >> 16) & 0xff, + (value >> 8) & 0xff, + value & 0xff, + ) : null; } diff --git a/pkg/analysis_server/lib/src/computer/computer_folding.dart b/pkg/analysis_server/lib/src/computer/computer_folding.dart index 2adb34dee36..7b855fd155c 100644 --- a/pkg/analysis_server/lib/src/computer/computer_folding.dart +++ b/pkg/analysis_server/lib/src/computer/computer_folding.dart @@ -127,13 +127,12 @@ class DartUnitFoldingComputer { _hasBlankLineBetween(end, _unit.beginToken.offset)); } - var kind = - isFileHeader - ? FoldingKind.FILE_HEADER - : (commentToken.lexeme.startsWith('///') || - commentToken.lexeme.startsWith('/**')) - ? FoldingKind.DOCUMENTATION_COMMENT - : FoldingKind.COMMENT; + var kind = isFileHeader + ? FoldingKind.FILE_HEADER + : (commentToken.lexeme.startsWith('///') || + commentToken.lexeme.startsWith('/**')) + ? FoldingKind.DOCUMENTATION_COMMENT + : FoldingKind.COMMENT; _addRegion(offset, end, kind); diff --git a/pkg/analysis_server/lib/src/computer/computer_highlights.dart b/pkg/analysis_server/lib/src/computer/computer_highlights.dart index a27d62c94ed..527e2e5b6da 100644 --- a/pkg/analysis_server/lib/src/computer/computer_highlights.dart +++ b/pkg/analysis_server/lib/src/computer/computer_highlights.dart @@ -215,10 +215,9 @@ class DartUnitHighlightsComputer { type, semanticTokenType: semanticType, semanticTokenModifiers: semanticModifiers, - additionalSemanticTokenModifiers: - _isAnnotationIdentifier(parent) - ? {CustomSemanticTokenModifiers.annotation} - : null, + additionalSemanticTokenModifiers: _isAnnotationIdentifier(parent) + ? {CustomSemanticTokenModifiers.annotation} + : null, ); } @@ -304,10 +303,9 @@ class DartUnitHighlightsComputer { } // Handle tokens that are references to record fields. if (staticType is RecordType) { - type = - staticType.fieldByName(nameToken.lexeme) != null - ? HighlightRegionType.INSTANCE_GETTER_REFERENCE - : HighlightRegionType.UNRESOLVED_INSTANCE_MEMBER_REFERENCE; + type = staticType.fieldByName(nameToken.lexeme) != null + ? HighlightRegionType.INSTANCE_GETTER_REFERENCE + : HighlightRegionType.UNRESOLVED_INSTANCE_MEMBER_REFERENCE; } } // Add the highlight region. @@ -315,10 +313,9 @@ class DartUnitHighlightsComputer { return _addRegion_token( nameToken, type, - additionalSemanticTokenModifiers: - _isAnnotationIdentifier(parent) - ? {CustomSemanticTokenModifiers.annotation} - : null, + additionalSemanticTokenModifiers: _isAnnotationIdentifier(parent) + ? {CustomSemanticTokenModifiers.annotation} + : null, ); } return false; @@ -337,14 +334,13 @@ class DartUnitHighlightsComputer { parent is MethodInvocation && parent.methodName.token == nameToken; HighlightRegionType type; var isTopLevel = element is TopLevelFunctionElement; - type = - isTopLevel - ? isInvocation - ? HighlightRegionType.TOP_LEVEL_FUNCTION_REFERENCE - : HighlightRegionType.TOP_LEVEL_FUNCTION_TEAR_OFF - : isInvocation - ? HighlightRegionType.LOCAL_FUNCTION_REFERENCE - : HighlightRegionType.LOCAL_FUNCTION_TEAR_OFF; + type = isTopLevel + ? isInvocation + ? HighlightRegionType.TOP_LEVEL_FUNCTION_REFERENCE + : HighlightRegionType.TOP_LEVEL_FUNCTION_TEAR_OFF + : isInvocation + ? HighlightRegionType.LOCAL_FUNCTION_REFERENCE + : HighlightRegionType.LOCAL_FUNCTION_TEAR_OFF; return _addRegion_token(nameToken, type); } @@ -412,10 +408,9 @@ class DartUnitHighlightsComputer { return _addRegion_token( nameToken, HighlightRegionType.LABEL, - semanticTokenModifiers: - parent is! BreakStatement - ? {SemanticTokenModifiers.declaration} - : null, + semanticTokenModifiers: parent is! BreakStatement + ? {SemanticTokenModifiers.declaration} + : null, ); } @@ -424,10 +419,9 @@ class DartUnitHighlightsComputer { return false; } // OK - var type = - element.type is DynamicType - ? HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_REFERENCE - : HighlightRegionType.LOCAL_VARIABLE_REFERENCE; + var type = element.type is DynamicType + ? HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_REFERENCE + : HighlightRegionType.LOCAL_VARIABLE_REFERENCE; return _addRegion_token(nameToken, type); } @@ -447,15 +441,13 @@ class DartUnitHighlightsComputer { // OK HighlightRegionType type; if (isStatic) { - type = - isInvocation - ? HighlightRegionType.STATIC_METHOD_REFERENCE - : HighlightRegionType.STATIC_METHOD_TEAR_OFF; + type = isInvocation + ? HighlightRegionType.STATIC_METHOD_REFERENCE + : HighlightRegionType.STATIC_METHOD_TEAR_OFF; } else { - type = - isInvocation - ? HighlightRegionType.INSTANCE_METHOD_REFERENCE - : HighlightRegionType.INSTANCE_METHOD_TEAR_OFF; + type = isInvocation + ? HighlightRegionType.INSTANCE_METHOD_REFERENCE + : HighlightRegionType.INSTANCE_METHOD_TEAR_OFF; } return _addRegion_token(nameToken, type); } @@ -468,21 +460,20 @@ class DartUnitHighlightsComputer { if (element is! FormalParameterElement) { return false; } - var type = - element.type is DynamicType - ? HighlightRegionType.DYNAMIC_PARAMETER_REFERENCE - : HighlightRegionType.PARAMETER_REFERENCE; - var modifiers = - parent is Label ? {CustomSemanticTokenModifiers.label} : null; + var type = element.type is DynamicType + ? HighlightRegionType.DYNAMIC_PARAMETER_REFERENCE + : HighlightRegionType.PARAMETER_REFERENCE; + var modifiers = parent is Label + ? {CustomSemanticTokenModifiers.label} + : null; return _addRegion_token(nameToken, type, semanticTokenModifiers: modifiers); } bool _addIdentifierRegion_typeAlias(Token nameToken, Element? element) { if (element is TypeAliasElement) { - var type = - element.aliasedType is FunctionType - ? HighlightRegionType.FUNCTION_TYPE_ALIAS - : HighlightRegionType.TYPE_ALIAS; + var type = element.aliasedType is FunctionType + ? HighlightRegionType.FUNCTION_TYPE_ALIAS + : HighlightRegionType.TYPE_ALIAS; return _addRegion_token(nameToken, type); } return false; @@ -1420,20 +1411,17 @@ class _DartUnitHighlightsComputerVisitor extends RecursiveAstVisitor { HighlightRegionType nameType; if (node.isGetter) { - nameType = - node.isStatic - ? HighlightRegionType.STATIC_GETTER_DECLARATION - : HighlightRegionType.INSTANCE_GETTER_DECLARATION; + nameType = node.isStatic + ? HighlightRegionType.STATIC_GETTER_DECLARATION + : HighlightRegionType.INSTANCE_GETTER_DECLARATION; } else if (node.isSetter) { - nameType = - node.isStatic - ? HighlightRegionType.STATIC_SETTER_DECLARATION - : HighlightRegionType.INSTANCE_SETTER_DECLARATION; + nameType = node.isStatic + ? HighlightRegionType.STATIC_SETTER_DECLARATION + : HighlightRegionType.INSTANCE_SETTER_DECLARATION; } else { - nameType = - node.isStatic - ? HighlightRegionType.STATIC_METHOD_DECLARATION - : HighlightRegionType.INSTANCE_METHOD_DECLARATION; + nameType = node.isStatic + ? HighlightRegionType.STATIC_METHOD_DECLARATION + : HighlightRegionType.INSTANCE_METHOD_DECLARATION; } computer._addRegion_token(node.name, nameType); diff --git a/pkg/analysis_server/lib/src/computer/computer_lazy_type_hierarchy.dart b/pkg/analysis_server/lib/src/computer/computer_lazy_type_hierarchy.dart index e3646480b91..8aa5488c4b7 100644 --- a/pkg/analysis_server/lib/src/computer/computer_lazy_type_hierarchy.dart +++ b/pkg/analysis_server/lib/src/computer/computer_lazy_type_hierarchy.dart @@ -138,13 +138,12 @@ class DartLazyTypeHierarchyComputer { var mixins = type.mixins; var superclassConstraints = type.superclassConstraints; - var supertypes = - [ - if (supertype != null) TypeHierarchyRelatedItem.extends_(supertype), - ...superclassConstraints.map(TypeHierarchyRelatedItem.constrainedTo), - ...interfaces.map(TypeHierarchyRelatedItem.implements), - ...mixins.map(TypeHierarchyRelatedItem.mixesIn), - ].nonNulls.toList(); + var supertypes = [ + if (supertype != null) TypeHierarchyRelatedItem.extends_(supertype), + ...superclassConstraints.map(TypeHierarchyRelatedItem.constrainedTo), + ...interfaces.map(TypeHierarchyRelatedItem.implements), + ...mixins.map(TypeHierarchyRelatedItem.mixesIn), + ].nonNulls.toList(); return supertypes; } diff --git a/pkg/analysis_server/lib/src/computer/computer_outline.dart b/pkg/analysis_server/lib/src/computer/computer_outline.dart index 8a2ca6366b5..12c4b89312b 100644 --- a/pkg/analysis_server/lib/src/computer/computer_outline.dart +++ b/pkg/analysis_server/lib/src/computer/computer_outline.dart @@ -321,8 +321,9 @@ class DartUnitOutlineComputer { var name = nameToken.lexeme; var aliasedType = node.type; - var aliasedFunctionType = - aliasedType is GenericFunctionType ? aliasedType : null; + var aliasedFunctionType = aliasedType is GenericFunctionType + ? aliasedType + : null; var element = Element( aliasedFunctionType != null @@ -335,14 +336,12 @@ class DartUnitOutlineComputer { ), aliasedType: _safeToSource(aliasedType), location: _getLocationToken(nameToken), - parameters: - aliasedFunctionType != null - ? _safeToSource(aliasedFunctionType.parameters) - : null, - returnType: - aliasedFunctionType != null - ? _safeToSource(aliasedFunctionType.returnType) - : null, + parameters: aliasedFunctionType != null + ? _safeToSource(aliasedFunctionType.parameters) + : null, + returnType: aliasedFunctionType != null + ? _safeToSource(aliasedFunctionType.returnType) + : null, typeParameters: _getTypeParametersStr(node.typeParameters), ); diff --git a/pkg/analysis_server/lib/src/computer/computer_overrides.dart b/pkg/analysis_server/lib/src/computer/computer_overrides.dart index a9166430c0f..1649fe96007 100644 --- a/pkg/analysis_server/lib/src/computer/computer_overrides.dart +++ b/pkg/analysis_server/lib/src/computer/computer_overrides.dart @@ -48,19 +48,17 @@ class DartUnitOverridesComputer { var superElements = overridesResult.superElements; var interfaceElements = overridesResult.interfaceElements; if (superElements.isNotEmpty || interfaceElements.isNotEmpty) { - var superMember = - superElements.isNotEmpty - ? proto.newOverriddenMember_fromEngine( - superElements.first.nonSynthetic, - ) - : null; - var interfaceMembers = - interfaceElements - .map( - (member) => - proto.newOverriddenMember_fromEngine(member.nonSynthetic), - ) - .toList(); + var superMember = superElements.isNotEmpty + ? proto.newOverriddenMember_fromEngine( + superElements.first.nonSynthetic, + ) + : null; + var interfaceMembers = interfaceElements + .map( + (member) => + proto.newOverriddenMember_fromEngine(member.nonSynthetic), + ) + .toList(); _overrides.add( proto.Override( token.offset, diff --git a/pkg/analysis_server/lib/src/computer/computer_signature.dart b/pkg/analysis_server/lib/src/computer/computer_signature.dart index 7975e2cb05f..c3da2443c38 100644 --- a/pkg/analysis_server/lib/src/computer/computer_signature.dart +++ b/pkg/analysis_server/lib/src/computer/computer_signature.dart @@ -43,8 +43,9 @@ class DartUnitSignatureComputer { if (parent is MethodInvocation) { name = parent.methodName.name; element = ElementLocator.locate(parent); - parameters = - element is FunctionTypedElement ? element.formalParameters : null; + parameters = element is FunctionTypedElement + ? element.formalParameters + : null; } else if (parent is InstanceCreationExpression) { name = parent.constructorName.type.qualifiedName; var constructorName = parent.constructorName.name; @@ -52,8 +53,9 @@ class DartUnitSignatureComputer { name += '.${constructorName.name}'; } element = ElementLocator.locate(parent); - parameters = - element is FunctionTypedElement ? element.formalParameters : null; + parameters = element is FunctionTypedElement + ? element.formalParameters + : null; } else if (parent case FunctionExpressionInvocation( function: Identifier function, )) { @@ -83,11 +85,10 @@ class DartUnitSignatureComputer { // If we're not a named expression, then we can count how many positional // parameters there are before us, and then find the index of the same // index positional parameter. - var positionalArgsToSkip = - argumentList.arguments - .where((argument) => argument is! NamedExpression) - .takeWhile((argument) => argument.end < _offset) - .length; + var positionalArgsToSkip = argumentList.arguments + .where((argument) => argument is! NamedExpression) + .takeWhile((argument) => argument.end < _offset) + .length; for (var i = 0; i < parameters.length; i++) { if (parameters[i].isPositional) { // This is the first positional parameter after our skips, so this is diff --git a/pkg/analysis_server/lib/src/computer/computer_type_arguments_signature.dart b/pkg/analysis_server/lib/src/computer/computer_type_arguments_signature.dart index cd6ca38e993..dd7a6c18c4d 100644 --- a/pkg/analysis_server/lib/src/computer/computer_type_arguments_signature.dart +++ b/pkg/analysis_server/lib/src/computer/computer_type_arguments_signature.dart @@ -88,20 +88,15 @@ class DartTypeArgumentsSignatureComputer { String? documentation, List typeParameters, ) { - var parameters = - typeParameters - .map( - (param) => - lsp.ParameterInformation(label: param.displayString()), - ) - .toList(); + var parameters = typeParameters + .map((param) => lsp.ParameterInformation(label: param.displayString())) + .toList(); var signature = lsp.SignatureInformation( label: label, - documentation: - documentation != null - ? asMarkupContentOrString(preferredFormats, documentation) - : null, + documentation: documentation != null + ? asMarkupContentOrString(preferredFormats, documentation) + : null, parameters: parameters, ); diff --git a/pkg/analysis_server/lib/src/context_manager.dart b/pkg/analysis_server/lib/src/context_manager.dart index 5321c99ab67..2440ab46aa2 100644 --- a/pkg/analysis_server/lib/src/context_manager.dart +++ b/pkg/analysis_server/lib/src/context_manager.dart @@ -389,8 +389,9 @@ class ContextManagerImpl implements ContextManager { var analysisOptions = driver.getAnalysisOptionsForFile(file); var content = file.readAsStringSync(); var lineInfo = LineInfo.fromContent(content); - var sdkVersionConstraint = - (package is PubPackage) ? package.sdkVersionConstraint : null; + var sdkVersionConstraint = (package is PubPackage) + ? package.sdkVersionConstraint + : null; var errors = analyzeAnalysisOptions( FileSource(file), content, @@ -582,22 +583,21 @@ class ContextManagerImpl implements ContextManager { _fileContentCache.invalidateAll(); var watchers = []; - var collection = - _collection = AnalysisContextCollectionImpl( - includedPaths: includedPaths, - excludedPaths: excludedPaths, - byteStore: _byteStore, - drainStreams: false, - enableIndex: true, - performanceLog: _performanceLog, - resourceProvider: resourceProvider, - scheduler: _scheduler, - sdkPath: sdkManager.defaultSdkDirectory, - packagesFile: packagesFile, - fileContentCache: _fileContentCache, - unlinkedUnitStore: _unlinkedUnitStore, - enabledExperiments: _enabledExperiments, - ); + var collection = _collection = AnalysisContextCollectionImpl( + includedPaths: includedPaths, + excludedPaths: excludedPaths, + byteStore: _byteStore, + drainStreams: false, + enableIndex: true, + performanceLog: _performanceLog, + resourceProvider: resourceProvider, + scheduler: _scheduler, + sdkPath: sdkManager.defaultSdkDirectory, + packagesFile: packagesFile, + fileContentCache: _fileContentCache, + unlinkedUnitStore: _unlinkedUnitStore, + enabledExperiments: _enabledExperiments, + ); for (var analysisContext in collection.contexts) { var driver = analysisContext.driver; @@ -671,37 +671,35 @@ class ContextManagerImpl implements ContextManager { // Create temporary watchers before we start the context build so we can // tell if any files were modified while waiting for the "real" watchers to // become ready and start the process again. - var temporaryWatchers = - includedPaths - .map((path) => resourceProvider.getResource(path)) - .map((resource) => resource.watch()) - .toList(); + var temporaryWatchers = includedPaths + .map((path) => resourceProvider.getResource(path)) + .map((resource) => resource.watch()) + .toList(); // If any watcher picks up an important change while we're running the // rest of this method, we will need to start again. var needsBuild = true; - var temporaryWatcherSubscriptions = - temporaryWatchers - .map( - (watcher) => watcher.changes.listen( - (event) { - if (shouldRestartBuild(event.path)) { - needsBuild = true; - } - }, - onError: (error, stackTrace) { - // Errors in the watcher such as "Directory watcher closed - // unexpectedly" on Windows when the buffer overflows also - // require that we restarted to be consistent. - needsBuild = true; - _instrumentationService.logError( - 'Temporary watcher error; restarting context build.\n' - '$error\n$stackTrace', - ); - }, - ), - ) - .toList(); + var temporaryWatcherSubscriptions = temporaryWatchers + .map( + (watcher) => watcher.changes.listen( + (event) { + if (shouldRestartBuild(event.path)) { + needsBuild = true; + } + }, + onError: (error, stackTrace) { + // Errors in the watcher such as "Directory watcher closed + // unexpectedly" on Windows when the buffer overflows also + // require that we restarted to be consistent. + needsBuild = true; + _instrumentationService.logError( + 'Temporary watcher error; restarting context build.\n' + '$error\n$stackTrace', + ); + }, + ), + ) + .toList(); try { // Ensure all watchers are ready before we begin any rebuild. @@ -949,10 +947,9 @@ class ContextManagerImpl implements ContextManager { class NoopContextManagerCallbacks implements ContextManagerCallbacks { @override - AnalysisServer get analysisServer => - throw StateError( - 'The callback object should have been set by the server.', - ); + AnalysisServer get analysisServer => throw StateError( + 'The callback object should have been set by the server.', + ); @override void afterContextsCreated() {} diff --git a/pkg/analysis_server/lib/src/domains/analysis/occurrences_dart.dart b/pkg/analysis_server/lib/src/domains/analysis/occurrences_dart.dart index d1597c1ae26..99d83c7a7fd 100644 --- a/pkg/analysis_server/lib/src/domains/analysis/occurrences_dart.dart +++ b/pkg/analysis_server/lib/src/domains/analysis/occurrences_dart.dart @@ -24,11 +24,10 @@ void addDartOccurrences(OccurrencesCollector collector, CompilationUnit unit) { // what is in the source. var length = serverElement.location?.length ?? engineElement.name?.length ?? 0; - var offsets = - nodes - .where((node) => node.length == length) - .map((node) => node.offset) - .toList(); + var offsets = nodes + .where((node) => node.length == length) + .map((node) => node.offset) + .toList(); var occurrences = protocol.Occurrences(serverElement, offsets, length); collector.addOccurrences(occurrences); @@ -285,10 +284,9 @@ class DartUnitOccurrencesComputerVisitor extends GeneralizingAstVisitor { var element = node.element; var pattern = node.pattern; // If no explicit field name, use the variables name. - var name = - node.name?.name == null && pattern is VariablePattern - ? pattern.name - : node.name?.name; + var name = node.name?.name == null && pattern is VariablePattern + ? pattern.name + : node.name?.name; if (element != null && name != null) { _addOccurrence(element, name); } diff --git a/pkg/analysis_server/lib/src/g3/utilities.dart b/pkg/analysis_server/lib/src/g3/utilities.dart index 02a4f7df697..61d650848f2 100644 --- a/pkg/analysis_server/lib/src/g3/utilities.dart +++ b/pkg/analysis_server/lib/src/g3/utilities.dart @@ -36,14 +36,13 @@ String format(String content, {Version? languageVersion}) { /// cause of the failure, a list of [Diagnostic]s. ParseStringResult sortDirectives(String contents, {String? fileName}) { var (unit, diagnostics) = _parse(contents, fullName: fileName); - var parseErrors = - diagnostics - .where( - (d) => - d.diagnosticCode is ScannerErrorCode || - d.diagnosticCode is ParserErrorCode, - ) - .toList(); + var parseErrors = diagnostics + .where( + (d) => + d.diagnosticCode is ScannerErrorCode || + d.diagnosticCode is ParserErrorCode, + ) + .toList(); if (parseErrors.isNotEmpty) { return ParseStringResultImpl(contents, unit, parseErrors); } @@ -63,10 +62,11 @@ ParseStringResult sortDirectives(String contents, {String? fileName}) { sdkLanguageVersion: ExperimentStatus.currentVersion, flags: [], ); - var scanner = Scanner(source, reader, diagnosticListener)..configureFeatures( - featureSetForOverriding: FeatureSet.latestLanguageVersion(), - featureSet: featureSet, - ); + var scanner = Scanner(source, reader, diagnosticListener) + ..configureFeatures( + featureSetForOverriding: FeatureSet.latestLanguageVersion(), + featureSet: featureSet, + ); var token = scanner.tokenize(reportScannerErrors: false); var lineInfo = LineInfo(scanner.lineStarts); var languageVersion = LibraryLanguageVersion( diff --git a/pkg/analysis_server/lib/src/handler/legacy/analysis_get_errors.dart b/pkg/analysis_server/lib/src/handler/legacy/analysis_get_errors.dart index 7b3fea82ccc..4da90c9151f 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/analysis_get_errors.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/analysis_get_errors.dart @@ -20,11 +20,10 @@ class AnalysisGetErrorsHandler extends LegacyHandler { @override Future handle() async { - var file = - AnalysisGetErrorsParams.fromRequest( - request, - clientUriConverter: server.uriConverter, - ).file; + var file = AnalysisGetErrorsParams.fromRequest( + request, + clientUriConverter: server.uriConverter, + ).file; if (server.sendResponseErrorIfInvalidFilePath(request, file)) { return; diff --git a/pkg/analysis_server/lib/src/handler/legacy/analysis_get_imported_elements.dart b/pkg/analysis_server/lib/src/handler/legacy/analysis_get_imported_elements.dart index bf9b56ebf39..9fac2eb8bd5 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/analysis_get_imported_elements.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/analysis_get_imported_elements.dart @@ -50,12 +50,11 @@ class AnalysisGetImportedElementsHandler extends LegacyHandler { if (disableManageImportsOnPaste) { elements = []; } else { - elements = - ImportedElementsComputer( - result.unit, - params.offset, - params.length, - ).compute(); + elements = ImportedElementsComputer( + result.unit, + params.offset, + params.length, + ).compute(); } sendResult(AnalysisGetImportedElementsResult(elements)); diff --git a/pkg/analysis_server/lib/src/handler/legacy/completion_utils.dart b/pkg/analysis_server/lib/src/handler/legacy/completion_utils.dart index 913b5ef8f60..cbcfb89ddc0 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/completion_utils.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/completion_utils.dart @@ -41,10 +41,9 @@ Future candidateToCompletionSuggestion( case TypedSuggestion(): var data = await createTypedSuggestionData(candidate, request); requiredImports = data?.imports.toList() ?? requiredImports; - var kind = - request.target.isFunctionalArgument() - ? CompletionSuggestionKind.IDENTIFIER - : null; + var kind = request.target.isFunctionalArgument() + ? CompletionSuggestionKind.IDENTIFIER + : null; candidate.data = data; return switch (candidate) { @@ -84,20 +83,20 @@ Future candidateToCompletionSuggestion( ), MethodSuggestion(kind: var suggestionKind) => - // TODO(brianwilkerson): Correctly set the kind of suggestion in cases - // where `isFunctionalArgument` would return `true` so we can stop - // using the `request.target`. - _getDartCompletionSuggestion( - candidate.element, - candidate.completion, - candidate.relevanceScore, - kind ?? suggestionKind, - request, - isNotImportedLibrary, - libraryUriStr, - requiredImports, - displayString: data?.displayText, - ), + // TODO(brianwilkerson): Correctly set the kind of suggestion in cases + // where `isFunctionalArgument` would return `true` so we can stop + // using the `request.target`. + _getDartCompletionSuggestion( + candidate.element, + candidate.completion, + candidate.relevanceScore, + kind ?? suggestionKind, + request, + isNotImportedLibrary, + libraryUriStr, + requiredImports, + displayString: data?.displayText, + ), RecordFieldSuggestion() => DartCompletionSuggestion( CompletionSuggestionKind.IDENTIFIER, candidate.relevanceScore, @@ -455,14 +454,14 @@ _ParameterData _createParameterData(e.Element element) { bool? hasNamedParameters; CompletionDefaultArgumentList? defaultArgumentList; if (element is e.ExecutableElement && element is! e.PropertyAccessorElement) { - parameterNames = - element.formalParameters.map((parameter) { - return parameter.displayName; - }).toList(); - parameterTypes = - element.formalParameters.map((e.FormalParameterElement parameter) { - return parameter.type.getDisplayString(); - }).toList(); + parameterNames = element.formalParameters.map((parameter) { + return parameter.displayName; + }).toList(); + parameterTypes = element.formalParameters.map(( + e.FormalParameterElement parameter, + ) { + return parameter.type.getDisplayString(); + }).toList(); var requiredParameters = element.formalParameters.where( (e.FormalParameterElement param) => param.isRequiredPositional, diff --git a/pkg/analysis_server/lib/src/handler/legacy/edit_get_assists.dart b/pkg/analysis_server/lib/src/handler/legacy/edit_get_assists.dart index 4b7f51d40f2..1c15642d004 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/edit_get_assists.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/edit_get_assists.dart @@ -134,7 +134,8 @@ class EditGetAssistsHandler extends LegacyHandler } on InconsistentAnalysisException { // ignore } catch (exception, stackTrace) { - var parametersFile = ''' + var parametersFile = + ''' offset: $offset length: $length '''; diff --git a/pkg/analysis_server/lib/src/handler/legacy/edit_get_fixes.dart b/pkg/analysis_server/lib/src/handler/legacy/edit_get_fixes.dart index 597758ec4fa..d325ac810b1 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/edit_get_fixes.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/edit_get_fixes.dart @@ -125,8 +125,9 @@ class EditGetFixesHandler extends LegacyHandler var package = analysisContext.contextRoot.workspace.findPackageFor( optionsFile.path, ); - var sdkVersionConstraint = - (package is PubPackage) ? package.sdkVersionConstraint : null; + var sdkVersionConstraint = (package is PubPackage) + ? package.sdkVersionConstraint + : null; var diagnostics = analyzeAnalysisOptions( FileSource(optionsFile), content, @@ -222,7 +223,8 @@ class EditGetFixesHandler extends LegacyHandler } on InconsistentAnalysisException { fixes = []; } catch (exception, stackTrace) { - var parametersFile = ''' + var parametersFile = + ''' offset: $offset error: $diagnostic error.errorCode: ${diagnostic.diagnosticCode} diff --git a/pkg/analysis_server/lib/src/handler/legacy/edit_list_postfix_completion_templates.dart b/pkg/analysis_server/lib/src/handler/legacy/edit_list_postfix_completion_templates.dart index 03b3c528182..005c78f70a0 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/edit_list_postfix_completion_templates.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/edit_list_postfix_completion_templates.dart @@ -21,13 +21,12 @@ class EditListPostfixCompletionTemplatesHandler extends LegacyHandler { @override Future handle() async { - var templates = - DartPostfixCompletion.ALL_TEMPLATES - .map( - (PostfixCompletionKind kind) => - PostfixTemplateDescriptor(kind.name, kind.key, kind.example), - ) - .toList(); + var templates = DartPostfixCompletion.ALL_TEMPLATES + .map( + (PostfixCompletionKind kind) => + PostfixTemplateDescriptor(kind.name, kind.key, kind.example), + ) + .toList(); sendResult(EditListPostfixCompletionTemplatesResult(templates)); } } diff --git a/pkg/analysis_server/lib/src/handler/legacy/execution_create_context.dart b/pkg/analysis_server/lib/src/handler/legacy/execution_create_context.dart index 892f8cd4723..baf99e10a20 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/execution_create_context.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/execution_create_context.dart @@ -20,11 +20,10 @@ class ExecutionCreateContextHandler extends LegacyHandler { @override Future handle() async { - var file = - ExecutionCreateContextParams.fromRequest( - request, - clientUriConverter: server.uriConverter, - ).contextRoot; + var file = ExecutionCreateContextParams.fromRequest( + request, + clientUriConverter: server.uriConverter, + ).contextRoot; var executionContext = server.executionContext; var contextId = (executionContext.nextContextId++).toString(); executionContext.contextMap[contextId] = file; diff --git a/pkg/analysis_server/lib/src/handler/legacy/execution_delete_context.dart b/pkg/analysis_server/lib/src/handler/legacy/execution_delete_context.dart index 26e948d95a6..45fd99a20c6 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/execution_delete_context.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/execution_delete_context.dart @@ -20,11 +20,10 @@ class ExecutionDeleteContextHandler extends LegacyHandler { @override Future handle() async { - var contextId = - ExecutionDeleteContextParams.fromRequest( - request, - clientUriConverter: server.uriConverter, - ).id; + var contextId = ExecutionDeleteContextParams.fromRequest( + request, + clientUriConverter: server.uriConverter, + ).id; server.executionContext.contextMap.remove(contextId); sendResult(ExecutionDeleteContextResult()); } diff --git a/pkg/analysis_server/lib/src/handler/legacy/lsp_over_legacy_handler.dart b/pkg/analysis_server/lib/src/handler/legacy/lsp_over_legacy_handler.dart index a1b13026e95..424235b83c8 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/lsp_over_legacy_handler.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/lsp_over_legacy_handler.dart @@ -40,14 +40,14 @@ class LspOverLegacyHandler extends LegacyHandler { var reporter = LspJsonReporter(); var lspMessage = lspMessageJson is Map && - RequestMessage.canParse(lspMessageJson, reporter) - ? RequestMessage.fromJson({ - // Pass across any clientRequestTime from the envelope so that we - // can record latency for LSP-over-Legacy requests. - 'clientRequestTime': request.clientRequestTime, - ...lspMessageJson, - }) - : null; + RequestMessage.canParse(lspMessageJson, reporter) + ? RequestMessage.fromJson({ + // Pass across any clientRequestTime from the envelope so that we + // can record latency for LSP-over-Legacy requests. + 'clientRequestTime': request.clientRequestTime, + ...lspMessageJson, + }) + : null; if (lspMessage != null) { server.analyticsManager.startedRequestMessage( diff --git a/pkg/analysis_server/lib/src/handler/legacy/search_get_element_declarations.dart b/pkg/analysis_server/lib/src/handler/legacy/search_get_element_declarations.dart index 186092bb2a8..0ee4d48012f 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/search_get_element_declarations.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/search_get_element_declarations.dart @@ -74,22 +74,21 @@ class SearchGetElementDeclarationsHandler extends LegacyHandler { ).compute(); var declarations = workspaceSymbols.declarations; - var elementDeclarations = - declarations.map((declaration) { - return protocol.ElementDeclaration( - declaration.name, - getElementKind(declaration.kind), - declaration.fileIndex, - declaration.offset, - declaration.line, - declaration.column, - declaration.codeOffset, - declaration.codeLength, - className: declaration.className, - mixinName: declaration.mixinName, - parameters: declaration.parameters, - ); - }).toList(); + var elementDeclarations = declarations.map((declaration) { + return protocol.ElementDeclaration( + declaration.name, + getElementKind(declaration.kind), + declaration.fileIndex, + declaration.offset, + declaration.line, + declaration.column, + declaration.codeOffset, + declaration.codeLength, + className: declaration.className, + mixinName: declaration.mixinName, + parameters: declaration.parameters, + ); + }).toList(); server.sendResponse( protocol.SearchGetElementDeclarationsResult( diff --git a/pkg/analysis_server/lib/src/handler/legacy/server_cancel_request.dart b/pkg/analysis_server/lib/src/handler/legacy/server_cancel_request.dart index ce1fb06162e..204fd36fdfa 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/server_cancel_request.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/server_cancel_request.dart @@ -20,11 +20,10 @@ class ServerCancelRequestHandler extends LegacyHandler { @override Future handle() async { - var id = - ServerCancelRequestParams.fromRequest( - request, - clientUriConverter: server.uriConverter, - ).id; + var id = ServerCancelRequestParams.fromRequest( + request, + clientUriConverter: server.uriConverter, + ).id; server.cancelRequest(id); sendResult(ServerCancelRequestResult()); } diff --git a/pkg/analysis_server/lib/src/handler/legacy/server_set_subscriptions.dart b/pkg/analysis_server/lib/src/handler/legacy/server_set_subscriptions.dart index 0e0cfabcb29..ffe9162bc5c 100644 --- a/pkg/analysis_server/lib/src/handler/legacy/server_set_subscriptions.dart +++ b/pkg/analysis_server/lib/src/handler/legacy/server_set_subscriptions.dart @@ -22,11 +22,10 @@ class ServerSetSubscriptionsHandler extends LegacyHandler { @override Future handle() async { try { - server.serverServices = - ServerSetSubscriptionsParams.fromRequest( - request, - clientUriConverter: server.uriConverter, - ).subscriptions.toSet(); + server.serverServices = ServerSetSubscriptionsParams.fromRequest( + request, + clientUriConverter: server.uriConverter, + ).subscriptions.toSet(); server.requestStatistics?.isNotificationSubscribed = server.serverServices .contains(ServerService.LOG); } on RequestFailure catch (exception) { diff --git a/pkg/analysis_server/lib/src/legacy_analysis_server.dart b/pkg/analysis_server/lib/src/legacy_analysis_server.dart index 3314ea85d25..2fc7f82c554 100644 --- a/pkg/analysis_server/lib/src/legacy_analysis_server.dart +++ b/pkg/analysis_server/lib/src/legacy_analysis_server.dart @@ -777,14 +777,14 @@ class LegacyAnalysisServer extends AnalysisServer { return lspResponse is Map ? lsp.ResponseMessage.fromJson(lspResponse) : lsp.ResponseMessage( - jsonrpc: lsp.jsonRpcVersion, - error: lsp.ResponseError( - code: lsp.ServerErrorCodes.UnhandledError, - message: - "The client responded to a '$method' LSP request but" - ' did not include a valid response in the lspResponse field', - ), - ); + jsonrpc: lsp.jsonRpcVersion, + error: lsp.ResponseError( + code: lsp.ServerErrorCodes.UnhandledError, + message: + "The client responded to a '$method' LSP request but" + ' did not include a valid response in the lspResponse field', + ), + ); } /// Send the given [notification] to the client. diff --git a/pkg/analysis_server/lib/src/lsp/client_configuration.dart b/pkg/analysis_server/lib/src/lsp/client_configuration.dart index 72bddf71f7b..10ebeb6adbb 100644 --- a/pkg/analysis_server/lib/src/lsp/client_configuration.dart +++ b/pkg/analysis_server/lib/src/lsp/client_configuration.dart @@ -157,14 +157,13 @@ class LspClientConfiguration { /// Gets the path for the WorkspaceFolder closest to [resourcePath]. String? _getWorkspaceFolderPath(String resourcePath) { - var candidates = - _resourceSettings.keys - .where( - (wfPath) => - wfPath == _normaliseFolderPath(resourcePath) || - pathContext.isWithin(wfPath, resourcePath), - ) - .toList(); + var candidates = _resourceSettings.keys + .where( + (wfPath) => + wfPath == _normaliseFolderPath(resourcePath) || + pathContext.isWithin(wfPath, resourcePath), + ) + .toList(); candidates.sort((a, b) => -a.length.compareTo(b.length)); return candidates.firstOrNull; } @@ -341,13 +340,12 @@ class LspGlobalClientConfiguration extends LspResourceClientConfiguration { /// /// [showAllTodos] should be checked first, as this will return an empty /// set if `showTodos` is a boolean. - Set get showTodoTypes => - _settings['showTodos'] is List - ? (_settings['showTodos'] as List) - .cast() - .map((kind) => kind.toUpperCase()) - .toSet() - : const {}; + Set get showTodoTypes => _settings['showTodos'] is List + ? (_settings['showTodos'] as List) + .cast() + .map((kind) => kind.toUpperCase()) + .toSet() + : const {}; } /// Wraps the client (editor) configuration for a specific resource. diff --git a/pkg/analysis_server/lib/src/lsp/completion_utils.dart b/pkg/analysis_server/lib/src/lsp/completion_utils.dart index 00b1368a5fb..7d60d3d3460 100644 --- a/pkg/analysis_server/lib/src/lsp/completion_utils.dart +++ b/pkg/analysis_server/lib/src/lsp/completion_utils.dart @@ -191,10 +191,9 @@ lsp.CompletionItem? toLspCompletionItem( // // In the case of show combinators, the parens will still be shown to indicate // functions but they should not be included in the completions. - var element = - suggestion is ElementBasedSuggestion - ? (suggestion as ElementBasedSuggestion).element - : null; + var element = suggestion is ElementBasedSuggestion + ? (suggestion as ElementBasedSuggestion).element + : null; var isCallable = element != null && (element is ConstructorElement || @@ -238,10 +237,9 @@ lsp.CompletionItem? toLspCompletionItem( // TODO(dantup): Consider including more of these raw fields in the original // suggestion to avoid needing to manipulate them in this way here. - var filterText = - !label.startsWith(completionFilterTextSplitPattern) - ? label.split(completionFilterTextSplitPattern).first.trim() - : label; + var filterText = !label.startsWith(completionFilterTextSplitPattern) + ? label.split(completionFilterTextSplitPattern).first.trim() + : label; // If we're using label details, we also don't want the label to include any // additional symbols as noted above, because they will appear in the extra @@ -266,18 +264,17 @@ lsp.CompletionItem? toLspCompletionItem( var colorPreviewHex = capabilities.completionItemKinds.contains(lsp.CompletionItemKind.Color) && - suggestion is ElementBasedSuggestion - ? server.getColorHexString(element) - : null; + suggestion is ElementBasedSuggestion + ? server.getColorHexString(element) + : null; - var completionKind = - colorPreviewHex != null - ? lsp.CompletionItemKind.Color - : _candidateToCompletionItemKind( - capabilities.completionItemKinds, - suggestion, - label, - ); + var completionKind = colorPreviewHex != null + ? lsp.CompletionItemKind.Color + : _candidateToCompletionItemKind( + capabilities.completionItemKinds, + suggestion, + label, + ); var labelDetails = _getCompletionDetail( suggestion, @@ -305,10 +302,9 @@ lsp.CompletionItem? toLspCompletionItem( var element = (suggestion as ElementBasedSuggestion).element; if (element is ExecutableElement && element is! PropertyAccessorElement) { - parameterNames = - element.formalParameters.map((parameter) { - return parameter.displayName; - }).toList(); + parameterNames = element.formalParameters.map((parameter) { + return parameter.displayName; + }).toList(); var requiredParameters = element.formalParameters.where( (FormalParameterElement param) => param.isRequiredPositional, @@ -328,10 +324,9 @@ lsp.CompletionItem? toLspCompletionItem( } var completion = suggestion.completion; - var selectionOffset = - (suggestion is KeywordSuggestion) - ? suggestion.selectionOffset - : completion.length; + var selectionOffset = (suggestion is KeywordSuggestion) + ? suggestion.selectionOffset + : completion.length; var selectionLength = 0; if (suggestion is SuggestionData) { @@ -361,10 +356,9 @@ lsp.CompletionItem? toLspCompletionItem( // To improve the display of some items (like pubspec version numbers), // short labels in the format `_foo_` in docComplete are "upgraded" to the // detail field. - var labelMatch = - cleanedDoc != null - ? upgradableDocCompletePattern.firstMatch(cleanedDoc) - : null; + var labelMatch = cleanedDoc != null + ? upgradableDocCompletePattern.firstMatch(cleanedDoc) + : null; if (labelMatch != null) { cleanedDoc = null; labelDetails = ( @@ -398,50 +392,46 @@ lsp.CompletionItem? toLspCompletionItem( ]), data: resolutionData, detail: labelDetails.detail.nullIfEmpty, - labelDetails: - useLabelDetails - ? lsp.CompletionItemLabelDetails( - detail: labelDetails.truncatedSignature.nullIfEmpty, - description: getCompletionDisplayUriString( - uriConverter: uriConverter, - pathContext: pathContext, - elementLibraryUri: labelDetails.autoImportUri, - completionFilePath: completionFilePath, - ), - ).nullIfEmpty - : null, - documentation: - cleanedDoc != null - ? asMarkupContentOrString(formats, cleanedDoc) - : null, + labelDetails: useLabelDetails + ? lsp.CompletionItemLabelDetails( + detail: labelDetails.truncatedSignature.nullIfEmpty, + description: getCompletionDisplayUriString( + uriConverter: uriConverter, + pathContext: pathContext, + elementLibraryUri: labelDetails.autoImportUri, + completionFilePath: completionFilePath, + ), + ).nullIfEmpty + : null, + documentation: cleanedDoc != null + ? asMarkupContentOrString(formats, cleanedDoc) + : null, deprecated: supportsCompletionDeprecatedFlag && isDeprecated ? true : null, sortText: relevanceToSortText(suggestion.relevanceScore), filterText: filterText.orNullIfSameAs( label, ), // filterText uses label if not set - insertTextFormat: - insertTextFormat != lsp.InsertTextFormat.PlainText - ? insertTextFormat - : null, // Defaults to PlainText if not supplied + insertTextFormat: insertTextFormat != lsp.InsertTextFormat.PlainText + ? insertTextFormat + : null, // Defaults to PlainText if not supplied insertTextMode: !hasDefaultTextMode && supportsAsIsInsertMode && isMultilineCompletion - ? lsp.InsertTextMode.asIs - : null, + ? lsp.InsertTextMode.asIs + : null, // When using defaults for edit range, don't use textEdit. - textEdit: - hasDefaultEditRange - ? null - : supportsInsertReplace && insertionRange != replacementRange - ? lsp.Either2.t1( - lsp.InsertReplaceEdit( - insert: insertionRange, - replace: replacementRange, - newText: insertText, - ), - ) - : lsp.Either2.t2( - lsp.TextEdit(range: replacementRange, newText: insertText), + textEdit: hasDefaultEditRange + ? null + : supportsInsertReplace && insertionRange != replacementRange + ? lsp.Either2.t1( + lsp.InsertReplaceEdit( + insert: insertionRange, + replace: replacementRange, + newText: insertText, ), + ) + : lsp.Either2.t2( + lsp.TextEdit(range: replacementRange, newText: insertText), + ), // When using defaults for edit range, use textEditText. textEditText: hasDefaultEditRange ? insertText.orNullIfSameAs(label) : null, ); @@ -490,13 +480,13 @@ lsp.CompletionItemKind? _candidateToCompletionItemKind( if (!label.startsWith('dart:')) { return label.endsWith('.dart') ? const [ - lsp.CompletionItemKind.File, - lsp.CompletionItemKind.Module, - ] + lsp.CompletionItemKind.File, + lsp.CompletionItemKind.Module, + ] : const [ - lsp.CompletionItemKind.Folder, - lsp.CompletionItemKind.Module, - ]; + lsp.CompletionItemKind.Folder, + lsp.CompletionItemKind.Module, + ]; } return const [lsp.CompletionItemKind.Module]; default: @@ -603,10 +593,9 @@ CompletionDetail _getCompletionDetail( } else if (suggestion is RecordFieldSuggestion) { returnType = suggestion.field.type.getDisplayString(); } - var element = - suggestion is ElementBasedSuggestion - ? (suggestion as ElementBasedSuggestion).element - : null; + var element = suggestion is ElementBasedSuggestion + ? (suggestion as ElementBasedSuggestion).element + : null; // Usually getter/setters look the same in completion because they insert the // same text. This is not the case for overrides because they will insert @@ -702,8 +691,9 @@ CompletionDetail _getCompletionDetail( isNotImported = importData.isNotImported; } } - var autoImportUri = - isNotImported && libraryUri.isNotEmpty ? Uri.parse(libraryUri) : null; + var autoImportUri = isNotImported && libraryUri.isNotEmpty + ? Uri.parse(libraryUri) + : null; return ( detail: detail, @@ -757,43 +747,41 @@ String? _getDocumentation( var docs = _getDocsFromComputer(element, request); var doc = removeDartDocDelimiters(docs?.full); - var rawDoc = - includeDocumentation == DocumentationPreference.full - ? doc - : includeDocumentation == DocumentationPreference.summary - ? getDartDocSummary(docs?.summary) - : null; + var rawDoc = includeDocumentation == DocumentationPreference.full + ? doc + : includeDocumentation == DocumentationPreference.summary + ? getDartDocSummary(docs?.summary) + : null; return cleanDartdoc(rawDoc); } /// Additional details about a completion that may be formatted differently /// depending on the client capabilities. -typedef CompletionDetail = - ({ - /// Additional details to go in the details popup. - /// - /// This is usually a full signature (with full parameters) and may also - /// include whether the item is deprecated if the client did not support the - /// native deprecated tag. - String detail, +typedef CompletionDetail = ({ + /// Additional details to go in the details popup. + /// + /// This is usually a full signature (with full parameters) and may also + /// include whether the item is deprecated if the client did not support the + /// native deprecated tag. + String detail, - /// Truncated parameters. Similar to [truncatedSignature] but does not - /// include return types. Used in clients that cannot format signatures - /// differently and is appended immediately after the completion label. The - /// return type is omitted to reduce noise because this text is not subtle. - String truncatedParams, + /// Truncated parameters. Similar to [truncatedSignature] but does not + /// include return types. Used in clients that cannot format signatures + /// differently and is appended immediately after the completion label. The + /// return type is omitted to reduce noise because this text is not subtle. + String truncatedParams, - /// A signature with truncated params. Used for showing immediately after - /// the completion label when it can be formatted differently. - /// - /// () → String - String truncatedSignature, + /// A signature with truncated params. Used for showing immediately after + /// the completion label when it can be formatted differently. + /// + /// () → String + String truncatedSignature, - /// The URI that will be auto-imported if this item is selected in a - /// user-friendly string format (for example a relative path if for a `file:/` - /// URI). - Uri? autoImportUri, - }); + /// The URI that will be auto-imported if this item is selected in a + /// user-friendly string format (for example a relative path if for a `file:/` + /// URI). + Uri? autoImportUri, +}); class _ElementDocumentation { final String full; diff --git a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/abstract_code_actions_producer.dart b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/abstract_code_actions_producer.dart index c0e75c88008..4c744a59ce2 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/abstract_code_actions_producer.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/abstract_code_actions_producer.dart @@ -27,8 +27,11 @@ import 'package:meta/meta.dart'; typedef CodeActionWithPriority = ({CodeAction action, int priority}); -typedef CodeActionWithPriorityAndIndex = - ({CodeAction action, int priority, int index}); +typedef CodeActionWithPriorityAndIndex = ({ + CodeAction action, + int priority, + int index, +}); /// A base for classes that produce [CodeAction]s for the LSP handler. abstract class AbstractCodeActionsProducer diff --git a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/analysis_options.dart b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/analysis_options.dart index 803b6d7a618..10a4b5d37e7 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/analysis_options.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/analysis_options.dart @@ -78,8 +78,9 @@ class AnalysisOptionsCodeActionsProducer extends AbstractCodeActionsProducer { var contextRoot = session.analysisContext.contextRoot; var package = contextRoot.workspace.findPackageFor(optionsFile.path); - var sdkVersionConstraint = - (package is PubPackage) ? package.sdkVersionConstraint : null; + var sdkVersionConstraint = (package is PubPackage) + ? package.sdkVersionConstraint + : null; var errors = analyzeAnalysisOptions( FileSource(optionsFile), diff --git a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/code_action_computer.dart b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/code_action_computer.dart index f4103d591c8..731c141955c 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/code_action_computer.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/code_action_computer.dart @@ -366,15 +366,10 @@ class _CodeActionSorter { var dedupedActions = _dedupeActions(actions, range.start); // Add each index so we can do a stable sort on priority. - var dedupedActionsWithIndex = - dedupedActions.indexed.map((item) { - var (index, action) = item; - return ( - action: action.action, - priority: action.priority, - index: index, - ); - }).toList(); + var dedupedActionsWithIndex = dedupedActions.indexed.map((item) { + var (index, action) = item; + return (action: action.action, priority: action.priority, index: index); + }).toList(); dedupedActionsWithIndex.sort(_compareCodeActions); return dedupedActionsWithIndex.map((action) => action.action).toList(); @@ -488,7 +483,7 @@ class _CodeActionSorter { return firstLiteral.edit != null ? firstLiteral.edit == other.edit : firstLiteral.command != null && - firstLiteral.command == other.command; + firstLiteral.command == other.command; }); // Build a new CodeAction that merges the diagnostics from each same diff --git a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/dart.dart b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/dart.dart index fe1fc06539e..9d84084ed0b 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/code_actions/dart.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/code_actions/dart.dart @@ -208,8 +208,9 @@ class DartCodeActionsProducer extends AbstractCodeActionsProducer { try { // If deduplicating the result only do the expensive "fix all in file" // calculation when we haven't before. - Set? skipAlreadyCalculatedIfNonNull = - willBeDeduplicated ? {} : null; + Set? skipAlreadyCalculatedIfNonNull = willBeDeduplicated + ? {} + : null; var workspace = DartChangeWorkspace(await server.currentSessions); CorrectionUtils? correctionUtils; for (var error in unitResult.diagnostics) { @@ -546,8 +547,12 @@ class DartCodeActionsProducer extends AbstractCodeActionsProducer { ) { return allowCodeActionLiterals ? CodeAction.t1( - CodeActionLiteral(title: command.title, kind: kind, command: command), - ) + CodeActionLiteral( + title: command.title, + kind: kind, + command: command, + ), + ) : CodeAction.t2(command); } } diff --git a/pkg/analysis_server/lib/src/lsp/handlers/commands/abstract_refactor.dart b/pkg/analysis_server/lib/src/lsp/handlers/commands/abstract_refactor.dart index a377593ccd7..e30019bb08b 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/commands/abstract_refactor.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/commands/abstract_refactor.dart @@ -106,8 +106,9 @@ abstract class AbstractRefactorCommandHandler // inject their own user-provided names until LSP has some native // support: // https://github.com/microsoft/language-server-protocol/issues/764 - refactor.name = - options != null ? options['name'] as String : 'NewWidget'; + refactor.name = options != null + ? options['name'] as String + : 'NewWidget'; return success(refactor); case RefactoringKind.INLINE_LOCAL_VARIABLE: diff --git a/pkg/analysis_server/lib/src/lsp/handlers/commands/fix_all_in_workspace.dart b/pkg/analysis_server/lib/src/lsp/handlers/commands/fix_all_in_workspace.dart index 70708c68cee..05dbcbe40b0 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/commands/fix_all_in_workspace.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/commands/fix_all_in_workspace.dart @@ -76,10 +76,9 @@ abstract class AbstractFixAllInWorkspaceCommandHandler server, clientCapabilities, change, - annotateChanges: - requireConfirmation - ? ChangeAnnotations.requireConfirmation - : ChangeAnnotations.include, + annotateChanges: requireConfirmation + ? ChangeAnnotations.requireConfirmation + : ChangeAnnotations.include, ); return sendWorkspaceEditToClient(edit); } diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/editable_arguments_mixin.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/editable_arguments_mixin.dart index 4c95dde64a0..87cf96525ec 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/editable_arguments_mixin.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/editable_arguments_mixin.dart @@ -12,18 +12,17 @@ import 'package:analyzer/src/dartdoc/dartdoc_directive_info.dart'; import 'package:analyzer/src/utilities/extensions/flutter.dart'; /// Information about the arguments and parameters for an invocation. -typedef EditableInvocationInfo = - ({ - AstNode invocation, - String? widgetName, - String? widgetDocumentation, - List parameters, - Map parameterArguments, - Map positionalParameterIndexes, - ArgumentList argumentList, - int numPositionals, - int numSuppliedPositionals, - }); +typedef EditableInvocationInfo = ({ + AstNode invocation, + String? widgetName, + String? widgetDocumentation, + List parameters, + Map parameterArguments, + Map positionalParameterIndexes, + ArgumentList argumentList, + int numPositionals, + int numSuppliedPositionals, +}); mixin EditableArgumentsMixin { DartdocDirectiveInfo getDartdocDirectiveInfoFor(ResolvedUnitResult result); @@ -115,10 +114,9 @@ mixin EditableArgumentsMixin { } var numPositionals = parameters.where((p) => p.isPositional).length; - var numSuppliedPositionals = - argumentList.arguments - .where((argument) => argument is! NamedExpression) - .length; + var numSuppliedPositionals = argumentList.arguments + .where((argument) => argument is! NamedExpression) + .length; // Build a map of parameters to their positional index so we can tell // whether a parameter that doesn't already have an argument will be diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_edit_argument.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_edit_argument.dart index aa8c6fc5bd6..85618943569 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_edit_argument.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_edit_argument.dart @@ -116,8 +116,9 @@ class EditArgumentHandler extends SharedMessageHandler } var argument = parameterArguments[parameter]; - var valueExpression = - argument is NamedExpression ? argument.expression : argument; + var valueExpression = argument is NamedExpression + ? argument.expression + : argument; // Determine whether a value for this parameter is editable. var notEditableReason = getNotEditableReason( @@ -179,10 +180,9 @@ class EditArgumentHandler extends SharedMessageHandler currentArgument is SimpleIdentifier || currentArgument == null; - var enumValue = - preferDotShorthand - ? getDotShorthandEnumConstantName(enumConstant) ?? requestValue - : requestValue; + var enumValue = preferDotShorthand + ? getDotShorthandEnumConstantName(enumConstant) ?? requestValue + : requestValue; return enumValue.toString(); } @@ -294,11 +294,10 @@ class EditArgumentHandler extends SharedMessageHandler // It is a bug if we produced edits in some file other than the one we // expect. var fileEdits = changeBuilder.sourceChange.edits; - var otherFilesEdited = - fileEdits - .map((edit) => edit.file) - .where((file) => file != result.path) - .toSet(); + var otherFilesEdited = fileEdits + .map((edit) => edit.file) + .where((file) => file != result.path) + .toSet(); if (otherFilesEdited.isNotEmpty) { var otherNames = otherFilesEdited.join(', '); throw 'Argument edit for ${result.path} unexpectedly produced edits for $otherNames'; @@ -405,8 +404,9 @@ class EditArgumentHandler extends SharedMessageHandler // If this parameter is positional, we need to first ensure arguments for // any earlier positional parameters are present. if (parameter.isPositional) { - var existingPositionalArguments = - argumentList.arguments.where((a) => a is! NamedExpression).length; + var existingPositionalArguments = argumentList.arguments + .where((a) => a is! NamedExpression) + .length; var unspecifiedPositionals = parameters .where((p) => p.isPositional) .skip(existingPositionalArguments) @@ -422,8 +422,9 @@ class EditArgumentHandler extends SharedMessageHandler } var parameterName = parameter.name; - var argumentNamePrefix = - parameter.isNamed && parameterName != null ? '$parameterName: ' : ''; + var argumentNamePrefix = parameter.isNamed && parameterName != null + ? '$parameterName: ' + : ''; var argumentCode = '$argumentNamePrefix$newValueCode'; // Usually we insert at the end (after the last argument), but if the last @@ -447,10 +448,9 @@ class EditArgumentHandler extends SharedMessageHandler lineInfo.getLocation(argumentList.rightParenthesis.offset).lineNumber; // If we are multiline, indent one level more than the invocation. - var indent = - isMultiline - ? '${utils.getLinePrefix(argumentList.leftParenthesis.offset)} ' - : ''; + var indent = isMultiline + ? '${utils.getLinePrefix(argumentList.leftParenthesis.offset)} ' + : ''; // The prefix we need depends on whether there is an argument before us // and whether we are multiline. diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_editable_arguments.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_editable_arguments.dart index 4fa53019587..60a82883450 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_editable_arguments.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/editable_arguments/handler_editable_arguments.dart @@ -161,8 +161,9 @@ class EditableArgumentsHandler required int numPositionals, required int numSuppliedPositionals, }) { - var valueExpression = - argument is NamedExpression ? argument.expression : argument; + var valueExpression = argument is NamedExpression + ? argument.expression + : argument; // Lazily compute the values if we will use this parameter/argument. late var values = _getValues(parameter, valueExpression); diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmentation.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmentation.dart index 308963aa1ca..694222b520c 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmentation.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmentation.dart @@ -40,10 +40,9 @@ class AugmentationHandler return (unit, offset).mapResultsSync((unit, offset) { // Find the nearest node that could have fragments. - var node = - unit.unit - .nodeCovering(offset: offset) - ?.thisOrAncestorOfType(); + var node = unit.unit + .nodeCovering(offset: offset) + ?.thisOrAncestorOfType(); var location = fragmentToLocation( uriConverter, diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmented.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmented.dart index 9d98d36bda4..830c3109d9b 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmented.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_augmented.dart @@ -40,10 +40,9 @@ class AugmentedHandler return (unit, offset).mapResultsSync((unit, offset) { // Find the nearest node that could have fragments. - var node = - unit.unit - .nodeCovering(offset: offset) - ?.thisOrAncestorOfType(); + var node = unit.unit + .nodeCovering(offset: offset) + ?.thisOrAncestorOfType(); var location = fragmentToLocation( uriConverter, diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_dart_text_document_content_provider.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_dart_text_document_content_provider.dart index 0e915028172..0e1ab8b9277 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_dart_text_document_content_provider.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_dart_text_document_content_provider.dart @@ -39,10 +39,9 @@ class DartTextDocumentContentProviderHandler var uri = params.uri; if (!allowedSchemes.contains(uri.scheme)) { - var supportedSchemesString = - allowedSchemes.isEmpty - ? '(none)' - : allowedSchemes.map((scheme) => "'$scheme'").join(', '); + var supportedSchemesString = allowedSchemes.isEmpty + ? '(none)' + : allowedSchemes.map((scheme) => "'$scheme'").join(', '); return error( ErrorCodes.InvalidParams, "Fetching content for scheme '${uri.scheme}' is not supported. " diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_imports.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_imports.dart index 458e5a1f198..8af9fed0c5a 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_imports.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_imports.dart @@ -49,9 +49,9 @@ class ImportsHandler return unit != null ? success(unit) : error( - ErrorCodes.InternalError, - 'The library containing a path did not contain the path.', - ); + ErrorCodes.InternalError, + 'The library containing a path did not contain the path.', + ); }); var offset = unit.mapResultSync( (unit) => toOffset(unit.unit.lineInfo, pos), @@ -143,15 +143,13 @@ class ImportsHandler var importPrefix = directive.prefix?.name; if (importPrefix != prefix) continue; - var importedElement = - prefix == null - ? import.namespace.get2(elementName) - : import.namespace.getPrefixed2(prefix, elementName); + var importedElement = prefix == null + ? import.namespace.get2(elementName) + : import.namespace.getPrefixed2(prefix, elementName); - var isMatch = - element is MultiplyDefinedElement - ? element.conflictingElements.contains(importedElement) - : element == importedElement; + var isMatch = element is MultiplyDefinedElement + ? element.conflictingElements.contains(importedElement) + : element == importedElement; if (isMatch) { var uri = uriConverter.toClientUri( diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_summary.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_summary.dart index 8f5b8d02960..c0925c9df19 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_summary.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_summary.dart @@ -540,7 +540,8 @@ extension on DirectiveUri { DirectiveUriWithLibrary(:var source) => source.uri.toString(), DirectiveUriWithRelativeUriString(:var relativeUriString) => relativeUriString, - DirectiveUri() => - throw UnimplementedError('Unhandled instance of type $runtimeType'), + DirectiveUri() => throw UnimplementedError( + 'Unhandled instance of type $runtimeType', + ), }; } diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_call_hierarchy.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_call_hierarchy.dart index 99a19549e38..e0866798c29 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_call_hierarchy.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_call_hierarchy.dart @@ -101,13 +101,12 @@ class IncomingCallHierarchyHandler itemLineInfo, supportedSymbolKinds: supportedSymbolKinds, ), - fromRanges: - calls.ranges - // For incoming calls, ranges are in the referenced item so we use - // itemLineInfo and not localLineInfo (which is for the original - // target we're collecting calls to). - .map((call) => sourceRangeToRange(itemLineInfo, call)) - .toList(), + fromRanges: calls.ranges + // For incoming calls, ranges are in the referenced item so we use + // itemLineInfo and not localLineInfo (which is for the original + // target we're collecting calls to). + .map((call) => sourceRangeToRange(itemLineInfo, call)) + .toList(), ); } } @@ -174,13 +173,12 @@ class OutgoingCallHierarchyHandler itemLineInfo, supportedSymbolKinds: supportedSymbolKinds, ), - fromRanges: - calls.ranges - // For incoming calls, ranges are in original target so we use - // localLineInfo and not itemLineInfo (which is for call target - // the outbound call points to). - .map((call) => sourceRangeToRange(localLineInfo, call)) - .toList(), + fromRanges: calls.ranges + // For incoming calls, ranges are in original target so we use + // localLineInfo and not itemLineInfo (which is for call target + // the outbound call points to). + .map((call) => sourceRangeToRange(localLineInfo, call)) + .toList(), ); } } diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart index e8b12954f68..f0152d71521 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart @@ -43,8 +43,9 @@ class CodeActionHandler } var supportsLiterals = callerCapabilities.literalCodeActions; - var supportedKinds = - supportsLiterals ? callerCapabilities.codeActionKinds : null; + var supportedKinds = supportsLiterals + ? callerCapabilities.codeActionKinds + : null; var computer = CodeActionComputer( server, @@ -86,12 +87,12 @@ class CodeActionRegistrations extends FeatureRegistration // signals code action literal support via the property // `textDocument.codeAction.codeActionLiteralSupport`." codeActionLiteralSupport - ? Either2.t2( - CodeActionOptions( - codeActionKinds: DartCodeActionKind.serverSupportedKinds, - ), - ) - : Either2.t1(true); + ? Either2.t2( + CodeActionOptions( + codeActionKinds: DartCodeActionKind.serverSupportedKinds, + ), + ) + : Either2.t1(true); @override bool get supportsDynamic => clientDynamic.codeActions; diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart index b0857beabe6..554553cf52d 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart @@ -71,10 +71,9 @@ class CompletionHandler : suggestFromUnimportedLibraries = server.initializationOptions?.suggestFromUnimportedLibraries ?? true { var budgetMs = server.initializationOptions?.completionBudgetMilliseconds; - completionBudgetDuration = - budgetMs != null - ? Duration(milliseconds: budgetMs) - : CompletionBudget.defaultDuration; + completionBudgetDuration = budgetMs != null + ? Duration(milliseconds: budgetMs) + : CompletionBudget.defaultDuration; } @override @@ -148,8 +147,9 @@ class CompletionHandler offset, ) async { var fileExtension = pathContext.extension(path); - var maxResults = - server.lspClientConfiguration.forResource(path).maxCompletionItems; + var maxResults = server.lspClientConfiguration + .forResource(path) + .maxCompletionItems; CompletionPerformance? completionPerformance; Future>? serverResultsFuture; if (fileExtension == '.dart') { @@ -216,18 +216,17 @@ class CompletionHandler var maxRankedItems = math.max(maxResults - unrankedItems.length, 0); var truncatedRankedItems = untruncatedRankedItems.length <= maxRankedItems - ? untruncatedRankedItems - : _truncateResults( - untruncatedRankedItems, - serverResults.targetPrefix, - maxRankedItems, - ); + ? untruncatedRankedItems + : _truncateResults( + untruncatedRankedItems, + serverResults.targetPrefix, + maxRankedItems, + ); - var truncatedItems = - truncatedRankedItems - .map((item) => item.item) - .followedBy(unrankedItems) - .toList(); + var truncatedItems = truncatedRankedItems + .map((item) => item.item) + .followedBy(unrankedItems) + .toList(); // If we're tracing performance (only Dart), record the number of results // after truncation. @@ -263,8 +262,9 @@ class CompletionHandler } return CompletionItemDefaults( - insertTextMode: - capabilities.completionDefaultTextMode ? InsertTextMode.asIs : null, + insertTextMode: capabilities.completionDefaultTextMode + ? InsertTextMode.asIs + : null, editRange: _computeDefaultEditRange( capabilities, insertionRange, @@ -541,10 +541,9 @@ class CompletionHandler resolutionData: resolutionInfo, // Exclude docs if we will be providing them via // `completionItem/resolve`, otherwise use users preference. - includeDocumentation: - resolutionInfo != null - ? DocumentationPreference.none - : server.lspClientConfiguration.global.preferredDocumentation, + includeDocumentation: resolutionInfo != null + ? DocumentationPreference.none + : server.lspClientConfiguration.global.preferredDocumentation, ); } @@ -562,8 +561,9 @@ class CompletionHandler }); // Add in any snippets. - var snippetsEnabled = - server.lspClientConfiguration.forResource(unit.path).enableSnippets; + var snippetsEnabled = server.lspClientConfiguration + .forResource(unit.path) + .enableSnippets; // We can only produce edits with edit builders for files inside // the root, so skip snippets entirely if not. var isEditableFile = unit.session.analysisContext.contextRoot.isAnalyzed( @@ -658,47 +658,41 @@ class CompletionHandler var fuzzyPattern = suggestions.targetPrefix; var fuzzyMatcher = FuzzyMatcher(fuzzyPattern); - var completionItems = - suggestions.suggestions - .where( - (item) => - fuzzyMatcher.score(item.displayText ?? item.completion) > 0, - ) - .map((item) { - var resolutionInfo = - item.kind == CompletionSuggestionKind.PACKAGE_NAME - ? PubPackageCompletionItemResolutionInfo( - // The completion for package names may contain a trailing - // ': ' for convenience, so if it's there, trim it off. - packageName: item.completion.split(':').first, - ) - : null; - return toCompletionItem( - capabilities, - lineInfo, - item, - uriConverter: uriConverter, - pathContext: pathContext, - completionFilePath: filePath, - replacementRange: replacementRange, - insertionRange: insertionRange, - commitCharactersEnabled: false, - completeFunctionCalls: false, - // Exclude docs if we could provide them via - // `completionItem/resolve`, otherwise use users preference. - includeDocumentation: - resolutionInfo != null - ? DocumentationPreference.none - : server - .lspClientConfiguration - .global - .preferredDocumentation, - // Add on any completion-kind-specific resolution data that will be - // used during resolve() calls to provide additional information. - resolutionData: resolutionInfo, - ); - }) - .toList(); + var completionItems = suggestions.suggestions + .where( + (item) => fuzzyMatcher.score(item.displayText ?? item.completion) > 0, + ) + .map((item) { + var resolutionInfo = + item.kind == CompletionSuggestionKind.PACKAGE_NAME + ? PubPackageCompletionItemResolutionInfo( + // The completion for package names may contain a trailing + // ': ' for convenience, so if it's there, trim it off. + packageName: item.completion.split(':').first, + ) + : null; + return toCompletionItem( + capabilities, + lineInfo, + item, + uriConverter: uriConverter, + pathContext: pathContext, + completionFilePath: filePath, + replacementRange: replacementRange, + insertionRange: insertionRange, + commitCharactersEnabled: false, + completeFunctionCalls: false, + // Exclude docs if we could provide them via + // `completionItem/resolve`, otherwise use users preference. + includeDocumentation: resolutionInfo != null + ? DocumentationPreference.none + : server.lspClientConfiguration.global.preferredDocumentation, + // Add on any completion-kind-specific resolution data that will be + // used during resolve() calls to provide additional information. + resolutionData: resolutionInfo, + ); + }) + .toList(); return success( _CompletionResults.unranked(completionItems, isIncomplete: false), ); @@ -784,12 +778,10 @@ class CompletionHandler // Skip the text comparisons if we don't have a prefix (plugin results, or // just no prefix when completion was invoked). - var shouldInclude = - prefixLower.isEmpty - ? (int index, _ScoredCompletionItem item) => - index < maxCompletionCount - : (int index, _ScoredCompletionItem item) => - index < maxCompletionCount || isExactMatch(item.item); + var shouldInclude = prefixLower.isEmpty + ? (int index, _ScoredCompletionItem item) => index < maxCompletionCount + : (int index, _ScoredCompletionItem item) => + index < maxCompletionCount || isExactMatch(item.item); return items.whereIndexed(shouldInclude); } @@ -851,8 +843,9 @@ class CompletionRegistrations extends FeatureRegistration CompletionRegistrationOptions( documentSelector: dartFiles, triggerCharacters: dartCompletionTriggerCharacters, - allCommitCharacters: - previewCommitCharacters ? dartCompletionCommitCharacters : null, + allCommitCharacters: previewCommitCharacters + ? dartCompletionCommitCharacters + : null, resolveProvider: true, completionItem: ServerCompletionItemOptions( labelDetailsSupport: true, @@ -892,8 +885,9 @@ class CompletionRegistrations extends FeatureRegistration @override CompletionOptions get staticOptions => CompletionOptions( triggerCharacters: dartCompletionTriggerCharacters, - allCommitCharacters: - previewCommitCharacters ? dartCompletionCommitCharacters : null, + allCommitCharacters: previewCommitCharacters + ? dartCompletionCommitCharacters + : null, resolveProvider: true, completionItem: ServerCompletionItemOptions(labelDetailsSupport: true), ); diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart index cf03445bed3..d8e32957eed 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart @@ -87,12 +87,9 @@ class CompletionResolveHandler return cancelled(token); } - var element = - elementReference != null - ? await ElementLocation.decode( - elementReference, - ).locateIn(session) - : null; + var element = elementReference != null + ? await ElementLocation.decode(elementReference).locateIn(session) + : null; var showName = element?.name; if (element?.enclosingElement case InstanceElement(:var name)) { @@ -111,10 +108,12 @@ class CompletionResolveHandler } var changes = builder.sourceChange; - var thisFilesChanges = - changes.edits.where((e) => e.file == file).toList(); - var otherFilesChanges = - changes.edits.where((e) => e.file != file).toList(); + var thisFilesChanges = changes.edits + .where((e) => e.file == file) + .toList(); + var otherFilesChanges = changes.edits + .where((e) => e.file != file) + .toList(); // If this completion involves editing other files, we'll need to build // a command that the client will call to apply those edits later. @@ -145,10 +144,9 @@ class CompletionResolveHandler server.lspClientConfiguration.global.preferredDocumentation, ); // `dartDoc` can be both null or empty. - documentation = - dartDoc != null && dartDoc.isNotEmpty - ? asMarkupContentOrString(formats, dartDoc) - : null; + documentation = dartDoc != null && dartDoc.isNotEmpty + ? asMarkupContentOrString(formats, dartDoc) + : null; } String? detail = item.detail; @@ -185,14 +183,13 @@ class CompletionResolveHandler insertTextFormat: item.insertTextFormat, insertTextMode: item.insertTextMode, textEdit: item.textEdit, - additionalTextEdits: - thisFilesChanges - .expand( - (change) => sortSourceEditsForLsp( - change.edits, - ).map((edit) => toTextEdit(result.lineInfo, edit)), - ) - .toList(), + additionalTextEdits: thisFilesChanges + .expand( + (change) => sortSourceEditsForLsp( + change.edits, + ).map((edit) => toTextEdit(result.lineInfo, edit)), + ) + .toList(), commitCharacters: item.commitCharacters, command: command ?? item.command, data: item.data, @@ -233,10 +230,9 @@ class CompletionResolveHandler kind: item.kind, tags: item.tags, detail: item.detail, - documentation: - description != null - ? Either2.t2(description) - : null, + documentation: description != null + ? Either2.t2(description) + : null, deprecated: item.deprecated, preselect: item.preselect, sortText: item.sortText, diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_definition.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_definition.dart index c277acb627f..201ffb84737 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_definition.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_definition.dart @@ -156,12 +156,11 @@ class DefinitionHandler // Convert and filter the results using the correct type of Location class // depending on the client capabilities. if (supportsLocationLink) { - var convertedResults = - convert( - mergedTargets, - (NavigationTarget target) => - _toLocationLink(mergedResults, lineInfo, target), - ).nonNulls.toList(); + var convertedResults = convert( + mergedTargets, + (NavigationTarget target) => + _toLocationLink(mergedResults, lineInfo, target), + ).nonNulls.toList(); var results = _filterResults( convertedResults, @@ -173,11 +172,10 @@ class DefinitionHandler return success(TextDocumentDefinitionResult.t2(results)); } else { - var convertedResults = - convert( - mergedTargets, - (NavigationTarget target) => _toLocation(mergedResults, target), - ).nonNulls.toList(); + var convertedResults = convert( + mergedTargets, + (NavigationTarget target) => _toLocation(mergedResults, target), + ).nonNulls.toList(); var results = _filterResults( convertedResults, @@ -210,14 +208,13 @@ class DefinitionHandler // adjacent to the var keyword, so providing navigation to it is not useful). // To prevent this, filter the list to only those on different lines (or // different files). - var otherResults = - results - .where( - (element) => - uriSelector(element) != sourceUri || - rangeSelector(element).start.line != sourceLineNumber, - ) - .toList(); + var otherResults = results + .where( + (element) => + uriSelector(element) != sourceUri || + rangeSelector(element).start.line != sourceLineNumber, + ) + .toList(); return otherResults.isNotEmpty ? otherResults : results; } @@ -306,12 +303,12 @@ class DefinitionHandler return targetLineInfo != null ? navigationTargetToLocationLink( - region, - sourceLineInfo, - targetFileUri, - target, - targetLineInfo, - ) + region, + sourceLineInfo, + targetFileUri, + target, + targetLineInfo, + ) : null; } diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color_presentation.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color_presentation.dart index 652ea4ea98c..a4914b1ce65 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color_presentation.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color_presentation.dart @@ -89,11 +89,10 @@ class DocumentColorPresentationHandler // We can only apply changes to the same file, so filter any change from the // builder to only include this file, otherwise we may corrupt the users // source (although hopefully we don't produce edits for other files). - var editsForThisFile = - builder.sourceChange.edits - .where((edit) => edit.file == unit.path) - .expand((edit) => edit.edits) - .toList(); + var editsForThisFile = builder.sourceChange.edits + .where((edit) => edit.file == unit.path) + .expand((edit) => edit.edits) + .toList(); // LSP requires that we separate the main edit (changing the color code) // from anything else (imports). @@ -107,12 +106,9 @@ class DocumentColorPresentationHandler return ColorPresentation( label: '$typeName$invocationString', textEdit: toTextEdit(unit.lineInfo, mainEdit), - additionalTextEdits: - otherEdits.isNotEmpty - ? otherEdits - .map((edit) => toTextEdit(unit.lineInfo, edit)) - .toList() - : null, + additionalTextEdits: otherEdits.isNotEmpty + ? otherEdits.map((edit) => toTextEdit(unit.lineInfo, edit)).toList() + : null, ); } @@ -245,8 +241,9 @@ class DocumentColorPresentationHandler return node.isConst; } else if (node is SimpleIdentifier) { var parent = node.parent; - var element = - parent is PrefixedIdentifier ? parent.element : node.element; + var element = parent is PrefixedIdentifier + ? parent.element + : node.element; return switch (element) { PropertyAccessorElement(:var variable) => variable.isConst, diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_highlights.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_highlights.dart index 5fe383e6a18..a91dbd37c9f 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_highlights.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_highlights.dart @@ -71,14 +71,13 @@ class DocumentHighlightsHandler // No matches will return an empty list (not null) because that prevents // the editor falling back to a text search. - var highlights = - matchingSet - .map( - (token) => DocumentHighlight( - range: toRange(unit.lineInfo, token.offset, token.length), - ), - ) - .toList(); + var highlights = matchingSet + .map( + (token) => DocumentHighlight( + range: toRange(unit.lineInfo, token.offset, token.length), + ), + ) + .toList(); return success(highlights); }); diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_symbols.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_symbols.dart index 52a0963896f..dbfba8b6b3f 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_symbols.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_symbols.dart @@ -57,10 +57,9 @@ class DocumentSymbolHandler ) { var codeRange = toRange(lineInfo, outline.codeOffset, outline.codeLength); var nameLocation = outline.element.location; - var nameRange = - nameLocation != null - ? toRange(lineInfo, nameLocation.offset, nameLocation.length) - : null; + var nameRange = nameLocation != null + ? toRange(lineInfo, nameLocation.offset, nameLocation.length) + : null; return DocumentSymbol( name: toElementName(outline.element), detail: outline.element.parameters, @@ -68,12 +67,9 @@ class DocumentSymbolHandler deprecated: outline.element.isDeprecated, range: codeRange, selectionRange: nameRange ?? codeRange, - children: - outline.children - ?.map( - (child) => _asDocumentSymbol(supportedKinds, lineInfo, child), - ) - .toList(), + children: outline.children + ?.map((child) => _asDocumentSymbol(supportedKinds, lineInfo, child)) + .toList(), ); } diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart index 6fb658ecfe8..9d68b77828b 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart @@ -98,14 +98,13 @@ class ExecuteCommandHandler var workDoneToken = params.workDoneToken; ProgressReporter progress = ProgressReporter.noop; if (server case LspAnalysisServer server) { - progress = - workDoneToken != null - ? ProgressReporter.clientProvided(server, workDoneToken) - // Use editor client capabilities, as that's who gets progress - // notifications, not the caller. - : server.editorClientCapabilities?.workDoneProgress ?? false - ? ProgressReporter.serverCreated(server) - : ProgressReporter.noop; + progress = workDoneToken != null + ? ProgressReporter.clientProvided(server, workDoneToken) + // Use editor client capabilities, as that's who gets progress + // notifications, not the caller. + : server.editorClientCapabilities?.workDoneProgress ?? false + ? ProgressReporter.serverCreated(server) + : ProgressReporter.noop; } // To make passing arguments easier in commands, instead of a diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_folding.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_folding.dart index a4813e6174e..94e4b761de6 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_folding.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_folding.dart @@ -73,16 +73,12 @@ class FoldingHandler // line mode below. regions.sort((r1, r2) => r1.offset.compareTo(r2.offset)); - var foldingRanges = - regions - .map( - (region) => _toFoldingRange( - lineInfo!, - region, - lineOnly: lineFoldingOnly, - ), - ) - .toList(); + var foldingRanges = regions + .map( + (region) => + _toFoldingRange(lineInfo!, region, lineOnly: lineFoldingOnly), + ) + .toList(); // When in line-only mode, ranges that end on the same line that another // ranges starts should be truncated to be on the line before (and if this diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_format_on_type.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_format_on_type.dart index 31bc0bfaf54..1db8aa42e5d 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_format_on_type.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_format_on_type.dart @@ -88,13 +88,12 @@ class FormatOnTypeRegistrations extends FeatureRegistration Method get registrationMethod => Method.textDocument_onTypeFormatting; @override - StaticOptions get staticOptions => - enableFormatter - ? DocumentOnTypeFormattingOptions( - firstTriggerCharacter: dartTypeFormattingCharacters.first, - moreTriggerCharacter: dartTypeFormattingCharacters.skip(1).toList(), - ) - : null; + StaticOptions get staticOptions => enableFormatter + ? DocumentOnTypeFormattingOptions( + firstTriggerCharacter: dartTypeFormattingCharacters.first, + moreTriggerCharacter: dartTypeFormattingCharacters.skip(1).toList(), + ) + : null; @override bool get supportsDynamic => enableFormatter && clientDynamic.typeFormatting; diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_implementation.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_implementation.dart index c9f1ed73f86..fea3637ab15 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_implementation.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_implementation.dart @@ -87,44 +87,37 @@ class ImplementationHandler var locations = performance.run( 'filter and get location', - (_) => - allSubtypes - .map((element) { - return needsMember - // Filter based on type, so when searching for members we don't - // include any intermediate classes that don't have - // implementations for the method. - ? helper.findMemberElement(element)?.nonSynthetic - : element; - }) - .nonNulls - .toSet() - .map((element) { - var firstFragment = element.firstFragment; - var libraryFragment = firstFragment.libraryFragment; - if (libraryFragment == null) { - return null; - } + (_) => allSubtypes + .map((element) { + return needsMember + // Filter based on type, so when searching for members we don't + // include any intermediate classes that don't have + // implementations for the method. + ? helper.findMemberElement(element)?.nonSynthetic + : element; + }) + .nonNulls + .toSet() + .map((element) { + var firstFragment = element.firstFragment; + var libraryFragment = firstFragment.libraryFragment; + if (libraryFragment == null) { + return null; + } - var nameOffset = firstFragment.nameOffset; - var name = firstFragment.name; - if (nameOffset == null || name == null) { - return null; - } + var nameOffset = firstFragment.nameOffset; + var name = firstFragment.name; + if (nameOffset == null || name == null) { + return null; + } - return Location( - uri: uriConverter.toClientUri( - libraryFragment.source.fullName, - ), - range: toRange( - libraryFragment.lineInfo, - nameOffset, - name.length, - ), - ); - }) - .nonNulls - .toList(), + return Location( + uri: uriConverter.toClientUri(libraryFragment.source.fullName), + range: toRange(libraryFragment.lineInfo, nameOffset, name.length), + ); + }) + .nonNulls + .toList(), ); return success(locations); diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_initialized.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_initialized.dart index be313b910c3..201c5a0957f 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_initialized.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_initialized.dart @@ -24,8 +24,8 @@ class InitializedMessageHandler MessageInfo message, CancellationToken token, ) async { - var initializedHandler = - server.messageHandler = InitializedLspStateMessageHandler(server); + var initializedHandler = server.messageHandler = + InitializedLspStateMessageHandler(server); server.analyticsManager.initialized(openWorkspacePaths: openWorkspacePaths); diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_rename.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_rename.dart index 3c29f98ee16..afeaa7cc065 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_rename.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_rename.dart @@ -274,13 +274,12 @@ class RenameHandler extends LspMessageHandler { _isClassRename(refactoring)) { // The rename must always be performed on the file that defines the // class which is not necessarily the one where the rename was invoked. - var declaringFile = - (refactoring as RenameUnitMemberRefactoringImpl) - .element - .firstFragment - .libraryFragment - ?.source - .fullName; + var declaringFile = (refactoring as RenameUnitMemberRefactoringImpl) + .element + .firstFragment + .libraryFragment + ?.source + .fullName; if (declaringFile != null) { var folder = pathContext.dirname(declaringFile); var actualFilename = pathContext.basename(declaringFile); @@ -358,12 +357,9 @@ class RenameRegistrations extends FeatureRegistration Method get registrationMethod => Method.textDocument_rename; @override - StaticOptions get staticOptions => - clientCapabilities.renameValidation - ? Either2.t2( - RenameOptions(prepareProvider: true), - ) - : Either2.t1(true); + StaticOptions get staticOptions => clientCapabilities.renameValidation + ? Either2.t2(RenameOptions(prepareProvider: true)) + : Either2.t1(true); @override bool get supportsDynamic => clientDynamic.rename; diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_selection_range.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_selection_range.dart index 23cf1043fba..97d4b73c05e 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_selection_range.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_selection_range.dart @@ -40,8 +40,9 @@ class SelectionRangeHandler var unit = await requireUnresolvedUnit(path); return unit.mapResultSync((unit) { var positions = params.positions; - var offsets = - positions.map((pos) => toOffset(unit.lineInfo, pos)).errorOrResults; + var offsets = positions + .map((pos) => toOffset(unit.lineInfo, pos)) + .errorOrResults; var allRanges = offsets.mapResultSync( (offsets) => success(_getSelectionRangesForOffsets(offsets, unit)), ); diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_semantic_tokens.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_semantic_tokens.dart index b296b9905a5..8c518ea5fd3 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_semantic_tokens.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_semantic_tokens.dart @@ -73,10 +73,9 @@ abstract class AbstractSemanticTokensHandler } return toSourceRangeNullable(lineInfo, range).mapResult((range) async { - var serverTokens = - resolvedUnit != null - ? await getServerResult(resolvedUnit.unit, range) - : []; + var serverTokens = resolvedUnit != null + ? await getServerResult(resolvedUnit.unit, range) + : []; var pluginHighlightRegions = getPluginResults(path).flattenedToList; if (token.isCancellationRequested) { @@ -102,8 +101,8 @@ abstract class AbstractSemanticTokensHandler // Some of the translation operations and the final encoding require // the tokens to be sorted. Do it once here to avoid each method needing // to do it itself (resulting in multiple sorts). - tokens = - tokens.toList()..sort(SemanticTokenInfo.offsetLengthPrioritySort); + tokens = tokens.toList() + ..sort(SemanticTokenInfo.offsetLengthPrioritySort); if (!allowOverlappingTokens) { tokens = encoder.splitOverlappingTokens(tokens); diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_type_definition.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_type_definition.dart index 2a7bce9a2c0..6d0179d45f6 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_type_definition.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_type_definition.dart @@ -180,10 +180,9 @@ class TypeDefinitionHandler _ => (null, null), }; - var codeRange = - codeOffset != null && codeLength != null - ? toRange(targetUnit.lineInfo, codeOffset, codeLength) - : targetNameRange; + var codeRange = codeOffset != null && codeLength != null + ? toRange(targetUnit.lineInfo, codeOffset, codeLength) + : targetNameRange; return LocationLink( originSelectionRange: toRange( diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart index 38199842ac3..5d3829b9b98 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart @@ -49,11 +49,10 @@ class WorkspaceSymbolHandler } var supportedSymbolKinds = clientCapabilities.workspaceSymbolKinds; - var searchOnlyAnalyzed = - !server - .lspClientConfiguration - .global - .includeDependenciesInWorkspaceSymbols; + var searchOnlyAnalyzed = !server + .lspClientConfiguration + .global + .includeDependenciesInWorkspaceSymbols; // Cap the number of results we'll return because short queries may match // huge numbers on large projects. diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart b/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart index bde6b5f65cc..f33ffcaca52 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart @@ -191,10 +191,9 @@ mixin HandlerHelperMixin { var supportedSchemes = server.uriConverter.supportedSchemes; var isValidScheme = supportedSchemes.contains(uri.scheme); if (!isValidScheme) { - var supportedSchemesString = - supportedSchemes.isEmpty - ? '(none)' - : supportedSchemes.map((scheme) => "'$scheme'").join(', '); + var supportedSchemesString = supportedSchemes.isEmpty + ? '(none)' + : supportedSchemes.map((scheme) => "'$scheme'").join(', '); return ErrorOr.error( ResponseError( code: ServerErrorCodes.InvalidFilePath, @@ -428,8 +427,9 @@ abstract class MessageHandler ); } - var params = - paramsJson != null ? jsonHandler.convertParams(paramsJson) : null as P; + var params = paramsJson != null + ? jsonHandler.convertParams(paramsJson) + : null as P; return handle(params, messageInfo, token); } } diff --git a/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart b/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart index accbcfb3926..6cc726fb990 100644 --- a/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart +++ b/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart @@ -374,10 +374,8 @@ class LspAnalysisServer extends AnalysisServer { ) { _clientCapabilities = LspClientCapabilities(capabilities); _clientInfo = clientInfo; - var initializationOptions = - _initializationOptions = LspInitializationOptions( - rawInitializationOptions, - ); + var initializationOptions = _initializationOptions = + LspInitializationOptions(rawInitializationOptions); /// Enable virtual file support. var supportsVirtualFiles = @@ -533,14 +531,13 @@ class LspAnalysisServer extends AnalysisServer { ); completer?.setComplete(); } catch (error, stackTrace) { - var errorMessage = - message is ResponseMessage - ? 'An error occurred while handling the response to request ${message.id}' - : message is RequestMessage - ? 'An error occurred while handling ${message.method} request' - : message is NotificationMessage - ? 'An error occurred while handling ${message.method} notification' - : 'Unknown message type'; + var errorMessage = message is ResponseMessage + ? 'An error occurred while handling the response to request ${message.id}' + : message is RequestMessage + ? 'An error occurred while handling ${message.method} request' + : message is NotificationMessage + ? 'An error occurred while handling ${message.method} notification' + : 'Unknown message type'; sendErrorResponse( message, ResponseError( @@ -579,8 +576,9 @@ class LspAnalysisServer extends AnalysisServer { fullMessage = '$fullMessage: $exception'; } - var fullError = - stackTrace == null ? fullMessage : '$fullMessage\n$stackTrace'; + var fullError = stackTrace == null + ? fullMessage + : '$fullMessage\n$stackTrace'; stackTrace ??= StackTrace.current; // Log the full message since showMessage above may be truncated or @@ -1027,12 +1025,11 @@ class LspAnalysisServer extends AnalysisServer { var packages = {}; var additionalFiles = []; for (var file in openFiles) { - var package = - roots - .where((root) => root.isAnalyzed(file)) - .map((root) => root.workspace.findPackageFor(file)?.root) - .nonNulls - .firstOrNull; + var package = roots + .where((root) => root.isAnalyzed(file)) + .map((root) => root.workspace.findPackageFor(file)?.root) + .nonNulls + .firstOrNull; if (package != null && !package.isRoot) { packages.add(package.path); } else { @@ -1101,30 +1098,25 @@ class LspAnalysisServer extends AnalysisServer { // When there are open folders, they are always the roots. If there are no // open workspace folders, then we use the open (priority) files to compute // roots. - var includedPaths = - _workspaceFolders.isNotEmpty - ? _workspaceFolders.toSet() - : _getRootsForOpenFiles(); + var includedPaths = _workspaceFolders.isNotEmpty + ? _workspaceFolders.toSet() + : _getRootsForOpenFiles(); - var excludedPaths = - lspClientConfiguration.global.analysisExcludedFolders - .expand( - (excludePath) => - resourceProvider.pathContext.isAbsolute(excludePath) - ? [excludePath] - // Apply the relative path to each open workspace folder. - // TODO(dantup): Consider supporting per-workspace config by - // calling workspace/configuration whenever workspace folders change - // and caching the config for each one. - : _workspaceFolders.map( - (root) => resourceProvider.pathContext.join( - root, - excludePath, - ), - ), - ) - .map(pathContext.normalize) - .toSet(); + var excludedPaths = lspClientConfiguration.global.analysisExcludedFolders + .expand( + (excludePath) => resourceProvider.pathContext.isAbsolute(excludePath) + ? [excludePath] + // Apply the relative path to each open workspace folder. + // TODO(dantup): Consider supporting per-workspace config by + // calling workspace/configuration whenever workspace folders change + // and caching the config for each one. + : _workspaceFolders.map( + (root) => + resourceProvider.pathContext.join(root, excludePath), + ), + ) + .map(pathContext.normalize) + .toSet(); var completer = analysisContextRebuildCompleter = Completer(); try { @@ -1252,17 +1244,18 @@ class LspServerContextManagerCallbacks var unit = result.unit; if (analysisServer.shouldSendClosingLabelsFor(path)) { - var labels = - DartUnitClosingLabelsComputer( - result.lineInfo, - unit, - ).compute().map((l) => toClosingLabel(result.lineInfo, l)).toList(); + var labels = DartUnitClosingLabelsComputer( + result.lineInfo, + unit, + ).compute().map((l) => toClosingLabel(result.lineInfo, l)).toList(); analysisServer.publishClosingLabels(path, labels); } if (analysisServer.shouldSendOutlineFor(path)) { - var outline = - DartUnitOutlineComputer(result, withBasicFlutter: true).compute(); + var outline = DartUnitOutlineComputer( + result, + withBasicFlutter: true, + ).compute(); var lspOutline = toOutline(result.lineInfo, outline); analysisServer.publishOutline(path, lspOutline); } diff --git a/pkg/analysis_server/lib/src/lsp/lsp_packet_transformer.dart b/pkg/analysis_server/lib/src/lsp/lsp_packet_transformer.dart index f183674f7e4..599c3be1e49 100644 --- a/pkg/analysis_server/lib/src/lsp/lsp_packet_transformer.dart +++ b/pkg/analysis_server/lib/src/lsp/lsp_packet_transformer.dart @@ -38,53 +38,54 @@ class LspPacketTransformer extends StreamTransformerBase, String> { Stream bind(Stream> stream) { LspHeaders? headersState; var buffer = []; - var controller = MoreTypedStreamController< - String, - _LspPacketTransformerListenData, - _LspPacketTransformerPauseData - >( - onListen: (controller) { - var input = stream - .expand((b) => b) - .listen( - (codeUnit) { - buffer.add(codeUnit); - var headers = headersState; - if (headers == null && _endsWithCrLfCrLf(buffer)) { - headersState = _parseHeaders(buffer); - buffer.clear(); - } else if (headers != null && - buffer.length >= headers.contentLength) { - // UTF-8 is the default - and only supported - encoding for LSP. - // The string 'utf8' is valid since it was published in the original spec. - // Any other encodings should be rejected with an error. - if ([ - null, - 'utf-8', - 'utf8', - ].contains(headers.encoding?.toLowerCase())) { - controller.add(utf8.decode(buffer)); - } else { - controller.addError( - InvalidEncodingError(headers.rawHeaders), - ); - } - buffer.clear(); - headersState = null; - } - }, - onError: controller.addError, - onDone: controller.close, - ); - return _LspPacketTransformerListenData(input); - }, - onPause: (listenData) { - listenData.input.pause(); - return _LspPacketTransformerPauseData(); - }, - onResume: (listenData, pauseData) => listenData.input.resume(), - onCancel: (listenData) => listenData.input.cancel(), - ); + var controller = + MoreTypedStreamController< + String, + _LspPacketTransformerListenData, + _LspPacketTransformerPauseData + >( + onListen: (controller) { + var input = stream + .expand((b) => b) + .listen( + (codeUnit) { + buffer.add(codeUnit); + var headers = headersState; + if (headers == null && _endsWithCrLfCrLf(buffer)) { + headersState = _parseHeaders(buffer); + buffer.clear(); + } else if (headers != null && + buffer.length >= headers.contentLength) { + // UTF-8 is the default - and only supported - encoding for LSP. + // The string 'utf8' is valid since it was published in the original spec. + // Any other encodings should be rejected with an error. + if ([ + null, + 'utf-8', + 'utf8', + ].contains(headers.encoding?.toLowerCase())) { + controller.add(utf8.decode(buffer)); + } else { + controller.addError( + InvalidEncodingError(headers.rawHeaders), + ); + } + buffer.clear(); + headersState = null; + } + }, + onError: controller.addError, + onDone: controller.close, + ); + return _LspPacketTransformerListenData(input); + }, + onPause: (listenData) { + listenData.input.pause(); + return _LspPacketTransformerPauseData(); + }, + onResume: (listenData, pauseData) => listenData.input.resume(), + onCancel: (listenData) => listenData.input.cancel(), + ); return controller.controller.stream; } diff --git a/pkg/analysis_server/lib/src/lsp/lsp_socket_server.dart b/pkg/analysis_server/lib/src/lsp/lsp_socket_server.dart index 5825b0690d4..5e819ccc705 100644 --- a/pkg/analysis_server/lib/src/lsp/lsp_socket_server.dart +++ b/pkg/analysis_server/lib/src/lsp/lsp_socket_server.dart @@ -89,19 +89,18 @@ class LspSocketServer implements AbstractSocketServer { stateLocation: analysisServerOptions.cacheFolder, ); - var server = - analysisServer = LspAnalysisServer( - serverChannel, - resourceProvider, - analysisServerOptions, - sdkManager, - analyticsManager, - CrashReportingAttachmentsBuilder.empty, - instrumentationService, - diagnosticServer: diagnosticServer, - detachableFileSystemManager: detachableFileSystemManager, - enableBlazeWatcher: true, - ); + var server = analysisServer = LspAnalysisServer( + serverChannel, + resourceProvider, + analysisServerOptions, + sdkManager, + analyticsManager, + CrashReportingAttachmentsBuilder.empty, + instrumentationService, + diagnosticServer: diagnosticServer, + detachableFileSystemManager: detachableFileSystemManager, + enableBlazeWatcher: true, + ); detachableFileSystemManager?.setAnalysisServer(server); } } diff --git a/pkg/analysis_server/lib/src/lsp/mapping.dart b/pkg/analysis_server/lib/src/lsp/mapping.dart index af3da9d2489..a2e1167d41f 100644 --- a/pkg/analysis_server/lib/src/lsp/mapping.dart +++ b/pkg/analysis_server/lib/src/lsp/mapping.dart @@ -88,8 +88,8 @@ lsp.Either2 asMarkupContentOrString( ) { return preferredFormats != null ? lsp.Either2.t1( - _asMarkup(preferredFormats, content), - ) + _asMarkup(preferredFormats, content), + ) : lsp.Either2.t2(content); } @@ -126,15 +126,15 @@ lsp.Either2 asMarkupContentOrString( requiredArgumentListTextRanges?.isNotEmpty ?? false; var functionCallSuffix = hasRequiredParameters && requiredArgumentListString != null - ? buildSnippetStringWithTabStops( - requiredArgumentListString, - requiredArgumentListTextRanges, - ) - // Optional params still gets a final tab stop in the parens. - : hasOptionalParameters - ? SnippetBuilder.finalTabStop - // And no parameters at all we skip the tabstop in the parens. - : ''; + ? buildSnippetStringWithTabStops( + requiredArgumentListString, + requiredArgumentListTextRanges, + ) + // Optional params still gets a final tab stop in the parens. + : hasOptionalParameters + ? SnippetBuilder.finalTabStop + // And no parameters at all we skip the tabstop in the parens. + : ''; insertText = '${SnippetBuilder.escapeSnippetPlainText(insertText)}($functionCallSuffix)'; } else if (selectionOffset != 0 && @@ -288,25 +288,26 @@ lsp.WorkspaceEdit createWorkspaceEdit( // Compile the edits into a TextDocumentEdit for this file. var textDocumentEdit = lsp.TextDocumentEdit( textDocument: analysisServer.getVersionedDocumentIdentifier(fileEdit.file), - edits: - snippetEdits - .map( - (e) => Either3< + edits: snippetEdits + .map( + (e) => + Either3< lsp.AnnotatedTextEdit, lsp.SnippetTextEdit, lsp.TextEdit >.t2(e), - ) - .toList(), + ) + .toList(), ); // Convert to the union that documentChanges require. - var textDocumentEditsAsUnion = Either4< - lsp.CreateFile, - lsp.DeleteFile, - lsp.RenameFile, - lsp.TextDocumentEdit - >.t4(textDocumentEdit); + var textDocumentEditsAsUnion = + Either4< + lsp.CreateFile, + lsp.DeleteFile, + lsp.RenameFile, + lsp.TextDocumentEdit + >.t4(textDocumentEdit); /// Add the textDocumentEdit to a WorkspaceEdit. return lsp.WorkspaceEdit(documentChanges: [textDocumentEditsAsUnion]); @@ -606,10 +607,9 @@ CompletionDetail getCompletionDetail( } var libraryUri = suggestion.libraryUri; - var autoImportUri = - (suggestion.isNotImported ?? false) && libraryUri != null - ? Uri.parse(libraryUri) - : null; + var autoImportUri = (suggestion.isNotImported ?? false) && libraryUri != null + ? Uri.parse(libraryUri) + : null; return ( detail: detail, @@ -638,13 +638,13 @@ String? getCompletionDisplayUriString({ // Compute the relative path and then put into a URI so the display // always uses forward slashes (as a URI) regardless of platform. ? uriConverter - .toClientUri( - pathContext.relative( - uriConverter.fromClientUri(elementLibraryUri), - from: pathContext.dirname(completionFilePath), - ), - ) - .toString() + .toClientUri( + pathContext.relative( + uriConverter.fromClientUri(elementLibraryUri), + from: pathContext.dirname(completionFilePath), + ), + ) + .toString() : elementLibraryUri.toString(); } @@ -656,10 +656,9 @@ List? getDiagnosticTags( return null; } - var tags = - diagnosticTagsForErrorCode[error.code] - ?.where(supportedTags.contains) - .toList(); + var tags = diagnosticTagsForErrorCode[error.code] + ?.where(supportedTags.contains) + .toList(); return tags != null && tags.isNotEmpty ? tags : null; } @@ -737,10 +736,9 @@ lsp.LocationLink? navigationTargetToLocationLink( var nameRange = toRange(targetLineInfo, target.offset, target.length); var codeOffset = target.codeOffset; var codeLength = target.codeLength; - var codeRange = - codeOffset != null && codeLength != null - ? toRange(targetLineInfo, codeOffset, codeLength) - : nameRange; + var codeRange = codeOffset != null && codeLength != null + ? toRange(targetLineInfo, codeOffset, codeLength) + : nameRange; return lsp.LocationLink( originSelectionRange: toRange(regionLineInfo, region.offset, region.length), @@ -760,17 +758,16 @@ lsp.Diagnostic pluginToDiagnostic( List? relatedInformation; var contextMessages = error.contextMessages; if (contextMessages != null && contextMessages.isNotEmpty) { - relatedInformation = - contextMessages - .map( - (message) => pluginToDiagnosticRelatedInformation( - uriConverter, - getLineInfo, - message, - ), - ) - .nonNulls - .toList(); + relatedInformation = contextMessages + .map( + (message) => pluginToDiagnosticRelatedInformation( + uriConverter, + getLineInfo, + message, + ), + ) + .nonNulls + .toList(); } var message = error.message; @@ -800,10 +797,9 @@ lsp.Diagnostic pluginToDiagnostic( relatedInformation: relatedInformation, // Only include codeDescription if the client explicitly supports it // (a minor optimization to avoid unnecessary payload/(de)serialization). - codeDescription: - clientSupportsCodeDescription && documentationUrl != null - ? CodeDescription(href: Uri.parse(documentationUrl)) - : null, + codeDescription: clientSupportsCodeDescription && documentationUrl != null + ? CodeDescription(href: Uri.parse(documentationUrl)) + : null, ); } @@ -991,10 +987,12 @@ lsp.CompletionItem snippetToCompletionItem( thisFilesChange, changes.linkedEditGroups, lineInfo, - selectionOffset: - changes.selection?.file == file ? changes.selection?.offset : null, - selectionLength: - changes.selection?.file == file ? changes.selectionLength : null, + selectionOffset: changes.selection?.file == file + ? changes.selection?.offset + : null, + selectionLength: changes.selection?.file == file + ? changes.selectionLength + : null, ); // For LSP, we need to provide the main edit and other edits separately. The @@ -1021,10 +1019,9 @@ lsp.CompletionItem snippetToCompletionItem( filterText: snippet.prefix.orNullIfSameAs(snippet.label), kind: lsp.CompletionItemKind.Snippet, command: command, - documentation: - documentation != null - ? asMarkupContentOrString(formats, documentation) - : null, + documentation: documentation != null + ? asMarkupContentOrString(formats, documentation) + : null, // Force snippets to be sorted at the bottom of the list. // TODO(dantup): Consider if we can rank these better. Client-side // snippets have always been forced to the bottom partly because they @@ -1034,14 +1031,12 @@ lsp.CompletionItem snippetToCompletionItem( insertTextMode: supportsAsIsInsertMode ? InsertTextMode.asIs : null, // Set textEdit or textEditText depending on whether we need to specify // a range or not. - textEdit: - hasDefaultEditRange - ? null - : Either2.t2(mainEdit), - textEditText: - hasDefaultEditRange - ? mainEdit.newText.orNullIfSameAs(snippet.label) - : null, + textEdit: hasDefaultEditRange + ? null + : Either2.t2(mainEdit), + textEditText: hasDefaultEditRange + ? mainEdit.newText.orNullIfSameAs(snippet.label) + : null, additionalTextEdits: nonMainEdits.nullIfEmpty, ); } @@ -1075,13 +1070,13 @@ lsp.CompletionItemKind? suggestionKindToCompletionItemKind( if (!label.startsWith('dart:')) { return label.endsWith('.dart') ? const [ - lsp.CompletionItemKind.File, - lsp.CompletionItemKind.Module, - ] + lsp.CompletionItemKind.File, + lsp.CompletionItemKind.Module, + ] : const [ - lsp.CompletionItemKind.Folder, - lsp.CompletionItemKind.Module, - ]; + lsp.CompletionItemKind.Folder, + lsp.CompletionItemKind.Module, + ]; } return const [lsp.CompletionItemKind.Module]; case server.CompletionSuggestionKind.IDENTIFIER: @@ -1207,10 +1202,9 @@ lsp.CompletionItem toCompletionItem( // TODO(dantup): Consider including more of these raw fields in the original // suggestion to avoid needing to manipulate them in this way here. - var filterText = - !label.startsWith(completionFilterTextSplitPattern) - ? label.split(completionFilterTextSplitPattern).first.trim() - : label; + var filterText = !label.startsWith(completionFilterTextSplitPattern) + ? label.split(completionFilterTextSplitPattern).first.trim() + : label; // If we're using label details, we also don't want the label to include any // additional symbols as noted above, because they will appear in the extra @@ -1227,22 +1221,21 @@ lsp.CompletionItem toCompletionItem( var element = suggestion.element; var colorPreviewHex = capabilities.completionItemKinds.contains(CompletionItemKind.Color) && - suggestion is DartCompletionSuggestion - ? suggestion.colorHex - : null; - var completionKind = - colorPreviewHex != null - ? CompletionItemKind.Color - : element != null - ? elementKindToCompletionItemKind( - capabilities.completionItemKinds, - element.kind, - ) - : suggestionKindToCompletionItemKind( - capabilities.completionItemKinds, - suggestion.kind, - label, - ); + suggestion is DartCompletionSuggestion + ? suggestion.colorHex + : null; + var completionKind = colorPreviewHex != null + ? CompletionItemKind.Color + : element != null + ? elementKindToCompletionItemKind( + capabilities.completionItemKinds, + element.kind, + ) + : suggestionKindToCompletionItemKind( + capabilities.completionItemKinds, + suggestion.kind, + label, + ); var labelDetails = getCompletionDetail( suggestion, @@ -1272,21 +1265,19 @@ lsp.CompletionItem toCompletionItem( var insertTextFormat = insertTextInfo.format; var isMultilineCompletion = insertText.contains('\n'); - var rawDoc = - includeDocumentation == DocumentationPreference.full - ? suggestion.docComplete - : includeDocumentation == DocumentationPreference.summary - ? suggestion.docSummary - : null; + var rawDoc = includeDocumentation == DocumentationPreference.full + ? suggestion.docComplete + : includeDocumentation == DocumentationPreference.summary + ? suggestion.docSummary + : null; var cleanedDoc = cleanDartdoc(rawDoc); // To improve the display of some items (like pubspec version numbers), // short labels in the format `_foo_` in docComplete are "upgraded" to the // detail field. - var labelMatch = - cleanedDoc != null - ? upgradableDocCompletePattern.firstMatch(cleanedDoc) - : null; + var labelMatch = cleanedDoc != null + ? upgradableDocCompletePattern.firstMatch(cleanedDoc) + : null; if (labelMatch != null) { cleanedDoc = null; labelDetails = ( @@ -1316,53 +1307,48 @@ lsp.CompletionItem toCompletionItem( ]), data: resolutionData, detail: labelDetails.detail.nullIfEmpty, - labelDetails: - useLabelDetails - ? CompletionItemLabelDetails( - detail: labelDetails.truncatedSignature.nullIfEmpty, - description: getCompletionDisplayUriString( - uriConverter: uriConverter, - pathContext: pathContext, - elementLibraryUri: labelDetails.autoImportUri, - completionFilePath: completionFilePath, - ), - ).nullIfEmpty - : null, - documentation: - cleanedDoc != null - ? asMarkupContentOrString(formats, cleanedDoc) - : null, - deprecated: - supportsCompletionDeprecatedFlag && suggestion.isDeprecated - ? true - : null, + labelDetails: useLabelDetails + ? CompletionItemLabelDetails( + detail: labelDetails.truncatedSignature.nullIfEmpty, + description: getCompletionDisplayUriString( + uriConverter: uriConverter, + pathContext: pathContext, + elementLibraryUri: labelDetails.autoImportUri, + completionFilePath: completionFilePath, + ), + ).nullIfEmpty + : null, + documentation: cleanedDoc != null + ? asMarkupContentOrString(formats, cleanedDoc) + : null, + deprecated: supportsCompletionDeprecatedFlag && suggestion.isDeprecated + ? true + : null, sortText: relevanceToSortText(suggestion.relevance), filterText: filterText.orNullIfSameAs( label, ), // filterText uses label if not set - insertTextFormat: - insertTextFormat != lsp.InsertTextFormat.PlainText - ? insertTextFormat - : null, // Defaults to PlainText if not supplied + insertTextFormat: insertTextFormat != lsp.InsertTextFormat.PlainText + ? insertTextFormat + : null, // Defaults to PlainText if not supplied insertTextMode: !hasDefaultTextMode && supportsAsIsInsertMode && isMultilineCompletion - ? InsertTextMode.asIs - : null, + ? InsertTextMode.asIs + : null, // When using defaults for edit range, don't use textEdit. - textEdit: - hasDefaultEditRange - ? null - : supportsInsertReplace && insertionRange != replacementRange - ? Either2.t1( - InsertReplaceEdit( - insert: insertionRange, - replace: replacementRange, - newText: insertText, - ), - ) - : Either2.t2( - TextEdit(range: replacementRange, newText: insertText), + textEdit: hasDefaultEditRange + ? null + : supportsInsertReplace && insertionRange != replacementRange + ? Either2.t1( + InsertReplaceEdit( + insert: insertionRange, + replace: replacementRange, + newText: insertText, ), + ) + : Either2.t2( + TextEdit(range: replacementRange, newText: insertText), + ), // When using defaults for edit range, use textEditText. textEditText: hasDefaultEditRange ? insertText.orNullIfSameAs(label) : null, ); @@ -1387,10 +1373,9 @@ lsp.Diagnostic toDiagnostic( lsp.Element toElement(server.LineInfo lineInfo, server.Element element) { var location = element.location; return lsp.Element( - range: - location != null - ? toRange(lineInfo, location.offset, location.length) - : null, + range: location != null + ? toRange(lineInfo, location.offset, location.length) + : null, name: toElementName(element), kind: element.kind.name, parameters: element.parameters, @@ -1403,8 +1388,8 @@ String toElementName(server.Element element) { return element.name.isNotEmpty ? element.name : (element.kind == server.ElementKind.EXTENSION - ? '' - : ''); + ? '' + : ''); } lsp.FlutterOutline toFlutterOutline( @@ -1420,10 +1405,9 @@ lsp.FlutterOutline toFlutterOutline( label: outline.label, className: outline.className, variableName: outline.variableName, - attributes: - attributes - ?.map((attribute) => toFlutterOutlineAttribute(lineInfo, attribute)) - .toList(), + attributes: attributes + ?.map((attribute) => toFlutterOutlineAttribute(lineInfo, attribute)) + .toList(), dartElement: dartElement != null ? toElement(lineInfo, dartElement) : null, range: toRange(lineInfo, outline.offset, outline.length), codeRange: toRange(lineInfo, outline.codeOffset, outline.codeLength), @@ -1439,10 +1423,9 @@ lsp.FlutterOutlineAttribute toFlutterOutlineAttribute( return lsp.FlutterOutlineAttribute( name: attribute.name, label: attribute.label, - valueRange: - valueLocation != null - ? toRange(lineInfo, valueLocation.offset, valueLocation.length) - : null, + valueRange: valueLocation != null + ? toRange(lineInfo, valueLocation.offset, valueLocation.length) + : null, ); } @@ -1480,10 +1463,9 @@ ErrorOr toOffset( if (pos.line >= lineInfo.lineCount) { return ErrorOr.error( lsp.ResponseError( - code: - failureIsCritical - ? lsp.ServerErrorCodes.ClientServerInconsistentState - : lsp.ServerErrorCodes.InvalidFileLineCol, + code: failureIsCritical + ? lsp.ServerErrorCodes.ClientServerInconsistentState + : lsp.ServerErrorCodes.InvalidFileLineCol, message: 'Invalid line number', data: pos.line.toString(), ), @@ -1535,8 +1517,9 @@ lsp.SignatureHelp toSignatureHelp( /// Gets the label for an individual parameter in the form /// String s = 'foo' String getParamLabel(FormalParameterElement p) { - var defaultCodeSuffix = - p.defaultValueCode != null ? ' = ${p.defaultValueCode}' : ''; + var defaultCodeSuffix = p.defaultValueCode != null + ? ' = ${p.defaultValueCode}' + : ''; var requiredPrefix = p.isRequiredNamed ? 'required ' : ''; return '$requiredPrefix${p.type} ${p.displayName}$defaultCodeSuffix'; } @@ -1544,10 +1527,12 @@ lsp.SignatureHelp toSignatureHelp( /// Gets the full signature label in the form /// foo(String s, int i, bool a = true) String getSignatureLabel(server.SignatureInformation resp) { - var positionalRequired = - signature.parameters.where((p) => p.isRequiredPositional).toList(); - var positionalOptional = - signature.parameters.where((p) => p.isOptionalPositional).toList(); + var positionalRequired = signature.parameters + .where((p) => p.isRequiredPositional) + .toList(); + var positionalOptional = signature.parameters + .where((p) => p.isOptionalPositional) + .toList(); var named = signature.parameters.where((p) => p.isNamed).toList(); var params = [ if (positionalRequired.isNotEmpty) @@ -1573,10 +1558,9 @@ lsp.SignatureHelp toSignatureHelp( signatures: [ lsp.SignatureInformation( label: getSignatureLabel(signature), - documentation: - cleanedDoc != null - ? asMarkupContentOrString(preferredFormats, cleanedDoc) - : null, + documentation: cleanedDoc != null + ? asMarkupContentOrString(preferredFormats, cleanedDoc) + : null, parameters: signature.parameters.map(toParameterInfo).toList(), ), ], @@ -1665,23 +1649,22 @@ lsp.TextDocumentEdit toTextDocumentEdit( ); return lsp.TextDocumentEdit( textDocument: fileEdit.doc, - edits: - sortSourceEditsForLsp(fileEdit.edits).map((edit) { - var annotation = recordEditAnnotation( - fileEdit.doc.uri, - edit, - annotateChanges: annotateChanges, - changeAnnotations: changeAnnotations, - ); - return toTextDocumentEditEdit( - capabilities, - fileEdit.lineInfo, - edit, - selectionOffsetRelative: fileEdit.selectionOffsetRelative, - selectionLength: fileEdit.selectionLength, - annotationIdentifier: annotation?.label, - ); - }).toList(), + edits: sortSourceEditsForLsp(fileEdit.edits).map((edit) { + var annotation = recordEditAnnotation( + fileEdit.doc.uri, + edit, + annotateChanges: annotateChanges, + changeAnnotations: changeAnnotations, + ); + return toTextDocumentEditEdit( + capabilities, + fileEdit.lineInfo, + edit, + selectionOffsetRelative: fileEdit.selectionOffsetRelative, + selectionLength: fileEdit.selectionLength, + annotationIdentifier: annotation?.label, + ); + }).toList(), ); } @@ -1726,14 +1709,14 @@ lsp.TextEdit toTextEdit( }) { return annotation != null ? lsp.AnnotatedTextEdit( - range: toRange(lineInfo, edit.offset, edit.length), - newText: edit.replacement, - annotationId: annotation.label, - ) + range: toRange(lineInfo, edit.offset, edit.length), + newText: edit.replacement, + annotationId: annotation.label, + ) : lsp.TextEdit( - range: toRange(lineInfo, edit.offset, edit.length), - newText: edit.replacement, - ); + range: toRange(lineInfo, edit.offset, edit.length), + newText: edit.replacement, + ); } /// Creates an [lsp.WorkspaceEdit] for [edits]. @@ -1751,10 +1734,9 @@ lsp.WorkspaceEdit toWorkspaceEdit( ChangeAnnotations annotateChanges = ChangeAnnotations.none, }) { var supportsDocumentChanges = clientCapabilities.documentChanges; - var changeAnnotations = - annotateChanges != ChangeAnnotations.none - ? {} - : null; + var changeAnnotations = annotateChanges != ChangeAnnotations.none + ? {} + : null; if (supportsDocumentChanges) { var supportsCreate = clientCapabilities.createResourceOperations; @@ -1774,12 +1756,13 @@ lsp.WorkspaceEdit toWorkspaceEdit( for (var fileEdit in edits) { if (supportsCreate && fileEdit.newFile) { var create = lsp.CreateFile(uri: fileEdit.doc.uri); - var createUnion = Either4< - lsp.CreateFile, - lsp.DeleteFile, - lsp.RenameFile, - lsp.TextDocumentEdit - >.t1(create); + var createUnion = + Either4< + lsp.CreateFile, + lsp.DeleteFile, + lsp.RenameFile, + lsp.TextDocumentEdit + >.t1(create); changes.add(createUnion); } @@ -1789,12 +1772,13 @@ lsp.WorkspaceEdit toWorkspaceEdit( annotateChanges: annotateChanges, changeAnnotations: changeAnnotations, ); - var textDocEditUnion = Either4< - lsp.CreateFile, - lsp.DeleteFile, - lsp.RenameFile, - lsp.TextDocumentEdit - >.t4(textDocEdit); + var textDocEditUnion = + Either4< + lsp.CreateFile, + lsp.DeleteFile, + lsp.RenameFile, + lsp.TextDocumentEdit + >.t4(textDocEdit); changes.add(textDocEditUnion); } @@ -1820,16 +1804,15 @@ Map> toWorkspaceEditChanges( Map? changeAnnotations, }) { MapEntry> createEdit(FileEditInformation file) { - var edits = - sortSourceEditsForLsp(file.edits).map((edit) { - var annotation = recordEditAnnotation( - file.doc.uri, - edit, - annotateChanges: annotateChanges, - changeAnnotations: changeAnnotations, - ); - return toTextEdit(file.lineInfo, edit, annotation: annotation); - }).toList(); + var edits = sortSourceEditsForLsp(file.edits).map((edit) { + var annotation = recordEditAnnotation( + file.doc.uri, + edit, + annotateChanges: annotateChanges, + changeAnnotations: changeAnnotations, + ); + return toTextEdit(file.lineInfo, edit, annotation: annotation); + }).toList(); return MapEntry(file.doc.uri, edits); } @@ -1848,10 +1831,9 @@ lsp.MarkupContent _asMarkup( var supportsPlain = preferredFormats.contains(lsp.MarkupKind.PlainText); // Since our PlainText version is actually just Markdown, only advertise it // as PlainText if the client explicitly supports PlainText and not Markdown. - var format = - supportsPlain && !supportsMarkdown - ? lsp.MarkupKind.PlainText - : lsp.MarkupKind.Markdown; + var format = supportsPlain && !supportsMarkdown + ? lsp.MarkupKind.PlainText + : lsp.MarkupKind.Markdown; return lsp.MarkupContent(kind: format, value: content); } @@ -1860,32 +1842,31 @@ String _diagnosticCode(server.DiagnosticCode code) => code.name.toLowerCase(); /// Additional details about a completion that may be formatted differently /// depending on the client capabilities. -typedef CompletionDetail = - ({ - /// Additional details to go in the details popup. - /// - /// This is usually a full signature (with full parameters) and may also - /// include whether the item is deprecated if the client did not support the - /// native deprecated tag. - String detail, +typedef CompletionDetail = ({ + /// Additional details to go in the details popup. + /// + /// This is usually a full signature (with full parameters) and may also + /// include whether the item is deprecated if the client did not support the + /// native deprecated tag. + String detail, - /// Truncated parameters. Similar to [truncatedSignature] but does not - /// include return types. Used in clients that cannot format signatures - /// differently and is appended immediately after the completion label. The - /// return type is omitted to reduce noise because this text is not subtle. - String truncatedParams, + /// Truncated parameters. Similar to [truncatedSignature] but does not + /// include return types. Used in clients that cannot format signatures + /// differently and is appended immediately after the completion label. The + /// return type is omitted to reduce noise because this text is not subtle. + String truncatedParams, - /// A signature with truncated params. Used for showing immediately after - /// the completion label when it can be formatted differently. - /// - /// () → String - String truncatedSignature, + /// A signature with truncated params. Used for showing immediately after + /// the completion label when it can be formatted differently. + /// + /// () → String + String truncatedSignature, - /// The URI that will be auto-imported if this item is selected in a - /// user-friendly string format (for example a relative path if for a `file:/` - /// URI). - Uri? autoImportUri, - }); + /// The URI that will be auto-imported if this item is selected in a + /// user-friendly string format (for example a relative path if for a `file:/` + /// URI). + Uri? autoImportUri, +}); extension CompletionLabelExtension on CompletionItemLabelDetails { /// Returns `null` if no fields are set, otherwise `this`. diff --git a/pkg/analysis_server/lib/src/lsp/notification_manager.dart b/pkg/analysis_server/lib/src/lsp/notification_manager.dart index 824d5cf1702..a0dc5d2bcab 100644 --- a/pkg/analysis_server/lib/src/lsp/notification_manager.dart +++ b/pkg/analysis_server/lib/src/lsp/notification_manager.dart @@ -25,19 +25,18 @@ class LspNotificationManager extends AbstractNotificationManager { // Currently these diagnostics are always sent to the editor client, so // use those client capabilities. var clientCapabilities = server.editorClientCapabilities; - var diagnostics = - errors - .map( - (error) => pluginToDiagnostic( - server.uriConverter, - (path) => server.getLineInfo(path), - error, - supportedTags: clientCapabilities?.diagnosticTags, - clientSupportsCodeDescription: - clientCapabilities?.diagnosticCodeDescription ?? false, - ), - ) - .toList(); + var diagnostics = errors + .map( + (error) => pluginToDiagnostic( + server.uriConverter, + (path) => server.getLineInfo(path), + error, + supportedTags: clientCapabilities?.diagnosticTags, + clientSupportsCodeDescription: + clientCapabilities?.diagnosticCodeDescription ?? false, + ), + ) + .toList(); server.publishDiagnostics(filePath, diagnostics); } diff --git a/pkg/analysis_server/lib/src/lsp/semantic_tokens/encoder.dart b/pkg/analysis_server/lib/src/lsp/semantic_tokens/encoder.dart index 4ab59ecc742..2388eda4434 100644 --- a/pkg/analysis_server/lib/src/lsp/semantic_tokens/encoder.dart +++ b/pkg/analysis_server/lib/src/lsp/semantic_tokens/encoder.dart @@ -65,8 +65,9 @@ class SemanticTokenEncoder { var relativeLine = tokenLine - lastLine; // Column is relative to last only if on the same line. - var relativeColumn = - relativeLine == 0 ? tokenColumn - lastColumn : tokenColumn; + var relativeColumn = relativeLine == 0 + ? tokenColumn - lastColumn + : tokenColumn; // The resulting array is groups of 5 items as described in the LSP spec: // https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/specification-3-16.md#textDocument_semanticTokens @@ -106,10 +107,9 @@ class SemanticTokenEncoder { var lineOffset = lineInfo.getOffsetOfLine(lineNumber - 1); var startOffset = isFirstLine ? start.columnNumber - 1 : 0; - var endOffset = - isLastLine - ? end.columnNumber - 1 - : lineInfo.getOffsetOfLine(lineNumber) - lineOffset; + var endOffset = isLastLine + ? end.columnNumber - 1 + : lineInfo.getOffsetOfLine(lineNumber) - lineOffset; var length = endOffset - startOffset; yield SemanticTokenInfo( diff --git a/pkg/analysis_server/lib/src/lsp/semantic_tokens/legend.dart b/pkg/analysis_server/lib/src/lsp/semantic_tokens/legend.dart index 0ee138e8fcb..7a2d92b385e 100644 --- a/pkg/analysis_server/lib/src/lsp/semantic_tokens/legend.dart +++ b/pkg/analysis_server/lib/src/lsp/semantic_tokens/legend.dart @@ -31,28 +31,26 @@ class SemanticTokenLegendLookup { SemanticTokenLegendLookup() { // Build lists of all tokens and modifiers that exist in our mappings or that // we have added as custom types. These will be used to determine the indexes used for communication. - _usedTokenTypes = - Set.of( - highlightRegionTokenTypes.values.followedBy( - CustomSemanticTokenTypes.values, - ), - ).toList(); - _usedTokenModifiers = - Set.of( - highlightRegionTokenModifiers.values.flattenedToList.followedBy( - CustomSemanticTokenModifiers.values, - ), - ).toList(); + _usedTokenTypes = Set.of( + highlightRegionTokenTypes.values.followedBy( + CustomSemanticTokenTypes.values, + ), + ).toList(); + _usedTokenModifiers = Set.of( + highlightRegionTokenModifiers.values.flattenedToList.followedBy( + CustomSemanticTokenModifiers.values, + ), + ).toList(); // Build the LSP Legend which tells the client all of the tokens and modifiers // we will use in the order they should be accessed by index/bit. lspLegend = SemanticTokensLegend( - tokenTypes: - _usedTokenTypes.map((tokenType) => tokenType.toString()).toList(), - tokenModifiers: - _usedTokenModifiers - .map((tokenModifier) => tokenModifier.toString()) - .toList(), + tokenTypes: _usedTokenTypes + .map((tokenType) => tokenType.toString()) + .toList(), + tokenModifiers: _usedTokenModifiers + .map((tokenModifier) => tokenModifier.toString()) + .toList(), ); } diff --git a/pkg/analysis_server/lib/src/lsp/semantic_tokens/mapping.dart b/pkg/analysis_server/lib/src/lsp/semantic_tokens/mapping.dart index 26c096c1046..1bcedaa0a82 100644 --- a/pkg/analysis_server/lib/src/lsp/semantic_tokens/mapping.dart +++ b/pkg/analysis_server/lib/src/lsp/semantic_tokens/mapping.dart @@ -7,102 +7,108 @@ import 'package:analysis_server/src/lsp/constants.dart'; import 'package:analyzer_plugin/protocol/protocol_common.dart'; /// A mapping from [HighlightRegionType] to a set of [SemanticTokenModifiers]. -final highlightRegionTokenModifiers = < - HighlightRegionType, - Set ->{ - HighlightRegionType.COMMENT_DOCUMENTATION: { - SemanticTokenModifiers.documentation, - }, - HighlightRegionType.CONSTRUCTOR_TEAR_OFF: { - CustomSemanticTokenModifiers.constructor, - }, - HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.DYNAMIC_PARAMETER_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.IMPORT_PREFIX: { - CustomSemanticTokenModifiers.importPrefix, - }, - HighlightRegionType.INSTANCE_FIELD_DECLARATION: { - SemanticTokenModifiers.declaration, - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_FIELD_REFERENCE: { - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_GETTER_DECLARATION: { - SemanticTokenModifiers.declaration, - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_GETTER_REFERENCE: { - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_METHOD_DECLARATION: { - SemanticTokenModifiers.declaration, - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_METHOD_REFERENCE: { - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_METHOD_TEAR_OFF: { - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_SETTER_DECLARATION: { - SemanticTokenModifiers.declaration, - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.INSTANCE_SETTER_REFERENCE: { - CustomSemanticTokenModifiers.instance, - }, - HighlightRegionType.LOCAL_FUNCTION_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.LOCAL_VARIABLE_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.PARAMETER_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.STATIC_FIELD_DECLARATION: { - SemanticTokenModifiers.declaration, - SemanticTokenModifiers.static, - }, - HighlightRegionType.STATIC_GETTER_DECLARATION: { - SemanticTokenModifiers.declaration, - SemanticTokenModifiers.static, - }, - HighlightRegionType.STATIC_GETTER_REFERENCE: {SemanticTokenModifiers.static}, - HighlightRegionType.STATIC_METHOD_DECLARATION: { - SemanticTokenModifiers.declaration, - SemanticTokenModifiers.static, - }, - HighlightRegionType.STATIC_METHOD_REFERENCE: {SemanticTokenModifiers.static}, - HighlightRegionType.STATIC_METHOD_TEAR_OFF: {SemanticTokenModifiers.static}, - HighlightRegionType.STATIC_SETTER_DECLARATION: { - SemanticTokenModifiers.declaration, - SemanticTokenModifiers.static, - }, - HighlightRegionType.STATIC_SETTER_REFERENCE: {SemanticTokenModifiers.static}, - HighlightRegionType.TOP_LEVEL_FUNCTION_DECLARATION: { - SemanticTokenModifiers.declaration, - SemanticTokenModifiers.static, - }, - HighlightRegionType.TOP_LEVEL_GETTER_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.TOP_LEVEL_SETTER_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.TOP_LEVEL_VARIABLE_DECLARATION: { - SemanticTokenModifiers.declaration, - }, - HighlightRegionType.VALID_STRING_ESCAPE: { - CustomSemanticTokenModifiers.escape, - }, -}; +final highlightRegionTokenModifiers = + >{ + HighlightRegionType.COMMENT_DOCUMENTATION: { + SemanticTokenModifiers.documentation, + }, + HighlightRegionType.CONSTRUCTOR_TEAR_OFF: { + CustomSemanticTokenModifiers.constructor, + }, + HighlightRegionType.DYNAMIC_LOCAL_VARIABLE_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.DYNAMIC_PARAMETER_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.IMPORT_PREFIX: { + CustomSemanticTokenModifiers.importPrefix, + }, + HighlightRegionType.INSTANCE_FIELD_DECLARATION: { + SemanticTokenModifiers.declaration, + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_FIELD_REFERENCE: { + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_GETTER_DECLARATION: { + SemanticTokenModifiers.declaration, + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_GETTER_REFERENCE: { + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_METHOD_DECLARATION: { + SemanticTokenModifiers.declaration, + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_METHOD_REFERENCE: { + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_METHOD_TEAR_OFF: { + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_SETTER_DECLARATION: { + SemanticTokenModifiers.declaration, + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.INSTANCE_SETTER_REFERENCE: { + CustomSemanticTokenModifiers.instance, + }, + HighlightRegionType.LOCAL_FUNCTION_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.LOCAL_VARIABLE_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.PARAMETER_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.STATIC_FIELD_DECLARATION: { + SemanticTokenModifiers.declaration, + SemanticTokenModifiers.static, + }, + HighlightRegionType.STATIC_GETTER_DECLARATION: { + SemanticTokenModifiers.declaration, + SemanticTokenModifiers.static, + }, + HighlightRegionType.STATIC_GETTER_REFERENCE: { + SemanticTokenModifiers.static, + }, + HighlightRegionType.STATIC_METHOD_DECLARATION: { + SemanticTokenModifiers.declaration, + SemanticTokenModifiers.static, + }, + HighlightRegionType.STATIC_METHOD_REFERENCE: { + SemanticTokenModifiers.static, + }, + HighlightRegionType.STATIC_METHOD_TEAR_OFF: { + SemanticTokenModifiers.static, + }, + HighlightRegionType.STATIC_SETTER_DECLARATION: { + SemanticTokenModifiers.declaration, + SemanticTokenModifiers.static, + }, + HighlightRegionType.STATIC_SETTER_REFERENCE: { + SemanticTokenModifiers.static, + }, + HighlightRegionType.TOP_LEVEL_FUNCTION_DECLARATION: { + SemanticTokenModifiers.declaration, + SemanticTokenModifiers.static, + }, + HighlightRegionType.TOP_LEVEL_GETTER_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.TOP_LEVEL_SETTER_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.TOP_LEVEL_VARIABLE_DECLARATION: { + SemanticTokenModifiers.declaration, + }, + HighlightRegionType.VALID_STRING_ESCAPE: { + CustomSemanticTokenModifiers.escape, + }, + }; /// A mapping from [HighlightRegionType] to [SemanticTokenTypes]. /// diff --git a/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart b/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart index 094a86e27ee..cd6a8fd59ab 100644 --- a/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart +++ b/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart @@ -149,20 +149,20 @@ class ServerCapabilitiesComputer { ServerCapabilitiesComputer(this._server); - List get pluginTypes => - _server.pluginManager.pluginIsolates - .expand( - (isolate) => - isolate.currentSession?.interestingFiles ?? const [], - ) - // All published plugins use something like `*.extension` as - // interestingFiles. Prefix a `**/` so that the glob matches nested - // folders as well. - .map( - (glob) => - TextDocumentFilterScheme(scheme: 'file', pattern: '**/$glob'), - ) - .toList(); + List get pluginTypes => _server + .pluginManager + .pluginIsolates + .expand( + (isolate) => + isolate.currentSession?.interestingFiles ?? const [], + ) + // All published plugins use something like `*.extension` as + // interestingFiles. Prefix a `**/` so that the glob matches nested + // folders as well. + .map( + (glob) => TextDocumentFilterScheme(scheme: 'file', pattern: '**/$glob'), + ) + .toList(); ServerCapabilities computeServerCapabilities( LspClientCapabilities clientCapabilities, @@ -204,12 +204,11 @@ class ServerCapabilitiesComputer { supported: true, changeNotifications: features.changeNotifications.staticRegistration, ), - fileOperations: - !context.clientDynamic.fileOperations - ? FileOperationOptions( - willRename: features.willRename.staticRegistration, - ) - : null, + fileOperations: !context.clientDynamic.fileOperations + ? FileOperationOptions( + willRename: features.willRename.staticRegistration, + ) + : null, ), experimental: { // 'experimental' is a field we can put any arbitrary data that is not @@ -287,17 +286,15 @@ class ServerCapabilitiesComputer { ); var currentRegistrationJsons = currentRegistrationsMap.values.toSet(); - var registrationsToAdd = - newRegistrationsMap.entries - .where((entry) => !currentRegistrationJsons.contains(entry.value)) - .map((entry) => entry.key) - .toList(); + var registrationsToAdd = newRegistrationsMap.entries + .where((entry) => !currentRegistrationJsons.contains(entry.value)) + .map((entry) => entry.key) + .toList(); - var registrationsToRemove = - currentRegistrationsMap.entries - .where((entry) => !newRegistrationsJsons.contains(entry.value)) - .map((entry) => entry.key) - .toList(); + var registrationsToRemove = currentRegistrationsMap.entries + .where((entry) => !newRegistrationsJsons.contains(entry.value)) + .map((entry) => entry.key) + .toList(); // Update the current list before we start sending requests since we // go async. @@ -307,10 +304,9 @@ class ServerCapabilitiesComputer { Future? unregistrationRequest; if (registrationsToRemove.isNotEmpty) { - var unregistrations = - registrationsToRemove - .map((r) => Unregistration(id: r.id, method: r.method)) - .toList(); + var unregistrations = registrationsToRemove + .map((r) => Unregistration(id: r.id, method: r.method)) + .toList(); // It's important not to await this request here, as we must ensure // we cannot re-enter this method until we have sent both the unregister // and register requests to the client atomically. diff --git a/pkg/analysis_server/lib/src/lsp/snippets.dart b/pkg/analysis_server/lib/src/lsp/snippets.dart index 56b4ebba4d0..7f9981bce31 100644 --- a/pkg/analysis_server/lib/src/lsp/snippets.dart +++ b/pkg/analysis_server/lib/src/lsp/snippets.dart @@ -28,8 +28,9 @@ String buildSnippetStringForEditGroups( filePath: filePath, editGroups: editGroups, editGroupsOffset: editOffset, - selectionOffset: - selectionOffset != null ? selectionOffset - editOffset : null, + selectionOffset: selectionOffset != null + ? selectionOffset - editOffset + : null, selectionLength: selectionLength, ); @@ -80,10 +81,9 @@ String _buildSnippetString( // Make the position relative to the supplied text. position.offset - editGroupsOffset, editGroup.length, - suggestions: - editGroup.suggestions - .map((suggestion) => suggestion.value) - .toList(), + suggestions: editGroup.suggestions + .map((suggestion) => suggestion.value) + .toList(), // Use the index as an ID to keep all related positions together (so // the remain "linked"). linkedGroupId: index, @@ -135,9 +135,8 @@ String _buildSnippetString( /// If there are no edit groups, then placeholders are all simple and /// guaranteed to be in the correct order. var isPreSorted = editGroups.isEmpty; - var builder = - SnippetBuilder() - ..appendPlaceholders(text, placeholders, isPreSorted: isPreSorted); + var builder = SnippetBuilder() + ..appendPlaceholders(text, placeholders, isPreSorted: isPreSorted); return builder.value; } diff --git a/pkg/analysis_server/lib/src/lsp/source_edits.dart b/pkg/analysis_server/lib/src/lsp/source_edits.dart index 6fb1e67e4cf..98173065c56 100644 --- a/pkg/analysis_server/lib/src/lsp/source_edits.dart +++ b/pkg/analysis_server/lib/src/lsp/source_edits.dart @@ -175,8 +175,9 @@ ErrorOr> generateMinimalEdits( }) { var unformatted = result.content; var lineInfo = result.lineInfo; - var rangeStart = - range != null ? toOffset(lineInfo, range.start) : success(null); + var rangeStart = range != null + ? toOffset(lineInfo, range.start) + : success(null); var rangeEnd = range != null ? toOffset(lineInfo, range.end) : success(null); return (rangeStart, rangeEnd).mapResultsSync((rangeStart, rangeEnd) { @@ -328,8 +329,8 @@ class _MinimalEditComputer { // Walk through the token streams computing edits for the differences. bool unformattedHasMore, formattedHasMore; - while ((unformattedHasMore = - unformattedTokens.moveNext()) & // Don't short-circuit. + while ((unformattedHasMore = unformattedTokens + .moveNext()) & // Don't short-circuit. (formattedHasMore = formattedTokens.moveNext())) { var unformattedToken = unformattedTokens.current; var formattedToken = formattedTokens.current; @@ -675,14 +676,15 @@ class _MinimalEditComputer { /// be parsed. static Token? _parse(String s, FeatureSet featureSet) { try { - var scanner = Scanner( - _SourceMock.instance, - CharSequenceReader(s), - DiagnosticListener.nullListener, - )..configureFeatures( - featureSetForOverriding: featureSet, - featureSet: featureSet, - ); + var scanner = + Scanner( + _SourceMock.instance, + CharSequenceReader(s), + DiagnosticListener.nullListener, + )..configureFeatures( + featureSetForOverriding: featureSet, + featureSet: featureSet, + ); return scanner.tokenize(); } catch (e) { return null; diff --git a/pkg/analysis_server/lib/src/operation/operation_analysis.dart b/pkg/analysis_server/lib/src/operation/operation_analysis.dart index 72e1f4c6d0a..41889662162 100644 --- a/pkg/analysis_server/lib/src/operation/operation_analysis.dart +++ b/pkg/analysis_server/lib/src/operation/operation_analysis.dart @@ -50,12 +50,11 @@ Future scheduleImplementedNotification( void sendAnalysisNotificationAnalyzedFiles(LegacyAnalysisServer server) { _sendNotification(server, () { - var analyzedFiles = - server.driverMap.values - .map((driver) => driver.knownFiles) - .flattenedToList - .map((file) => file.path) - .toSet(); + var analyzedFiles = server.driverMap.values + .map((driver) => driver.knownFiles) + .flattenedToList + .map((file) => file.path) + .toSet(); // Exclude *.yaml files because IDEA Dart plugin attempts to index // all the files in folders which contain analyzed files. @@ -138,8 +137,10 @@ void sendAnalysisNotificationOutline( var libraryName = _computeLibraryName(unit); // compute Outline - var outline = - DartUnitOutlineComputer(resolvedUnit, withBasicFlutter: true).compute(); + var outline = DartUnitOutlineComputer( + resolvedUnit, + withBasicFlutter: true, + ).compute(); // send notification var params = protocol.AnalysisOutlineParams( diff --git a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart index 02a8c074df1..067eb7bbd8d 100644 --- a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart +++ b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart @@ -646,11 +646,10 @@ class PluginManager { var uri = Uri.parse('package:$packageName/$packageName.dart'); var packageSource = packageUriResolver.resolveAbsolute(uri); if (packageSource != null) { - var packageRoot = - _resourceProvider - .getFile(packageSource.fullName) - .parent - .parent; + var packageRoot = _resourceProvider + .getFile(packageSource.fullName) + .parent + .parent; packages.add(_Package(packageName, packageRoot)); pubspecFiles.add( packageRoot.getChildAssumingFile(file_paths.pubspecYaml), diff --git a/pkg/analysis_server/lib/src/plugin/result_converter.dart b/pkg/analysis_server/lib/src/plugin/result_converter.dart index 5a5831238de..0b093821690 100644 --- a/pkg/analysis_server/lib/src/plugin/result_converter.dart +++ b/pkg/analysis_server/lib/src/plugin/result_converter.dart @@ -16,13 +16,12 @@ class ResultConverter { server.AnalysisErrorFixes convertAnalysisErrorFixes( plugin.AnalysisErrorFixes fixes, ) { - var changes = - fixes.fixes - .map( - (plugin.PrioritizedSourceChange change) => - convertPrioritizedSourceChange(change), - ) - .toList(); + var changes = fixes.fixes + .map( + (plugin.PrioritizedSourceChange change) => + convertPrioritizedSourceChange(change), + ) + .toList(); return server.AnalysisErrorFixes(fixes.error, fixes: changes); } diff --git a/pkg/analysis_server/lib/src/plugin/result_merger.dart b/pkg/analysis_server/lib/src/plugin/result_merger.dart index 034c7e36ceb..638440d8389 100644 --- a/pkg/analysis_server/lib/src/plugin/result_merger.dart +++ b/pkg/analysis_server/lib/src/plugin/result_merger.dart @@ -302,11 +302,10 @@ class ResultMerger { // for (var j = 0; j < regions.length; j++) { var region = regions[j]; - var newTargets = - region.targets - .map((int oldTarget) => targetMap[oldTarget]) - .toList() - .cast(); + var newTargets = region.targets + .map((int oldTarget) => targetMap[oldTarget]) + .toList() + .cast(); if (region.targets != newTargets) { region = NavigationRegion(region.offset, region.length, newTargets); } @@ -496,8 +495,9 @@ class ResultMerger { if (currentChildren == null || currentChildren.isEmpty) { return outline; } - var updatedChildren = - currentChildren.map((Outline child) => traverse(child)).toList(); + var updatedChildren = currentChildren + .map((Outline child) => traverse(child)) + .toList(); if (currentChildren != updatedChildren) { if (!isCopied) { return Outline( @@ -604,14 +604,12 @@ class ResultMerger { names.toList(), offsets, lengths, - coveringExpressionOffsets: - coveringExpressionOffsets.isEmpty - ? null - : coveringExpressionOffsets, - coveringExpressionLengths: - coveringExpressionLengths.isEmpty - ? null - : coveringExpressionLengths, + coveringExpressionOffsets: coveringExpressionOffsets.isEmpty + ? null + : coveringExpressionOffsets, + coveringExpressionLengths: coveringExpressionLengths.isEmpty + ? null + : coveringExpressionLengths, ); } else if (first is ExtractMethodFeedback) { var offset = first.offset; diff --git a/pkg/analysis_server/lib/src/protocol_server.dart b/pkg/analysis_server/lib/src/protocol_server.dart index 32f9c4d1d7c..3d1cb66d864 100644 --- a/pkg/analysis_server/lib/src/protocol_server.dart +++ b/pkg/analysis_server/lib/src/protocol_server.dart @@ -186,10 +186,9 @@ AnalysisError newAnalysisError_fromEngine( var code = diagnosticCode.name.toLowerCase(); List? contextMessages; if (diagnostic.contextMessages.isNotEmpty) { - contextMessages = - diagnostic.contextMessages - .map((message) => newDiagnosticMessage(result, message)) - .toList(); + contextMessages = diagnostic.contextMessages + .map((message) => newDiagnosticMessage(result, message)) + .toList(); } var correction = diagnostic.correctionMessage; var url = diagnosticCode.url; diff --git a/pkg/analysis_server/lib/src/scheduler/message_scheduler.dart b/pkg/analysis_server/lib/src/scheduler/message_scheduler.dart index 19cbd803c20..f019fd8b20d 100644 --- a/pkg/analysis_server/lib/src/scheduler/message_scheduler.dart +++ b/pkg/analysis_server/lib/src/scheduler/message_scheduler.dart @@ -94,11 +94,10 @@ final class MessageScheduler { var request = message.request; var method = request.method; if (method == legacy.SERVER_REQUEST_CANCEL_REQUEST) { - var id = - legacy.ServerCancelRequestParams.fromRequest( - request, - clientUriConverter: server.uriConverter, - ).id; + var id = legacy.ServerCancelRequestParams.fromRequest( + request, + clientUriConverter: server.uriConverter, + ).id; listener?.addActiveMessage(message); (server as LegacyAnalysisServer).cancelRequest(id); // The message needs to be added to the queue of pending messages, but @@ -154,10 +153,9 @@ final class MessageScheduler { // Cancel in progress completion and refactoring requests. var incomingMsgMethod = msg.method; if (_isCancelableRequest(msg)) { - var reason = - incomingMsgMethod == lsp.Method.workspace_executeCommand - ? 'Another workspace/executeCommand request for a refactor was started' - : 'Another textDocument/completion request was started'; + var reason = incomingMsgMethod == lsp.Method.workspace_executeCommand + ? 'Another workspace/executeCommand request for a refactor was started' + : 'Another textDocument/completion request was started'; for (var activeMessage in _activeMessages) { if (activeMessage is LspMessage && activeMessage.isRequest) { var message = activeMessage.message as lsp.RequestMessage; diff --git a/pkg/analysis_server/lib/src/search/type_hierarchy.dart b/pkg/analysis_server/lib/src/search/type_hierarchy.dart index 279300c4dc5..da59478c42b 100644 --- a/pkg/analysis_server/lib/src/search/type_hierarchy.dart +++ b/pkg/analysis_server/lib/src/search/type_hierarchy.dart @@ -71,10 +71,9 @@ class TypeHierarchyComputer { var subMemberElementDeclared = subMemberElement?.nonSynthetic; subItem = TypeHierarchyItem( convertElement(subElement), - memberElement: - subMemberElementDeclared != null - ? convertElement(subMemberElementDeclared) - : null, + memberElement: subMemberElementDeclared != null + ? convertElement(subMemberElementDeclared) + : null, superclass: itemId, ); var subItemId = _items.length; @@ -124,10 +123,9 @@ class TypeHierarchyComputer { item = TypeHierarchyItem( convertElement(classElement), displayName: displayName, - memberElement: - memberElementDeclared != null - ? convertElement(memberElementDeclared) - : null, + memberElement: memberElementDeclared != null + ? convertElement(memberElementDeclared) + : null, ); _elementItemMap[classElement] = item; itemId = _items.length; diff --git a/pkg/analysis_server/lib/src/server/crash_reporting.dart b/pkg/analysis_server/lib/src/server/crash_reporting.dart index 9bc42009829..dccae64c8cd 100644 --- a/pkg/analysis_server/lib/src/server/crash_reporting.dart +++ b/pkg/analysis_server/lib/src/server/crash_reporting.dart @@ -20,13 +20,12 @@ class CrashReportingInstrumentation extends NoopInstrumentationService { StackTrace? stackTrace, List? attachments, ]) { - var crashReportAttachments = - (attachments ?? []).map((e) { - return CrashReportAttachment.string( - field: 'attachment_${e.id}', - value: e.stringValue, - ); - }).toList(); + var crashReportAttachments = (attachments ?? []).map((e) { + return CrashReportAttachment.string( + field: 'attachment_${e.id}', + value: e.stringValue, + ); + }).toList(); if (exception is CaughtException) { // Get the root CaughtException, which matters most for debugging. diff --git a/pkg/analysis_server/lib/src/server/dev_server.dart b/pkg/analysis_server/lib/src/server/dev_server.dart index f9f9939667c..35286b67e62 100644 --- a/pkg/analysis_server/lib/src/server/dev_server.dart +++ b/pkg/analysis_server/lib/src/server/dev_server.dart @@ -142,8 +142,9 @@ class DevAnalysisServer { }), ); - directories = - directories.map((dir) => path.normalize(path.absolute(dir))).toList(); + directories = directories + .map((dir) => path.normalize(path.absolute(dir))) + .toList(); await _channel.simulateRequestFromClient( Request('${_nextId++}', 'analysis.setAnalysisRoots', { diff --git a/pkg/analysis_server/lib/src/server/driver.dart b/pkg/analysis_server/lib/src/server/driver.dart index 3f2f6151767..c02007101c7 100644 --- a/pkg/analysis_server/lib/src/server/driver.dart +++ b/pkg/analysis_server/lib/src/server/driver.dart @@ -377,10 +377,9 @@ class Driver implements ServerStarter { ErrorNotifier errorNotifier, SendPort? sendPort, ) { - var capture = - results.flag(DISABLE_SERVER_EXCEPTION_HANDLING) - ? (_, Function f, {void Function(String)? print}) => f() - : _captureExceptions; + var capture = results.flag(DISABLE_SERVER_EXCEPTION_HANDLING) + ? (_, Function f, {void Function(String)? print}) => f() + : _captureExceptions; var trainDirectory = results.option(TRAIN_USING); if (trainDirectory != null) { if (!FileSystemEntity.isDirectorySync(trainDirectory)) { @@ -479,10 +478,9 @@ class Driver implements ServerStarter { if (sendPort == null) exit(0); }); }, - print: - results.flag(INTERNAL_PRINT_TO_CONSOLE) - ? null - : diagnosticServer.httpServer.recordPrint, + print: results.flag(INTERNAL_PRINT_TO_CONSOLE) + ? null + : diagnosticServer.httpServer.recordPrint, ); } } @@ -496,10 +494,9 @@ class Driver implements ServerStarter { int? diagnosticServerPort, ErrorNotifier errorNotifier, ) { - var capture = - args.flag(DISABLE_SERVER_EXCEPTION_HANDLING) - ? (_, Function f, {void Function(String)? print}) => f() - : _captureExceptions; + var capture = args.flag(DISABLE_SERVER_EXCEPTION_HANDLING) + ? (_, Function f, {void Function(String)? print}) => f() + : _captureExceptions; linter.registerLintRules(); registerBuiltInAssistGenerators(); @@ -555,14 +552,13 @@ class Driver implements ServerStarter { throw exception; } - var printFunction = - print == null - ? null - : (Zone self, ZoneDelegate parent, Zone zone, String line) { - // Note: we don't pass the line on to stdout, because that is - // reserved for communication to the client. - print(line); - }; + var printFunction = print == null + ? null + : (Zone self, ZoneDelegate parent, Zone zone, String line) { + // Note: we don't pass the line on to stdout, because that is + // reserved for communication to the client. + print(line); + }; var zoneSpecification = ZoneSpecification( handleUncaughtError: errorFunction, print: printFunction, diff --git a/pkg/analysis_server/lib/src/services/completion/dart/candidate_suggestion.dart b/pkg/analysis_server/lib/src/services/completion/dart/candidate_suggestion.dart index 4ce4e5d019d..030fd7b0eb0 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/candidate_suggestion.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/candidate_suggestion.dart @@ -183,10 +183,9 @@ final class ConstructorSuggestion extends ExecutableSuggestion required super.matcherScore, }) : assert((isTearOff ? 1 : 0) | (isRedirect ? 1 : 0) < 2), super( - kind: - isTearOff || isRedirect - ? CompletionSuggestionKind.IDENTIFIER - : CompletionSuggestionKind.INVOCATION, + kind: isTearOff || isRedirect + ? CompletionSuggestionKind.IDENTIFIER + : CompletionSuggestionKind.INVOCATION, ); @override @@ -1406,26 +1405,25 @@ extension SuggestionBuilderExtension on SuggestionBuilder { if (suggestion case MemberSuggestion(:var inheritanceDistance)) { distance = inheritanceDistance(request.featureComputer); } - var kind = - request.target.isFunctionalArgument() - ? CompletionSuggestionKind.IDENTIFIER - : null; + var kind = request.target.isFunctionalArgument() + ? CompletionSuggestionKind.IDENTIFIER + : null; suggestion.data = data; (switch (suggestion) { FieldSuggestion(:var element) => element.isEnumConstant ? suggestEnumConstant( - element, - suggestion.completion, - relevance: relevance, - ) + element, + suggestion.completion, + relevance: relevance, + ) : suggestField( - element, - inheritanceDistance: distance!, - relevance: relevance, - completion: suggestion.completion, - displayString: data?.displayText, - ), + element, + inheritanceDistance: distance!, + relevance: relevance, + completion: suggestion.completion, + displayString: data?.displayText, + ), GetterSuggestion() => suggestGetter( suggestion.element, displayString: data?.displayText, @@ -1443,17 +1441,17 @@ extension SuggestionBuilderExtension on SuggestionBuilder { relevance: relevance, ), MethodSuggestion(kind: var suggestionKind) => - // TODO(brianwilkerson): Correctly set the kind of suggestion in cases - // where `isFunctionalArgument` would return `true` so we can stop - // using the `request.target`. - suggestMethod( - suggestion.element, - completion: suggestion.completion, - displayString: data?.displayText, - kind: kind ?? suggestionKind, - inheritanceDistance: distance!, - relevance: relevance, - ), + // TODO(brianwilkerson): Correctly set the kind of suggestion in cases + // where `isFunctionalArgument` would return `true` so we can stop + // using the `request.target`. + suggestMethod( + suggestion.element, + completion: suggestion.completion, + displayString: data?.displayText, + kind: kind ?? suggestionKind, + inheritanceDistance: distance!, + relevance: relevance, + ), RecordFieldSuggestion() => suggestRecordField( field: suggestion.field, completion: suggestion.completion, diff --git a/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart b/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart index b5eb3e6415c..116e625e4e6 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart @@ -116,8 +116,9 @@ class DartCompletionManager { } var tokenData = TokenData.fromSelection(selection); var targetPrefix = tokenData?.prefix ?? ''; - var matcher = - targetPrefix.isEmpty ? NoPrefixMatcher() : FuzzyMatcher(targetPrefix); + var matcher = targetPrefix.isEmpty + ? NoPrefixMatcher() + : FuzzyMatcher(targetPrefix); var state = CompletionState(request, selection, budget, matcher); var operations = performance.run('InScopeCompletionPass', (performance) { var pass = InScopeCompletionPass( diff --git a/pkg/analysis_server/lib/src/services/completion/dart/declaration_helper.dart b/pkg/analysis_server/lib/src/services/completion/dart/declaration_helper.dart index 25eb308e6d3..1ea01d41d62 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/declaration_helper.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/declaration_helper.dart @@ -145,10 +145,9 @@ class DeclarationHelper { }); /// Return the suggestion kind that should be used for executable elements. - CompletionSuggestionKind get _executableSuggestionKind => - preferNonInvocation - ? CompletionSuggestionKind.IDENTIFIER - : CompletionSuggestionKind.INVOCATION; + CompletionSuggestionKind get _executableSuggestionKind => preferNonInvocation + ? CompletionSuggestionKind.IDENTIFIER + : CompletionSuggestionKind.INVOCATION; /// Add any constructors that are visible within the current library. void addConstructorInvocations() { @@ -412,8 +411,9 @@ class DeclarationHelper { /// local variables, local functions, parameters, members of the enclosing /// declaration, and top-level declarations in the enclosing library. void addLexicalDeclarations(AstNode node) { - var containingMember = - mustBeType ? _addLocalTypes(node) : _addLocalDeclarations(node); + var containingMember = mustBeType + ? _addLocalTypes(node) + : _addLocalDeclarations(node); if (containingMember == null) { return; } @@ -460,8 +460,9 @@ class DeclarationHelper { required bool includeSetters, }) { var extendedType = extension.extendedType; - var referencingInterface = - (extendedType is InterfaceType) ? extendedType.element : null; + var referencingInterface = (extendedType is InterfaceType) + ? extendedType.element + : null; if (includeMethods) { for (var method in extension.methods) { if (method.isStatic || @@ -594,10 +595,9 @@ class DeclarationHelper { } if (node.isNamed) { - var superConstructorInvocation = - constructor.initializers - .whereType() - .singleOrNull; + var superConstructorInvocation = constructor.initializers + .whereType() + .singleOrNull; var specified = { ...constructorElement.formalParameters.map((e) => e.name).nonNulls, ...?superConstructorInvocation?.argumentList.arguments @@ -612,10 +612,9 @@ class DeclarationHelper { } } else if (node.isPositional) { var indexOfThis = element.indexIn(constructorElement); - var superPositionalList = - superConstructor.formalParameters - .where((parameter) => parameter.isPositional) - .toList(); + var superPositionalList = superConstructor.formalParameters + .where((parameter) => parameter.isPositional) + .toList(); if (indexOfThis >= 0 && indexOfThis < superPositionalList.length) { var superPositional = superPositionalList[indexOfThis]; _suggestSuperParameter(superPositional); @@ -1120,10 +1119,9 @@ class DeclarationHelper { bool onlySuper = false, }) { var substitution = Substitution.fromInterfaceType(type); - var map = - onlySuper - ? type.element.inheritedConcreteMembers - : type.element.interfaceMembers; + var map = onlySuper + ? type.element.inheritedConcreteMembers + : type.element.interfaceMembers; var membersByName = >{}; for (var rawMember in map.values) { @@ -1833,10 +1831,9 @@ class DeclarationHelper { // Use the constructor element's name without the interface type to // calculate the matcher score for dot shorthands. var elementName = element.name; - var matcherName = - suggestingDotShorthand && elementName != null - ? elementName - : element.displayName; + var matcherName = suggestingDotShorthand && elementName != null + ? elementName + : element.displayName; // TODO(keertip): Compute the completion string. var matcherScore = state.matcher.score(matcherName); if (matcherScore != -1) { @@ -1918,10 +1915,9 @@ class DeclarationHelper { importData: importData, element: element, matcherScore: matcherScore, - kind: - preferNonInvocation - ? CompletionSuggestionKind.IDENTIFIER - : CompletionSuggestionKind.INVOCATION, + kind: preferNonInvocation + ? CompletionSuggestionKind.IDENTIFIER + : CompletionSuggestionKind.INVOCATION, ); collector.addSuggestion(suggestion); } diff --git a/pkg/analysis_server/lib/src/services/completion/dart/feature_computer.dart b/pkg/analysis_server/lib/src/services/completion/dart/feature_computer.dart index 374b7f96893..7551bb8c409 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/feature_computer.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/feature_computer.dart @@ -447,10 +447,9 @@ class FeatureComputer { double superMatchesFeature( String? containingMethodName, String proposedMemberName, - ) => - containingMethodName == null - ? 0.0 - : (proposedMemberName == containingMethodName ? 1.0 : 0.0); + ) => containingMethodName == null + ? 0.0 + : (proposedMemberName == containingMethodName ? 1.0 : 0.0); /// Return the inheritance distance between the [subclass] and the /// [superclass]. The set of [visited] elements is used to guard against diff --git a/pkg/analysis_server/lib/src/services/completion/dart/fuzzy_filter_sort.dart b/pkg/analysis_server/lib/src/services/completion/dart/fuzzy_filter_sort.dart index 204ba16331c..2653afb3058 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/fuzzy_filter_sort.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/fuzzy_filter_sort.dart @@ -16,8 +16,8 @@ List fuzzyFilterSort({ }) { var matchStyle = suggestions.firstOrNull?.kind == CompletionSuggestionKind.IMPORT - ? MatchStyle.FILENAME - : MatchStyle.SYMBOL; + ? MatchStyle.FILENAME + : MatchStyle.SYMBOL; var matcher = FuzzyMatcher(pattern, matchStyle: matchStyle); double score(CompletionSuggestionBuilder suggestion) { @@ -35,11 +35,10 @@ List fuzzyFilterSort({ return matcher.score(textToMatch); } - var scored = - suggestions - .map((e) => _FuzzyScoredSuggestion(e, score(e))) - .where((e) => e.score > 0) - .toList(); + var scored = suggestions + .map((e) => _FuzzyScoredSuggestion(e, score(e))) + .where((e) => e.score > 0) + .toList(); scored.sort((a, b) { // Prefer what the user requested by typing. diff --git a/pkg/analysis_server/lib/src/services/completion/dart/in_scope_completion_pass.dart b/pkg/analysis_server/lib/src/services/completion/dart/in_scope_completion_pass.dart index a143165ca2b..dd3b2787f28 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/in_scope_completion_pass.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/in_scope_completion_pass.dart @@ -2458,10 +2458,9 @@ class InScopeCompletionPass extends SimpleAstVisitor { collector.completionLocation = 'PatternField_pattern'; keywordHelper.addKeyword(Keyword.DYNAMIC); _forExpression(node); - var targetField = - node.fields.skipWhile((field) { - return field.end < offset; - }).firstOrNull; + var targetField = node.fields.skipWhile((field) { + return field.end < offset; + }).firstOrNull; if (targetField != null) { var nameNode = targetField.name; if (nameNode != null && offset <= nameNode.colon.offset) { @@ -3459,11 +3458,10 @@ class InScopeCompletionPass extends SimpleAstVisitor { if (existingNames.contains(coveringNode)) { excludedName = coveringNode; } - var excludedNames = - existingNames - .where((element) => element != excludedName) - .map((element) => element.name) - .toSet(); + var excludedNames = existingNames + .where((element) => element != excludedName) + .map((element) => element.name) + .toSet(); declarationHelper( preferNonInvocation: true, ).addFromLibrary(library, excludedNames); @@ -4109,11 +4107,10 @@ class InScopeCompletionPass extends SimpleAstVisitor { var includedNames = const {}; if (recordLiteral != null) { - includedNames = - recordLiteral.fields - .whereType() - .map((e) => e.name.label.name) - .toSet(); + includedNames = recordLiteral.fields + .whereType() + .map((e) => e.name.label.name) + .toSet(); } for (var field in recordType.namedFields) { @@ -4295,8 +4292,8 @@ extension on AstNode { MethodDeclaration(:var metadata) => metadata.contains(child), MixinDeclaration(:var members, :var metadata) => members.contains(child) || metadata.contains(child), - MixinOnClause(:var superclassConstraints) => superclassConstraints - .contains(child), + MixinOnClause(:var superclassConstraints) => + superclassConstraints.contains(child), ObjectPattern(:var fields) => fields.contains(child), PartDirective(:var metadata) => metadata.contains(child), PartOfDirective(:var metadata) => metadata.contains(child), diff --git a/pkg/analysis_server/lib/src/services/completion/dart/relevance_computer.dart b/pkg/analysis_server/lib/src/services/completion/dart/relevance_computer.dart index 86207736e5f..778011c70da 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/relevance_computer.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/relevance_computer.dart @@ -54,9 +54,8 @@ class RelevanceComputer { if (!_hasContainingMemberName) { _hasContainingMemberName = true; if (request.target.dotTarget is SuperExpression) { - var containingMethod = - request.target.containingNode - .thisOrAncestorOfType(); + var containingMethod = request.target.containingNode + .thisOrAncestorOfType(); if (containingMethod != null) { _cachedContainingMemberName = containingMethod.name.lexeme; } @@ -79,8 +78,9 @@ class RelevanceComputer { distance: inheritanceDistance, ); var hasDeprecated = featureComputer.hasDeprecatedFeature(element); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(element) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(element) + : 0.0; var startsWithDollar = featureComputer.startsWithDollarFeature( element.displayName, ); @@ -363,8 +363,9 @@ class RelevanceComputer { ); var elementKind = _computeElementKind(element); var hasDeprecated = featureComputer.hasDeprecatedFeature(element); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(element) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(element) + : 0.0; return computeScore( contextType: contextType, elementKind: elementKind, @@ -390,8 +391,9 @@ class RelevanceComputer { ); var elementKind = _computeElementKind2(element); var hasDeprecated = featureComputer.hasDeprecatedFeature(element); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(element) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(element) + : 0.0; return computeScore( contextType: contextType, elementKind: elementKind, @@ -416,8 +418,9 @@ class RelevanceComputer { ); var elementKind = _computeElementKind(accessor, distance: distance); var hasDeprecated = featureComputer.hasDeprecatedFeature(accessor); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(accessor) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(accessor) + : 0.0; return computeScore( contextType: contextType, elementKind: elementKind, @@ -518,8 +521,9 @@ class RelevanceComputer { suggestion.distance, ); var elementKind = _computeElementKind(element); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(element) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(element) + : 0.0; return computeScore( contextType: contextType, elementKind: elementKind, @@ -563,8 +567,9 @@ class RelevanceComputer { element, distance: localVariableDistance, ); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(element) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(element) + : 0.0; return computeScore( contextType: contextType, elementKind: elementKind, @@ -588,8 +593,9 @@ class RelevanceComputer { distance: inheritanceDistance, ); var hasDeprecated = featureComputer.hasDeprecatedFeature(method); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(method) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(method) + : 0.0; var isNoSuchMethod = featureComputer.isNoSuchMethodFeature( _containingMemberName, method.displayName, @@ -706,8 +712,9 @@ class RelevanceComputer { /// Compute the relevance for [TypeParameterElement]. int _computeTypeParameterRelevance(TypeParameterElement parameter) { var elementKind = _computeElementKind(parameter); - var isConstant = - preferConstants ? featureComputer.isConstantFeature(parameter) : 0.0; + var isConstant = preferConstants + ? featureComputer.isConstantFeature(parameter) + : 0.0; return computeScore(elementKind: elementKind, isConstant: isConstant); } diff --git a/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart b/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart index 8da42012852..ca4f7fce4ad 100644 --- a/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart +++ b/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart @@ -122,9 +122,8 @@ class SuggestionBuilder { if (!_hasContainingMemberName) { _hasContainingMemberName = true; if (request.target.dotTarget is SuperExpression) { - var containingMethod = - request.target.containingNode - .thisOrAncestorOfType(); + var containingMethod = request.target.containingNode + .thisOrAncestorOfType(); if (containingMethod != null) { _cachedContainingMemberName = containingMethod.name.lexeme; } @@ -298,8 +297,9 @@ class SuggestionBuilder { distance: inheritanceDistance, ); var hasDeprecated = featureComputer.hasDeprecatedFeature(field); - var isConstant = - _preferConstants ? featureComputer.isConstantFeature(field) : 0.0; + var isConstant = _preferConstants + ? featureComputer.isConstantFeature(field) + : 0.0; var startsWithDollar = featureComputer.startsWithDollarFeature( field.name ?? '', ); @@ -343,10 +343,9 @@ class SuggestionBuilder { distance, ); var elementKind = _computeElementKind(element); - var isConstant = - _preferConstants - ? request.featureComputer.isConstantFeature(element) - : 0.0; + var isConstant = _preferConstants + ? request.featureComputer.isConstantFeature(element) + : 0.0; relevance ??= relevanceComputer.computeScore( contextType: contextType, elementKind: elementKind, @@ -423,8 +422,9 @@ class SuggestionBuilder { distance: inheritanceDistance, ); var hasDeprecated = featureComputer.hasDeprecatedFeature(getter); - var isConstant = - _preferConstants ? featureComputer.isConstantFeature(getter) : 0.0; + var isConstant = _preferConstants + ? featureComputer.isConstantFeature(getter) + : 0.0; var startsWithDollar = featureComputer.startsWithDollarFeature( getter.displayName, ); @@ -607,10 +607,9 @@ class SuggestionBuilder { element, distance: localVariableDistance, ); - var isConstant = - _preferConstants - ? request.featureComputer.isConstantFeature(element) - : 0.0; + var isConstant = _preferConstants + ? request.featureComputer.isConstantFeature(element) + : 0.0; relevance ??= relevanceComputer.computeScore( contextType: contextType, elementKind: elementKind, @@ -651,8 +650,9 @@ class SuggestionBuilder { distance: inheritanceDistance, ); var hasDeprecated = featureComputer.hasDeprecatedFeature(method); - var isConstant = - _preferConstants ? featureComputer.isConstantFeature(method) : 0.0; + var isConstant = _preferConstants + ? featureComputer.isConstantFeature(method) + : 0.0; var isNoSuchMethod = featureComputer.isNoSuchMethodFeature( _containingMemberName, method.displayName, @@ -970,8 +970,9 @@ class SuggestionBuilder { distance: inheritanceDistance, ); var hasDeprecated = featureComputer.hasDeprecatedFeature(setter); - var isConstant = - _preferConstants ? featureComputer.isConstantFeature(setter) : 0.0; + var isConstant = _preferConstants + ? featureComputer.isConstantFeature(setter) + : 0.0; var startsWithDollar = featureComputer.startsWithDollarFeature( setter.displayName, ); @@ -1104,8 +1105,9 @@ class SuggestionBuilder { ); var elementKind = _computeElementKind(getter); var hasDeprecated = featureComputer.hasDeprecatedFeature(getter); - var isConstant = - _preferConstants ? featureComputer.isConstantFeature(getter) : 0.0; + var isConstant = _preferConstants + ? featureComputer.isConstantFeature(getter) + : 0.0; var startsWithDollar = featureComputer.startsWithDollarFeature( getter.displayName, ); @@ -1156,8 +1158,9 @@ class SuggestionBuilder { ); var elementKind = _computeElementKind(setter); var hasDeprecated = featureComputer.hasDeprecatedFeature(setter); - var isConstant = - _preferConstants ? featureComputer.isConstantFeature(setter) : 0.0; + var isConstant = _preferConstants + ? featureComputer.isConstantFeature(setter) + : 0.0; var startsWithDollar = featureComputer.startsWithDollarFeature( setter.displayName, ); @@ -1243,10 +1246,9 @@ class SuggestionBuilder { /// Add a suggestion for a type [parameter]. void suggestTypeParameter(TypeParameterElement parameter, {int? relevance}) { var elementKind = _computeElementKind(parameter); - var isConstant = - _preferConstants - ? request.featureComputer.isConstantFeature(parameter) - : 0.0; + var isConstant = _preferConstants + ? request.featureComputer.isConstantFeature(parameter) + : 0.0; relevance ??= relevanceComputer.computeScore( elementKind: elementKind, isConstant: isConstant, @@ -1263,8 +1265,9 @@ class SuggestionBuilder { /// Add a suggestion to use the [uri] in an import, export, or part directive. void suggestUri(String uri) { - var relevance = - uri == 'dart:core' ? Relevance.importDartCore : Relevance.import; + var relevance = uri == 'dart:core' + ? Relevance.importDartCore + : Relevance.import; _addSuggestion( CompletionSuggestion( CompletionSuggestionKind.IMPORT, @@ -1433,14 +1436,14 @@ class SuggestionBuilder { bool? hasNamedParameters; CompletionDefaultArgumentList? defaultArgumentList; if (element is ExecutableElement && element is! PropertyAccessorElement) { - parameterNames = - element.formalParameters.map((parameter) { - return parameter.displayName; - }).toList(); - parameterTypes = - element.formalParameters.map((FormalParameterElement parameter) { - return parameter.type.getDisplayString(); - }).toList(); + parameterNames = element.formalParameters.map((parameter) { + return parameter.displayName; + }).toList(); + parameterTypes = element.formalParameters.map(( + FormalParameterElement parameter, + ) { + return parameter.type.getDisplayString(); + }).toList(); var requiredParameters = element.formalParameters.where( (FormalParameterElement param) => param.isRequiredPositional, diff --git a/pkg/analysis_server/lib/src/services/completion/statement/statement_completion.dart b/pkg/analysis_server/lib/src/services/completion/statement/statement_completion.dart index 94cf00577c4..45d4997db08 100644 --- a/pkg/analysis_server/lib/src/services/completion/statement/statement_completion.dart +++ b/pkg/analysis_server/lib/src/services/completion/statement/statement_completion.dart @@ -411,10 +411,9 @@ class StatementCompletionProcessor { } bool _complete_controlFlowBlock(AstNode node) { - var expr = - (node is ExpressionStatement) - ? node.expression - : (node is ReturnStatement ? node.expression : null); + var expr = (node is ExpressionStatement) + ? node.expression + : (node is ReturnStatement ? node.expression : null); if (!(node is ReturnStatement || expr is ThrowExpression)) { return false; } @@ -1028,8 +1027,9 @@ class StatementCompletionProcessor { var member = _findInvalidElement(node.members); if (member != null) { if (member.colon.isSynthetic) { - var loc = - member is SwitchCase ? member.expression.end : member.keyword.end; + var loc = member is SwitchCase + ? member.expression.end + : member.keyword.end; sb = SourceBuilder(file, loc); sb.append(': '); exitPosition = Position(file, loc + 2); diff --git a/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart b/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart index 219591fd6d1..73d90506ab4 100644 --- a/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart +++ b/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart @@ -56,8 +56,10 @@ import 'package:linter/src/rules/directives_ordering.dart'; import 'package:meta/meta.dart'; import 'package:yaml/yaml.dart'; -typedef PubspecFixRequestResult = - ({List edits, List details}); +typedef PubspecFixRequestResult = ({ + List edits, + List details, +}); /// A fix producer that produces changes that will fix multiple diagnostics in /// one or more files. @@ -146,11 +148,13 @@ class BulkFixProcessor { /// Cached results of [_canBulkFix]. static final Map _bulkFixableCodes = {}; - static final Set _diagnosticCodes = - diagnosticCodeValues.map((code) => code.name.toLowerCase()).toSet(); + static final Set _diagnosticCodes = diagnosticCodeValues + .map((code) => code.name.toLowerCase()) + .toSet(); - static final Set _lintCodes = - Registry.ruleRegistry.rules.map((rule) => rule.name).toSet(); + static final Set _lintCodes = Registry.ruleRegistry.rules + .map((rule) => rule.name) + .toSet(); /// The service used to report errors when building fixes. final InstrumentationService _instrumentationService; @@ -356,10 +360,9 @@ class BulkFixProcessor { !parsedOnly || producer is ParsedCorrectionProducer, '$producer must be a ParsedCorrectionProducer', ); - var shouldFix = - (context.dartFixContext?.autoTriggered ?? false) - ? producer.canBeAppliedAutomatically - : producer.canBeAppliedAcrossFiles; + var shouldFix = (context.dartFixContext?.autoTriggered ?? false) + ? producer.canBeAppliedAutomatically + : producer.canBeAppliedAcrossFiles; if (shouldFix) { await _generateFix(context, producer, codeName); if (isCancelled) { @@ -409,8 +412,9 @@ class BulkFixProcessor { for (var unitResult in libraryResult.units) { var directives = unitResult.unit.directives; for (var directive in directives) { - var uri = - (directive is ImportDirective) ? directive.uri.stringValue : ''; + var uri = (directive is ImportDirective) + ? directive.uri.stringValue + : ''; if (uri!.startsWith('package:')) { var name = Uri.parse(uri).pathSegments.first; if (libPath.contains(path) || binPath.contains(path)) { @@ -527,10 +531,9 @@ class BulkFixProcessor { // TODO(srawlins): We are passing `currentUnit` in as `definingUnit`. Seems // wrong. var context = RuleContextWithParsedResults(allUnits, currentUnit); - var lintRules = - _syntacticLintCodes - .map((name) => Registry.ruleRegistry.getRule(name)) - .nonNulls; + var lintRules = _syntacticLintCodes + .map((name) => Registry.ruleRegistry.getRule(name)) + .nonNulls; for (var lintRule in lintRules) { lintRule.reporter = currentUnit.diagnosticReporter; lintRule.registerNodeProcessors(nodeRegistry, context); @@ -983,10 +986,9 @@ class BulkFixProcessor { bool hasBulkFixProducers(List? generators) { return generators != null && generators.any( - (generator) => - generator( - context: StubCorrectionProducerContext.instance, - ).canBeAppliedAcrossFiles, + (generator) => generator( + context: StubCorrectionProducerContext.instance, + ).canBeAppliedAcrossFiles, ); } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_await.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_await.dart index 6690c04b233..285a019cdbe 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_await.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_await.dart @@ -101,11 +101,10 @@ class AddAwait extends ResolvedCorrectionProducer { typeSystem.isAssignableTo(type, typeProvider.streamDynamicType); if (isStream || _isValidFutureType( - isValid: - (type) => typeSystem.isAssignableTo( - type, - typeProvider.iterableDynamicType, - ), + isValid: (type) => typeSystem.isAssignableTo( + type, + typeProvider.iterableDynamicType, + ), )) { await _addAwait( builder, diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_call_super.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_call_super.dart index c3728e217a4..45ec797d710 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_call_super.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_call_super.dart @@ -31,10 +31,9 @@ class AddCallSuper extends ResolvedCorrectionProducer { var methodDeclaration = node; if (methodDeclaration is! MethodDeclaration) return; - var classFragment = - methodDeclaration - .thisOrAncestorOfType() - ?.declaredFragment; + var classFragment = methodDeclaration + .thisOrAncestorOfType() + ?.declaredFragment; if (classFragment == null) return; var classElement = classFragment.element; diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart index 54bdf593e53..af1151f3546 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart @@ -101,8 +101,9 @@ class AddConst extends ResolvedCorrectionProducer { :var parent, constKeyword: var keyword, )) { - var constDeclarations = - getCodeStyleOptions(unitResult.file).preferConstDeclarations; + var constDeclarations = getCodeStyleOptions( + unitResult.file, + ).preferConstDeclarations; if (parent is VariableDeclaration && constDeclarations) { if (parent.parent case VariableDeclarationList( @@ -220,8 +221,9 @@ class AddConst extends ResolvedCorrectionProducer { /// one of [targetNode]s ancestors. bool _isAncestorConstant(List edits, Expression targetNode) { var child = targetNode.parent; - var editsWhichStartWithConst = - edits.where((e) => e.replacement.startsWith('const')).toList(); + var editsWhichStartWithConst = edits + .where((e) => e.replacement.startsWith('const')) + .toList(); if (editsWhichStartWithConst.isEmpty) { return false; } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_diagnostic_property_reference.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_diagnostic_property_reference.dart index 133b758b408..001580a5001 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_diagnostic_property_reference.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_diagnostic_property_reference.dart @@ -465,9 +465,8 @@ class _PropertyInfo { } extension on ClassDeclaration { - MethodDeclaration? get debugFillPropertiesDeclaration => - members - .whereType() - .where((e) => e.name.lexeme == 'debugFillProperties') - .singleOrNull; + MethodDeclaration? get debugFillPropertiesDeclaration => members + .whereType() + .where((e) => e.name.lexeme == 'debugFillProperties') + .singleOrNull; } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_digit_separators.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_digit_separators.dart index fda01051cec..abe7b22f545 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_digit_separators.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_digit_separators.dart @@ -122,10 +122,9 @@ abstract class _AddDigitSeparators extends ResolvedCorrectionProducer { var decimalIndex = source.indexOf('.'); if (decimalIndex > -1) { wholePart = source.substring(0, decimalIndex); - fractionalPart = - eIndex > -1 - ? source.substring(decimalIndex + 1, eIndex) - : source.substring(decimalIndex + 1); + fractionalPart = eIndex > -1 + ? source.substring(decimalIndex + 1, eIndex) + : source.substring(decimalIndex + 1); } else { assert( eIndex > -1, diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_field_formal_parameters.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_field_formal_parameters.dart index e07778cacf3..da4ac666428 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_field_formal_parameters.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_field_formal_parameters.dart @@ -83,8 +83,9 @@ class AddFieldFormalParameters extends ResolvedCorrectionProducer { } var fieldsRecords = fields.map(_parameterForField).toList(); - var requiredFirst = - getCodeStyleOptions(unitResult.file).requiredNamedParametersFirst; + var requiredFirst = getCodeStyleOptions( + unitResult.file, + ).requiredNamedParametersFirst; if (requiredFirst) { fieldsRecords.sort((a, b) { if (a.isRequired && !b.isRequired) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_missing_parameter.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_missing_parameter.dart index cad4d0a1e2e..325b9b6a329 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_missing_parameter.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_missing_parameter.dart @@ -145,10 +145,9 @@ class _AddMissingRequiredPositionalParameter extends _AddMissingParameter { } else { var parameterList = await _executableParameters.getParameterList(); var offset = parameterList?.leftParenthesis.end; - var suffix = - _executableParameters.executable.formalParameters.isNotEmpty - ? ', ' - : ''; + var suffix = _executableParameters.executable.formalParameters.isNotEmpty + ? ', ' + : ''; await _addParameter(builder, offset, '', suffix); } } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_null_check.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_null_check.dart index e0405f4d031..92aba34479a 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_null_check.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_null_check.dart @@ -35,10 +35,9 @@ class AddNullCheck extends ResolvedCorrectionProducer { final Token? _nullAwareToken; factory AddNullCheck({required CorrectionProducerContext context}) { - var (:target, :nullAwareToken) = - context is StubCorrectionProducerContext - ? (target: null, nullAwareToken: null) - : _computeTargetAndNullAwareToken(context.node); + var (:target, :nullAwareToken) = context is StubCorrectionProducerContext + ? (target: null, nullAwareToken: null) + : _computeTargetAndNullAwareToken(context.node); return AddNullCheck._( context: context, @@ -52,10 +51,9 @@ class AddNullCheck extends ResolvedCorrectionProducer { factory AddNullCheck.withoutAssignabilityCheck({ required CorrectionProducerContext context, }) { - var (:target, :nullAwareToken) = - context is StubCorrectionProducerContext - ? (target: null, nullAwareToken: null) - : _computeTargetAndNullAwareToken(context.node); + var (:target, :nullAwareToken) = context is StubCorrectionProducerContext + ? (target: null, nullAwareToken: null) + : _computeTargetAndNullAwareToken(context.node); return AddNullCheck._( context: context, @@ -74,10 +72,9 @@ class AddNullCheck extends ResolvedCorrectionProducer { required Token? nullAwareToken, }) : _target = target, _nullAwareToken = nullAwareToken, - fixKind = - nullAwareToken == null - ? DartFixKind.ADD_NULL_CHECK - : DartFixKind.REPLACE_WITH_NULL_AWARE; + fixKind = nullAwareToken == null + ? DartFixKind.ADD_NULL_CHECK + : DartFixKind.REPLACE_WITH_NULL_AWARE; @override Future compute(ChangeBuilder builder) async { @@ -131,14 +128,14 @@ class AddNullCheck extends ResolvedCorrectionProducer { if (literal is ListLiteral) { toType = literal.typeOrThrow.asInstanceOf(typeProvider.iterableElement); } else if (literal is SetOrMapLiteral) { - toType = - literal.typeOrThrow.isDartCoreSet - ? literal.typeOrThrow.asInstanceOf(typeProvider.iterableElement) - : literal.typeOrThrow.asInstanceOf(typeProvider.mapElement); + toType = literal.typeOrThrow.isDartCoreSet + ? literal.typeOrThrow.asInstanceOf(typeProvider.iterableElement) + : literal.typeOrThrow.asInstanceOf(typeProvider.mapElement); } } else if (parent is YieldStatement) { - var enclosingExecutable = - parent.thisOrAncestorOfType()?.parent; + var enclosingExecutable = parent + .thisOrAncestorOfType() + ?.parent; if (enclosingExecutable is MethodDeclaration) { toType = enclosingExecutable.returnType?.type; } else if (enclosingExecutable is FunctionExpressionImpl) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_super_constructor_invocation.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_super_constructor_invocation.dart index 89a293523e2..a58ea653afa 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_super_constructor_invocation.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_super_constructor_invocation.dart @@ -103,8 +103,8 @@ class _AddInvocation extends ResolvedCorrectionProducer { _constructor.formalParameters.any((p) => p.name == null)) { return; } - var currentConstructor = - node.thisOrAncestorOfType(); + var currentConstructor = node + .thisOrAncestorOfType(); var positionalParameters = 0; var namedParameters = {}; if (currentConstructor case ConstructorDeclaration(:var parameters)) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_super_parameter.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_super_parameter.dart index c7c4637fbac..d5c5deef680 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/add_super_parameter.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/add_super_parameter.dart @@ -83,10 +83,9 @@ class AddSuperParameter extends ResolvedCorrectionProducer { var missingPositionalParameters = []; if (arePositionalOrdered) { - var index = - lastPositionalParameter == null - ? 0 - : parameters.indexOf(lastPositionalParameter) + 1; + var index = lastPositionalParameter == null + ? 0 + : parameters.indexOf(lastPositionalParameter) + 1; missingPositionalParameters = superPositionalParameters.sublist(index); } @@ -115,10 +114,9 @@ class AddSuperParameter extends ResolvedCorrectionProducer { (parameter) => parameter.isNamed, ); if (missingPositionalParameters.isNotEmpty) { - var offset = - lastPositionalParameter == null - ? constructorDeclaration.parameters.leftParenthesis.end - : lastPositionalParameter.end; + var offset = lastPositionalParameter == null + ? constructorDeclaration.parameters.leftParenthesis.end + : lastPositionalParameter.end; await builder.addDartFileEdit(file, (builder) { builder.addInsertion(offset, (builder) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/ambiguous_import_fix.dart b/pkg/analysis_server/lib/src/services/correction/dart/ambiguous_import_fix.dart index ff0fea34c4e..3ab7d34b2e4 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/ambiguous_import_fix.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/ambiguous_import_fix.dart @@ -69,10 +69,9 @@ class AmbiguousImportFix extends MultiCorrectionProducer { ); for (var uri in uris) { - var directives = - importDirectives - .whereNot((directive) => directive.uri.stringValue == uri) - .toList(); + var directives = importDirectives + .whereNot((directive) => directive.uri.stringValue == uri) + .toList(); producers.add( _ImportAddHide(name, uri, prefix, directives, context: thisContext), ); @@ -127,10 +126,9 @@ class AmbiguousImportFix extends MultiCorrectionProducer { // If this library is imported directly or if the directive exports // the library for this element. - var element = - prefix != null - ? libraryImport.namespace.getPrefixed2(prefix, name) - : libraryImport.namespace.get2(name); + var element = prefix != null + ? libraryImport.namespace.getPrefixed2(prefix, name) + : libraryImport.namespace.get2(name); if (element == conflictingElement) { var uri = directive.uri.stringValue; if (uri != null) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/change_to.dart b/pkg/analysis_server/lib/src/services/correction/dart/change_to.dart index 83d7215351e..ce1ebacf686 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/change_to.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/change_to.dart @@ -203,8 +203,8 @@ class ChangeTo extends ResolvedCorrectionProducer { if (node is! FieldFormalParameter) return; var exclusions = {}; - var constructorDeclaration = - node.thisOrAncestorOfType(); + var constructorDeclaration = node + .thisOrAncestorOfType(); var initializers = constructorDeclaration?.initializers; if (initializers != null) { for (var initializer in initializers) { @@ -339,13 +339,12 @@ class ChangeTo extends ResolvedCorrectionProducer { var superParameter = node; if (superParameter is! SuperFormalParameter) return; - var constructorDeclaration = - superParameter.thisOrAncestorOfType(); + var constructorDeclaration = superParameter + .thisOrAncestorOfType(); if (constructorDeclaration == null) return; - var formalParameters = - constructorDeclaration.parameters.parameters - .whereType(); + var formalParameters = constructorDeclaration.parameters.parameters + .whereType(); var finder = _ClosestElementFinder(superParameter.name.lexeme, (e) => true); @@ -358,8 +357,8 @@ class ChangeTo extends ResolvedCorrectionProducer { var list = _formalParameterSuggestions(element, formalParameters); finder._updateList(list); } else { - var targetClassNode = - superParameter.thisOrAncestorOfType(); + var targetClassNode = superParameter + .thisOrAncestorOfType(); if (targetClassNode == null) return; var targetClassElement = targetClassNode.declaredFragment!.element; diff --git a/pkg/analysis_server/lib/src/services/correction/dart/change_to_nearest_precise_value.dart b/pkg/analysis_server/lib/src/services/correction/dart/change_to_nearest_precise_value.dart index fd95fe87b82..2988db3d3da 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/change_to_nearest_precise_value.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/change_to_nearest_precise_value.dart @@ -35,10 +35,9 @@ class ChangeToNearestPreciseValue extends ResolvedCorrectionProducer { var lexeme = integer.literal.lexeme; var precise = BigInt.from(IntegerLiteralImpl.nearestValidDouble(lexeme)); - _correction = - lexeme.toLowerCase().contains('x') - ? '0x${precise.toRadixString(16).toUpperCase()}' - : precise.toString(); + _correction = lexeme.toLowerCase().contains('x') + ? '0x${precise.toRadixString(16).toUpperCase()}' + : precise.toString(); await builder.addDartFileEdit(file, (builder) { builder.addSimpleReplacement(range.node(integer), _correction); }); diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_add_all_to_spread.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_add_all_to_spread.dart index 602eaf2a7f1..b789f21292d 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_add_all_to_spread.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_add_all_to_spread.dart @@ -76,25 +76,22 @@ class ConvertAddAllToSpread extends ResolvedCorrectionProducer { List get assistArguments => _args; @override - AssistKind get assistKind => - _isInlineInvocation - ? DartAssistKind.inlineInvocation - : DartAssistKind.convertToSpread; + AssistKind get assistKind => _isInlineInvocation + ? DartAssistKind.inlineInvocation + : DartAssistKind.convertToSpread; @override List get fixArguments => _args; @override - FixKind get fixKind => - _isInlineInvocation - ? DartFixKind.INLINE_INVOCATION - : DartFixKind.CONVERT_TO_SPREAD; + FixKind get fixKind => _isInlineInvocation + ? DartFixKind.INLINE_INVOCATION + : DartFixKind.CONVERT_TO_SPREAD; @override - FixKind get multiFixKind => - _isInlineInvocation - ? DartFixKind.INLINE_INVOCATION_MULTI - : DartFixKind.CONVERT_TO_SPREAD_MULTI; + FixKind get multiFixKind => _isInlineInvocation + ? DartFixKind.INLINE_INVOCATION_MULTI + : DartFixKind.CONVERT_TO_SPREAD_MULTI; @override Future compute(ChangeBuilder builder) async { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_class_to_enum.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_class_to_enum.dart index ad77ff12bd5..9439ead5919 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_class_to_enum.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_class_to_enum.dart @@ -699,8 +699,9 @@ class _EnumVisitor extends _BaseVisitor { /// Initialize a newly created visitor to visit the class declaration /// corresponding to the given [classElement]. _EnumVisitor(super.classElement, List<_ConstantField> fieldsToConvert) - : fieldsToConvert = - fieldsToConvert.map((field) => field.declaration).toList(); + : fieldsToConvert = fieldsToConvert + .map((field) => field.declaration) + .toList(); @override void visitInstanceCreationExpression(InstanceCreationExpression node) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_field_formal_to_normal.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_field_formal_to_normal.dart index a357018ec7a..070243c93d0 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_field_formal_to_normal.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_field_formal_to_normal.dart @@ -30,8 +30,9 @@ class ConvertFieldFormalToNormal extends ResolvedCorrectionProducer { if (field == null) { return; } - var constructor = - parameter.thisOrAncestorOfType()?.parent; + var constructor = parameter + .thisOrAncestorOfType() + ?.parent; if (constructor is! ConstructorDeclaration) { return; } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_into_for_index.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_into_for_index.dart index 24e4cc4c233..2b0a7eb8081 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_into_for_index.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_into_for_index.dart @@ -41,10 +41,9 @@ class ConvertIntoForIndex extends ResolvedCorrectionProducer { return; } // loop should declare variable - var loopVariable = - forEachParts is ForEachPartsWithDeclaration - ? forEachParts.loopVariable - : null; + var loopVariable = forEachParts is ForEachPartsWithDeclaration + ? forEachParts.loopVariable + : null; if (loopVariable == null) { return; } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_related_to_cascade.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_related_to_cascade.dart index 7b06b903be1..4ac100fd58c 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_related_to_cascade.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_related_to_cascade.dart @@ -72,16 +72,14 @@ class ConvertRelatedToCascade extends ResolvedCorrectionProducer { for (var (index, statement) in relatedStatements.indexed) { Token? previousOperator; Token? semicolon; - var previous = - index > 0 - ? relatedStatements[index - 1] - : _getPrevious(block, statement); + var previous = index > 0 + ? relatedStatements[index - 1] + : _getPrevious(block, statement); if (previous is ExpressionStatement) { semicolon = previous.semicolon; - previousOperator = - (index == 0) - ? _getTargetAndOperator(previous.expression)?.operator - : null; + previousOperator = (index == 0) + ? _getTargetAndOperator(previous.expression)?.operator + : null; } else if (previous is VariableDeclarationStatement) { // Single variable declaration. if (previous.variables.variables.length != 1) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_boolean_expression.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_boolean_expression.dart index 4601f5f466b..b9671e43a21 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_boolean_expression.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_boolean_expression.dart @@ -65,12 +65,11 @@ class ConvertToBooleanExpression extends ResolvedCorrectionProducer { await (switch ((thenExpression, elseExpression)) { (BooleanLiteral then, BooleanLiteral elseExp) => () async { var equalValues = then.value == elseExp.value; - var rangeStart = - equalValues - // keep `then` - ? range.startStart(condition, then) - // keep `condition` - : range.endEnd(condition, then); + var rangeStart = equalValues + // keep `then` + ? range.startStart(condition, then) + // keep `condition` + : range.endEnd(condition, then); // remove ` : elseExp` var rangeEnd = range.endEnd(then, elseExp); await _addEdit( @@ -95,8 +94,9 @@ class ConvertToBooleanExpression extends ResolvedCorrectionProducer { then.value ? operator : null, ), bangBeforeParens: true, - parensRange2: - elseExp.needsParens(operator) ? range.node(elseExp) : null, + parensRange2: elseExp.needsParens(operator) + ? range.node(elseExp) + : null, ); }(), (Expression then, BooleanLiteral elseExp) => () async { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart index 90f995197df..ef3cc2995f2 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart @@ -89,10 +89,9 @@ class ConvertToFunctionDeclaration extends ResolvedCorrectionProducer { parameterList = aliasedType.formalParameters; } else if (type is GenericFunctionType) { returnType = type.returnType?.type; - parameterList = - type.parameters.parameters - .map((node) => node.declaredFragment!.element) - .toList(); + parameterList = type.parameters.parameters + .map((node) => node.declaredFragment!.element) + .toList(); } else if (initializer case FunctionExpression( declaredFragment: ExecutableFragment(:var element), :var body, diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_generic_function_syntax.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_generic_function_syntax.dart index d25c6f11ecf..bbd7c075b28 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_generic_function_syntax.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_generic_function_syntax.dart @@ -104,12 +104,14 @@ class ConvertToGenericFunctionSyntax extends ParsedCorrectionProducer { var required = node.requiredKeyword != null ? 'required ' : ''; var covariant = node.covariantKeyword != null ? 'covariant ' : ''; var returnTypeNode = node.returnType; - var returnType = - returnTypeNode != null ? '${utils.getNodeText(returnTypeNode)} ' : ''; + var returnType = returnTypeNode != null + ? '${utils.getNodeText(returnTypeNode)} ' + : ''; var functionName = node.name.lexeme; var typeParametersNode = node.typeParameters; - var typeParameters = - typeParametersNode != null ? utils.getNodeText(typeParametersNode) : ''; + var typeParameters = typeParametersNode != null + ? utils.getNodeText(typeParametersNode) + : ''; var parameters = utils.getNodeText(node.parameters); var question = node.question != null ? '?' : ''; diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_if_case_statement_chain.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_if_case_statement_chain.dart index b0a8e277e50..8929660af51 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_if_case_statement_chain.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_if_case_statement_chain.dart @@ -87,11 +87,10 @@ class ConvertToIfCaseStatementChain extends ResolvedCorrectionProducer { } // We expect only `SwitchPatternCase`s. - var guardedPatterns = - members - .whereType() - .map((e) => e.guardedPattern) - .toList(); + var guardedPatterns = members + .whereType() + .map((e) => e.guardedPattern) + .toList(); if (guardedPatterns.length != members.length) { return null; } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_map_literal.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_map_literal.dart index 45c85bb1409..fcb0df3e759 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_map_literal.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_map_literal.dart @@ -54,8 +54,8 @@ class ConvertToMapLiteral extends ResolvedCorrectionProducer { var constructorTypeArguments = creation.constructorName.type.typeArguments; List? staticTypeArguments; if (constructorTypeArguments == null) { - var variableDeclarationList = - creation.thisOrAncestorOfType(); + var variableDeclarationList = creation + .thisOrAncestorOfType(); if (variableDeclarationList?.type == null) { staticTypeArguments = type.typeArguments; if (staticTypeArguments.first is DynamicType && diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_super_parameters.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_super_parameters.dart index 54ccc69c04d..ab9348775f5 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_super_parameters.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_super_parameters.dart @@ -133,8 +133,9 @@ class ConvertToSuperParameters extends ResolvedCorrectionProducer { var allParameters = <_ParameterData>[...?positional, ...named]; - var argumentsToDelete = - allParameters.map((data) => data.argumentIndex).toList(); + var argumentsToDelete = allParameters + .map((data) => data.argumentIndex) + .toList(); argumentsToDelete.sort(); await builder.addDartFileEdit(file, (builder) { @@ -445,10 +446,9 @@ class ConvertToSuperParameters extends ResolvedCorrectionProducer { } else if (parameter is FunctionTypedFormalParameter) { var returnType = parameter.returnType; return _TypeData( - primaryRange: - returnType != null - ? range.startStart(returnType, parameter.name) - : null, + primaryRange: returnType != null + ? range.startStart(returnType, parameter.name) + : null, parameterRange: range.node(parameter.parameters), ); } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_switch_expression.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_switch_expression.dart index 14e52412fb6..b658fc56c87 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_switch_expression.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_switch_expression.dart @@ -96,16 +96,15 @@ class ConvertToSwitchExpression extends ResolvedCorrectionProducer { if (statement is ExpressionStatement) { var invocation = statement.expression; if (invocation is MethodInvocation) { - var deletion = - !hasComment - ? range.startOffsetEndOffset( - lastColon.end, - invocation.argumentList.leftParenthesis.end, - ) - : range.startOffsetEndOffset( - invocation.offset, - invocation.argumentList.leftParenthesis.end, - ); + var deletion = !hasComment + ? range.startOffsetEndOffset( + lastColon.end, + invocation.argumentList.leftParenthesis.end, + ) + : range.startOffsetEndOffset( + invocation.offset, + invocation.argumentList.leftParenthesis.end, + ); if (hasComment) { builder.addDeletion(deletion); } else { @@ -195,16 +194,15 @@ class ConvertToSwitchExpression extends ResolvedCorrectionProducer { var expression = statement.expression; if (expression is AssignmentExpression) { var hasComment = statement.beginToken.precedingComments != null; - var deletion = - !hasComment - ? range.startOffsetEndOffset( - lastColon.end, - expression.operator.end, - ) - : range.startOffsetEndOffset( - expression.beginToken.offset, - expression.rightHandSide.offset, - ); + var deletion = !hasComment + ? range.startOffsetEndOffset( + lastColon.end, + expression.operator.end, + ) + : range.startOffsetEndOffset( + expression.beginToken.offset, + expression.rightHandSide.offset, + ); builder.addDeletion(deletion); } else if (expression is ThrowExpression) { var deletionRange = range.startOffsetEndOffset( @@ -595,7 +593,7 @@ class ConvertToSwitchExpression extends ResolvedCorrectionProducer { static SourceRange _getBreakRange(BreakStatement statement) { var previous = (statement.beginToken.precedingComments ?? - statement.beginToken.previous)!; + statement.beginToken.previous)!; var deletion = range.startOffsetEndOffset( previous.end, statement.endToken.end, diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_class.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_class.dart index 9743dd8edc5..8d6365e65b7 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/create_class.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/create_class.dart @@ -147,10 +147,9 @@ class _CreateClass extends ResolvedCorrectionProducer { _targetNode = targetNode, _requiresConstConstructor = requiresConstConstructor, _arguments = arguments, - fixKind = - withKeyword - ? DartFixKind.CREATE_CLASS_LOWERCASE_WITH - : DartFixKind.CREATE_CLASS_LOWERCASE; + fixKind = withKeyword + ? DartFixKind.CREATE_CLASS_LOWERCASE_WITH + : DartFixKind.CREATE_CLASS_LOWERCASE; _CreateClass.uppercase({ required super.context, @@ -165,10 +164,9 @@ class _CreateClass extends ResolvedCorrectionProducer { _targetNode = targetNode, _requiresConstConstructor = requiresConstConstructor, _arguments = arguments, - fixKind = - withKeyword - ? DartFixKind.CREATE_CLASS_UPPERCASE_WITH - : DartFixKind.CREATE_CLASS_UPPERCASE; + fixKind = withKeyword + ? DartFixKind.CREATE_CLASS_UPPERCASE_WITH + : DartFixKind.CREATE_CLASS_UPPERCASE; @override CorrectionApplicability get applicability => diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart index 31bdfd41b90..00c53960d62 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart @@ -86,8 +86,9 @@ class CreateConstructorForFinalFields extends ResolvedCorrectionProducer { return; } - var requiredNamedParametersFirst = - getCodeStyleOptions(unitResult.file).requiredNamedParametersFirst; + var requiredNamedParametersFirst = getCodeStyleOptions( + unitResult.file, + ).requiredNamedParametersFirst; if (superType.isExactlyStatelessWidgetType || superType.isExactlyStatefulWidgetType) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_extension_member.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_extension_member.dart index 2cabc140f05..f5343170675 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/create_extension_member.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/create_extension_member.dart @@ -242,11 +242,10 @@ class CreateExtensionMethod extends _CreateExtensionMember { builder.writeTypeParameters( ([ - isInvocation ? returnType : functionType?.returnType, - ...?functionType?.formalParameters.map((e) => e.type), - ...?invocation?.argumentList.arguments.map((e) => e.staticType), - ].typeParameters - ..addAll([...?functionType?.typeParameters])) + isInvocation ? returnType : functionType?.returnType, + ...?functionType?.formalParameters.map((e) => e.type), + ...?invocation?.argumentList.arguments.map((e) => e.staticType), + ].typeParameters..addAll([...?functionType?.typeParameters])) .whereNot([targetType].typeParameters.contains) .toList(), ); @@ -669,15 +668,14 @@ extension on List { /// it uses and get any type parameters they use by using this same getter. /// /// These types are added internally to a set so that we don't add duplicates. - List get typeParameters => - { - for (var type in whereType()) ...[ - type.element, - ...[type.bound].typeParameters, - ], - for (var type in whereType()) - ...type.typeArguments.typeParameters, - }.toList(); + List get typeParameters => { + for (var type in whereType()) ...[ + type.element, + ...[type.bound].typeParameters, + ], + for (var type in whereType()) + ...type.typeArguments.typeParameters, + }.toList(); } extension on Element? { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart index e8d60c4bee6..e00b42408ff 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart @@ -55,10 +55,9 @@ class CreateMethodOrFunction extends ResolvedCorrectionProducer { return CreateMethodOrFunction._( context: context, targetElement: targetElement, - fixKind: - targetElement is InterfaceElement - ? DartFixKind.CREATE_METHOD_TEAROFF - : DartFixKind.CREATE_FUNCTION_TEAROFF, + fixKind: targetElement is InterfaceElement + ? DartFixKind.CREATE_METHOD_TEAROFF + : DartFixKind.CREATE_FUNCTION_TEAROFF, ); } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart index da0c78cff43..11f984f2bdf 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart @@ -100,10 +100,9 @@ class _CreateMixin extends ResolvedCorrectionProducer { this.prefixElement, { required bool withKeyword, required super.context, - }) : fixKind = - withKeyword - ? DartFixKind.CREATE_MIXIN_LOWERCASE_WITH - : DartFixKind.CREATE_MIXIN_LOWERCASE; + }) : fixKind = withKeyword + ? DartFixKind.CREATE_MIXIN_LOWERCASE_WITH + : DartFixKind.CREATE_MIXIN_LOWERCASE; _CreateMixin.uppercase( this._mixinName, @@ -111,10 +110,9 @@ class _CreateMixin extends ResolvedCorrectionProducer { this.prefixElement, { required bool withKeyword, required super.context, - }) : fixKind = - withKeyword - ? DartFixKind.CREATE_MIXIN_UPPERCASE_WITH - : DartFixKind.CREATE_MIXIN_UPPERCASE; + }) : fixKind = withKeyword + ? DartFixKind.CREATE_MIXIN_UPPERCASE_WITH + : DartFixKind.CREATE_MIXIN_UPPERCASE; @override CorrectionApplicability get applicability => diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_operator.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_operator.dart index ff4ab7c1e23..206c0761453 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/create_operator.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/create_operator.dart @@ -134,8 +134,9 @@ class CreateOperator extends ResolvedCorrectionProducer { var targetSource = targetFragment.libraryFragment!.source; var targetFile = targetSource.fullName; - var writeReturnType = - getCodeStyleOptions(unitResult.file).specifyReturnTypes; + var writeReturnType = getCodeStyleOptions( + unitResult.file, + ).specifyReturnTypes; if (returnType is TypeParameterType) { returnType = returnType.bound; diff --git a/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart b/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart index 9f624068ff5..b5348ac9fcf 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart @@ -186,10 +186,9 @@ class EncapsulateField extends ResolvedCorrectionProducer { ); var previous = constructor.separator ?? constructor.parameters; - var replacement = - constructor.initializers.isEmpty - ? ' : _$name = $name' - : ' _$name = $name,'; + var replacement = constructor.initializers.isEmpty + ? ' : _$name = $name' + : ' _$name = $name,'; builder.addSimpleInsertion(previous.end, replacement); break; } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart index 79e8c182342..c2cd6467241 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart @@ -54,10 +54,9 @@ class FlutterConvertToStatefulWidget extends ResolvedCorrectionProducer { } var widgetName = widgetClassElement.displayName; - var stateName = - widgetClassElement.isPrivate - ? '${widgetName}State' - : '_${widgetName}State'; + var stateName = widgetClassElement.isPrivate + ? '${widgetName}State' + : '_${widgetName}State'; // Find fields assigned in constructors. var visitor = _FieldFinder(); @@ -332,8 +331,9 @@ class _ReplacementEditBuilder extends RecursiveAstVisitor { element.enclosingElement == widgetClassElement && !elementsToMove.contains(element)) { var offset = node.offset - linesRange.offset; - var qualifier = - element.isStatic ? widgetClassElement.displayName : 'widget'; + var qualifier = element.isStatic + ? widgetClassElement.displayName + : 'widget'; var parent = node.parent; if (parent is InterpolationExpression && diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateless_widget.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateless_widget.dart index 2a75e39bb5d..33eb5d1cda2 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateless_widget.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateless_widget.dart @@ -416,8 +416,8 @@ class _StateUsageVisitor extends RecursiveAstVisitor { return; } var methodDeclaration = node.thisOrAncestorOfType(); - var classDeclaration = - methodDeclaration?.thisOrAncestorOfType(); + var classDeclaration = methodDeclaration + ?.thisOrAncestorOfType(); if (methodDeclaration?.name.lexeme != 'createState' || classDeclaration?.declaredFragment!.element != widgetClassElement) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart index 9e1b07034bd..45d5e8624e8 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart @@ -79,13 +79,12 @@ class FlutterRemoveWidget extends ResolvedCorrectionProducer { ) async { var builderExpression = builderArgument.expression; if (builderExpression is! FunctionExpression) return; - var parameterElement = - builderExpression - .parameters - ?.parameters - .firstOrNull - ?.declaredFragment - ?.element; + var parameterElement = builderExpression + .parameters + ?.parameters + .firstOrNull + ?.declaredFragment + ?.element; if (parameterElement == null) return; var visitor = _UsageFinder(parameterElement); diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_builder.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_builder.dart index d5bea1cd80a..c3d3bd4d036 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_builder.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_builder.dart @@ -95,8 +95,9 @@ abstract class _FlutterBaseWrapBuilder extends ResolvedCorrectionProducer { builder.writeln(';'); builder.write(indentNew1); - var addTrailingCommas = - getCodeStyleOptions(unitResult.file).addTrailingCommas; + var addTrailingCommas = getCodeStyleOptions( + unitResult.file, + ).addTrailingCommas; builder.writeln('}${addTrailingCommas ? "," : ""}'); builder.write(indentOld); diff --git a/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart b/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart index 02d87d0eace..35aeabdda8f 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart @@ -294,44 +294,36 @@ class ImportLibrary extends MultiCorrectionProducer { FixKind fixKind; FixKind fixKindShow; if (libraryElement.isInSdk) { - fixKind = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_SDK - : DartFixKind.IMPORT_LIBRARY_SDK_PREFIXED; - fixKindShow = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_SDK_SHOW - : DartFixKind.IMPORT_LIBRARY_SDK_PREFIXED_SHOW; + fixKind = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_SDK + : DartFixKind.IMPORT_LIBRARY_SDK_PREFIXED; + fixKindShow = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_SDK_SHOW + : DartFixKind.IMPORT_LIBRARY_SDK_PREFIXED_SHOW; } else if (_isLibSrcPath(librarySource.fullName)) { // Bad: non-API. - fixKind = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_PROJECT3 - : DartFixKind.IMPORT_LIBRARY_PROJECT3_PREFIXED; - fixKindShow = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_PROJECT3_SHOW - : DartFixKind.IMPORT_LIBRARY_PROJECT3_PREFIXED_SHOW; + fixKind = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_PROJECT3 + : DartFixKind.IMPORT_LIBRARY_PROJECT3_PREFIXED; + fixKindShow = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_PROJECT3_SHOW + : DartFixKind.IMPORT_LIBRARY_PROJECT3_PREFIXED_SHOW; } else if (declaration.library != libraryElement) { // Ugly: exports. - fixKind = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_PROJECT2 - : DartFixKind.IMPORT_LIBRARY_PROJECT2_PREFIXED; - fixKindShow = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_PROJECT2_SHOW - : DartFixKind.IMPORT_LIBRARY_PROJECT2_PREFIXED_SHOW; + fixKind = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_PROJECT2 + : DartFixKind.IMPORT_LIBRARY_PROJECT2_PREFIXED; + fixKindShow = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_PROJECT2_SHOW + : DartFixKind.IMPORT_LIBRARY_PROJECT2_PREFIXED_SHOW; } else { // Good: direct declaration. - fixKind = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_PROJECT1 - : DartFixKind.IMPORT_LIBRARY_PROJECT1_PREFIXED; - fixKindShow = - prefix.isEmptyOrNull - ? DartFixKind.IMPORT_LIBRARY_PROJECT1_SHOW - : DartFixKind.IMPORT_LIBRARY_PROJECT1_PREFIXED_SHOW; + fixKind = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_PROJECT1 + : DartFixKind.IMPORT_LIBRARY_PROJECT1_PREFIXED; + fixKindShow = prefix.isEmptyOrNull + ? DartFixKind.IMPORT_LIBRARY_PROJECT1_SHOW + : DartFixKind.IMPORT_LIBRARY_PROJECT1_PREFIXED_SHOW; } // If both files are in the same package's 'lib' folder, also include a // relative import. @@ -685,15 +677,15 @@ class ImportLibrary extends MultiCorrectionProducer { /// names where this fix can be applied besides the current diagnostic. Future> _otherUnresolvedNames(String? prefix, String name) async { var errorsForThisFix = _codesWhereThisIsValid; - var diagnostics = - >{}..addEntries( - unitResult.diagnostics.map((d) { - if (d == diagnostic) return null; - var generators = errorsForThisFix[d.diagnosticCode]; - if (generators == null) return null; - return MapEntry(d, generators); - }).nonNulls, - ); + var diagnostics = >{} + ..addEntries( + unitResult.diagnostics.map((d) { + if (d == diagnostic) return null; + var generators = errorsForThisFix[d.diagnosticCode]; + if (generators == null) return null; + return MapEntry(d, generators); + }).nonNulls, + ); var otherNames = {}; if (diagnostics.isNotEmpty) { for (var MapEntry(:key, :value) in diagnostics.entries) { @@ -871,10 +863,9 @@ class _ImportLibraryCombinatorMultiple extends ResolvedCorrectionProducer { keyword = Keyword.HIDE; } - var names = - codeStyleOptions.sortCombinators - ? combinatorNames.sorted() - : combinatorNames; + var names = codeStyleOptions.sortCombinators + ? combinatorNames.sorted() + : combinatorNames; var newCombinatorCode = ''; if (names.isNotEmpty) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/insert_on_keyword.dart b/pkg/analysis_server/lib/src/services/correction/dart/insert_on_keyword.dart index dfd4c827a20..4753c258296 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/insert_on_keyword.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/insert_on_keyword.dart @@ -53,8 +53,9 @@ class InsertOnKeyword extends ResolvedCorrectionProducer { // `extension int {}` // `extension E int {}` - var insertOffset = - extendedType.isSynthetic ? name.offset : extendedType.offset; + var insertOffset = extendedType.isSynthetic + ? name.offset + : extendedType.offset; await builder.addDartFileEdit(file, (builder) { builder.addSimpleInsertion(insertOffset, 'on '); diff --git a/pkg/analysis_server/lib/src/services/correction/dart/make_super_invocation_last.dart b/pkg/analysis_server/lib/src/services/correction/dart/make_super_invocation_last.dart index 2c53e8b263e..35323054d8b 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/make_super_invocation_last.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/make_super_invocation_last.dart @@ -39,15 +39,14 @@ class MakeSuperInvocationLast extends ResolvedCorrectionProducer { var nodeRange = range.nodeWithComments(lineInfo, node); var text = utils.getRangeText(nodeRange); - var insertionOffset = - range - .trailingComment( - lineInfo, - initializers.last.endToken, - returnComma: false, - ) - .token - .end; + var insertionOffset = range + .trailingComment( + lineInfo, + initializers.last.endToken, + returnComma: false, + ) + .token + .end; await builder.addDartFileEdit(file, (builder) { builder.addDeletion(deletionRange); builder.addSimpleInsertion(insertionOffset, ', $text'); diff --git a/pkg/analysis_server/lib/src/services/correction/dart/merge_combinators.dart b/pkg/analysis_server/lib/src/services/correction/dart/merge_combinators.dart index fa7ad2cae8d..82b400b5ebe 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/merge_combinators.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/merge_combinators.dart @@ -122,14 +122,13 @@ class _MergeCombinators extends ResolvedCorrectionProducer { var explicitlyHiddenNames = directive.hideCombinators.hiddenNames; - var hiddenNames = - { - ...explicitlyHiddenNames, - ...originalNamespace.hiddenNames({ - ...explicitlyHiddenNames, - ...namespace.keys, - }), - }.toList(); + var hiddenNames = { + ...explicitlyHiddenNames, + ...originalNamespace.hiddenNames({ + ...explicitlyHiddenNames, + ...namespace.keys, + }), + }.toList(); await _buildNewCombinator(builder, Keyword.HIDE, hiddenNames); } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/move_annotation_to_library_directive.dart b/pkg/analysis_server/lib/src/services/correction/dart/move_annotation_to_library_directive.dart index 2100fe5f3dc..f2d7f43c163 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/move_annotation_to_library_directive.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/move_annotation_to_library_directive.dart @@ -33,10 +33,9 @@ class MoveAnnotationToLibraryDirective extends ResolvedCorrectionProducer { return; } - var firstDirective = - compilationUnit.directives.isEmpty - ? null - : compilationUnit.directives.first; + var firstDirective = compilationUnit.directives.isEmpty + ? null + : compilationUnit.directives.first; if (firstDirective is LibraryDirective) { await _moveToExistingLibraryDirective( builder, diff --git a/pkg/analysis_server/lib/src/services/correction/dart/remove_dead_code.dart b/pkg/analysis_server/lib/src/services/correction/dart/remove_dead_code.dart index 084ff409bc6..a061a844195 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/remove_dead_code.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/remove_dead_code.dart @@ -150,13 +150,9 @@ class RemoveDeadCode extends ResolvedCorrectionProducer { var isComma = !isFirstNode && rightParenthesis.previous?.type == TokenType.COMMA; var previous = node.beginToken.previous!; - var deletionRange = - isComma - ? range.endStart(previous, rightParenthesis) - : range.startStart( - isFirstNode ? node : previous, - rightParenthesis, - ); + var deletionRange = isComma + ? range.endStart(previous, rightParenthesis) + : range.startStart(isFirstNode ? node : previous, rightParenthesis); await _addEdit((builder) { builder.addDeletion(deletionRange); }); @@ -176,8 +172,9 @@ class RemoveDeadCode extends ResolvedCorrectionProducer { // effects (or so we presume--see `_looksSideEffectFree` for details). // So the conditional expression can be replaced with the `live` // subexpression. - var nodeToKeep = - node == thenExpression ? elseExpression : thenExpression; + var nodeToKeep = node == thenExpression + ? elseExpression + : thenExpression; if (nodeToKeep is ThrowExpression && grandParent is CascadeExpression && grandParent.target == parent) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/remove_default_value.dart b/pkg/analysis_server/lib/src/services/correction/dart/remove_default_value.dart index 1b6f602427e..a6aa6f4a601 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/remove_default_value.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/remove_default_value.dart @@ -22,8 +22,8 @@ class RemoveDefaultValue extends ResolvedCorrectionProducer { @override Future compute(ChangeBuilder builder) async { - var defaultFormalParameter = - node.thisOrAncestorOfType(); + var defaultFormalParameter = node + .thisOrAncestorOfType(); if (defaultFormalParameter is! DefaultFormalParameter) return; var separator = defaultFormalParameter.separator; if (separator == null) return; diff --git a/pkg/analysis_server/lib/src/services/correction/dart/remove_initializer.dart b/pkg/analysis_server/lib/src/services/correction/dart/remove_initializer.dart index 5ea942df74b..7367d4a5980 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/remove_initializer.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/remove_initializer.dart @@ -74,8 +74,8 @@ class RemoveInitializer extends ResolvedCorrectionProducer { } } } else { - var initializer = - node.thisOrAncestorOfType(); + var initializer = node + .thisOrAncestorOfType(); var parent = initializer?.parent; if (parent is ConstructorDeclaration) { await builder.addDartFileEdit(file, (builder) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/remove_leading_underscore.dart b/pkg/analysis_server/lib/src/services/correction/dart/remove_leading_underscore.dart index 451dabfb9f9..077aa8e8bbb 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/remove_leading_underscore.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/remove_leading_underscore.dart @@ -64,15 +64,14 @@ class RemoveLeadingUnderscore extends ResolvedCorrectionProducer { List? references; if (element is FormalParameterElement) { if (!element.isNamed) { - var root = - node - .thisOrAncestorMatching( - (node) => - node.parent is FunctionDeclaration || - node.parent is MethodDeclaration || - node.parent is ConstructorDeclaration, - ) - ?.parent; + var root = node + .thisOrAncestorMatching( + (node) => + node.parent is FunctionDeclaration || + node.parent is MethodDeclaration || + node.parent is ConstructorDeclaration, + ) + ?.parent; if (root != null) { references = findLocalElementReferences(root, element); } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/remove_on_clause.dart b/pkg/analysis_server/lib/src/services/correction/dart/remove_on_clause.dart index 13d40ee35a6..1ad73246bdf 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/remove_on_clause.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/remove_on_clause.dart @@ -24,8 +24,8 @@ class RemoveOnClause extends ResolvedCorrectionProducer { @override Future compute(ChangeBuilder builder) async { - var extensionDeclaration = - node.thisOrAncestorOfType(); + var extensionDeclaration = node + .thisOrAncestorOfType(); if (extensionDeclaration == null) return; await builder.addDartFileEdit(file, (builder) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/rename_to_camel_case.dart b/pkg/analysis_server/lib/src/services/correction/dart/rename_to_camel_case.dart index b4b939432eb..3778e0d2c51 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/rename_to_camel_case.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/rename_to_camel_case.dart @@ -80,14 +80,13 @@ class RenameToCamelCase extends ResolvedCorrectionProducer { } } else if (element is FormalParameterElement) { if (!element.isNamed) { - var root = - node - .thisOrAncestorMatching( - (node) => - node.parent is FunctionDeclaration || - node.parent is MethodDeclaration, - ) - ?.parent; + var root = node + .thisOrAncestorMatching( + (node) => + node.parent is FunctionDeclaration || + node.parent is MethodDeclaration, + ) + ?.parent; if (root != null) { references = findLocalElementReferences(root, element); } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_empty_map_pattern.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_empty_map_pattern.dart index ab5ceeda164..8521c89d5bb 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/replace_empty_map_pattern.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_empty_map_pattern.dart @@ -51,10 +51,9 @@ class ReplaceEmptyMapPattern extends ResolvedCorrectionProducer { } /// Return the replacement for the map pattern. - String replacement(String typeArguments) => - _style == _Style.any - ? 'Map$typeArguments()' - : 'Map$typeArguments(isEmpty: true)'; + String replacement(String typeArguments) => _style == _Style.any + ? 'Map$typeArguments()' + : 'Map$typeArguments(isEmpty: true)'; } /// An indication of the style of replacement being offered. diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_final_with_var.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_final_with_var.dart index b193c5ffac0..90304c74beb 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/replace_final_with_var.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_final_with_var.dart @@ -52,16 +52,14 @@ class ReplaceFinalWithVar extends ResolvedCorrectionProducer { CorrectionApplicability.automatically; @override - FixKind get fixKind => - _removeFinal - ? DartFixKind.REMOVE_UNNECESSARY_FINAL - : DartFixKind.REPLACE_FINAL_WITH_VAR; + FixKind get fixKind => _removeFinal + ? DartFixKind.REMOVE_UNNECESSARY_FINAL + : DartFixKind.REPLACE_FINAL_WITH_VAR; @override - FixKind get multiFixKind => - _removeFinal - ? DartFixKind.REMOVE_UNNECESSARY_FINAL_MULTI - : DartFixKind.REPLACE_FINAL_WITH_VAR_MULTI; + FixKind get multiFixKind => _removeFinal + ? DartFixKind.REMOVE_UNNECESSARY_FINAL_MULTI + : DartFixKind.REPLACE_FINAL_WITH_VAR_MULTI; @override Future compute(ChangeBuilder builder) async { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_conditional_assignment.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_conditional_assignment.dart index d3235071af7..cfa0ded0da2 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_conditional_assignment.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_conditional_assignment.dart @@ -26,8 +26,9 @@ class ReplaceWithConditionalAssignment extends ResolvedCorrectionProducer { @override Future compute(ChangeBuilder builder) async { var node = this.node; - var ifStatement = - node is IfStatement ? node : node.thisOrAncestorOfType(); + var ifStatement = node is IfStatement + ? node + : node.thisOrAncestorOfType(); if (ifStatement == null) { return; } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_decorated_box.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_decorated_box.dart index 2273672a144..a4713cc88cb 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_decorated_box.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_decorated_box.dart @@ -27,19 +27,18 @@ class ReplaceWithDecoratedBox extends ResolvedCorrectionProducer { @override Future compute(ChangeBuilder builder) async { - var instanceCreation = - node.thisOrAncestorOfType(); + var instanceCreation = node + .thisOrAncestorOfType(); if (instanceCreation is! InstanceCreationExpression) return; if (applyingBulkFixes) { - var parent = - instanceCreation.parent - ?.thisOrAncestorOfType(); + var parent = instanceCreation.parent + ?.thisOrAncestorOfType(); while (parent != null) { if (_hasLint(parent)) return; - parent = - parent.parent?.thisOrAncestorOfType(); + parent = parent.parent + ?.thisOrAncestorOfType(); } } diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_extension_name.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_extension_name.dart index 46a34509131..16fe26fb586 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_extension_name.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_extension_name.dart @@ -33,10 +33,9 @@ class ReplaceWithExtensionName extends ResolvedCorrectionProducer { var target = _getTarget(node.parent); if (target is ExtensionOverride) { var importPrefix = target.importPrefix; - var prefixedName = - importPrefix != null - ? '${importPrefix.name.lexeme}.${target.name.lexeme}' - : target.name.lexeme; + var prefixedName = importPrefix != null + ? '${importPrefix.name.lexeme}.${target.name.lexeme}' + : target.name.lexeme; await builder.addDartFileEdit(file, (builder) { builder.addSimpleReplacement(range.node(target), prefixedName); }); diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_identifier.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_identifier.dart index 266766caf08..600c3b82c46 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_identifier.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_identifier.dart @@ -24,8 +24,8 @@ class ReplaceWithIdentifier extends ResolvedCorrectionProducer { @override Future compute(ChangeBuilder builder) async { - var functionTyped = - node.thisOrAncestorOfType(); + var functionTyped = node + .thisOrAncestorOfType(); if (functionTyped != null) { await builder.addDartFileEdit(file, (builder) { builder.addSimpleReplacement( diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_not_null_aware.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_not_null_aware.dart index 0e7f92bae0b..938c5ad909e 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_not_null_aware.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_not_null_aware.dart @@ -41,8 +41,9 @@ class ReplaceWithNotNullAware extends ResolvedCorrectionProducer { }); } } else if (node is PropertyAccess) { - _newOperator = - node.operator.type == TokenType.QUESTION_PERIOD ? '.' : '..'; + _newOperator = node.operator.type == TokenType.QUESTION_PERIOD + ? '.' + : '..'; await builder.addDartFileEdit(file, (builder) { builder.addSimpleReplacement(range.token(node.operator), _newOperator); }); diff --git a/pkg/analysis_server/lib/src/services/correction/dart/sort_unnamed_constructor_first.dart b/pkg/analysis_server/lib/src/services/correction/dart/sort_unnamed_constructor_first.dart index 68f2a438dcf..02d2d93c1cd 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/sort_unnamed_constructor_first.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/sort_unnamed_constructor_first.dart @@ -58,10 +58,9 @@ class SortUnnamedConstructorFirst extends ResolvedCorrectionProducer { builder.addDeletion(moveRange); var firstIndex = members.indexOf(firstConstructor); - var tokenBeforeFirst = - firstIndex != 0 - ? members[firstIndex - 1].endToken - : clazz.leftBracket; + var tokenBeforeFirst = firstIndex != 0 + ? members[firstIndex - 1].endToken + : clazz.leftBracket; builder.addSimpleInsertion( tokenBeforeFirst.end, utils.getRangeText(moveRange), diff --git a/pkg/analysis_server/lib/src/services/correction/dart/surround_with.dart b/pkg/analysis_server/lib/src/services/correction/dart/surround_with.dart index 97b6dbc89c6..881d274fe60 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/surround_with.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/surround_with.dart @@ -345,11 +345,10 @@ class _SurroundWithSetState extends _SurroundWith { @override Future compute(ChangeBuilder builder) async { - var classElement = - node.parent - ?.thisOrAncestorOfType() - ?.declaredFragment - ?.element; + var classElement = node.parent + ?.thisOrAncestorOfType() + ?.declaredFragment + ?.element; if (classElement != null && classElement.isState) { await builder.addDartFileEdit(file, (builder) { builder.addReplacement(statementsRange, (builder) { diff --git a/pkg/analysis_server/lib/src/services/correction/dart/wrap_in_unawaited.dart b/pkg/analysis_server/lib/src/services/correction/dart/wrap_in_unawaited.dart index a407e87aae5..1edf6182cc9 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/wrap_in_unawaited.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/wrap_in_unawaited.dart @@ -72,8 +72,9 @@ class WrapInUnawaited extends ResolvedCorrectionProducer { var value = utils.getNodeText(expression); await builder.addDartFileEdit(file, (builder) { - var libraryPrefix = - builder.importLibraryElement(Uri.parse('dart:async')).prefix; + var libraryPrefix = builder + .importLibraryElement(Uri.parse('dart:async')) + .prefix; var prefix = libraryPrefix != null ? '$libraryPrefix.' : ''; builder.addSimpleReplacement( range.node(expression!), diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart index 85e9b4321eb..09eb137f22d 100644 --- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart +++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart @@ -53,8 +53,11 @@ class CodeFragmentParser { /// ('.' )* List? parseAccessors(String content, int delta) { this.delta = delta; - var scannedTokens = - _CodeFragmentScanner(content, delta, diagnosticReporter).scan(); + var scannedTokens = _CodeFragmentScanner( + content, + delta, + diagnosticReporter, + ).scan(); if (scannedTokens == null) { // The error has already been reported. return null; @@ -99,8 +102,11 @@ class CodeFragmentParser { /// Expression? parseCondition(String content, int delta) { this.delta = delta; - var scannedTokens = - _CodeFragmentScanner(content, delta, diagnosticReporter).scan(); + var scannedTokens = _CodeFragmentScanner( + content, + delta, + diagnosticReporter, + ).scan(); if (scannedTokens == null) { // The error has already been reported. return null; @@ -257,8 +263,9 @@ class CodeFragmentParser { var kind = _currentToken?.kind; if (kind == _TokenKind.equal || kind == _TokenKind.notEqual) { advance(); - var operator = - kind == _TokenKind.equal ? Operator.equal : Operator.notEqual; + var operator = kind == _TokenKind.equal + ? Operator.equal + : Operator.notEqual; var rightOperand = _parsePrimaryExpression(); if (rightOperand == null) { return null; diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart index 37ad8834eb7..7364f2fe139 100644 --- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart +++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart @@ -386,10 +386,9 @@ class _MatcherBuilder { kinds: const [ElementKind.constructorKind, ElementKind.methodKind], ); // We can invoke methods of supertypes of the target type. - var superElements = - targetType.allSupertypes - .map((superType) => superType.element) - .toList(); + var superElements = targetType.allSupertypes + .map((superType) => superType.element) + .toList(); for (var element in superElements) { _addMatcher( components: [methodName.name, element.name!], diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart index 745fa962610..301cb6def86 100644 --- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart +++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart @@ -128,12 +128,11 @@ class ModifyParameters extends Change<_Data> { if (argument == null) { // If there is no argument corresponding to the parameter then we assume // that the parameter was absent. - var index = - reference is PositionalFormalParameterReference - ? reference.index - : remainingArguments.isNotEmpty - ? remainingArguments.last + 1 - : 0; + var index = reference is PositionalFormalParameterReference + ? reference.index + : remainingArguments.isNotEmpty + ? remainingArguments.last + 1 + : 0; remainingArguments.add(index); indexToNewArgumentMap[index] = modification; argumentsToInsert.add(index); @@ -247,10 +246,9 @@ class ModifyParameters extends Change<_Data> { offset = arguments[remainingIndex - 1].end; needsInitialComma = true; } else { - offset = - arguments.isNotEmpty - ? arguments[remainingIndex].offset - : argumentList.leftParenthesis.end; + offset = arguments.isNotEmpty + ? arguments[remainingIndex].offset + : argumentList.leftParenthesis.end; } builder.addInsertion(offset, (builder) { writeInsertionRange(builder, insertionRange, needsInitialComma); @@ -283,10 +281,9 @@ class ModifyParameters extends Change<_Data> { } // The remaining insertion ranges might include new required arguments // that need to be inserted after the last argument. - var offset = - arguments.isEmpty - ? argumentList.leftParenthesis.end - : arguments[arguments.length - 1].end; + var offset = arguments.isEmpty + ? argumentList.leftParenthesis.end + : arguments[arguments.length - 1].end; while (nextInsertionRange < insertionRanges.length) { var insertionRange = insertionRanges[nextInsertionRange]; var lower = insertionRange.lower; diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart index 068796fbf37..7e19df1fa80 100644 --- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart +++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart @@ -373,10 +373,9 @@ class TransformSetParser { Object? valueNode = entry.value; if (keyNode is YamlScalar && valueNode is YamlNode) { if (keyNode.value case String key) { - var translator = - translators.entries - .firstWhereOrNull((entry) => entry.key.contains(key)) - ?.value; + var translator = translators.entries + .firstWhereOrNull((entry) => entry.key.contains(key)) + ?.value; if (translator != null) { entries.add( _SingleKeyEntry( @@ -1185,14 +1184,13 @@ class TransformSetParser { ) ?? false); var argumentsNode = node.valueAt(_arguments); - var argumentList = - argumentsNode == null - ? null - : _translateList( - argumentsNode, - ErrorContext(key: _arguments, parentNode: node), - _translateCodeTemplate, - ); + var argumentList = argumentsNode == null + ? null + : _translateList( + argumentsNode, + ErrorContext(key: _arguments, parentNode: node), + _translateCodeTemplate, + ); return ReplacedBy( newElement: newElement, replaceTarget: replaceTarget, diff --git a/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart b/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart index e8155430c14..69c8271abb8 100644 --- a/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart +++ b/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart @@ -228,18 +228,16 @@ class PubspecFixGenerator { } } - var startOffset = - prevEntry != null - ? prevEntry.value.span.end.offset - : (currentEntry.key as YamlNode).span.start.offset; + var startOffset = prevEntry != null + ? prevEntry.value.span.end.offset + : (currentEntry.key as YamlNode).span.start.offset; // If nextEntry is null, this is the last entry in the // dev_dependencies section, and also dev_dependencies is the last // section in the pubspec file. So delete till the end of the // section. - var endOffset = - nextEntry == null - ? currentEntry.value.span.end.offset - : (nextEntry.key as YamlNode).span.start.offset; + var endOffset = nextEntry == null + ? currentEntry.value.span.end.offset + : (nextEntry.key as YamlNode).span.start.offset; // If entry in the middle of two other entries that are not to be // removed, delete the line. if (prevEntry != null && @@ -322,10 +320,9 @@ class PubspecFixGenerator { buffer.write(endOfLine); } - var offset = - section == null - ? node.span.end.offset - : (section as YamlNode).span.end.offset; + var offset = section == null + ? node.span.end.offset + : (section as YamlNode).span.end.offset; return (buffer.toString(), offset); } diff --git a/pkg/analysis_server/lib/src/services/correction/organize_imports.dart b/pkg/analysis_server/lib/src/services/correction/organize_imports.dart index 5ea900d5e20..f150962736d 100644 --- a/pkg/analysis_server/lib/src/services/correction/organize_imports.dart +++ b/pkg/analysis_server/lib/src/services/correction/organize_imports.dart @@ -129,10 +129,9 @@ class ImportOrganizer { // after any non-library annotation. If there are already // non-library annotations before library annotations, we will not // try to correct those. - lastLibraryAnnotation = - directive.metadata - .takeWhile(_isLibraryTargetAnnotation) - .lastOrNull; + lastLibraryAnnotation = directive.metadata + .takeWhile(_isLibraryTargetAnnotation) + .lastOrNull; // If there is no annotation, use the end of the doc text (since the // doc text is considered library-level here). @@ -164,27 +163,26 @@ class ImportOrganizer { // Usually we look for leading comments on the directive. However if // some library annotations were trimmed off, those comments are part // of that and should not also be included here. - var leadingToken = - lastLibraryAnnotation == null ? directive.beginToken : null; - var leadingComment = - leadingToken != null - ? getLeadingComment( - unit, - leadingToken, - lineInfo, - isPseudoLibraryDirective: isPseudoLibraryDirective, - ) - : null; + var leadingToken = lastLibraryAnnotation == null + ? directive.beginToken + : null; + var leadingComment = leadingToken != null + ? getLeadingComment( + unit, + leadingToken, + lineInfo, + isPseudoLibraryDirective: isPseudoLibraryDirective, + ) + : null; var trailingComment = getTrailingComment(unit, directive, lineInfo); if (leadingComment != null && leadingToken != null) { - offset = - libraryDocsAndAnnotationsEndOffset != null - ? math.max( - libraryDocsAndAnnotationsEndOffset, - leadingComment.offset, - ) - : leadingComment.offset; + offset = libraryDocsAndAnnotationsEndOffset != null + ? math.max( + libraryDocsAndAnnotationsEndOffset, + leadingComment.offset, + ) + : leadingComment.offset; } if (trailingComment != null) { end = trailingComment.end; @@ -321,8 +319,9 @@ class ImportOrganizer { // Skip over any comments on the same line as the previous directive // as they will be attached to the end of it. - var previousDirectiveLine = - lineInfo.getLocation(beginToken.previous!.end).lineNumber; + var previousDirectiveLine = lineInfo + .getLocation(beginToken.previous!.end) + .lineNumber; comment = firstComment; // For first directive, do not attach comment if there is a line break // between comment and directive. diff --git a/pkg/analysis_server/lib/src/services/correction/statement_analyzer.dart b/pkg/analysis_server/lib/src/services/correction/statement_analyzer.dart index 96a9132af08..aff5d518f16 100644 --- a/pkg/analysis_server/lib/src/services/correction/statement_analyzer.dart +++ b/pkg/analysis_server/lib/src/services/correction/statement_analyzer.dart @@ -23,14 +23,15 @@ import 'package:analyzer_plugin/utilities/range_factory.dart'; List _getTokens(String text, FeatureSet featureSet) { try { var tokens = []; - var scanner = Scanner( - _SourceMock.instance, - CharSequenceReader(text), - DiagnosticListener.nullListener, - )..configureFeatures( - featureSetForOverriding: featureSet, - featureSet: featureSet, - ); + var scanner = + Scanner( + _SourceMock.instance, + CharSequenceReader(text), + DiagnosticListener.nullListener, + )..configureFeatures( + featureSetForOverriding: featureSet, + featureSet: featureSet, + ); var token = scanner.tokenize(); while (!token.isEof) { tokens.add(token); diff --git a/pkg/analysis_server/lib/src/services/flutter/widget_descriptions.dart b/pkg/analysis_server/lib/src/services/flutter/widget_descriptions.dart index 2dcfa8e347e..a2cbac0d974 100644 --- a/pkg/analysis_server/lib/src/services/flutter/widget_descriptions.dart +++ b/pkg/analysis_server/lib/src/services/flutter/widget_descriptions.dart @@ -68,20 +68,18 @@ class WidgetDescriptions { var property = _properties[id]; if (property == null) { return SetPropertyValueResult._( - errorCode: - protocol - .RequestErrorCode - .FLUTTER_SET_WIDGET_PROPERTY_VALUE_INVALID_ID, + errorCode: protocol + .RequestErrorCode + .FLUTTER_SET_WIDGET_PROPERTY_VALUE_INVALID_ID, ); } if (value == null) { if (property.protocolProperty.isRequired) { return SetPropertyValueResult._( - errorCode: - protocol - .RequestErrorCode - .FLUTTER_SET_WIDGET_PROPERTY_VALUE_IS_REQUIRED, + errorCode: protocol + .RequestErrorCode + .FLUTTER_SET_WIDGET_PROPERTY_VALUE_IS_REQUIRED, ); } var change = await property.removeValue(); @@ -92,10 +90,9 @@ class WidgetDescriptions { return SetPropertyValueResult._(change: change); } on FormatterException { return SetPropertyValueResult._( - errorCode: - protocol - .RequestErrorCode - .FLUTTER_SET_WIDGET_PROPERTY_VALUE_INVALID_EXPRESSION, + errorCode: protocol + .RequestErrorCode + .FLUTTER_SET_WIDGET_PROPERTY_VALUE_INVALID_EXPRESSION, ); } } diff --git a/pkg/analysis_server/lib/src/services/pub/pub_api.dart b/pkg/analysis_server/lib/src/services/pub/pub_api.dart index c98adb8316c..3bdad54330e 100644 --- a/pkg/analysis_server/lib/src/services/pub/pub_api.dart +++ b/pkg/analysis_server/lib/src/services/pub/pub_api.dart @@ -52,8 +52,9 @@ class PubApi { this.instrumentationService, http.Client? httpClient, String? envPubHostedUrl, - ) : httpClient = - httpClient != null ? _NoCloseHttpClient(httpClient) : http.Client(), + ) : httpClient = httpClient != null + ? _NoCloseHttpClient(httpClient) + : http.Client(), pubHostedUrl = _validPubHostedUrl(envPubHostedUrl); /// Fetches a list of package names from the Pub API. @@ -92,8 +93,9 @@ class PubApi { } var pubspec = latest['pubspec'] as Map?; - var description = - pubspec != null ? pubspec['description'] as String? : null; + var description = pubspec != null + ? pubspec['description'] as String? + : null; var version = latest['version'] as String?; return PubApiPackageDetails(packageName, description, version); } @@ -151,9 +153,9 @@ class PubApi { static String _validPubHostedUrl(String? envPubHostedUrl) { var validUrl = envPubHostedUrl != null && - (Uri.tryParse(envPubHostedUrl)?.isAbsolute ?? false) - ? envPubHostedUrl - : 'https://pub.dev'; + (Uri.tryParse(envPubHostedUrl)?.isAbsolute ?? false) + ? envPubHostedUrl + : 'https://pub.dev'; // Discard any trailing slashes, as all API paths start with them. return validUrl.endsWith('/') diff --git a/pkg/analysis_server/lib/src/services/pub/pub_command.dart b/pkg/analysis_server/lib/src/services/pub/pub_command.dart index d9afb1e49ba..b20f42b3be5 100644 --- a/pkg/analysis_server/lib/src/services/pub/pub_command.dart +++ b/pkg/analysis_server/lib/src/services/pub/pub_command.dart @@ -73,8 +73,8 @@ class PubCommand { return []; } - var packages = - (result['packages'] as List?)?.cast>(); + var packages = (result['packages'] as List?) + ?.cast>(); if (packages == null) { return []; } @@ -162,8 +162,9 @@ class PubCommand { String? _version(Map json, String type) { var versionType = json[type] as Map?; - var version = - versionType != null ? versionType['version'] as String? : null; + var version = versionType != null + ? versionType['version'] as String? + : null; return version; } } diff --git a/pkg/analysis_server/lib/src/services/pub/pub_package_service.dart b/pkg/analysis_server/lib/src/services/pub/pub_package_service.dart index d8c2299119e..73ce3fbe729 100644 --- a/pkg/analysis_server/lib/src/services/pub/pub_package_service.dart +++ b/pkg/analysis_server/lib/src/services/pub/pub_package_service.dart @@ -191,9 +191,9 @@ class PubPackageService { @visibleForTesting File get packageCacheFile { - var cacheFolder = - resourceProvider.getStateLocation('.pub-package-details-cache')! - ..create(); + var cacheFolder = resourceProvider.getStateLocation( + '.pub-package-details-cache', + )!..create(); return cacheFolder.getChildAssumingFile('packages.json'); } diff --git a/pkg/analysis_server/lib/src/services/refactoring/agnostic/change_method_signature.dart b/pkg/analysis_server/lib/src/services/refactoring/agnostic/change_method_signature.dart index 5ec8e76899d..182d45e284c 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/agnostic/change_method_signature.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/agnostic/change_method_signature.dart @@ -696,31 +696,29 @@ class _SignatureUpdater { required ArgumentList argumentList, required ChangeBuilder builder, }) async { - var formalParameters = - signatureUpdate.formalParameters - .whereNot(excludedFormalParameters.contains) - .toList(); + var formalParameters = signatureUpdate.formalParameters + .whereNot(excludedFormalParameters.contains) + .toList(); var frameworkStatus = await framework.writeArguments( - formalParameterUpdates: - formalParameters.map((update) { - // TODO(scheglov): Maybe support adding formal parameters. - var existing = selectionState.formalParameters[update.id]; - var reference = _asFrameworkFormalParameterReference(existing); - switch (update.kind) { - case FormalParameterKind.requiredPositional: - case FormalParameterKind.optionalPositional: - return framework.FormalParameterUpdateExistingPositional( - reference: reference, - ); - case FormalParameterKind.requiredNamed: - case FormalParameterKind.optionalNamed: - return framework.FormalParameterUpdateExistingNamed( - reference: reference, - name: existing.name, - ); - } - }).toList(), + formalParameterUpdates: formalParameters.map((update) { + // TODO(scheglov): Maybe support adding formal parameters. + var existing = selectionState.formalParameters[update.id]; + var reference = _asFrameworkFormalParameterReference(existing); + switch (update.kind) { + case FormalParameterKind.requiredPositional: + case FormalParameterKind.optionalPositional: + return framework.FormalParameterUpdateExistingPositional( + reference: reference, + ); + case FormalParameterKind.requiredNamed: + case FormalParameterKind.optionalNamed: + return framework.FormalParameterUpdateExistingNamed( + reference: reference, + name: existing.name, + ); + } + }).toList(), removedNamedFormalParameters: signatureUpdate.removedNamedFormalParameters, trailingComma: signatureUpdate.argumentsTrailingComma, @@ -1102,19 +1100,17 @@ class _SignatureUpdater { } } - var selectionPositional = - selectionState.formalParameters - .where((state) => state.kind.isPositional) - .toList(); + var selectionPositional = selectionState.formalParameters + .where((state) => state.kind.isPositional) + .toList(); if (positional.length != selectionPositional.length) { return null; } for (var i = 0; i < positional.length; i++) { - var positionalKind = - positional[i].isRequiredPositional - ? FormalParameterKind.requiredPositional - : FormalParameterKind.optionalPositional; + var positionalKind = positional[i].isRequiredPositional + ? FormalParameterKind.requiredPositional + : FormalParameterKind.optionalPositional; if (positionalKind != selectionPositional[i].kind) { return null; } diff --git a/pkg/analysis_server/lib/src/services/refactoring/convert_all_formal_parameters_to_named.dart b/pkg/analysis_server/lib/src/services/refactoring/convert_all_formal_parameters_to_named.dart index a9034ee37f6..0c22176c6d1 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/convert_all_formal_parameters_to_named.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/convert_all_formal_parameters_to_named.dart @@ -49,14 +49,15 @@ class ConvertAllFormalParametersToNamed extends RefactoringProducer { return ComputeStatusFailure(); } - var formalParameterUpdates = - selection.formalParameters.map((formalParameter) { - var newKind = formalParameter.kind; - if (formalParameter.kind.isPositional) { - newKind = FormalParameterKind.requiredNamed; - } - return FormalParameterUpdate(id: formalParameter.id, kind: newKind); - }).toList(); + var formalParameterUpdates = selection.formalParameters.map(( + formalParameter, + ) { + var newKind = formalParameter.kind; + if (formalParameter.kind.isPositional) { + newKind = FormalParameterKind.requiredNamed; + } + return FormalParameterUpdate(id: formalParameter.id, kind: newKind); + }).toList(); var signatureUpdate = MethodSignatureUpdate( formalParameters: formalParameterUpdates, diff --git a/pkg/analysis_server/lib/src/services/refactoring/convert_selected_formal_parameters_to_named.dart b/pkg/analysis_server/lib/src/services/refactoring/convert_selected_formal_parameters_to_named.dart index 7f0f84a0f22..20e06d0d58f 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/convert_selected_formal_parameters_to_named.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/convert_selected_formal_parameters_to_named.dart @@ -63,20 +63,19 @@ class ConvertSelectedFormalParametersToNamed extends RefactoringProducer { reordered = formalParameters.stablePartition((e) => !e.isSelected); } - var formalParameterUpdates = - reordered.map((formalParameter) { - if (formalParameter.isSelected) { - return FormalParameterUpdate( - id: formalParameter.id, - kind: FormalParameterKind.requiredNamed, - ); - } else { - return FormalParameterUpdate( - id: formalParameter.id, - kind: formalParameter.kind, - ); - } - }).toList(); + var formalParameterUpdates = reordered.map((formalParameter) { + if (formalParameter.isSelected) { + return FormalParameterUpdate( + id: formalParameter.id, + kind: FormalParameterKind.requiredNamed, + ); + } else { + return FormalParameterUpdate( + id: formalParameter.id, + kind: formalParameter.kind, + ); + } + }).toList(); var signatureUpdate = MethodSignatureUpdate( formalParameters: formalParameterUpdates, diff --git a/pkg/analysis_server/lib/src/services/refactoring/framework/refactoring_processor.dart b/pkg/analysis_server/lib/src/services/refactoring/framework/refactoring_processor.dart index 8404441cb0d..2eaa30c6c0d 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/framework/refactoring_processor.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/framework/refactoring_processor.dart @@ -94,8 +94,9 @@ class RefactoringProcessor { 'filePath': context.resolvedUnitResult.path, 'selectionOffset': context.selectionOffset, 'selectionLength': context.selectionLength, - 'arguments': - parameters.map((param) => param.defaultValue).toList(), + 'arguments': parameters + .map((param) => param.defaultValue) + .toList(), }, ], ), diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_local.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_local.dart index e184a9391ec..41a4ccf9c32 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_local.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_local.dart @@ -65,10 +65,9 @@ class ExtractLocalRefactoringImpl extends RefactoringImpl ) : selectionRange = SourceRange(selectionOffset, selectionLength), utils = CorrectionUtils(resolveResult); - CodeStyleOptions get codeStyleOptions => - resolveResult.session.analysisContext - .getAnalysisOptionsForFile(resolveResult.file) - .codeStyleOptions; + CodeStyleOptions get codeStyleOptions => resolveResult.session.analysisContext + .getAnalysisOptionsForFile(resolveResult.file) + .codeStyleOptions; String get file => resolveResult.path; @@ -97,12 +96,11 @@ class ExtractLocalRefactoringImpl extends RefactoringImpl String? typeString; if (codeStyleOptions.specifyTypes || dotShorthandRequiresType) { - typeString = - expression != null - ? expression.staticType?.getDisplayString() - : stringLiteralPart != null - ? 'String' - : null; + typeString = expression != null + ? expression.staticType?.getDisplayString() + : stringLiteralPart != null + ? 'String' + : null; } var useFinal = codeStyleOptions.makeLocalsFinal; diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_method.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_method.dart index a2066c4807e..1e29fa12b5e 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_method.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_method.dart @@ -536,10 +536,9 @@ final class ExtractMethodRefactoringImpl extends RefactoringImpl } else { // Left indent once; returnExpressionSource was indented for method // shorthands. - returnExpressionSource = - _utils - .indentSourceLeftRight('${returnExpressionSource.trim()};') - .trim(); + returnExpressionSource = _utils + .indentSourceLeftRight('${returnExpressionSource.trim()};') + .trim(); // add return type if (returnType.isNotEmpty) { @@ -864,8 +863,8 @@ final class ExtractMethodRefactoringImpl extends RefactoringImpl // change indentation var selectionFunctionExpression = _selectionFunctionExpression; if (selectionFunctionExpression != null) { - var baseNode = - selectionFunctionExpression.thisOrAncestorOfType(); + var baseNode = selectionFunctionExpression + .thisOrAncestorOfType(); if (baseNode != null) { var baseIndent = _utils.getNodePrefix(baseNode); var targetIndent = _utils.getNodePrefix(_parentMember!); @@ -1649,8 +1648,9 @@ class _InitializeParametersVisitor extends GeneralizingAstVisitor { if (parameterTypeCode == null) { return; } - var parametersCode = - parametersBuffer.isNotEmpty ? parametersBuffer.toString() : null; + var parametersCode = parametersBuffer.isNotEmpty + ? parametersBuffer.toString() + : null; parameter = RefactoringMethodParameter( RefactoringMethodParameterKind.REQUIRED, parameterTypeCode, diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_widget.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_widget.dart index 28c730a1c53..65fb558f939 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_widget.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/extract_widget.dart @@ -411,8 +411,9 @@ class ExtractWidgetRefactoringImpl extends RefactoringImpl builder.writeln(); builder.writeln(); var useSuperParameters = _featureSet.isEnabled(Feature.super_parameters); - var paramsToInitialize = - _parameters.where((p) => p.constructorName != p.name).toList(); + var paramsToInitialize = _parameters + .where((p) => p.constructorName != p.name) + .toList(); builder.writeClassDeclaration( name, superclass: classStatelessWidget!.instantiate( @@ -459,26 +460,25 @@ class ExtractWidgetRefactoringImpl extends RefactoringImpl builder.write(' }'); }, - initializerWriter: - useSuperParameters && paramsToInitialize.isEmpty - ? null - : () { - for (var i = 0; i < paramsToInitialize.length; ++i) { - var parameter = paramsToInitialize[i]; - if (i > 0) { - builder.write(', '); - } - builder.write(parameter.name); - builder.write(' = '); - builder.write(parameter.constructorName); + initializerWriter: useSuperParameters && paramsToInitialize.isEmpty + ? null + : () { + for (var i = 0; i < paramsToInitialize.length; ++i) { + var parameter = paramsToInitialize[i]; + if (i > 0) { + builder.write(', '); } - if (!useSuperParameters) { - if (paramsToInitialize.isNotEmpty) { - builder.write(', '); - } - builder.write('super(key: key)'); + builder.write(parameter.name); + builder.write(' = '); + builder.write(parameter.constructorName); + } + if (!useSuperParameters) { + if (paramsToInitialize.isNotEmpty) { + builder.write(', '); } - }, + builder.write('super(key: key)'); + } + }, ); builder.writeln(); builder.writeln(); @@ -664,11 +664,10 @@ class _ParametersCollector extends RecursiveAstVisitor { bool _isMemberOfEnclosingClass(Element element) { var enclosingClass = this.enclosingClass; if (enclosingClass != null) { - var enclosingClasses = - this.enclosingClasses ??= [ - enclosingClass, - ...enclosingClass.allSupertypes.map((t) => t.element), - ]; + var enclosingClasses = this.enclosingClasses ??= [ + enclosingClass, + ...enclosingClass.allSupertypes.map((t) => t.element), + ]; return enclosingClasses.contains(element.enclosingElement); } return false; diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/inline_method.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/inline_method.dart index e9737a84be1..d136c18a77f 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/inline_method.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/inline_method.dart @@ -1185,10 +1185,9 @@ class _VariablesVisitor extends GeneralizingAstVisitor { } // Here we found a variable with that name in the block scope - var nodeRange = - node is VariableDeclaration - ? range.token(node.name) - : range.node(node); + var nodeRange = node is VariableDeclaration + ? range.token(node.name) + : range.node(node); result.addVariable(element, nodeRange); } } diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/move_file.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/move_file.dart index 2a9b8e9b649..b151c75ef63 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/move_file.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/move_file.dart @@ -20,13 +20,12 @@ import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dar import 'package:analyzer_plugin/utilities/range_factory.dart'; import 'package:path/path.dart' as path show posix, Context; -typedef _FileReference = - ({ - SourceRange range, - String sourceFile, - String targetFile, - String quotedUriValue, - }); +typedef _FileReference = ({ + SourceRange range, + String sourceFile, + String targetFile, + String quotedUriValue, +}); /// [MoveFileRefactoring] implementation. class MoveFileRefactoringImpl extends RefactoringImpl @@ -159,11 +158,8 @@ class MoveFileRefactoringImpl extends RefactoringImpl var newSource = resolvedMapping[sourceFile] ?? sourceFile; var newTarget = resolvedMapping[targetFile] ?? targetFile; - var ( - :startQuote, - :endQuote, - unquotedValue: uriValue, - ) = _extractQuotes(reference.quotedUriValue); + var (:startQuote, :endQuote, unquotedValue: uriValue) = + _extractQuotes(reference.quotedUriValue); var newUri = _computeNewUri( sourceFile: newSource, @@ -352,12 +348,11 @@ class MoveFileRefactoringImpl extends RefactoringImpl /// Gets the string for the URI in a directive, or `null` if it's not a /// directive with a URI. SimpleStringLiteral? _getDirectiveUri(Directive directive) { - var uri = - directive is PartOfDirective - ? directive.uri - : directive is UriBasedDirective - ? directive.uri - : null; + var uri = directive is PartOfDirective + ? directive.uri + : directive is UriBasedDirective + ? directive.uri + : null; // We only handle simple string literals. return uri is SimpleStringLiteral ? uri : null; diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/refactoring_manager.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/refactoring_manager.dart index 5dd656fbb92..843c59c801d 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/refactoring_manager.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/refactoring_manager.dart @@ -103,12 +103,11 @@ class RefactoringManager { ) { // prepare for processing the request this.request = request; - var result = - this.result = EditGetRefactoringResult( - EMPTY_PROBLEM_LIST, - EMPTY_PROBLEM_LIST, - EMPTY_PROBLEM_LIST, - ); + var result = this.result = EditGetRefactoringResult( + EMPTY_PROBLEM_LIST, + EMPTY_PROBLEM_LIST, + EMPTY_PROBLEM_LIST, + ); // process the request var file = params.file; diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename.dart index e0435d0c0ce..4119fa8becd 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename.dart @@ -154,10 +154,11 @@ abstract class RenameRefactoringImpl extends RefactoringImpl /// Adds individual edits to [change]. Future fillChange(); - CodeStyleOptions getCodeStyleOptions(File file) => - sessionHelper.session.analysisContext - .getAnalysisOptionsForFile(file) - .codeStyleOptions; + CodeStyleOptions getCodeStyleOptions(File file) => sessionHelper + .session + .analysisContext + .getAnalysisOptionsForFile(file) + .codeStyleOptions; static String _getOldName(Element element) { if (element is ConstructorElement) { diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_class_member.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_class_member.dart index 9cb360920c1..fc6dcb3a808 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_class_member.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_class_member.dart @@ -145,10 +145,9 @@ class RenameClassMemberRefactoringImpl extends RenameRefactoringImpl { if (constructor != null) { var previous = constructor.separator ?? constructor.parameters; var replacement = '$newName = ${parameter.name.lexeme}'; - replacement = - constructor.initializers.isEmpty - ? ' : $replacement' - : ' $replacement,'; + replacement = constructor.initializers.isEmpty + ? ' : $replacement' + : ' $replacement,'; var edit = SourceEdit(previous.end, 0, replacement); doSourceChange_addSourceEdit(change, reference.unitSource, edit); } @@ -240,8 +239,9 @@ class _BaseClassMemberValidator { required bool isRename, required Set subClasses, }) async { - var superClasses = - interfaceElement.allSupertypes.map((e) => e.element).toSet(); + var superClasses = interfaceElement.allSupertypes + .map((e) => e.element) + .toSet(); // check shadowing in the hierarchy var declarations = await searchEngine.searchMemberDeclarations(name); for (var declaration in declarations) { @@ -531,13 +531,12 @@ class _RenameClassMemberValidator extends _BaseClassMemberValidator { var interfaceElement = element.enclosingElement; if (interfaceElement is InterfaceElement && interfaceElement is! ExtensionTypeElement) { - var formalParameters = - interfaceElement.constructors - .expand((constructor) => constructor.formalParameters) - .whereType() - .where((formalParameter) => formalParameter.field == element) - .cast() - .toList(); + var formalParameters = interfaceElement.constructors + .expand((constructor) => constructor.formalParameters) + .whereType() + .where((formalParameter) => formalParameter.field == element) + .cast() + .toList(); // The language doesn't allow private named formal parameters. if (name.startsWith('_')) { diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_local.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_local.dart index 9668f595d5e..17abd95b950 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_local.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_local.dart @@ -175,12 +175,11 @@ class RenameLocalRefactoringImpl extends RenameRefactoringImpl { if (element is PatternVariableElement) { var rootVariable = (element.firstFragment as PatternVariableFragmentImpl).rootVariable; - var declaredFragments = - rootVariable is JoinPatternVariableFragmentImpl - ? rootVariable.transitiveVariables - .whereType() - .toList() - : [element.firstFragment]; + var declaredFragments = rootVariable is JoinPatternVariableFragmentImpl + ? rootVariable.transitiveVariables + .whereType() + .toList() + : [element.firstFragment]; for (var declaredFragment in declaredFragments) { processor.addDeclarationEdit(declaredFragment.element); if (declaredFragment is BindPatternVariableFragmentImpl) { diff --git a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_parameter.dart b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_parameter.dart index e6b9923ca0d..2afa735c4a6 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_parameter.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/legacy/rename_parameter.dart @@ -52,10 +52,9 @@ class RenameParameterRefactoringImpl extends RenameRefactoringImpl { // If any of the resolved units have the lint enabled, we should avoid // renaming method parameters separately from the other implementations. if (element.isPositional && !_renameAllPositionalOccurrences) { - _renameAllPositionalOccurrences |= - getCodeStyleOptions( - resolvedUnit.file, - ).avoidRenamingMethodParameters; + _renameAllPositionalOccurrences |= getCodeStyleOptions( + resolvedUnit.file, + ).avoidRenamingMethodParameters; } var unit = resolvedUnit.unit; diff --git a/pkg/analysis_server/lib/src/services/refactoring/move_selected_formal_parameters_left.dart b/pkg/analysis_server/lib/src/services/refactoring/move_selected_formal_parameters_left.dart index 17581005a5e..71ef284ece9 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/move_selected_formal_parameters_left.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/move_selected_formal_parameters_left.dart @@ -74,13 +74,12 @@ class MoveSelectedFormalParametersLeft extends RefactoringProducer { ...afterPrevious.whereNot(selected.contains), ]; - var formalParameterUpdates = - reordered.map((formalParameter) { - return FormalParameterUpdate( - id: formalParameter.id, - kind: formalParameter.kind, - ); - }).toList(); + var formalParameterUpdates = reordered.map((formalParameter) { + return FormalParameterUpdate( + id: formalParameter.id, + kind: formalParameter.kind, + ); + }).toList(); var signatureUpdate = MethodSignatureUpdate( formalParameters: formalParameterUpdates, diff --git a/pkg/analysis_server/lib/src/services/refactoring/move_top_level_to_file.dart b/pkg/analysis_server/lib/src/services/refactoring/move_top_level_to_file.dart index 5bc914f61a6..377b4737f7e 100644 --- a/pkg/analysis_server/lib/src/services/refactoring/move_top_level_to_file.dart +++ b/pkg/analysis_server/lib/src/services/refactoring/move_top_level_to_file.dart @@ -50,10 +50,9 @@ class MoveTopLevelToFile extends RefactoringProducer { parameterTitle: 'Select a file to move to', actionLabel: 'Move', // defaultValue is a String URI. - defaultValue: - refactoringContext.server.pathContext - .toUri(defaultFilePath) - .toString(), + defaultValue: refactoringContext.server.pathContext + .toUri(defaultFilePath) + .toString(), filters: { 'Dart': ['dart'], }, @@ -105,13 +104,11 @@ class MoveTopLevelToFile extends RefactoringProducer { } var lineInfo = unitResult.lineInfo; - var ranges = - members.groups - .map( - (group) => - group.sourceRange(lineInfo, includePreceedingLine: false), - ) - .toList(); + var ranges = members.groups + .map( + (group) => group.sourceRange(lineInfo, includePreceedingLine: false), + ) + .toList(); var analyzer = ImportAnalyzer(libraryResult, sourcePath, ranges); await builder.addDartFileEdit(destinationFilePath, (builder) { @@ -225,8 +222,9 @@ class MoveTopLevelToFile extends RefactoringProducer { if (library == null || library.isDartCore) { continue; } - var hasShowCombinator = - import.combinators.whereType().isNotEmpty; + var hasShowCombinator = import.combinators + .whereType() + .isNotEmpty; builder.importLibrary( library.uri, prefix: import.prefix?.element.name, @@ -298,11 +296,10 @@ class MoveTopLevelToFile extends RefactoringProducer { var index = _SealedSubclassIndex( unitResult.unit, - candidateElements: - candidateMembers.keys - .map((member) => member.declaredFragment?.element) - .nonNulls - .toSet(), + candidateElements: candidateMembers.keys + .map((member) => member.declaredFragment?.element) + .nonNulls + .toSet(), ); if (index.hasInvalidCandidateSet) { @@ -313,8 +310,9 @@ class MoveTopLevelToFile extends RefactoringProducer { for (var sub in index.findSubclassesOfSealedRecursively( candidateMembers.keys.toSet(), )) { - candidateMembers[sub] ??= - sub is NamedCompilationUnitMember ? sub.name.lexeme : null; + candidateMembers[sub] ??= sub is NamedCompilationUnitMember + ? sub.name.lexeme + : null; } // Ensure there aren't any subclasses of sealed items in other parts of this diff --git a/pkg/analysis_server/lib/src/services/search/hierarchy.dart b/pkg/analysis_server/lib/src/services/search/hierarchy.dart index cc9796f11e2..75b0d9bc2ab 100644 --- a/pkg/analysis_server/lib/src/services/search/hierarchy.dart +++ b/pkg/analysis_server/lib/src/services/search/hierarchy.dart @@ -149,13 +149,12 @@ getHierarchyMembersAndParameters( if (enclosingElement is InterfaceElement) { var name = member2.displayName; - var superElementsToSearch = - enclosingElement.allSupertypes - .map((superType) => superType.element) - .where((interface) { - return member2.isPublic || interface.library == member2.library; - }) - .toList(); + var superElementsToSearch = enclosingElement.allSupertypes + .map((superType) => superType.element) + .where((interface) { + return member2.isPublic || interface.library == member2.library; + }) + .toList(); var searchClasses = [...superElementsToSearch, enclosingElement]; var subClasses = {}; for (var superClass in searchClasses) { diff --git a/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart b/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart index b321e81908c..8bcd1632b2c 100644 --- a/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart +++ b/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart @@ -188,8 +188,7 @@ class SearchEngineImpl implements SearchEngine { var allElements = HashSet( hashCode: (e) => e.name.hashCode, equals: (a, b) { - return a.lookupName == b.lookupName && - a.library?.uri == b.library?.uri; + return a.lookupName == b.lookupName && a.library?.uri == b.library?.uri; }, ); var regExp = RegExp(pattern); @@ -220,8 +219,8 @@ class SearchEngineImpl implements SearchEngine { // Fill out cache if needed. var drivers = searchEngineCache.drivers ??= _drivers.toList(); - var searchedFiles = - searchEngineCache.searchedFiles ??= _createSearchedFiles(drivers); + var searchedFiles = searchEngineCache.searchedFiles ??= + _createSearchedFiles(drivers); var assignedFiles = searchEngineCache.assignedFiles; if (assignedFiles == null) { assignedFiles = searchEngineCache.assignedFiles = {}; diff --git a/pkg/analysis_server/lib/src/services/snippets/dart/main_function.dart b/pkg/analysis_server/lib/src/services/snippets/dart/main_function.dart index faf820c4b38..31e05c572d4 100644 --- a/pkg/analysis_server/lib/src/services/snippets/dart/main_function.dart +++ b/pkg/analysis_server/lib/src/services/snippets/dart/main_function.dart @@ -41,10 +41,9 @@ class MainFunction extends DartSnippetProducer { builder.writeFunctionDeclaration( 'main', returnType: VoidTypeImpl.instance, - parameterWriter: - _insertArgsParameter - ? () => builder.writeParameter('args', type: listString) - : null, + parameterWriter: _insertArgsParameter + ? () => builder.writeParameter('args', type: listString) + : null, bodyWriter: () { builder.writeln('{'); builder.write(' '); diff --git a/pkg/analysis_server/lib/src/services/snippets/snippet_producer.dart b/pkg/analysis_server/lib/src/services/snippets/snippet_producer.dart index 4ea322ee475..f137fd47cec 100644 --- a/pkg/analysis_server/lib/src/services/snippets/snippet_producer.dart +++ b/pkg/analysis_server/lib/src/services/snippets/snippet_producer.dart @@ -41,10 +41,9 @@ abstract class DartSnippetProducer extends SnippetProducer { ), _elementImportCache = elementImportCache; - CodeStyleOptions get codeStyleOptions => - sessionHelper.session.analysisContext - .getAnalysisOptionsForFile(request.unit.file) - .codeStyleOptions; + CodeStyleOptions get codeStyleOptions => sessionHelper.session.analysisContext + .getAnalysisOptionsForFile(request.unit.file) + .codeStyleOptions; bool get isInTestDirectory => request.unit.unit.inTestDir; } diff --git a/pkg/analysis_server/lib/src/services/user_prompts/dart_fix_prompt_manager.dart b/pkg/analysis_server/lib/src/services/user_prompts/dart_fix_prompt_manager.dart index 814d523ff2f..811a5dcc5e5 100644 --- a/pkg/analysis_server/lib/src/services/user_prompts/dart_fix_prompt_manager.dart +++ b/pkg/analysis_server/lib/src/services/user_prompts/dart_fix_prompt_manager.dart @@ -87,13 +87,12 @@ class DartFixPromptManager { var constraintMap = >{}; for (var context in server.contextManager.analysisContexts) { var workspace = context.contextRoot.workspace; - var sdkConstraints = - workspace is PackageConfigWorkspace - ? workspace.allPackages - .whereType() - .map((p) => p.sdkVersionConstraint?.toString()) - .toList() - : []; + var sdkConstraints = workspace is PackageConfigWorkspace + ? workspace.allPackages + .whereType() + .map((p) => p.sdkVersionConstraint?.toString()) + .toList() + : []; constraintMap[context.contextRoot.root.path] = sdkConstraints; } return constraintMap; @@ -188,10 +187,9 @@ class DartFixPromptManager { case (previewFixesActionText, ExecuteCommandHandler execHandler): case (applyFixesActionText, ExecuteCommandHandler execHandler): - var command = - response == applyFixesActionText - ? Commands.fixAllInWorkspace - : Commands.previewFixAllInWorkspace; + var command = response == applyFixesActionText + ? Commands.fixAllInWorkspace + : Commands.previewFixAllInWorkspace; unawaited( _executeCommand( clientCapabilities, diff --git a/pkg/analysis_server/lib/src/socket_server.dart b/pkg/analysis_server/lib/src/socket_server.dart index 213f7b02374..bb27c8ed3bb 100644 --- a/pkg/analysis_server/lib/src/socket_server.dart +++ b/pkg/analysis_server/lib/src/socket_server.dart @@ -88,20 +88,19 @@ class SocketServer implements AbstractSocketServer { stateLocation: analysisServerOptions.cacheFolder, ); - var server = - analysisServer = LegacyAnalysisServer( - serverChannel, - resourceProvider, - analysisServerOptions, - sdkManager, - analyticsManager, - crashReportingAttachmentsBuilder, - instrumentationService, - requestStatistics: requestStatistics, - diagnosticServer: diagnosticServer, - detachableFileSystemManager: detachableFileSystemManager, - enableBlazeWatcher: true, - ); + var server = analysisServer = LegacyAnalysisServer( + serverChannel, + resourceProvider, + analysisServerOptions, + sdkManager, + analyticsManager, + crashReportingAttachmentsBuilder, + instrumentationService, + requestStatistics: requestStatistics, + diagnosticServer: diagnosticServer, + detachableFileSystemManager: detachableFileSystemManager, + enableBlazeWatcher: true, + ); detachableFileSystemManager?.setAnalysisServer(server); } } diff --git a/pkg/analysis_server/lib/src/status/pages/analysis_driver_page.dart b/pkg/analysis_server/lib/src/status/pages/analysis_driver_page.dart index 664ac24448e..907e37310d7 100644 --- a/pkg/analysis_server/lib/src/status/pages/analysis_driver_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/analysis_driver_page.dart @@ -43,9 +43,8 @@ class AnalysisDriverPage extends DiagnosticPageWithNav implements PostablePage { @override Future handlePost(Map params) async { if (params[_resetFormId]?.isNotEmpty ?? false) { - server - .analysisDriverScheduler - .accumulatedPerformance = OperationPerformanceImpl(''); + server.analysisDriverScheduler.accumulatedPerformance = + OperationPerformanceImpl(''); } return path; diff --git a/pkg/analysis_server/lib/src/status/pages/assists_page.dart b/pkg/analysis_server/lib/src/status/pages/assists_page.dart index 74bc3ebbb29..1d73ed39822 100644 --- a/pkg/analysis_server/lib/src/status/pages/assists_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/assists_page.dart @@ -33,8 +33,9 @@ class AssistsPage extends DiagnosticPageWithNav with PerformanceChartMixin { return; } - var fastCount = - requests.where((c) => c.elapsedInMilliseconds <= 100).length; + var fastCount = requests + .where((c) => c.elapsedInMilliseconds <= 100) + .length; p( '${requests.length} results; ${printPercentage(fastCount / requests.length)} within 100ms.', ); diff --git a/pkg/analysis_server/lib/src/status/pages/code_completion_page.dart b/pkg/analysis_server/lib/src/status/pages/code_completion_page.dart index ae7ce4efbd7..4a81e296b7d 100644 --- a/pkg/analysis_server/lib/src/status/pages/code_completion_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/code_completion_page.dart @@ -34,8 +34,9 @@ class CodeCompletionPage extends DiagnosticPageWithNav return; } - var fastCount = - completions.where((c) => c.elapsedInMilliseconds <= 100).length; + var fastCount = completions + .where((c) => c.elapsedInMilliseconds <= 100) + .length; p( '${completions.length} results; ${printPercentage(fastCount / completions.length)} within 100ms.', ); diff --git a/pkg/analysis_server/lib/src/status/pages/collect_report_page.dart b/pkg/analysis_server/lib/src/status/pages/collect_report_page.dart index ed85845fab5..660a95dfed0 100644 --- a/pkg/analysis_server/lib/src/status/pages/collect_report_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/collect_report_page.dart @@ -105,20 +105,20 @@ class CollectReportPage extends DiagnosticPage { Map collectedData, AnalysisServer server, ) { - for (var data - in { - 'startup': server.performanceDuringStartup, - if (server.performanceAfterStartup != null) - 'afterStartup': server.performanceAfterStartup!, - }.entries) { + for (var data in { + 'startup': server.performanceDuringStartup, + if (server.performanceAfterStartup != null) + 'afterStartup': server.performanceAfterStartup!, + }.entries) { var perf = data.value; var perfData = {}; collectedData[data.key] = perfData; var requestCount = perf.requestCount; var latencyCount = perf.latencyCount; - var averageLatency = - latencyCount > 0 ? (perf.requestLatency ~/ latencyCount) : null; + var averageLatency = latencyCount > 0 + ? (perf.requestLatency ~/ latencyCount) + : null; var maximumLatency = perf.maxLatency; var slowRequestCount = perf.slowRequestCount; @@ -198,13 +198,11 @@ class CollectReportPage extends DiagnosticPage { Map collectedData, AnalysisServer server, ) { - var byteStoreTimings = - server.byteStoreTimings - ?.where( - (timing) => - timing.readCount != 0 || timing.readTime != Duration.zero, - ) - .toList(); + var byteStoreTimings = server.byteStoreTimings + ?.where( + (timing) => timing.readCount != 0 || timing.readTime != Duration.zero, + ) + .toList(); if (byteStoreTimings != null && byteStoreTimings.isNotEmpty) { var performance = []; collectedData['byteStoreTimings'] = performance; @@ -214,8 +212,9 @@ class CollectReportPage extends DiagnosticPage { continue; } - var nextTiming = - i + 1 < byteStoreTimings.length ? byteStoreTimings[i + 1] : null; + var nextTiming = i + 1 < byteStoreTimings.length + ? byteStoreTimings[i + 1] + : null; var duration = (nextTiming?.time ?? DateTime.now()).difference( timing.time, ); @@ -245,8 +244,9 @@ class CollectReportPage extends DiagnosticPage { collectedData['serverType'] = server.runtimeType.toString(); collectedData['uptime'] = server.uptime.toString(); if (server is LegacyAnalysisServer) { - collectedData['serverServices'] = - server.serverServices.map((e) => e.toString()).toList(); + collectedData['serverServices'] = server.serverServices + .map((e) => e.toString()) + .toList(); } else if (server is LspAnalysisServer) { collectedData['clientDiagnosticInformation'] = server.clientDiagnosticInformation; diff --git a/pkg/analysis_server/lib/src/status/pages/communications_page.dart b/pkg/analysis_server/lib/src/status/pages/communications_page.dart index 8d70e6f3854..0241c5bfa67 100644 --- a/pkg/analysis_server/lib/src/status/pages/communications_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/communications_page.dart @@ -75,11 +75,13 @@ class CommunicationsPage extends DiagnosticPageWithNav { ) { var requestCount = perf.requestCount; var latencyCount = perf.latencyCount; - var averageLatency = - latencyCount > 0 ? (perf.requestLatency ~/ latencyCount) : 0; + var averageLatency = latencyCount > 0 + ? (perf.requestLatency ~/ latencyCount) + : 0; var maximumLatency = perf.maxLatency; - var slowRequestPercent = - latencyCount > 0 ? (perf.slowRequestCount / latencyCount) : 0.0; + var slowRequestPercent = latencyCount > 0 + ? (perf.slowRequestCount / latencyCount) + : 0.0; buf.write(''); writeRow(['$requestCount', 'requests'], classes: ['right', null]); diff --git a/pkg/analysis_server/lib/src/status/pages/contexts_page.dart b/pkg/analysis_server/lib/src/status/pages/contexts_page.dart index 97ad4eb0ea2..f73c5c82892 100644 --- a/pkg/analysis_server/lib/src/status/pages/contexts_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/contexts_page.dart @@ -215,8 +215,8 @@ class ContextsPage extends DiagnosticPageWithNav { cycles.add(kind.libraryCycle); } } - var sortedCycles = - cycles.toList()..sort((first, second) => second.size - first.size); + var sortedCycles = cycles.toList() + ..sort((first, second) => second.size - first.size); var cyclesToDisplay = math.min(sortedCycles.length, 10); var initialPathLength = contextRoot.root.path.length + 1; buf.write('

There are ${sortedCycles.length} library cycles. '); diff --git a/pkg/analysis_server/lib/src/status/pages/file_byte_store_timing_page.dart b/pkg/analysis_server/lib/src/status/pages/file_byte_store_timing_page.dart index 494da88e134..e8a7303ba16 100644 --- a/pkg/analysis_server/lib/src/status/pages/file_byte_store_timing_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/file_byte_store_timing_page.dart @@ -22,13 +22,11 @@ class FileByteStoreTimingPage extends DiagnosticPageWithNav Future generateContent(Map params) async { h3('FileByteStore Timings'); - var byteStoreTimings = - server.byteStoreTimings - ?.where( - (timing) => - timing.readCount != 0 || timing.readTime != Duration.zero, - ) - .toList(); + var byteStoreTimings = server.byteStoreTimings + ?.where( + (timing) => timing.readCount != 0 || timing.readTime != Duration.zero, + ) + .toList(); if (byteStoreTimings == null || byteStoreTimings.isEmpty) { p( 'There are currently no timings. ' @@ -47,8 +45,9 @@ class FileByteStoreTimingPage extends DiagnosticPageWithNav continue; } - var nextTiming = - i + 1 < byteStoreTimings.length ? byteStoreTimings[i + 1] : null; + var nextTiming = i + 1 < byteStoreTimings.length + ? byteStoreTimings[i + 1] + : null; var duration = (nextTiming?.time ?? DateTime.now()).difference( timing.time, ); diff --git a/pkg/analysis_server/lib/src/status/pages/fixes_page.dart b/pkg/analysis_server/lib/src/status/pages/fixes_page.dart index 86f7e241c52..8ba64a79b63 100644 --- a/pkg/analysis_server/lib/src/status/pages/fixes_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/fixes_page.dart @@ -33,8 +33,9 @@ class FixesPage extends DiagnosticPageWithNav with PerformanceChartMixin { return; } - var fastCount = - requests.where((c) => c.elapsedInMilliseconds <= 100).length; + var fastCount = requests + .where((c) => c.elapsedInMilliseconds <= 100) + .length; p( '${requests.length} results; ${printPercentage(fastCount / requests.length)} within 100ms.', ); diff --git a/pkg/analysis_server/lib/src/status/pages/refactorings_page.dart b/pkg/analysis_server/lib/src/status/pages/refactorings_page.dart index 7c56706c138..795384e0fea 100644 --- a/pkg/analysis_server/lib/src/status/pages/refactorings_page.dart +++ b/pkg/analysis_server/lib/src/status/pages/refactorings_page.dart @@ -34,8 +34,9 @@ class RefactoringsPage extends DiagnosticPageWithNav return; } - var fastCount = - requests.where((c) => c.elapsedInMilliseconds <= 100).length; + var fastCount = requests + .where((c) => c.elapsedInMilliseconds <= 100) + .length; p( '${requests.length} results; ${printPercentage(fastCount / requests.length)} within 100ms.', ); diff --git a/pkg/analysis_server/lib/src/utilities/element_location2.dart b/pkg/analysis_server/lib/src/utilities/element_location2.dart index 879d933ad8f..5cdfd2ded9c 100644 --- a/pkg/analysis_server/lib/src/utilities/element_location2.dart +++ b/pkg/analysis_server/lib/src/utilities/element_location2.dart @@ -26,12 +26,11 @@ class ElementLocation { [String library, String topName] => ElementLocation._(library, topName), [String library, String topName, String memberName] => _MemberElementLocation._(library, topName, memberName), - _ => - throw ArgumentError.value( - encoded, - 'encoded', - "Encoded string should be in the format 'libraryUri;topLevelName[;memberName]'", - ), + _ => throw ArgumentError.value( + encoded, + 'encoded', + "Encoded string should be in the format 'libraryUri;topLevelName[;memberName]'", + ), }; } diff --git a/pkg/analysis_server/lib/src/utilities/extensions/range_factory.dart b/pkg/analysis_server/lib/src/utilities/extensions/range_factory.dart index 5bcc46209b1..e93f56812b2 100644 --- a/pkg/analysis_server/lib/src/utilities/extensions/range_factory.dart +++ b/pkg/analysis_server/lib/src/utilities/extensions/range_factory.dart @@ -139,8 +139,9 @@ extension RangeFactoryExtensions on RangeFactory { // as headers and should never be included in the range. var isFirstItem = beginToken == node.root.beginToken; - var thisLeadingComment = - isFirstItem ? beginToken : _leadingComment(lineInfo, beginToken); + var thisLeadingComment = isFirstItem + ? beginToken + : _leadingComment(lineInfo, beginToken); var thisTrailingComment = trailingComment( lineInfo, node.endToken, diff --git a/pkg/analysis_server/lib/src/utilities/extensions/string.dart b/pkg/analysis_server/lib/src/utilities/extensions/string.dart index 9bf08fb4763..2c0a9e24cc2 100644 --- a/pkg/analysis_server/lib/src/utilities/extensions/string.dart +++ b/pkg/analysis_server/lib/src/utilities/extensions/string.dart @@ -16,11 +16,10 @@ extension StringExtension on String { /// It is assumed that this String is a valid identifier and does not contain /// characters that are invalid in file names. String get toFileName { - var fileName = - replaceAllMapped( - RegExp('[A-Z]'), - (match) => match.start == 0 ? match[0]! : '_${match[0]}', - ).toLowerCase(); + var fileName = replaceAllMapped( + RegExp('[A-Z]'), + (match) => match.start == 0 ? match[0]! : '_${match[0]}', + ).toLowerCase(); return '$fileName.dart'; } diff --git a/pkg/analysis_server/lib/src/utilities/extensions/yaml.dart b/pkg/analysis_server/lib/src/utilities/extensions/yaml.dart index 6c542191723..78037db75d2 100644 --- a/pkg/analysis_server/lib/src/utilities/extensions/yaml.dart +++ b/pkg/analysis_server/lib/src/utilities/extensions/yaml.dart @@ -26,10 +26,9 @@ extension YamlNodeExtensions on YamlNode { var entries = node.nodes.entries.toList(); for (var i = 0; i < entries.length; i++) { var entry = entries[i]; - var nextEntryOffset = - i + 1 < entries.length - ? (entries[i + 1].key as YamlNode).span.start.offset - : null; + var nextEntryOffset = i + 1 < entries.length + ? (entries[i + 1].key as YamlNode).span.start.offset + : null; var key = entry.key as YamlNode; if (key.containsOffset(offset)) { return key; diff --git a/pkg/analysis_server/lib/src/utilities/import_analyzer.dart b/pkg/analysis_server/lib/src/utilities/import_analyzer.dart index 770f60dcf54..e92383938b2 100644 --- a/pkg/analysis_server/lib/src/utilities/import_analyzer.dart +++ b/pkg/analysis_server/lib/src/utilities/import_analyzer.dart @@ -326,34 +326,31 @@ class _ReferenceFinder extends RecursiveAstVisitor { return null; } - var import = - _importsByPrefix[prefix ?? '']?.where((import) { - // Check if this import is providing our element with the correct - // prefix/name. - var exportedElement = - prefix != null - ? import.namespace.getPrefixed2(prefix, lookupName) - : import.namespace.get2(lookupName); - return exportedElement == element; - }).firstOrNull; + var import = _importsByPrefix[prefix ?? '']?.where((import) { + // Check if this import is providing our element with the correct + // prefix/name. + var exportedElement = prefix != null + ? import.namespace.getPrefixed2(prefix, lookupName) + : import.namespace.get2(lookupName); + return exportedElement == element; + }).firstOrNull; // Extensions can be used without a prefix, so we can use any import that // brings in the extension. if (import == null && prefix == null && element is ExtensionElement) { - import = - _importsByPrefix.values.flattenedToList - .where( - (import) => - // Because we don't know what prefix we're looking for (any is - // allowed), use the imports own prefix when checking for the - // element. - import.namespace.getPrefixed2( - import.prefix?.element.name ?? '', - lookupName, - ) == - element, - ) - .firstOrNull; + import = _importsByPrefix.values.flattenedToList + .where( + (import) => + // Because we don't know what prefix we're looking for (any is + // allowed), use the imports own prefix when checking for the + // element. + import.namespace.getPrefixed2( + import.prefix?.element.name ?? '', + lookupName, + ) == + element, + ) + .firstOrNull; } return import; diff --git a/pkg/analysis_server/lib/src/utilities/mocks.dart b/pkg/analysis_server/lib/src/utilities/mocks.dart index 24414f8e058..dd816afecf4 100644 --- a/pkg/analysis_server/lib/src/utilities/mocks.dart +++ b/pkg/analysis_server/lib/src/utilities/mocks.dart @@ -134,8 +134,9 @@ class MockServerChannel implements ServerCommunicationChannel { // Round-trip via JSON to ensure all types are fully serialized as they // would be in a real setup. - response = - Response.fromJson(jsonDecode(jsonString) as Map)!; + response = Response.fromJson( + jsonDecode(jsonString) as Map, + )!; responsesReceived.add(response); responseController.add(response); @@ -165,10 +166,9 @@ class MockServerChannel implements ServerCommunicationChannel { // Round-trip via JSON to ensure all types are fully serialized as they // would be in a real setup. - response = - Response.fromJson( - jsonDecode(jsonEncode(response)) as Map, - )!; + response = Response.fromJson( + jsonDecode(jsonEncode(response)) as Map, + )!; return response; } @@ -188,8 +188,9 @@ class MockServerChannel implements ServerCommunicationChannel { // Round-trip via JSON to ensure all types are fully serialized as they // would be in a real setup. - response = - Response.fromJson(jsonDecode(jsonString) as Map)!; + response = Response.fromJson( + jsonDecode(jsonString) as Map, + )!; requestController.add(response); } diff --git a/pkg/analysis_server/lib/src/utilities/source_change_merger.dart b/pkg/analysis_server/lib/src/utilities/source_change_merger.dart index 17c80547ea1..8e9654318a7 100644 --- a/pkg/analysis_server/lib/src/utilities/source_change_merger.dart +++ b/pkg/analysis_server/lib/src/utilities/source_change_merger.dart @@ -121,15 +121,13 @@ class SourceChangeMerger { // 1. The start of first that is not replaced by second (prefix) // 2. The text from second (middle) // 3. The end of first that is not replaced by second (suffix) - var prefix = - second.offset > first.offset - ? first.replacement.substring(0, second.offset - first.offset) - : ''; + var prefix = second.offset > first.offset + ? first.replacement.substring(0, second.offset - first.offset) + : ''; var middle = second.replacement; - var suffix = - second.end < first.offset + first.replacement.length - ? first.replacement.substring(second.end - first.offset) - : ''; + var suffix = second.end < first.offset + first.replacement.length + ? first.replacement.substring(second.end - first.offset) + : ''; return SourceEdit(actualStart, length, '$prefix$middle$suffix'); } diff --git a/pkg/analysis_server/pubspec.yaml b/pkg/analysis_server/pubspec.yaml index 407f4f343cd..321757af160 100644 --- a/pkg/analysis_server/pubspec.yaml +++ b/pkg/analysis_server/pubspec.yaml @@ -3,7 +3,7 @@ name: analysis_server publish_to: none environment: - sdk: '^3.7.0' + sdk: '^3.9.0' resolution: workspace diff --git a/pkg/analysis_server/test/analysis/notification_highlights2_test.dart b/pkg/analysis_server/test/analysis/notification_highlights2_test.dart index b9ee7487634..ba04367bb83 100644 --- a/pkg/analysis_server/test/analysis/notification_highlights2_test.dart +++ b/pkg/analysis_server/test/analysis/notification_highlights2_test.dart @@ -2631,10 +2631,9 @@ void f(Object o) { /// Returns the textual dump of the highlight regions that intersect with /// the [index]th range in [testCode] (or all code if `-1`). String _getHighlightText(TestCode testCode, int index) { - var window = - index == -1 - ? SourceRange(0, testCode.code.length) - : testCode.ranges[index].sourceRange; + var window = index == -1 + ? SourceRange(0, testCode.code.length) + : testCode.ranges[index].sourceRange; // TODO(scheglov): Apparently, we don't sort in the server. var sortedRegions = regions.sortedBy((e) => e.offset); diff --git a/pkg/analysis_server/test/analysis/update_content_test.dart b/pkg/analysis_server/test/analysis/update_content_test.dart index ed211e10fe0..0f3e8062821 100644 --- a/pkg/analysis_server/test/analysis/update_content_test.dart +++ b/pkg/analysis_server/test/analysis/update_content_test.dart @@ -88,9 +88,8 @@ class UpdateContentTest extends PubPackageAnalysisServerTest { Future test_multiple_contexts() async { writePackageConfig( workspaceRootPath, - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), ); var aaa = newFile('$workspaceRootPath/aaa/lib/aaa.dart', r''' diff --git a/pkg/analysis_server/test/benchmarks_test.dart b/pkg/analysis_server/test/benchmarks_test.dart index 686ba843212..990a025ef9a 100644 --- a/pkg/analysis_server/test/benchmarks_test.dart +++ b/pkg/analysis_server/test/benchmarks_test.dart @@ -37,10 +37,9 @@ void defineTests() { // variable. var runBenchmarks = Platform.environment['TEST_SERVER_BENCHMARKS'] != 'false'; - var skipReason = - runBenchmarks - ? null - : 'Skipped by TEST_SERVER_BENCHMARKS environment variable'; + var skipReason = runBenchmarks + ? null + : 'Skipped by TEST_SERVER_BENCHMARKS environment variable'; for (var benchmarkId in benchmarks) { if (benchmarkIdsToSkip.contains(benchmarkId)) { diff --git a/pkg/analysis_server/test/completion_test_support.dart b/pkg/analysis_server/test/completion_test_support.dart index 8b5c92b063a..701fa06b25c 100644 --- a/pkg/analysis_server/test/completion_test_support.dart +++ b/pkg/analysis_server/test/completion_test_support.dart @@ -13,10 +13,9 @@ import 'domain_completion_util.dart'; class CompletionTestCase extends AbstractCompletionDomainTest { static const String CURSOR_MARKER = '!'; - List get suggestedCompletions => - suggestions - .map((CompletionSuggestion suggestion) => suggestion.completion) - .toList(); + List get suggestedCompletions => suggestions + .map((CompletionSuggestion suggestion) => suggestion.completion) + .toList(); void assertHasCompletion( String completion, { @@ -83,16 +82,15 @@ class CompletionTestCase extends AbstractCompletionDomainTest { /// Discard any results that do not start with the characters the user has /// "already typed". void filterResults(String content) { - var charsAlreadyTyped = - content.substring(replacementOffset!, completionOffset).toLowerCase(); - suggestions = - suggestions - .where( - (CompletionSuggestion suggestion) => suggestion.completion - .toLowerCase() - .startsWith(charsAlreadyTyped), - ) - .toList(); + var charsAlreadyTyped = content + .substring(replacementOffset!, completionOffset) + .toLowerCase(); + suggestions = suggestions + .where( + (CompletionSuggestion suggestion) => + suggestion.completion.toLowerCase().startsWith(charsAlreadyTyped), + ) + .toList(); } Future runTest( diff --git a/pkg/analysis_server/test/domain_analysis_test.dart b/pkg/analysis_server/test/domain_analysis_test.dart index d9b80171ecc..5351045be15 100644 --- a/pkg/analysis_server/test/domain_analysis_test.dart +++ b/pkg/analysis_server/test/domain_analysis_test.dart @@ -446,8 +446,8 @@ AnalysisErrors // Write `package_config.json`, recreate analysis contexts. writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRootPath), ); await pumpEventQueue(times: 5000); @@ -996,8 +996,8 @@ AnalysisErrors // Write `package_config.json`, recreate analysis contexts. writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRootPath), ); await pumpEventQueue(times: 5000); @@ -1329,8 +1329,8 @@ class A {} // Write the empty file, without `package:aaa`. writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRootPath), ); newFile(testFilePath, ''' @@ -1907,8 +1907,8 @@ class A {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRootPath), ); newFile(testFilePath, ''' @@ -2446,8 +2446,8 @@ class SetAnalysisRootsTest extends PubPackageAnalysisServerTest { ); if (withPackageConfig) { - var packageConfig = - PackageConfigFileBuilder()..add(name: name, rootPath: packagePath); + var packageConfig = PackageConfigFileBuilder() + ..add(name: name, rootPath: packagePath); for (var plugin in plugins) { packageConfig.add(name: plugin.name, rootPath: plugin.path); } @@ -2515,9 +2515,8 @@ class A {} '''); writePackageConfig( convertPath('/project'), - config: - (PackageConfigFileBuilder() - ..add(name: 'pkgA', rootPath: convertPath('/packages/pkgA'))), + config: (PackageConfigFileBuilder() + ..add(name: 'pkgA', rootPath: convertPath('/packages/pkgA'))), ); // addTestFile(''' @@ -2568,9 +2567,8 @@ class A {} '''); writePackageConfig( convertPath('/project'), - config: - (PackageConfigFileBuilder() - ..add(name: 'pkgA', rootPath: convertPath('/packages/pkgA'))), + config: (PackageConfigFileBuilder() + ..add(name: 'pkgA', rootPath: convertPath('/packages/pkgA'))), ); // addTestFile('// no "pkgA" reference'); diff --git a/pkg/analysis_server/test/domain_completion_test.dart b/pkg/analysis_server/test/domain_completion_test.dart index 7c2e8f09954..5f1bc8e1c5b 100644 --- a/pkg/analysis_server/test/domain_completion_test.dart +++ b/pkg/analysis_server/test/domain_completion_test.dart @@ -106,8 +106,8 @@ class Test {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path), ); await _configureWithWorkspaceRoot(); @@ -774,10 +774,9 @@ class A02 {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: aaaRoot.path) - ..add(name: 'bbb', rootPath: bbbRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path) + ..add(name: 'bbb', rootPath: bbbRoot.path), ); await _configureWithWorkspaceRoot(); @@ -829,10 +828,9 @@ class A04 {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: aaaRoot.path) - ..add(name: 'bbb', rootPath: bbbRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path) + ..add(name: 'bbb', rootPath: bbbRoot.path), ); await _configureWithWorkspaceRoot(); @@ -880,10 +878,9 @@ class A04 {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: aaaRoot.path) - ..add(name: 'bbb', rootPath: bbbRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path) + ..add(name: 'bbb', rootPath: bbbRoot.path), ); await _configureWithWorkspaceRoot(); @@ -933,10 +930,9 @@ class A02 {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: aaaRoot.path) - ..add(name: 'bbb', rootPath: bbbRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path) + ..add(name: 'bbb', rootPath: bbbRoot.path), ); await _configureWithWorkspaceRoot(); diff --git a/pkg/analysis_server/test/edit/fixes_test.dart b/pkg/analysis_server/test/edit/fixes_test.dart index 19bd8831c03..c64aa816355 100644 --- a/pkg/analysis_server/test/edit/fixes_test.dart +++ b/pkg/analysis_server/test/edit/fixes_test.dart @@ -193,9 +193,8 @@ print(1) Future test_suggestImportFromDifferentAnalysisRoot() async { writePackageConfig( convertPath('$workspaceRootPath/aaa'), - config: - (PackageConfigFileBuilder() - ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb')), + config: (PackageConfigFileBuilder() + ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb')), ); newPubspecYamlFile('$workspaceRootPath/aaa', r''' dependencies: @@ -221,11 +220,10 @@ dependencies: await waitForTasksFinished(); - var fixes = - (await _getFixesAt( - file, - 'Foo()', - )).single.fixes.map((f) => f.message).toList(); + var fixes = (await _getFixesAt( + file, + 'Foo()', + )).single.fixes.map((f) => f.message).toList(); expect(fixes, contains("Import library 'package:bbb/target.dart'")); expect( fixes, diff --git a/pkg/analysis_server/test/edit/refactoring_test.dart b/pkg/analysis_server/test/edit/refactoring_test.dart index 44e3e7cd5ce..cb5699027d2 100644 --- a/pkg/analysis_server/test/edit/refactoring_test.dart +++ b/pkg/analysis_server/test/edit/refactoring_test.dart @@ -262,8 +262,9 @@ class ExtractLocalVariableTest extends _AbstractGetRefactoring_Test { bool extractAll, ) { var kind = RefactoringKind.EXTRACT_LOCAL_VARIABLE; - var options = - name != null ? ExtractLocalVariableOptions(name, extractAll) : null; + var options = name != null + ? ExtractLocalVariableOptions(name, extractAll) + : null; return sendRequest(kind, offset, length, options); } diff --git a/pkg/analysis_server/test/lsp/change_verifier.dart b/pkg/analysis_server/test/lsp/change_verifier.dart index 586007c7a25..b1fb3660c79 100644 --- a/pkg/analysis_server/test/lsp/change_verifier.dart +++ b/pkg/analysis_server/test/lsp/change_verifier.dart @@ -185,10 +185,9 @@ class LspChangeVerifier { String _applyTextDocumentEditEdit(String content, TextDocumentEdit edit) { // Extract the edits from the union (they all have the same superclass). - var edits = - edit.edits - .map((edit) => edit.map((e) => e, (e) => e, (e) => e)) - .toList(); + var edits = edit.edits + .map((edit) => edit.map((e) => e, (e) => e, (e) => e)) + .toList(); return _applyTextEdits(content, edits); } @@ -343,8 +342,7 @@ class _Change { } extension on Range { - String toDisplayString() => - start.line == end.line - ? 'line ${start.line + 1}' - : 'lines ${start.line + 1}-${end.line + 1}'; + String toDisplayString() => start.line == end.line + ? 'line ${start.line + 1}' + : 'lines ${start.line + 1}-${end.line + 1}'; } diff --git a/pkg/analysis_server/test/lsp/code_actions_assists_test.dart b/pkg/analysis_server/test/lsp/code_actions_assists_test.dart index 44b0feb6c74..932fbc5098f 100644 --- a/pkg/analysis_server/test/lsp/code_actions_assists_test.dart +++ b/pkg/analysis_server/test/lsp/code_actions_assists_test.dart @@ -58,9 +58,8 @@ bar ), ]); configureTestPlugin( - handler: - (request) => - request is plugin.EditGetAssistsParams ? pluginResult : null, + handler: (request) => + request is plugin.EditGetAssistsParams ? pluginResult : null, ); await verifyCodeActionLiteralEdits( @@ -88,9 +87,8 @@ bar plugin.PrioritizedSourceChange(100, plugin.SourceChange('High')), ]); configureTestPlugin( - handler: - (request) => - request is plugin.EditGetAssistsParams ? pluginResult : null, + handler: (request) => + request is plugin.EditGetAssistsParams ? pluginResult : null, ); createFile(testFilePath, code.code); diff --git a/pkg/analysis_server/test/lsp/code_actions_fixes_test.dart b/pkg/analysis_server/test/lsp/code_actions_fixes_test.dart index 752239948a6..9844446d700 100644 --- a/pkg/analysis_server/test/lsp/code_actions_fixes_test.dart +++ b/pkg/analysis_server/test/lsp/code_actions_fixes_test.dart @@ -72,9 +72,8 @@ bar ), ]); configureTestPlugin( - handler: - (request) => - request is plugin.EditGetFixesParams ? pluginResult : null, + handler: (request) => + request is plugin.EditGetFixesParams ? pluginResult : null, ); await verifyCodeActionLiteralEdits( @@ -122,9 +121,8 @@ bar ), ]); configureTestPlugin( - handler: - (request) => - request is plugin.EditGetFixesParams ? pluginResult : null, + handler: (request) => + request is plugin.EditGetFixesParams ? pluginResult : null, ); newFile(testFilePath, code.code); diff --git a/pkg/analysis_server/test/lsp/code_actions_mixin.dart b/pkg/analysis_server/test/lsp/code_actions_mixin.dart index edf75544af3..0abba433940 100644 --- a/pkg/analysis_server/test/lsp/code_actions_mixin.dart +++ b/pkg/analysis_server/test/lsp/code_actions_mixin.dart @@ -333,7 +333,8 @@ mixin CodeActionsTestMixin // For convenience, if a test doesn't provide an full set of edits // we assume only a single edit of the file that was being modified. if (!expected.startsWith(LspChangeVerifier.editMarkerStart)) { - expected = ''' + expected = + ''' ${LspChangeVerifier.editMarkerStart} ${relativePath(filePath)} $expected'''; } @@ -376,7 +377,8 @@ $expected'''; // For convenience, if a test doesn't provide an full set of edits // we assume only a single edit of the file that was being modified. if (!expected.startsWith(LspChangeVerifier.editMarkerStart)) { - expected = ''' + expected = + ''' ${LspChangeVerifier.editMarkerStart} ${relativePath(filePath)} $expected'''; } diff --git a/pkg/analysis_server/test/lsp/completion.dart b/pkg/analysis_server/test/lsp/completion.dart index 0290f5df4bd..ff4fc12c2f3 100644 --- a/pkg/analysis_server/test/lsp/completion.dart +++ b/pkg/analysis_server/test/lsp/completion.dart @@ -116,6 +116,6 @@ mixin CompletionTestMixin on AbstractLspAnalysisServerTest { /// of the cursor position in completions. String withCaret(String contents, InsertTextFormat? format) => format == InsertTextFormat.Snippet - ? contents.replaceFirst(r'$0', '^') - : contents; + ? contents.replaceFirst(r'$0', '^') + : contents; } diff --git a/pkg/analysis_server/test/lsp/completion_dart_test.dart b/pkg/analysis_server/test/lsp/completion_dart_test.dart index efba6d14ff7..91a16717681 100644 --- a/pkg/analysis_server/test/lsp/completion_dart_test.dart +++ b/pkg/analysis_server/test/lsp/completion_dart_test.dart @@ -45,21 +45,20 @@ void main() { }); } -typedef ExpectedLabel = - ({ - // Main label of the completion (eg 'myFunc') - String? label, - // The detail part of the label (shown after label, usually truncated signature) - String? labelDetail, - // Additional label description (usually the auto-import URI) - String? labelDescription, - // Filter text (usually same as label, never with `()` or other suffixes) - String? filterText, - // Main detail (shown in popout, usually full signature) - String? detail, - // Sometimes resolved detail has a prefix added (eg. "Auto-import from"). - String? resolvedDetailPrefix, - }); +typedef ExpectedLabel = ({ + // Main label of the completion (eg 'myFunc') + String? label, + // The detail part of the label (shown after label, usually truncated signature) + String? labelDetail, + // Additional label description (usually the auto-import URI) + String? labelDescription, + // Filter text (usually same as label, never with `()` or other suffixes) + String? filterText, + // Main detail (shown in popout, usually full signature) + String? detail, + // Sometimes resolved detail has a prefix added (eg. "Auto-import from"). + String? resolvedDetailPrefix, +}); abstract class AbstractCompletionTest extends AbstractLspAnalysisServerTest with CompletionTestMixin { @@ -1261,9 +1260,8 @@ void f() { var res = await getCompletion(mainFileUri, code.position.position); var item = res.singleWhere( (c) => c.label == completion, - orElse: - () => - throw 'Did not find $completion in ${res.map((r) => r.label).toList()}', + orElse: () => + throw 'Did not find $completion in ${res.map((r) => r.label).toList()}', ); expect(item.insertTextFormat, equals(insertTextFormat)); @@ -2957,19 +2955,22 @@ final a = Flex(children: []); required String expectedReplace, required String expectedInsert, }) async { - content = ''' + content = + ''' class A { const A({int argOne, int argTwo, String argThree}); } final varOne = ''; $code void f() { } '''; - var expectedReplaced = ''' + var expectedReplaced = + ''' class A { const A({int argOne, int argTwo, String argThree}); } final varOne = ''; $expectedReplace void f() { } '''; - var expectedInserted = ''' + var expectedInserted = + ''' class A { const A({int argOne, int argTwo, String argThree}); } final varOne = ''; $expectedInsert @@ -3396,11 +3397,10 @@ void f() { await openFile(mainFileUri, code.code); var res = await getCompletion(mainFileUri, code.position.position); - var setters = - res - .where((c) => c.label.endsWith('Setter')) - .map((c) => c.detail != null ? '${c.label} (${c.detail})' : c.label) - .toList(); + var setters = res + .where((c) => c.label.endsWith('Setter')) + .map((c) => c.detail != null ? '${c.label} (${c.detail})' : c.label) + .toList(); expect(setters, [ 'stringSetter (String)', 'noArgSetter (dynamic)', @@ -3692,8 +3692,9 @@ void f() { await initialAnalysis; var res = await getCompletion(mainFileUri, code.position.position); - var enumCompletions = - res.where((c) => c.label.startsWith('MyExportedEnum')).toList(); + var enumCompletions = res + .where((c) => c.label.startsWith('MyExportedEnum')) + .toList(); expect( enumCompletions.map((c) => c.label), unorderedEquals([ @@ -3772,8 +3773,9 @@ void f() { await initialAnalysis; var res = await getCompletion(mainFileUri, code.position.position); - var completions = - res.where((c) => c.label == 'MyExportedEnum.One').toList(); + var completions = res + .where((c) => c.label == 'MyExportedEnum.One') + .toList(); expect(completions, hasLength(1)); var resolved = await resolveCompletion(completions.first); // It should not include auto-import text since it's already imported. diff --git a/pkg/analysis_server/test/lsp/completion_yaml_test.dart b/pkg/analysis_server/test/lsp/completion_yaml_test.dart index 0faaa1290c3..18134e11619 100644 --- a/pkg/analysis_server/test/lsp/completion_yaml_test.dart +++ b/pkg/analysis_server/test/lsp/completion_yaml_test.dart @@ -407,15 +407,14 @@ dependencies: // Versions are currently only available if we've previously resolved on the // package name, so first complete/resolve that. - var newContent = - (await verifyCompletions( - pubspecFileUri, - content, - expectCompletions: ['one: '], - resolve: true, - applyEditsFor: 'one: ', - openCloseFile: false, - ))!; + var newContent = (await verifyCompletions( + pubspecFileUri, + content, + expectCompletions: ['one: '], + resolve: true, + applyEditsFor: 'one: ', + openCloseFile: false, + ))!; await replaceFile(222, pubspecFileUri, newContent); await verifyCompletions( @@ -443,8 +442,8 @@ dependencies: ] } '''; - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 0, json, ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 0, json, ''); var content = ''' name: foo @@ -498,8 +497,8 @@ dependencies: ] } '''; - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 0, initialJson, ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 0, initialJson, ''); var content = ''' name: foo @@ -523,8 +522,8 @@ dependencies: // Modify the underlying file which should trigger an update of the // cached data. - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 0, updatedJson, ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 0, updatedJson, ''); modifyFile2(pubspecFile, '$content# trailing comment'); await pumpEventQueue(times: 500); @@ -560,8 +559,8 @@ dependencies: ] } '''; - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 0, initialJson, ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 0, initialJson, ''); var content = ''' name: foo diff --git a/pkg/analysis_server/test/lsp/dart_text_document_content_provider_test.dart b/pkg/analysis_server/test/lsp/dart_text_document_content_provider_test.dart index aef7aa5fb4b..a67ff037965 100644 --- a/pkg/analysis_server/test/lsp/dart_text_document_content_provider_test.dart +++ b/pkg/analysis_server/test/lsp/dart_text_document_content_provider_test.dart @@ -22,12 +22,11 @@ void main() { class DartTextDocumentContentProviderTest extends AbstractLspAnalysisServerTest { @override - AnalysisServerOptions get serverOptions => - AnalysisServerOptions() - ..enabledExperiments = [ - ...super.serverOptions.enabledExperiments, - ...experimentsForTests, - ]; + AnalysisServerOptions get serverOptions => AnalysisServerOptions() + ..enabledExperiments = [ + ...super.serverOptions.enabledExperiments, + ...experimentsForTests, + ]; @override void setUp() { diff --git a/pkg/analysis_server/test/lsp/definition_test.dart b/pkg/analysis_server/test/lsp/definition_test.dart index ffc742056f3..ebc0c5ffa0a 100644 --- a/pkg/analysis_server/test/lsp/definition_test.dart +++ b/pkg/analysis_server/test/lsp/definition_test.dart @@ -23,12 +23,11 @@ void main() { @reflectiveTest class DefinitionTest extends AbstractLspAnalysisServerTest { @override - AnalysisServerOptions get serverOptions => - AnalysisServerOptions() - ..enabledExperiments = [ - ...super.serverOptions.enabledExperiments, - ...experimentsForTests, - ]; + AnalysisServerOptions get serverOptions => AnalysisServerOptions() + ..enabledExperiments = [ + ...super.serverOptions.enabledExperiments, + ...experimentsForTests, + ]; Future test_acrossFiles() async { var mainContents = ''' diff --git a/pkg/analysis_server/test/lsp/diagnostic_test.dart b/pkg/analysis_server/test/lsp/diagnostic_test.dart index ae637193a7c..fc38babef2a 100644 --- a/pkg/analysis_server/test/lsp/diagnostic_test.dart +++ b/pkg/analysis_server/test/lsp/diagnostic_test.dart @@ -268,9 +268,8 @@ void f() { var onePackagePath = convertPath('/home/one'); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'one', rootPath: onePackagePath), + config: PackageConfigFileBuilder() + ..add(name: 'one', rootPath: onePackagePath), ); newFile(convertPath('$onePackagePath/lib/one.dart'), ''' @deprecated @@ -293,9 +292,8 @@ void f() { Future test_diagnosticTag_notSupported() async { var onePackagePath = convertPath('/home/one'); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'one', rootPath: onePackagePath), + config: PackageConfigFileBuilder() + ..add(name: 'one', rootPath: onePackagePath), ); newFile(convertPath('$onePackagePath/lib/one.dart'), ''' @deprecated @@ -616,9 +614,8 @@ linter: var projectPackagePath = '$rootWorkspacePath/my_project'; writePackageConfig( projectPackagePath, - config: - PackageConfigFileBuilder() - ..add(name: 'my_lints', rootPath: lintsPackagePath), + config: PackageConfigFileBuilder() + ..add(name: 'my_lints', rootPath: lintsPackagePath), ); newFile('$projectPackagePath/analysis_options.yaml', ''' include: package:my_lints/analysis_options.yaml @@ -704,7 +701,8 @@ void f(dynamic a) => a.foo(); Future test_stableOrder() async { /// Helper to pad out the content in a way that has previously triggered /// this issue. - String wrappedContent(String content) => ''' + String wrappedContent(String content) => + ''' // // // diff --git a/pkg/analysis_server/test/lsp/document_highlights_test.dart b/pkg/analysis_server/test/lsp/document_highlights_test.dart index 6d2738b37b1..47d387d30ed 100644 --- a/pkg/analysis_server/test/lsp/document_highlights_test.dart +++ b/pkg/analysis_server/test/lsp/document_highlights_test.dart @@ -480,7 +480,8 @@ typedef /*[0*/TD/*0]*/ = String; String loopStart, String loopEnd, ) async { - var content = ''' + var content = + ''' void f() { outer: $loopKeyword $loopStart { @@ -535,12 +536,9 @@ void f() { await initialize(); await openFile(mainFileUri, code.code); - var positions = - code.positions.isNotEmpty - ? code.positions.map((position) => position.position) - : code.ranges.expand( - (range) => [range.range.start, range.range.end], - ); + var positions = code.positions.isNotEmpty + ? code.positions.map((position) => position.position) + : code.ranges.expand((range) => [range.range.start, range.range.end]); for (var position in positions) { var highlights = await getDocumentHighlights(mainFileUri, position); diff --git a/pkg/analysis_server/test/lsp/document_link_test.dart b/pkg/analysis_server/test/lsp/document_link_test.dart index 97ca5c671b1..74c4c298f7b 100644 --- a/pkg/analysis_server/test/lsp/document_link_test.dart +++ b/pkg/analysis_server/test/lsp/document_link_test.dart @@ -264,8 +264,9 @@ dev_dependencies: var links = await getDocumentLinks(fileUri); // Convert the results into the same format as expectedLinksWithRanges. - var linkData = - links!.map((link) => (link.range, link.target?.toString())).toList(); + var linkData = links! + .map((link) => (link.range, link.target?.toString())) + .toList(); expect(linkData, equals(expectedLinksWithRanges)); } diff --git a/pkg/analysis_server/test/lsp/error_or_test.dart b/pkg/analysis_server/test/lsp/error_or_test.dart index 38a130899c8..6cbccb4579c 100644 --- a/pkg/analysis_server/test/lsp/error_or_test.dart +++ b/pkg/analysis_server/test/lsp/error_or_test.dart @@ -167,18 +167,14 @@ class ErrorOrRecord4ExtensionTest { } test_mapResults_result() async { - var result = await ( - success(1), - success(2), - success(3), - success(4), - ).mapResults((a, b, c, d) async { - expect(a, 1); - expect(b, 2); - expect(c, 3); - expect(d, 4); - return success(100); - }); + var result = await (success(1), success(2), success(3), success(4)) + .mapResults((a, b, c, d) async { + expect(a, 1); + expect(b, 2); + expect(c, 3); + expect(d, 4); + return success(100); + }); expect(result.result, 100); } @@ -195,18 +191,14 @@ class ErrorOrRecord4ExtensionTest { } test_mapResultsSync_result() async { - var result = ( - success(1), - success(2), - success(3), - success(4), - ).mapResultsSync((a, b, c, d) { - expect(a, 1); - expect(b, 2); - expect(c, 3); - expect(d, 4); - return success(100); - }); + var result = (success(1), success(2), success(3), success(4)) + .mapResultsSync((a, b, c, d) { + expect(a, 1); + expect(b, 2); + expect(c, 3); + expect(d, 4); + return success(100); + }); expect(result.result, 100); } } diff --git a/pkg/analysis_server/test/lsp/flutter_outline_test.dart b/pkg/analysis_server/test/lsp/flutter_outline_test.dart index 3e076a06ff0..93ee59c04a2 100644 --- a/pkg/analysis_server/test/lsp/flutter_outline_test.dart +++ b/pkg/analysis_server/test/lsp/flutter_outline_test.dart @@ -98,8 +98,9 @@ Widget build(BuildContext context) => Icon(Icons.alarm); // Find the path to our mock 'package:flutter/widgets.dart'. var driver = server.getAnalysisDriver(mainFilePath)!; - var widgetsFilePath = - driver.currentSession.uriConverter.uriToPath(Uri.parse(widgetsUri))!; + var widgetsFilePath = driver.currentSession.uriConverter.uriToPath( + Uri.parse(widgetsUri), + )!; var widgetsFileUri = Uri.file(widgetsFilePath); // We have to provide content to open a file so just read it. diff --git a/pkg/analysis_server/test/lsp/folding_test.dart b/pkg/analysis_server/test/lsp/folding_test.dart index 7133716553b..a7ae93a8701 100644 --- a/pkg/analysis_server/test/lsp/folding_test.dart +++ b/pkg/analysis_server/test/lsp/folding_test.dart @@ -55,17 +55,16 @@ class FoldingTest extends AbstractLspAnalysisServerTest { Map expected, { bool requireAll = true, }) { - var expectedRanges = - expected.entries.map((entry) { - var range = code.ranges[entry.key].range; - return FoldingRange( - startLine: range.start.line, - startCharacter: lineFoldingOnly ? null : range.start.character, - endLine: range.end.line, - endCharacter: lineFoldingOnly ? null : range.end.character, - kind: entry.value, - ); - }).toSet(); + var expectedRanges = expected.entries.map((entry) { + var range = code.ranges[entry.key].range; + return FoldingRange( + startLine: range.start.line, + startCharacter: lineFoldingOnly ? null : range.start.character, + endLine: range.end.line, + endCharacter: lineFoldingOnly ? null : range.end.character, + kind: entry.value, + ); + }).toSet(); if (requireAll) { expect(ranges, expectedRanges); @@ -172,9 +171,8 @@ class AnnotatedDartClass/*[1*/ { await computeRanges( content, uri: pluginAnalyzedUri, - initializePlugin: - () => - configureTestPlugin(notification: pluginResult.toNotification()), + initializePlugin: () => + configureTestPlugin(notification: pluginResult.toNotification()), ); expectRanges({ 0: FoldingRangeKind.Imports, // From plugin @@ -199,9 +197,8 @@ CREATE TABLE foo( await computeRanges( content, uri: pluginAnalyzedUri, - initializePlugin: - () => - configureTestPlugin(notification: pluginResult.toNotification()), + initializePlugin: () => + configureTestPlugin(notification: pluginResult.toNotification()), ); expectRanges({ 0: noFoldingKind, // From plugin diff --git a/pkg/analysis_server/test/lsp/format_test.dart b/pkg/analysis_server/test/lsp/format_test.dart index 5f5401bc5f4..084c7971233 100644 --- a/pkg/analysis_server/test/lsp/format_test.dart +++ b/pkg/analysis_server/test/lsp/format_test.dart @@ -208,8 +208,11 @@ void f () await initialize(); await openFile(mainFileUri, code.code); - var formatEdits = - (await formatOnType(mainFileUri, code.position.position, '}'))!; + var formatEdits = (await formatOnType( + mainFileUri, + code.position.position, + '}', + ))!; var formattedContents = applyTextEdits(code.code, formatEdits); expect(formattedContents, equals(expected)); } diff --git a/pkg/analysis_server/test/lsp/hover_test.dart b/pkg/analysis_server/test/lsp/hover_test.dart index 4faa98860c5..59bff861abf 100644 --- a/pkg/analysis_server/test/lsp/hover_test.dart +++ b/pkg/analysis_server/test/lsp/hover_test.dart @@ -617,7 +617,8 @@ With some [refs] and some ```dart print(); ``` - '''.trim(); + ''' + .trim(); await assertMarkdownContents(content, equals(expectedHoverContent)); } @@ -711,7 +712,8 @@ String? abc Type: `String?` Declared in _package:test/main.dart_. - '''.trim(); + ''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } @@ -873,7 +875,8 @@ void f(aaa) { dynamic aaa ``` Type: `String` - '''.trim(); + ''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } @@ -962,7 +965,8 @@ String? get myField Type: `String?` Declared in `A` in _package:test/main.dart_. -'''.trim(); +''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } @@ -984,7 +988,8 @@ String get myGetter Type: `String` Declared in `A` in _package:test/main.dart_. -'''.trim(); +''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } @@ -1007,7 +1012,8 @@ String? get myGetter Type: `String?` Declared in `A` in _package:test/main.dart_. -'''.trim(); +''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } @@ -1031,7 +1037,8 @@ set mySetter(String value) Type: `String` Declared in `A` in _package:test/main.dart_. -'''.trim(); +''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } @@ -1055,7 +1062,8 @@ set mySetter(String value) Type: `String` Declared in `A` in _package:test/main.dart_. -'''.trim(); +''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } @@ -1073,7 +1081,8 @@ String? abc Type: `String?` Declared in _package:test/main.dart_. - '''.trim(); + ''' + .trim(); await assertStringContents(content, equals(expectedHoverContent)); } diff --git a/pkg/analysis_server/test/lsp/initialization_test.dart b/pkg/analysis_server/test/lsp/initialization_test.dart index 8e8c8e926d3..e972be982ad 100644 --- a/pkg/analysis_server/test/lsp/initialization_test.dart +++ b/pkg/analysis_server/test/lsp/initialization_test.dart @@ -54,8 +54,9 @@ class InitializationTest extends AbstractLspAnalysisServerTest { var registrations = []; await monitorDynamicRegistrations(registrations, initialize); - var registeredMethods = - registrations.map((registration) => registration.method).toSet(); + var registeredMethods = registrations + .map((registration) => registration.method) + .toSet(); var result = expectedResult.map((method) => method.toJson()).toSet(); expect(registeredMethods, equals(result)); @@ -164,10 +165,9 @@ class InitializationTest extends AbstractLspAnalysisServerTest { var nonDartOptions = CompletionRegistrationOptions.fromJson( nonDartRegistration.registerOptions as Map, ); - var otherLanguages = - nonDartOptions.documentSelector! - .map((selector) => selector.language) - .toList(); + var otherLanguages = nonDartOptions.documentSelector! + .map((selector) => selector.language) + .toList(); expect(otherLanguages, isNot(contains('dart'))); expect(nonDartOptions.triggerCharacters, isNull); } @@ -239,52 +239,49 @@ class InitializationTest extends AbstractLspAnalysisServerTest { var registrations = []; await monitorDynamicRegistrations(registrations, initialize); - var knownRegistrationsIds = - registrations.map((registration) => registration.id).toSet(); + var knownRegistrationsIds = registrations + .map((registration) => registration.id) + .toSet(); var numberOfReregistrations = 10; // Listen to incoming registrations, ensure they're not in the set, and add // them. - var registrationsDone = - requestsFromServer - .where((n) => n.method == Method.client_registerCapability) - .take(numberOfReregistrations) - .listen((request) { - respondTo(request, null); - var registrations = - RegistrationParams.fromJson( - request.params as Map, - ).registrations; - for (var registration in registrations) { - var id = registration.id; - if (!knownRegistrationsIds.add(id)) { - throw 'Registration $id was already in the existing set!'; - } - } - }) - .asFuture(); + var registrationsDone = requestsFromServer + .where((n) => n.method == Method.client_registerCapability) + .take(numberOfReregistrations) + .listen((request) { + respondTo(request, null); + var registrations = RegistrationParams.fromJson( + request.params as Map, + ).registrations; + for (var registration in registrations) { + var id = registration.id; + if (!knownRegistrationsIds.add(id)) { + throw 'Registration $id was already in the existing set!'; + } + } + }) + .asFuture(); // Listen to incoming unregistrations, verify they're in the set, and remove // them. - var unregistrationsDone = - requestsFromServer - .where((n) => n.method == Method.client_unregisterCapability) - .take(numberOfReregistrations) - .listen((request) { - respondTo(request, null); - var unregistrations = - UnregistrationParams.fromJson( - request.params as Map, - ).unregisterations; - for (var unregistration in unregistrations) { - var id = unregistration.id; - if (!knownRegistrationsIds.remove(id)) { - throw 'Registration $id was not in the existing set!'; - } - } - }) - .asFuture(); + var unregistrationsDone = requestsFromServer + .where((n) => n.method == Method.client_unregisterCapability) + .take(numberOfReregistrations) + .listen((request) { + respondTo(request, null); + var unregistrations = UnregistrationParams.fromJson( + request.params as Map, + ).unregisterations; + for (var unregistration in unregistrations) { + var id = unregistration.id; + if (!knownRegistrationsIds.remove(id)) { + throw 'Registration $id was not in the existing set!'; + } + } + }) + .asFuture(); // Trigger multiple plugin events that will rebuild the registrations. for (var i = 0; i < numberOfReregistrations; i++) { @@ -627,17 +624,15 @@ class InitializationTest extends AbstractLspAnalysisServerTest { pluginManager.pluginsChangedController.add(null); }, ); - var unregistrations = - UnregistrationParams.fromJson( - unregisterRequest.params as Map, - ).unregisterations; + var unregistrations = UnregistrationParams.fromJson( + unregisterRequest.params as Map, + ).unregisterations; // folding method should have been unregistered as the server now supports // *.foo files for it as well. - var registrationIdForFolding = - registrations - .singleWhere((r) => r.method == 'textDocument/foldingRange') - .id; + var registrationIdForFolding = registrations + .singleWhere((r) => r.method == 'textDocument/foldingRange') + .id; expect( unregistrations, contains( @@ -671,10 +666,9 @@ class InitializationTest extends AbstractLspAnalysisServerTest { pluginManager.pluginsChangedController.add(null); }); - var registrations = - RegistrationParams.fromJson( - request.params as Map, - ).registrations; + var registrations = RegistrationParams.fromJson( + request.params as Map, + ).registrations; var documentFilterSql = TextDocumentFilterScheme( scheme: 'file', @@ -691,10 +685,9 @@ class InitializationTest extends AbstractLspAnalysisServerTest { isA() .having((r) => r.method, 'method', 'textDocument/foldingRange') .having( - (r) => - TextDocumentRegistrationOptions.fromJson( - r.registerOptions as Map, - ).documentSelector, + (r) => TextDocumentRegistrationOptions.fromJson( + r.registerOptions as Map, + ).documentSelector, 'registerOptions.documentSelector', containsAll([documentFilterSql, documentFilterDart]), ), diff --git a/pkg/analysis_server/test/lsp/mapping_test.dart b/pkg/analysis_server/test/lsp/mapping_test.dart index b828db99749..22effa2caac 100644 --- a/pkg/analysis_server/test/lsp/mapping_test.dart +++ b/pkg/analysis_server/test/lsp/mapping_test.dart @@ -108,15 +108,30 @@ class MappingTest extends AbstractLspAnalysisServerTest { void test_relevanceToSortText() { // The expected order is the same as from the highest relevance. - var expectedOrder = - [999999, 1000, 100, 1, 0].map(lsp.relevanceToSortText).toList(); + var expectedOrder = [ + 999999, + 1000, + 100, + 1, + 0, + ].map(lsp.relevanceToSortText).toList(); // Test with inputs in both directions to ensure the results are actually // unique and sorted. - var results1 = - [999999, 1000, 100, 1, 0].map(lsp.relevanceToSortText).toList()..sort(); - var results2 = - [0, 1, 100, 1000, 999999].map(lsp.relevanceToSortText).toList()..sort(); + var results1 = [ + 999999, + 1000, + 100, + 1, + 0, + ].map(lsp.relevanceToSortText).toList()..sort(); + var results2 = [ + 0, + 1, + 100, + 1000, + 999999, + ].map(lsp.relevanceToSortText).toList()..sort(); expect(results1, equals(expectedOrder)); expect(results2, equals(expectedOrder)); diff --git a/pkg/analysis_server/test/lsp/pub_package_service_test.dart b/pkg/analysis_server/test/lsp/pub_package_service_test.dart index cc00967dcca..3393b71c0bf 100644 --- a/pkg/analysis_server/test/lsp/pub_package_service_test.dart +++ b/pkg/analysis_server/test/lsp/pub_package_service_test.dart @@ -57,9 +57,9 @@ class PubApiTest { check_pubHostedUrl('test', pubDefaultUrl); Future test_envPubHostedUrl_missingScheme() => - // It's hard to tell that this is intended to be a valid URL minus the scheme - // so it will fail validation and fall back to the default. - check_pubHostedUrl('pub.example.org', pubDefaultUrl); + // It's hard to tell that this is intended to be a valid URL minus the scheme + // so it will fail validation and fall back to the default. + check_pubHostedUrl('pub.example.org', pubDefaultUrl); Future test_envPubHostedUrl_null() => check_pubHostedUrl(null, pubDefaultUrl); @@ -178,8 +178,8 @@ class PubCommandTest with ResourceProviderMixin { ] } '''; - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 0, validJson, ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 0, validJson, ''); var result = await pubCommand.outdatedVersions(pubspecPath); expect(result, hasLength(1)); var package = result.first; @@ -214,10 +214,9 @@ class PubCommandTest with ResourceProviderMixin { processRunner.startHandler = (executable, args, {dir, env}) { // Return different json based on the directory we were invoked in. - var json = - dir == resourceProvider.pathContext.dirname(pubspecPath) - ? pubspecJson1 - : pubspecJson2; + var json = dir == resourceProvider.pathContext.dirname(pubspecPath) + ? pubspecJson1 + : pubspecJson2; return MockProcess(1, 0, json, ''); }; var result1 = await pubCommand.outdatedVersions(pubspecPath); @@ -227,8 +226,8 @@ class PubCommandTest with ResourceProviderMixin { } Future test_outdated_nonZeroExitCode() async { - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 123, '{}', ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 123, '{}', ''); var result = await pubCommand.outdatedVersions(pubspecPath); expect(result, isEmpty); } @@ -254,8 +253,8 @@ class PubCommandTest with ResourceProviderMixin { ] } '''; - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 0, validJson, ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 0, validJson, ''); var result = await pubCommand.outdatedVersions(pubspecPath); expect(result, hasLength(2)); for (var (index, package) in result.indexed) { @@ -358,8 +357,8 @@ class PubPackageServiceTest extends AbstractLspAnalysisServerTest { } Future test_packageCache_doesNotRetryUnknownException() async { - httpClient.sendHandler = - (BaseRequest request) async => throw UnimplementedError(); + httpClient.sendHandler = (BaseRequest request) async => + throw UnimplementedError(); await initialize(); expectPackages([]); diff --git a/pkg/analysis_server/test/lsp/rename_test.dart b/pkg/analysis_server/test/lsp/rename_test.dart index 736f6ba982e..3be838e7a77 100644 --- a/pkg/analysis_server/test/lsp/rename_test.dart +++ b/pkg/analysis_server/test/lsp/rename_test.dart @@ -856,13 +856,12 @@ class MyNewClass {} version: referencedVersion, ); - var result = - (await rename( - mainFileUri, - mainVersion, - mainCode.position.position, - 'MyNewClass', - ))!; + var result = (await rename( + mainFileUri, + mainVersion, + mainCode.position.position, + 'MyNewClass', + ))!; var expectedVersions = { mainFileUri: mainVersion, @@ -1023,8 +1022,12 @@ final a = new MyNewClass(); await initialize(); await openFile(mainFileUri, code.code, version: 222); - var result = - (await rename(mainFileUri, 222, code.position.position, 'MyNewClass'))!; + var result = (await rename( + mainFileUri, + 222, + code.position.position, + 'MyNewClass', + ))!; verifyEdit(result, expectedContent); } @@ -1153,10 +1156,9 @@ final a = new MyNewClass(); var code = TestCode.parse(content); await initialize( - experimentalCapabilities: - supportsWindowShowMessageRequest - ? const {'supportsWindowShowMessageRequest': true} - : null, + experimentalCapabilities: supportsWindowShowMessageRequest + ? const {'supportsWindowShowMessageRequest': true} + : null, ); await openFile(mainFileUri, code.code, version: openFileVersion); @@ -1189,10 +1191,9 @@ final a = new MyNewClass(); var code = TestCode.parseNormalized(content); await initialize( - experimentalCapabilities: - supportsWindowShowMessageRequest - ? const {'supportsWindowShowMessageRequest': true} - : null, + experimentalCapabilities: supportsWindowShowMessageRequest + ? const {'supportsWindowShowMessageRequest': true} + : null, ); await openFile(mainFileUri, code.code, version: openFileVersion); @@ -1259,10 +1260,9 @@ final a = new MyNewClass(); var code = TestCode.parse(content); await initialize( - experimentalCapabilities: - supportsWindowShowMessageRequest - ? const {'supportsWindowShowMessageRequest': true} - : null, + experimentalCapabilities: supportsWindowShowMessageRequest + ? const {'supportsWindowShowMessageRequest': true} + : null, workspaceFolders: workspaceFolders, ); await openFile(fileUri, code.code, version: documentVersion); @@ -1281,7 +1281,8 @@ final a = new MyNewClass(); // For convenience, if a test doesn't provide an full set of edits // we assume only a single edit of the file that was being modified. if (!expectedContent.startsWith(LspChangeVerifier.editMarkerStart)) { - expectedContent = ''' + expectedContent = + ''' ${LspChangeVerifier.editMarkerStart} ${relativePath(filePath)} $expectedContent'''; } diff --git a/pkg/analysis_server/test/lsp/request_helpers_mixin.dart b/pkg/analysis_server/test/lsp/request_helpers_mixin.dart index 0a48b0db0ef..bd255c16444 100644 --- a/pkg/analysis_server/test/lsp/request_helpers_mixin.dart +++ b/pkg/analysis_server/test/lsp/request_helpers_mixin.dart @@ -348,10 +348,9 @@ mixin LspRequestHelpersMixin { CodeActionTriggerKind? triggerKind, ProgressToken? workDoneToken, }) async { - range ??= - position != null - ? Range(start: position, end: position) - : throw 'Supply either a Range or Position for CodeActions requests'; + range ??= position != null + ? Range(start: position, end: position) + : throw 'Supply either a Range or Position for CodeActions requests'; var request = makeRequest( Method.textDocument_codeAction, CodeActionParams( @@ -386,10 +385,9 @@ mixin LspRequestHelpersMixin { if (kinds != null && kinds.isNotEmpty) { // Kinds must either by an exact match, or start with the // requested value followed by a dot (a sub-kind). - var allowedKinds = - kinds - .expand((kind) => [equals('$kind'), startsWith('$kind.')]) - .toList(); + var allowedKinds = kinds + .expand((kind) => [equals('$kind'), startsWith('$kind.')]) + .toList(); // Only CodeActionLiterals can be checked because bare commands do not // have CodeActionKinds (once they've left the server). @@ -885,10 +883,9 @@ mixin LspRequestHelpersMixin { method: method, params: params is ToJsonable ? params.toJson() : params, jsonrpc: jsonRpcVersion, - clientRequestTime: - includeClientRequestTime - ? DateTime.now().millisecondsSinceEpoch - : null, + clientRequestTime: includeClientRequestTime + ? DateTime.now().millisecondsSinceEpoch + : null, ); } @@ -1150,7 +1147,8 @@ mixin LspRequestHelpersMixin { List Function(List) _fromJsonList( T Function(Map) fromJson, - ) => (input) => input.cast>().map(fromJson).toList(); + ) => + (input) => input.cast>().map(fromJson).toList(); /// Creates a `canParse()` function for an `Either2` using /// the `canParse` function for each type. @@ -1208,12 +1206,10 @@ mixin LspReverseRequestHelpersMixin { var requestFromServer = await firstRequest.timeout( timeout, - onTimeout: - () => - throw TimeoutException( - 'Did not receive the expected $method request from the server in the timeout period', - timeout, - ), + onTimeout: () => throw TimeoutException( + 'Did not receive the expected $method request from the server in the timeout period', + timeout, + ), ); expect(requestFromServer, isNotNull); @@ -1250,29 +1246,30 @@ mixin LspReverseRequestHelpersMixin { Object? outboundRequestError; // Run [f] and wait for the incoming request from the server. - var incomingRequest = await expectRequest(method, () { - // Don't return/await the response yet, as this may not complete until - // after we have handled the request that comes from the server. - outboundRequest = f(); + var incomingRequest = + await expectRequest(method, () { + // Don't return/await the response yet, as this may not complete until + // after we have handled the request that comes from the server. + outboundRequest = f(); - // Because we don't await this future until "later", if it throws the - // error is treated as unhandled and will fail the test even if expected. - // Instead, capture the error and suppress it. But if we time out (in - // which case we will never return outboundRequest), then we'll raise this - // error. - outboundRequest.then( - (_) {}, - onError: (e) { - outboundRequestError = e; - return null; - }, - ); - }, timeout: timeout).catchError((Object timeoutException) { - // We timed out waiting for the request from the server. Probably this is - // because our outbound request for some reason, so if we have an error - // for that, then throw it. Otherwise, propogate the timeout. - throw outboundRequestError ?? timeoutException; - }, test: (e) => e is TimeoutException); + // Because we don't await this future until "later", if it throws the + // error is treated as unhandled and will fail the test even if expected. + // Instead, capture the error and suppress it. But if we time out (in + // which case we will never return outboundRequest), then we'll raise this + // error. + outboundRequest.then( + (_) {}, + onError: (e) { + outboundRequestError = e; + return null; + }, + ); + }, timeout: timeout).catchError((Object timeoutException) { + // We timed out waiting for the request from the server. Probably this is + // because our outbound request for some reason, so if we have an error + // for that, then throw it. Otherwise, propogate the timeout. + throw outboundRequestError ?? timeoutException; + }, test: (e) => e is TimeoutException); // Handle the request from the server and send the response back. var clientsResponse = await handler( @@ -1352,21 +1349,22 @@ mixin LspVerifyEditHelpersMixin }) async { ApplyWorkspaceEditParams? editParams; - var commandResponse = await handleExpectedRequest< - Object?, - ApplyWorkspaceEditParams, - ApplyWorkspaceEditResult - >( - Method.workspace_applyEdit, - ApplyWorkspaceEditParams.fromJson, - function, - handler: (edit) { - // When the server sends the edit back, just keep a copy and say we - // applied successfully (it'll be verified by the caller). - editParams = edit; - return applyEditResult ?? ApplyWorkspaceEditResult(applied: true); - }, - ); + var commandResponse = + await handleExpectedRequest< + Object?, + ApplyWorkspaceEditParams, + ApplyWorkspaceEditResult + >( + Method.workspace_applyEdit, + ApplyWorkspaceEditParams.fromJson, + function, + handler: (edit) { + // When the server sends the edit back, just keep a copy and say we + // applied successfully (it'll be verified by the caller). + editParams = edit; + return applyEditResult ?? ApplyWorkspaceEditResult(applied: true); + }, + ); // Successful edits return an empty success() response. expect(commandResponse, isNull); diff --git a/pkg/analysis_server/test/lsp/selection_range_test.dart b/pkg/analysis_server/test/lsp/selection_range_test.dart index 7511b8bbeeb..ca884d2eb25 100644 --- a/pkg/analysis_server/test/lsp/selection_range_test.dart +++ b/pkg/analysis_server/test/lsp/selection_range_test.dart @@ -37,8 +37,11 @@ void f() { code.position.position, ]); expect(regions!.length, equals(1)); - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, @@ -72,8 +75,11 @@ void f() { code.position.position, ]); expect(regions!.length, equals(1)); - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, @@ -105,8 +111,11 @@ void f() { code.position.position, ]); expect(regions!.length, equals(1)); - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, @@ -141,10 +150,16 @@ class Foo { positionFromOffset(content.indexOf('/*2*/'), content), ]); expect(regions!.length, equals(2)); - var firstTexts = - _getSelectionRangeText(lineInfo, content, regions[0]).toList(); - var secondTexts = - _getSelectionRangeText(lineInfo, content, regions[1]).toList(); + var firstTexts = _getSelectionRangeText( + lineInfo, + content, + regions[0], + ).toList(); + var secondTexts = _getSelectionRangeText( + lineInfo, + content, + regions[1], + ).toList(); expect( firstTexts, @@ -184,8 +199,11 @@ class Foo { code.position.position, ]); expect(regions!.length, equals(1)); // Only one position was sent. - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, @@ -223,8 +241,11 @@ class Foo { code.position.position, ]); expect(regions!.length, equals(1)); // Only one position was sent. - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, @@ -262,8 +283,11 @@ class Foo { code.position.position, ]); expect(regions!.length, equals(1)); // Only one position was sent. - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, @@ -301,8 +325,11 @@ class Foo { code.position.position, ]); expect(regions!.length, equals(1)); // Only one position was sent. - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, @@ -340,8 +367,11 @@ class Foo { code.position.position, ]); expect(regions!.length, equals(1)); // Only one position was sent. - var regionTexts = - _getSelectionRangeText(lineInfo, code.code, regions.first).toList(); + var regionTexts = _getSelectionRangeText( + lineInfo, + code.code, + regions.first, + ).toList(); expect( regionTexts, diff --git a/pkg/analysis_server/test/lsp/semantic_tokens_test.dart b/pkg/analysis_server/test/lsp/semantic_tokens_test.dart index 9c529068394..f8181acefed 100644 --- a/pkg/analysis_server/test/lsp/semantic_tokens_test.dart +++ b/pkg/analysis_server/test/lsp/semantic_tokens_test.dart @@ -3022,10 +3022,9 @@ class _Token { /// args for easy copy/pasting into tests to update expectations. @override String toString() { - var modifiersString = - modifiers.isEmpty - ? '' - : ', [${modifiers.map((m) => 'SemanticTokenModifiers.$m').join(', ')}]'; + var modifiersString = modifiers.isEmpty + ? '' + : ', [${modifiers.map((m) => 'SemanticTokenModifiers.$m').join(', ')}]'; return "('$content', SemanticTokenTypes.$type$modifiersString)"; } } diff --git a/pkg/analysis_server/test/lsp/server_abstract.dart b/pkg/analysis_server/test/lsp/server_abstract.dart index 0d9fdb0f6c5..840392fe790 100644 --- a/pkg/analysis_server/test/lsp/server_abstract.dart +++ b/pkg/analysis_server/test/lsp/server_abstract.dart @@ -121,10 +121,10 @@ abstract class AbstractLspAnalysisServerTest return response == null ? null : { - pluginIsolate: Future.delayed( - respondAfter, - ).then((_) => response.toResponse('-', 1)), - }; + pluginIsolate: Future.delayed( + respondAfter, + ).then((_) => response.toResponse('-', 1)), + }; }; } @@ -457,13 +457,12 @@ mixin ClientCapabilitiesHelperMixin { void setChangeAnnotationSupport([bool supported = true]) { workspaceCapabilities = extendWorkspaceCapabilities(workspaceCapabilities, { 'workspaceEdit': { - 'changeAnnotationSupport': - supported - ? { - // This is set to an empty object to indicate support. We don't - // currently use any of the child properties. - } - : null, + 'changeAnnotationSupport': supported + ? { + // This is set to an empty object to indicate support. We don't + // currently use any of the child properties. + } + : null, }, }); } @@ -501,11 +500,10 @@ mixin ClientCapabilitiesHelperMixin { 'completion': { 'completionItem': { 'insertTextModeSupport': { - 'valueSet': - [ - InsertTextMode.adjustIndentation, - InsertTextMode.asIs, - ].map((k) => k.toJson()).toList(), + 'valueSet': [ + InsertTextMode.adjustIndentation, + InsertTextMode.asIs, + ].map((k) => k.toJson()).toList(), }, }, }, @@ -738,14 +736,13 @@ mixin ClientCapabilitiesHelperMixin { textDocumentCapabilities, { 'codeAction': { - 'codeActionLiteralSupport': - kinds != null - ? { - 'codeActionKind': { - 'valueSet': kinds.map((k) => k.toJson()).toList(), - }, - } - : null, + 'codeActionLiteralSupport': kinds != null + ? { + 'codeActionKind': { + 'valueSet': kinds.map((k) => k.toJson()).toList(), + }, + } + : null, }, }, ); @@ -758,16 +755,15 @@ mixin ClientCapabilitiesHelperMixin { } void setTextDocumentDynamicRegistration(String name) { - var json = - name == 'semanticTokens' - ? SemanticTokensClientCapabilities( - dynamicRegistration: true, - requests: ClientSemanticTokensRequestOptions(), - formats: [], - tokenModifiers: [], - tokenTypes: [], - ).toJson() - : {'dynamicRegistration': true}; + var json = name == 'semanticTokens' + ? SemanticTokensClientCapabilities( + dynamicRegistration: true, + requests: ClientSemanticTokensRequestOptions(), + formats: [], + tokenModifiers: [], + tokenTypes: [], + ).toJson() + : {'dynamicRegistration': true}; textDocumentCapabilities = extendTextDocumentCapabilities( textDocumentCapabilities, {name: json}, @@ -1189,10 +1185,9 @@ mixin LspAnalysisServerTestMixin method: method, params: params, jsonrpc: jsonRpcVersion, - clientRequestTime: - includeClientRequestTime - ? DateTime.now().millisecondsSinceEpoch - : null, + clientRequestTime: includeClientRequestTime + ? DateTime.now().millisecondsSinceEpoch + : null, ); } @@ -1202,10 +1197,9 @@ mixin LspAnalysisServerTestMixin Position pos, String newName, ) { - var docIdentifier = - version != null - ? VersionedTextDocumentIdentifier(version: version, uri: uri) - : TextDocumentIdentifier(uri: uri); + var docIdentifier = version != null + ? VersionedTextDocumentIdentifier(version: version, uri: uri) + : TextDocumentIdentifier(uri: uri); var request = makeRequest( Method.textDocument_rename, RenameParams( @@ -1496,16 +1490,12 @@ mixin LspAnalysisServerTestMixin } if (params.value is Map) { - var isDesiredStatusMessage = - analyzing - ? WorkDoneProgressBegin.canParse( - params.value, - nullLspJsonReporter, - ) - : WorkDoneProgressEnd.canParse( - params.value, - nullLspJsonReporter, - ); + var isDesiredStatusMessage = analyzing + ? WorkDoneProgressBegin.canParse( + params.value, + nullLspJsonReporter, + ) + : WorkDoneProgressEnd.canParse(params.value, nullLspJsonReporter); return isDesiredStatusMessage; } else { diff --git a/pkg/analysis_server/test/lsp/server_test.dart b/pkg/analysis_server/test/lsp/server_test.dart index a4e23f4502b..fd4996c7fc4 100644 --- a/pkg/analysis_server/test/lsp/server_test.dart +++ b/pkg/analysis_server/test/lsp/server_test.dart @@ -60,10 +60,9 @@ class ServerDartFixPromptTest extends AbstractLspAnalysisServerTest { @reflectiveTest class ServerTest extends AbstractLspAnalysisServerTest { - List get currentContextPaths => - server.contextManager.analysisContexts - .map((context) => context.contextRoot.root.path) - .toList(); + List get currentContextPaths => server.contextManager.analysisContexts + .map((context) => context.contextRoot.root.path) + .toList(); @override MemoryResourceProvider get resourceProvider => diff --git a/pkg/analysis_server/test/lsp/signature_help_test.dart b/pkg/analysis_server/test/lsp/signature_help_test.dart index acd6a5b91eb..c2bab8b0434 100644 --- a/pkg/analysis_server/test/lsp/signature_help_test.dart +++ b/pkg/analysis_server/test/lsp/signature_help_test.dart @@ -54,8 +54,11 @@ mixin SignatureHelpMixin on AbstractLspAnalysisServerTest { } await initialAnalysis; - var res = - (await getSignatureHelp(mainFileUri, code.position.position, context))!; + var res = (await getSignatureHelp( + mainFileUri, + code.position.position, + context, + ))!; if (activeParameter != null) { expect(res.activeParameter, activeParameter); diff --git a/pkg/analysis_server/test/lsp/snippets_test.dart b/pkg/analysis_server/test/lsp/snippets_test.dart index 5c077d78f02..85913d22a6c 100644 --- a/pkg/analysis_server/test/lsp/snippets_test.dart +++ b/pkg/analysis_server/test/lsp/snippets_test.dart @@ -18,13 +18,12 @@ void main() { @reflectiveTest class SnippetBuilderTest { Future test_appendChoice() async { - var builder = - SnippetBuilder() - ..appendChoice({r'a'}) - ..appendChoice({r'a', r'b'}) - ..appendChoice({}, placeholderNumber: 6) - ..appendChoice({r'aaa', r'bbb'}, placeholderNumber: 12) - ..appendChoice({r'aaa', r'bbb \ bbb $ bbb | bbb , bbb } bbb'}); + var builder = SnippetBuilder() + ..appendChoice({r'a'}) + ..appendChoice({r'a', r'b'}) + ..appendChoice({}, placeholderNumber: 6) + ..appendChoice({r'aaa', r'bbb'}, placeholderNumber: 12) + ..appendChoice({r'aaa', r'bbb \ bbb $ bbb | bbb , bbb } bbb'}); expect( builder.value, @@ -40,11 +39,10 @@ class SnippetBuilderTest { } Future test_appendPlaceholder() async { - var builder = - SnippetBuilder() - ..appendPlaceholder(r'placeholder $ 1') - ..appendPlaceholder(r'') - ..appendPlaceholder(r'placeholder } 3', placeholderNumber: 6); + var builder = SnippetBuilder() + ..appendPlaceholder(r'placeholder $ 1') + ..appendPlaceholder(r'') + ..appendPlaceholder(r'placeholder } 3', placeholderNumber: 6); expect( builder.value, @@ -55,11 +53,10 @@ class SnippetBuilderTest { } Future test_appendTabStop() async { - var builder = - SnippetBuilder() - ..appendTabStop() - ..appendTabStop(placeholderNumber: 10) - ..appendTabStop(); + var builder = SnippetBuilder() + ..appendTabStop() + ..appendTabStop(placeholderNumber: 10) + ..appendTabStop(); expect( builder.value, @@ -70,11 +67,10 @@ class SnippetBuilderTest { } Future test_appendText() async { - var builder = - SnippetBuilder() - ..appendText(r'text 1') - ..appendText(r'text ${that needs} escaping $0') - ..appendText(r'text 2'); + var builder = SnippetBuilder() + ..appendText(r'text 1') + ..appendText(r'text ${that needs} escaping $0') + ..appendText(r'text 2'); expect( builder.value, @@ -101,9 +97,8 @@ class SnippetBuilderTest { lsp.SnippetPlaceholder(22, 2, suggestions: ['aaa', 'bbb']), ]; - var builder = - SnippetBuilder() - ..appendPlaceholders(code, placeholders, isPreSorted: false); + var builder = SnippetBuilder() + ..appendPlaceholders(code, placeholders, isPreSorted: false); expect(builder.value, r''' 01${1:23}45678 @@ -115,15 +110,14 @@ class SnippetBuilderTest { } Future test_mixed() async { - var builder = - SnippetBuilder() - ..appendText('text1') - ..appendPlaceholder('placeholder') - ..appendText('text2') - ..appendChoice({'aaa', 'bbb'}) - ..appendText('text3') - ..appendTabStop() - ..appendText('text4'); + var builder = SnippetBuilder() + ..appendText('text1') + ..appendPlaceholder('placeholder') + ..appendText('text2') + ..appendChoice({'aaa', 'bbb'}) + ..appendText('text3') + ..appendTabStop() + ..appendText('text4'); expect( builder.value, diff --git a/pkg/analysis_server/test/lsp/source_edits_test.dart b/pkg/analysis_server/test/lsp/source_edits_test.dart index 1066390a7bb..feba3ba355b 100644 --- a/pkg/analysis_server/test/lsp/source_edits_test.dart +++ b/pkg/analysis_server/test/lsp/source_edits_test.dart @@ -321,8 +321,7 @@ Delete 1:24-1:26 /// https://github.com/Dart-Code/Dart-Code/issues/5200 Future test_minimalEdits_comment_multiLine_trailingWhitespace() async { // The initial content has a trailing space on the end of the comment. - var startContent = - TestCode.parse(r''' + var startContent = TestCode.parse(r''' /** * line with trailing whitespace /**/ * line with trailing whitespace /**/ @@ -626,8 +625,10 @@ void g() { end = normalizeSource(end); await parseTestCode(start); - var edits = - generateEditsForFormatting(testParsedResult, range: range).result!; + var edits = generateEditsForFormatting( + testParsedResult, + range: range, + ).result!; expect(edits.toText().trim(), expected.trim()); expect(applyTextEdits(start, edits), expectedFormatResult ?? end); } diff --git a/pkg/analysis_server/test/lsp/type_hierarchy_test.dart b/pkg/analysis_server/test/lsp/type_hierarchy_test.dart index 6b35c2d8013..70b3a44a3d1 100644 --- a/pkg/analysis_server/test/lsp/type_hierarchy_test.dart +++ b/pkg/analysis_server/test/lsp/type_hierarchy_test.dart @@ -435,10 +435,9 @@ class ^E extends D {} while (item != null) { names.add(item.name); var supertypes = await typeHierarchySupertypes(item); - item = - (supertypes != null && supertypes.isNotEmpty) - ? supertypes.single - : null; + item = (supertypes != null && supertypes.isNotEmpty) + ? supertypes.single + : null; } // Check for substituted type args. diff --git a/pkg/analysis_server/test/lsp/will_rename_files_test.dart b/pkg/analysis_server/test/lsp/will_rename_files_test.dart index 597b48ad04f..d30f68537f6 100644 --- a/pkg/analysis_server/test/lsp/will_rename_files_test.dart +++ b/pkg/analysis_server/test/lsp/will_rename_files_test.dart @@ -240,10 +240,9 @@ final a = A(); // Build a mapping of old -> new paths. var pathMappings = { for (final relativeTestPath in relativeTestPaths) - relativeTestPath: - relativeTestPath.contains('not_moving') - ? relativeTestPath - : convertPath('dest/${pathContext.basename(relativeTestPath)}'), + relativeTestPath: relativeTestPath.contains('not_moving') + ? relativeTestPath + : convertPath('dest/${pathContext.basename(relativeTestPath)}'), }; var initialContent = buildFiles(pathMappings.keys.toList()); @@ -269,15 +268,14 @@ final a = A(); // Build expected edits in the format the change verifier uses (to avoid // hard-coding ~100 lines of files/imports here). - var expectedEdits = - expectedContent.entries - .expand( - (entry) => [ - '>>>>>>>>>> lib/${_asUriString(entry.key)}\n', - entry.value, - ], - ) - .join(); + var expectedEdits = expectedContent.entries + .expand( + (entry) => [ + '>>>>>>>>>> lib/${_asUriString(entry.key)}\n', + entry.value, + ], + ) + .join(); // Verify they match what the content would be using the destination paths. verifyEdit(edit, expectedEdits); diff --git a/pkg/analysis_server/test/mocks.dart b/pkg/analysis_server/test/mocks.dart index 4c736bffbcd..81ba17f5e31 100644 --- a/pkg/analysis_server/test/mocks.dart +++ b/pkg/analysis_server/test/mocks.dart @@ -99,8 +99,8 @@ class MockProcessRunner implements ProcessRunner { String? dir, Map? env, }) - startHandler = - (executable, arguments, {dir, env}) => throw UnimplementedError(); + startHandler = (executable, arguments, {dir, env}) => + throw UnimplementedError(); @override dynamic noSuchMethod(Invocation invocation) { diff --git a/pkg/analysis_server/test/search/declarations_test.dart b/pkg/analysis_server/test/search/declarations_test.dart index 3c5429a7adb..1b870a5cb48 100644 --- a/pkg/analysis_server/test/search/declarations_test.dart +++ b/pkg/analysis_server/test/search/declarations_test.dart @@ -240,8 +240,7 @@ void f(bool a, String b) {} /// parent library. Future test_parts() async { var a = newFile('$testPackageLibPath/a.dart', "part 'b.dart';").path; - var b = - newFile('$testPackageLibPath/b.dart', ''' + var b = newFile('$testPackageLibPath/b.dart', ''' part of 'a.dart'; class A {} ''').path; diff --git a/pkg/analysis_server/test/search/element_references_test.dart b/pkg/analysis_server/test/search/element_references_test.dart index 5fb68d67f8f..be963ca9d42 100644 --- a/pkg/analysis_server/test/search/element_references_test.dart +++ b/pkg/analysis_server/test/search/element_references_test.dart @@ -43,29 +43,27 @@ class ElementReferencesTest extends AbstractSearchDomainTest { await findElementReferences(offset: code.position.offset, false); expect(searchElement!.kind, kind); - var expected = - resultKinds.entries.map((entry) { - var index = entry.key; - var kind = entry.value; - var range = code.ranges[index].sourceRange; - return { - 'kind': kind, - 'path': testFile.path, - 'range': range.offset, - 'length': range.length, - }; - }).toSet(); - var actual = - results - .map( - (result) => { - 'kind': result.kind, - 'path': result.location.file, - 'range': result.location.offset, - 'length': result.location.length, - }, - ) - .toSet(); + var expected = resultKinds.entries.map((entry) { + var index = entry.key; + var kind = entry.value; + var range = code.ranges[index].sourceRange; + return { + 'kind': kind, + 'path': testFile.path, + 'range': range.offset, + 'length': range.length, + }; + }).toSet(); + var actual = results + .map( + (result) => { + 'kind': result.kind, + 'path': result.location.file, + 'range': result.location.offset, + 'length': result.location.length, + }, + ) + .toSet(); expect(actual, equals(expected)); } diff --git a/pkg/analysis_server/test/search/member_references_test.dart b/pkg/analysis_server/test/search/member_references_test.dart index 17583fa4426..9fc0542a30b 100644 --- a/pkg/analysis_server/test/search/member_references_test.dart +++ b/pkg/analysis_server/test/search/member_references_test.dart @@ -27,11 +27,10 @@ class MemberReferencesTest extends AbstractSearchDomainTest { name, ).toRequest('0', clientUriConverter: server.uriConverter); var response = await handleSuccessfulRequest(request); - searchId = - SearchFindMemberReferencesResult.fromResponse( - response, - clientUriConverter: server.uriConverter, - ).id; + searchId = SearchFindMemberReferencesResult.fromResponse( + response, + clientUriConverter: server.uriConverter, + ).id; return waitForSearchResults(); } diff --git a/pkg/analysis_server/test/search/top_level_declarations_test.dart b/pkg/analysis_server/test/search/top_level_declarations_test.dart index 7cfea052746..3dbca83934f 100644 --- a/pkg/analysis_server/test/search/top_level_declarations_test.dart +++ b/pkg/analysis_server/test/search/top_level_declarations_test.dart @@ -43,11 +43,10 @@ class TopLevelDeclarationsTest extends AbstractSearchDomainTest { if (response.error != null) { return response.error; } - searchId = - SearchFindTopLevelDeclarationsResult.fromResponse( - response, - clientUriConverter: server.uriConverter, - ).id; + searchId = SearchFindTopLevelDeclarationsResult.fromResponse( + response, + clientUriConverter: server.uriConverter, + ).id; return waitForSearchResults(); } diff --git a/pkg/analysis_server/test/search/type_hierarchy_test.dart b/pkg/analysis_server/test/search/type_hierarchy_test.dart index 5d5f1269204..48d510a08a1 100644 --- a/pkg/analysis_server/test/search/type_hierarchy_test.dart +++ b/pkg/analysis_server/test/search/type_hierarchy_test.dart @@ -230,9 +230,8 @@ class B extends A {} writePackageConfig(convertPath('$packagesRootPath/pkgA')); // reference the package from a project writeTestPackageConfig( - config: - (PackageConfigFileBuilder() - ..add(name: 'pkgA', rootPath: '$packagesRootPath/pkgA')), + config: (PackageConfigFileBuilder() + ..add(name: 'pkgA', rootPath: '$packagesRootPath/pkgA')), ); addTestFile(''' import 'package:pkgA/libA.dart'; @@ -1158,11 +1157,10 @@ class D extends C {} superOnly: true, ).toRequest(requestId, clientUriConverter: server.uriConverter); var response = await serverChannel.simulateRequestFromClient(request); - var items = - SearchGetTypeHierarchyResult.fromResponse( - response, - clientUriConverter: server.uriConverter, - ).hierarchyItems; + var items = SearchGetTypeHierarchyResult.fromResponse( + response, + clientUriConverter: server.uriConverter, + ).hierarchyItems; expect(items, isNull); } diff --git a/pkg/analysis_server/test/services/completion/dart/declaration/uri_test.dart b/pkg/analysis_server/test/services/completion/dart/declaration/uri_test.dart index b2bbece6f54..cb421ff80a1 100644 --- a/pkg/analysis_server/test/services/completion/dart/declaration/uri_test.dart +++ b/pkg/analysis_server/test/services/completion/dart/declaration/uri_test.dart @@ -76,10 +76,9 @@ suggestions var fooRootPath = '$workspaceRootPath/foo'; var barRootPath = '$workspaceRootPath/bar'; writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: fooRootPath) - ..add(name: 'bar', rootPath: barRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: fooRootPath) + ..add(name: 'bar', rootPath: barRootPath), ); newFile('$fooRootPath/lib/foo.dart', ''' library foo; @@ -679,10 +678,9 @@ suggestions var fooRootPath = '$workspaceRootPath/foo'; var barRootPath = '$workspaceRootPath/bar'; writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: fooRootPath) - ..add(name: 'bar', rootPath: barRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: fooRootPath) + ..add(name: 'bar', rootPath: barRootPath), ); newFile('$fooRootPath/lib/foo.dart', ''' @@ -727,10 +725,9 @@ suggestions var fooRootPath = '$workspaceRootPath/foo'; var barRootPath = '$workspaceRootPath/bar'; writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: fooRootPath) - ..add(name: 'bar', rootPath: barRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: fooRootPath) + ..add(name: 'bar', rootPath: barRootPath), ); newFile('$fooRootPath/lib/foo.dart', ''' @@ -759,10 +756,9 @@ suggestions var fooRootPath = '$workspaceRootPath/foo'; var barRootPath = '$workspaceRootPath/bar'; writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: fooRootPath) - ..add(name: 'bar', rootPath: barRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: fooRootPath) + ..add(name: 'bar', rootPath: barRootPath), ); newFile('$fooRootPath/lib/foo.dart', ''' @@ -791,10 +787,9 @@ suggestions var fooRootPath = '$workspaceRootPath/foo'; var barRootPath = '$workspaceRootPath/bar'; writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: fooRootPath) - ..add(name: 'bar', rootPath: barRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: fooRootPath) + ..add(name: 'bar', rootPath: barRootPath), ); newFile('$fooRootPath/lib/foo.dart', ''' @@ -823,8 +818,8 @@ suggestions Future test_import_package_missing_lib() async { var barRootPath = '$workspaceRootPath/bar'; writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'bar', rootPath: barRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'bar', rootPath: barRootPath), ); await computeSuggestions(''' import "p^" class @@ -852,10 +847,9 @@ suggestions var fooRootPath = '$workspaceRootPath/foo'; var barRootPath = '$workspaceRootPath/bar'; writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: fooRootPath) - ..add(name: 'bar', rootPath: barRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: fooRootPath) + ..add(name: 'bar', rootPath: barRootPath), ); newFile('$fooRootPath/lib/foo.dart', ''' diff --git a/pkg/analysis_server/test/services/completion/dart/location/argument_list_test.dart b/pkg/analysis_server/test/services/completion/dart/location/argument_list_test.dart index 5167e7cfa66..d3602564936 100644 --- a/pkg/analysis_server/test/services/completion/dart/location/argument_list_test.dart +++ b/pkg/analysis_server/test/services/completion/dart/location/argument_list_test.dart @@ -906,10 +906,9 @@ suggestions required String arguments, required void Function(String) check, }) async { - var languageVersionLine = - languageVersion != null - ? '// @dart = $languageVersion' - : '// no language version override'; + var languageVersionLine = languageVersion != null + ? '// @dart = $languageVersion' + : '// no language version override'; Future computeAndCheck(String code, String where) async { await computeSuggestions(code); diff --git a/pkg/analysis_server/test/services/completion/dart/location/block_test.dart b/pkg/analysis_server/test/services/completion/dart/location/block_test.dart index ae2df168e73..a8a9da8b9c1 100644 --- a/pkg/analysis_server/test/services/completion/dart/location/block_test.dart +++ b/pkg/analysis_server/test/services/completion/dart/location/block_test.dart @@ -64,7 +64,8 @@ mixin BlockTestCases on AbstractCompletionDriverTest { Future test_flutter_setState_indent6_hasPrefix() async { await _check_flutter_setState( line: '${spaces_6}setSt^', - expected: ''' + expected: + ''' replacement left: 5 suggestions @@ -80,7 +81,8 @@ $spaces_6}); Future test_flutter_setState_indent_hasPrefix() async { await _check_flutter_setState( line: '${spaces_4}setSt^', - expected: ''' + expected: + ''' replacement left: 5 suggestions @@ -96,7 +98,8 @@ $spaces_4}); Future test_flutter_setState_indent_noPrefix() async { await _check_flutter_setState( line: '$spaces_4^', - expected: ''' + expected: + ''' suggestions setState(() { $spaces_6 diff --git a/pkg/analysis_server/test/services/completion/dart/location/class_body_test.dart b/pkg/analysis_server/test/services/completion/dart/location/class_body_test.dart index b0ad64debfd..72a31f2a886 100644 --- a/pkg/analysis_server/test/services/completion/dart/location/class_body_test.dart +++ b/pkg/analysis_server/test/services/completion/dart/location/class_body_test.dart @@ -1690,16 +1690,15 @@ class _Context { this.isMixin = false, }); - String get where => - isClass - ? ' in class' - : isEnum - ? ' in enum' - : isExtension - ? ' in extension' - : isExtensionType - ? ' in extension type' - : ' in mixin'; + String get where => isClass + ? ' in class' + : isEnum + ? ' in enum' + : isExtension + ? ' in extension' + : isExtensionType + ? ' in extension type' + : ' in mixin'; } extension on Iterable { diff --git a/pkg/analysis_server/test/services/completion/dart/location/directive_uri_test.dart b/pkg/analysis_server/test/services/completion/dart/location/directive_uri_test.dart index 75b6218fb8b..873f25243a8 100644 --- a/pkg/analysis_server/test/services/completion/dart/location/directive_uri_test.dart +++ b/pkg/analysis_server/test/services/completion/dart/location/directive_uri_test.dart @@ -89,10 +89,9 @@ import '$uriContent'; newFile('$packagesRootPath/bar/lib/bar01.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: fooPackageRoot.path) - ..add(name: 'bar', rootPath: barPackageRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: fooPackageRoot.path) + ..add(name: 'bar', rootPath: barPackageRoot.path), ); } } diff --git a/pkg/analysis_server/test/services/completion/dart/location/property_access_expression_test.dart b/pkg/analysis_server/test/services/completion/dart/location/property_access_expression_test.dart index d9d8bb7ad9e..782ba803670 100644 --- a/pkg/analysis_server/test/services/completion/dart/location/property_access_expression_test.dart +++ b/pkg/analysis_server/test/services/completion/dart/location/property_access_expression_test.dart @@ -189,9 +189,8 @@ class A { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'other', rootPath: otherRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'other', rootPath: otherRoot.path), meta: true, ); @@ -543,9 +542,8 @@ class A { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'other', rootPath: otherRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'other', rootPath: otherRoot.path), meta: true, ); @@ -578,9 +576,8 @@ class A { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'other', rootPath: otherRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'other', rootPath: otherRoot.path), meta: true, ); diff --git a/pkg/analysis_server/test/services/refactoring/agnostic/change_method_signature_test.dart b/pkg/analysis_server/test/services/refactoring/agnostic/change_method_signature_test.dart index 276b6538220..3bca7199027 100644 --- a/pkg/analysis_server/test/services/refactoring/agnostic/change_method_signature_test.dart +++ b/pkg/analysis_server/test/services/refactoring/agnostic/change_method_signature_test.dart @@ -115,10 +115,9 @@ class AbstractChangeMethodSignatureTest extends AbstractContextTest { if (reference != null) { return _referenceToString(reference); } else if (element is FormalParameterElement) { - var enclosingStr = - enclosingElement != null - ? _elementToReferenceString(enclosingElement) - : 'root'; + var enclosingStr = enclosingElement != null + ? _elementToReferenceString(enclosingElement) + : 'root'; return '$enclosingStr::@parameter::${element.name}'; } else { return '${element.name}'; @@ -612,9 +611,8 @@ void test(int a, int b) {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$packagesRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$packagesRootPath/foo'), ); var availability = await _analyzeAvailability(r''' diff --git a/pkg/analysis_server/test/services/refactoring/legacy/extract_method_test.dart b/pkg/analysis_server/test/services/refactoring/legacy/extract_method_test.dart index 7f864cca734..530dc239f5a 100644 --- a/pkg/analysis_server/test/services/refactoring/legacy/extract_method_test.dart +++ b/pkg/analysis_server/test/services/refactoring/legacy/extract_method_test.dart @@ -242,10 +242,9 @@ class A {} newFile('$workspaceRootPath/bbb/lib/bbb.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa') - ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa') + ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb'), ); await resolveTestCode(''' @@ -270,10 +269,9 @@ import 'package:bbb/bbb.dart'; newFile('$workspaceRootPath/bbb/lib/bbb.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa') - ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa') + ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb'), ); await resolveTestCode(''' @@ -300,12 +298,11 @@ import 'package:bbb/bbb.dart'; newFile('$workspaceRootPath/ddd/lib/ddd.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa') - ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb') - ..add(name: 'ccc', rootPath: '$workspaceRootPath/ccc') - ..add(name: 'ddd', rootPath: '$workspaceRootPath/ddd'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa') + ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb') + ..add(name: 'ccc', rootPath: '$workspaceRootPath/ccc') + ..add(name: 'ddd', rootPath: '$workspaceRootPath/ddd'), ); await resolveTestCode(''' diff --git a/pkg/analysis_server/test/services/refactoring/legacy/inline_local_test.dart b/pkg/analysis_server/test/services/refactoring/legacy/inline_local_test.dart index 3209e777ae8..47f21849729 100644 --- a/pkg/analysis_server/test/services/refactoring/legacy/inline_local_test.dart +++ b/pkg/analysis_server/test/services/refactoring/legacy/inline_local_test.dart @@ -379,7 +379,8 @@ a'''; $a bbb'''; } -""".replaceAll('\n', '\r\n'), +""" + .replaceAll('\n', '\r\n'), ); _createRefactoring('a ='); // validate change @@ -392,7 +393,8 @@ a a bbb'''; } -""".replaceAll('\n', '\r\n'), +""" + .replaceAll('\n', '\r\n'), ); } diff --git a/pkg/analysis_server/test/services/refactoring/legacy/rename_class_member_test.dart b/pkg/analysis_server/test/services/refactoring/legacy/rename_class_member_test.dart index 0cfba9d186a..cfa5a2bff04 100644 --- a/pkg/analysis_server/test/services/refactoring/legacy/rename_class_member_test.dart +++ b/pkg/analysis_server/test/services/refactoring/legacy/rename_class_member_test.dart @@ -1103,9 +1103,8 @@ processObj(p) { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$packagesRootPath/aaa'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$packagesRootPath/aaa'), ); await indexTestUnit(''' @@ -1187,9 +1186,8 @@ void foo(A a) { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), ); await indexTestUnit(''' diff --git a/pkg/analysis_server/test/services/refactoring/legacy/rename_unit_member_test.dart b/pkg/analysis_server/test/services/refactoring/legacy/rename_unit_member_test.dart index 97dbdeae965..897c1d34d50 100644 --- a/pkg/analysis_server/test/services/refactoring/legacy/rename_unit_member_test.dart +++ b/pkg/analysis_server/test/services/refactoring/legacy/rename_unit_member_test.dart @@ -263,9 +263,8 @@ class A {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), ); await indexTestUnit(''' diff --git a/pkg/analysis_server/test/services/search/hierarchy_test.dart b/pkg/analysis_server/test/services/search/hierarchy_test.dart index 8dbb1737570..6816da82290 100644 --- a/pkg/analysis_server/test/services/search/hierarchy_test.dart +++ b/pkg/analysis_server/test/services/search/hierarchy_test.dart @@ -135,8 +135,9 @@ class C extends B { await resolveTestCode(sb.toString()); var classLast = findElement2.class_('X$last'); - var member = - classLast.methods.where((element) => element.name == 'foo').single; + var member = classLast.methods + .where((element) => element.name == 'foo') + .single; OperationPerformanceImpl performance = OperationPerformanceImpl(''); var result = await performance.runAsync( 'getHierarchyMembers', diff --git a/pkg/analysis_server/test/services/search/search_engine_test.dart b/pkg/analysis_server/test/services/search/search_engine_test.dart index 1291a1109d0..0ba61e4ad28 100644 --- a/pkg/analysis_server/test/services/search/search_engine_test.dart +++ b/pkg/analysis_server/test/services/search/search_engine_test.dart @@ -412,13 +412,11 @@ T b; Future test_searchReferences_discover_owned() async { var aaaRootPath = _configureForPackage_aaa(); - var a = - newFile('$aaaRootPath/lib/a.dart', ''' + var a = newFile('$aaaRootPath/lib/a.dart', ''' int a; ''').path; - var t = - newFile('$testPackageLibPath/lib/t.dart', ''' + var t = newFile('$testPackageLibPath/lib/t.dart', ''' import 'package:aaa/a.dart'; int t; ''').path; @@ -426,8 +424,9 @@ int t; var coreLibResult = await driverFor(testFile).getLibraryByUri('dart:core') as LibraryElementResult; - var intElement = - coreLibResult.element.classes.firstWhereOrNull((e) => e.name == 'int')!; + var intElement = coreLibResult.element.classes.firstWhereOrNull( + (e) => e.name == 'int', + )!; var matches = await searchEngine.searchReferences(intElement); @@ -740,8 +739,8 @@ class B extends A {} writePackageConfig(aaaRootPath, config: PackageConfigFileBuilder()); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRootPath), ); return aaaRootPath; diff --git a/pkg/analysis_server/test/services/snippets/dart/main_function_test.dart b/pkg/analysis_server/test/services/snippets/dart/main_function_test.dart index c0a27c0f898..bae9da35c56 100644 --- a/pkg/analysis_server/test/services/snippets/dart/main_function_test.dart +++ b/pkg/analysis_server/test/services/snippets/dart/main_function_test.dart @@ -54,7 +54,8 @@ class MainFunctionTest extends DartSnippetProducerTest { }) async { testFilePath = file; var expectedParams = expectArgsParameter ? 'List args' : ''; - var expectedCode = ''' + var expectedCode = + ''' void main($expectedParams) { ^ }'''; diff --git a/pkg/analysis_server/test/services/snippets/dart/test_support.dart b/pkg/analysis_server/test/services/snippets/dart/test_support.dart index addbcd674bf..13c2683f802 100644 --- a/pkg/analysis_server/test/services/snippets/dart/test_support.dart +++ b/pkg/analysis_server/test/services/snippets/dart/test_support.dart @@ -59,20 +59,20 @@ abstract class DartSnippetProducerTest extends AbstractSingleUnitTest { expect(selection.offset, expectedCode.position.offset); // Verify all linked edits/placeholders. - var expectedLinkedGroups = - expectedCode.ranges - .map( - (range) => { - 'positions': [ - {'file': testFile.path, 'offset': range.sourceRange.offset}, - ], - 'length': range.sourceRange.length, - 'suggestions': [], - }, - ) - .toSet(); - var actualLinkedGroups = - snippet.change.linkedEditGroups.map((group) => group.toJson()).toSet(); + var expectedLinkedGroups = expectedCode.ranges + .map( + (range) => { + 'positions': [ + {'file': testFile.path, 'offset': range.sourceRange.offset}, + ], + 'length': range.sourceRange.length, + 'suggestions': [], + }, + ) + .toSet(); + var actualLinkedGroups = snippet.change.linkedEditGroups + .map((group) => group.toJson()) + .toSet(); expect(actualLinkedGroups, equals(expectedLinkedGroups)); return snippet; diff --git a/pkg/analysis_server/test/services/user_prompts/dart_fix_prompt_manager_test.dart b/pkg/analysis_server/test/services/user_prompts/dart_fix_prompt_manager_test.dart index 035f24224ef..5a576cba982 100644 --- a/pkg/analysis_server/test/services/user_prompts/dart_fix_prompt_manager_test.dart +++ b/pkg/analysis_server/test/services/user_prompts/dart_fix_prompt_manager_test.dart @@ -394,15 +394,14 @@ class TestServer implements LspAnalysisServer { (executeCommandHandler as TestExecuteCommandHandler).lastParams!; @override - UserPromptSender? get userPromptSender => - supportsShowMessageRequest - ? (_, promptText, promptActions) async { - lastPromptText = promptText; - lastPromptActions = promptActions; - assert(promptActions.contains(respondToPromptWithAction)); - return respondToPromptWithAction; - } - : null; + UserPromptSender? get userPromptSender => supportsShowMessageRequest + ? (_, promptText, promptActions) async { + lastPromptText = promptText; + lastPromptActions = promptActions; + assert(promptActions.contains(respondToPromptWithAction)); + return respondToPromptWithAction; + } + : null; @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); diff --git a/pkg/analysis_server/test/shared/shared_code_actions_assists_tests.dart b/pkg/analysis_server/test/shared/shared_code_actions_assists_tests.dart index dd235e0187e..25c1fa4ffae 100644 --- a/pkg/analysis_server/test/shared/shared_code_actions_assists_tests.dart +++ b/pkg/analysis_server/test/shared/shared_code_actions_assists_tests.dart @@ -346,17 +346,16 @@ build() { // Also ensure there was a single edit that was correctly marked // as a SnippetTextEdit. - var textEdits = - extractTextDocumentEdits(verifier.edit.documentChanges!) - .expand((tde) => tde.edits) - .map( - (edit) => edit.map( - (e) => throw 'Expected SnippetTextEdit, got AnnotatedTextEdit', - (e) => e, - (e) => throw 'Expected SnippetTextEdit, got TextEdit', - ), - ) - .toList(); + var textEdits = extractTextDocumentEdits(verifier.edit.documentChanges!) + .expand((tde) => tde.edits) + .map( + (edit) => edit.map( + (e) => throw 'Expected SnippetTextEdit, got AnnotatedTextEdit', + (e) => e, + (e) => throw 'Expected SnippetTextEdit, got TextEdit', + ), + ) + .toList(); expect(textEdits, hasLength(1)); expect(textEdits.first.insertTextFormat, equals(InsertTextFormat.Snippet)); } @@ -390,11 +389,10 @@ build() { // Extract just TextDocumentEdits, create/rename/delete are not relevant. var edit = assist.edit!; var textDocumentEdits = extractTextDocumentEdits(edit.documentChanges!); - var textEdits = - textDocumentEdits - .expand((tde) => tde.edits) - .map((edit) => edit.map((e) => e, (e) => e, (e) => e)) - .toList(); + var textEdits = textDocumentEdits + .expand((tde) => tde.edits) + .map((edit) => edit.map((e) => e, (e) => e, (e) => e)) + .toList(); // Ensure the edit does _not_ have a format of Snippet, nor does it include // any $ characters that would indicate snippet text. @@ -460,17 +458,16 @@ void f() { // Also ensure there was a single edit that was correctly marked // as a SnippetTextEdit. - var textEdits = - extractTextDocumentEdits(verifier.edit.documentChanges!) - .expand((tde) => tde.edits) - .map( - (edit) => edit.map( - (e) => throw 'Expected SnippetTextEdit, got AnnotatedTextEdit', - (e) => e, - (e) => throw 'Expected SnippetTextEdit, got TextEdit', - ), - ) - .toList(); + var textEdits = extractTextDocumentEdits(verifier.edit.documentChanges!) + .expand((tde) => tde.edits) + .map( + (edit) => edit.map( + (e) => throw 'Expected SnippetTextEdit, got AnnotatedTextEdit', + (e) => e, + (e) => throw 'Expected SnippetTextEdit, got TextEdit', + ), + ) + .toList(); expect(textEdits, hasLength(1)); expect(textEdits.first.insertTextFormat, equals(InsertTextFormat.Snippet)); } diff --git a/pkg/analysis_server/test/shared/shared_code_actions_fixes_tests.dart b/pkg/analysis_server/test/shared/shared_code_actions_fixes_tests.dart index c43a5c6698b..700073b5768 100644 --- a/pkg/analysis_server/test/shared/shared_code_actions_fixes_tests.dart +++ b/pkg/analysis_server/test/shared/shared_code_actions_fixes_tests.dart @@ -516,12 +516,11 @@ Future foo; testFileUri, range: code.range.range, ); - var fixAction = - findCodeActionLiteral( - codeActions, - title: 'Remove unused import', - kind: CodeActionKind('quickfix.remove.unusedImport'), - )!; + var fixAction = findCodeActionLiteral( + codeActions, + title: 'Remove unused import', + kind: CodeActionKind('quickfix.remove.unusedImport'), + )!; await executeCommand(fixAction.command!); expectCommandLogged('dart.fix.remove.unusedImport'); @@ -580,12 +579,11 @@ void f() { testFileUri, position: code.position.position, ); - var removeNnaAction = - findCodeActionLiteral( - codeActions, - title: "Remove the '!'", - kind: CodeActionKind('quickfix.remove.nonNullAssertion'), - )!; + var removeNnaAction = findCodeActionLiteral( + codeActions, + title: "Remove the '!'", + kind: CodeActionKind('quickfix.remove.nonNullAssertion'), + )!; // Ensure the action is for the diagnostic on the second bang which was // closest to the range requested. @@ -608,12 +606,11 @@ var a = [Test, Test, Te[!!]st]; testFileUri, range: code.range.range, ); - var createClassAction = - findCodeActionLiteral( - codeActions, - title: "Create class 'Test'", - kind: CodeActionKind('quickfix.create.class.uppercase'), - )!; + var createClassAction = findCodeActionLiteral( + codeActions, + title: "Create class 'Test'", + kind: CodeActionKind('quickfix.create.class.uppercase'), + )!; expect(createClassAction.diagnostics, hasLength(3)); } @@ -630,12 +627,11 @@ var a = [Test, Test, Te[!!]st]; testFileUri, range: code.range.range, ); - var createClassActions = - findCodeActionLiteral( - codeActions, - title: "Create class 'Test'", - kind: CodeActionKind('quickfix.create.class.uppercase'), - )!; + var createClassActions = findCodeActionLiteral( + codeActions, + title: "Create class 'Test'", + kind: CodeActionKind('quickfix.create.class.uppercase'), + )!; expect(createClassActions.diagnostics, hasLength(3)); } @@ -691,7 +687,8 @@ ProcessInfo b; Future test_pubspec() async { const content = '^'; - var expectedContent = ''' + var expectedContent = + ''' name: $testPackageName '''; diff --git a/pkg/analysis_server/test/shared/shared_code_actions_refactor_tests.dart b/pkg/analysis_server/test/shared/shared_code_actions_refactor_tests.dart index 97e406544c4..4432baa3e1a 100644 --- a/pkg/analysis_server/test/shared/shared_code_actions_refactor_tests.dart +++ b/pkg/analysis_server/test/shared/shared_code_actions_refactor_tests.dart @@ -706,7 +706,8 @@ class MyWidget extends StatelessWidget { } } '''; - var expectedContent = ''' + var expectedContent = + ''' import 'package:flutter/material.dart'; class MyWidget extends StatelessWidget { diff --git a/pkg/analysis_server/test/shared/shared_code_actions_source_tests.dart b/pkg/analysis_server/test/shared/shared_code_actions_source_tests.dart index ef7d3aa67ff..b993a22d635 100644 --- a/pkg/analysis_server/test/shared/shared_code_actions_source_tests.dart +++ b/pkg/analysis_server/test/shared/shared_code_actions_source_tests.dart @@ -239,23 +239,23 @@ String? a; ); var command = codeAction.command!; - var commandResponse = handleExpectedRequest< - Object?, - ApplyWorkspaceEditParams, - ApplyWorkspaceEditResult - >( - Method.workspace_applyEdit, - ApplyWorkspaceEditParams.fromJson, - () => executeCommand(command), - // Claim that we failed tpo apply the edits. This is what the client - // would do if the edits provided were for an old version of the - // document. - handler: - (edit) => ApplyWorkspaceEditResult( + var commandResponse = + handleExpectedRequest< + Object?, + ApplyWorkspaceEditParams, + ApplyWorkspaceEditResult + >( + Method.workspace_applyEdit, + ApplyWorkspaceEditParams.fromJson, + () => executeCommand(command), + // Claim that we failed tpo apply the edits. This is what the client + // would do if the edits provided were for an old version of the + // document. + handler: (edit) => ApplyWorkspaceEditResult( applied: false, failureReason: 'Document changed', ), - ); + ); // Ensure the request returned an error (error responses are thrown by // the test helper to make consuming success results simpler). diff --git a/pkg/analysis_server/test/shared/shared_edit_argument_tests.dart b/pkg/analysis_server/test/shared/shared_edit_argument_tests.dart index 1298fc0e8e8..d3a88d53358 100644 --- a/pkg/analysis_server/test/shared/shared_edit_argument_tests.dart +++ b/pkg/analysis_server/test/shared/shared_edit_argument_tests.dart @@ -900,7 +900,8 @@ const myConst = E.one; String? additionalCode, }) async { additionalCode ??= ''; - var content = ''' + var content = + ''' import 'package:flutter/widgets.dart'; $additionalCode @@ -933,7 +934,8 @@ class MyWidget extends StatelessWidget { String? additionalCode = '', String? fileComment = '', }) async { - var content = ''' + var content = + ''' $fileComment import 'package:flutter/widgets.dart'; @@ -946,7 +948,8 @@ class MyWidget extends StatelessWidget { Widget build(BuildContext context) => MyW^idget$originalArgs; } '''; - var expectedContent = ''' + var expectedContent = + ''' >>>>>>>>>> lib/test.dart $fileComment import 'package:flutter/widgets.dart'; diff --git a/pkg/analysis_server/test/shared/shared_editable_arguments_tests.dart b/pkg/analysis_server/test/shared/shared_editable_arguments_tests.dart index f7808c90fb0..0bb2a810e44 100644 --- a/pkg/analysis_server/test/shared/shared_editable_arguments_tests.dart +++ b/pkg/analysis_server/test/shared/shared_editable_arguments_tests.dart @@ -121,10 +121,9 @@ $content isTrue, ) .having( - (arg) => - arg.type == 'enum' - ? (arg.options?.isNotEmpty ?? false) - : arg.options == null, + (arg) => arg.type == 'enum' + ? (arg.options?.isNotEmpty ?? false) + : arg.options == null, 'enum types must have options / non-enums must not have options', isTrue, ); diff --git a/pkg/analysis_server/test/src/cider/cider_service.dart b/pkg/analysis_server/test/src/cider/cider_service.dart index fd317858320..ec04eaf4c01 100644 --- a/pkg/analysis_server/test/src/cider/cider_service.dart +++ b/pkg/analysis_server/test/src/cider/cider_service.dart @@ -33,8 +33,10 @@ class CiderServiceTest with ResourceProviderMixin { createMockSdk(resourceProvider: resourceProvider, root: sdkRoot); var sdk = FolderBasedDartSdk(resourceProvider, sdkRoot); - var workspace = - BlazeWorkspace.find(resourceProvider, convertPath(testPath))!; + var workspace = BlazeWorkspace.find( + resourceProvider, + convertPath(testPath), + )!; fileResolver = FileResolver( logger: logger, diff --git a/pkg/analysis_server/test/src/computer/color_computer_test.dart b/pkg/analysis_server/test/src/computer/color_computer_test.dart index b1b35fed7ae..ef2e46ec97d 100644 --- a/pkg/analysis_server/test/src/computer/color_computer_test.dart +++ b/pkg/analysis_server/test/src/computer/color_computer_test.dart @@ -138,8 +138,9 @@ class ColorComputerTest extends AbstractContextTest { String? otherCode, }) async { dartCode = _withCommonImportsNormalized(dartCode); - otherCode = - otherCode != null ? _withCommonImportsNormalized(otherCode) : null; + otherCode = otherCode != null + ? _withCommonImportsNormalized(otherCode) + : null; newFile(testPath, dartCode); if (otherCode != null) { diff --git a/pkg/analysis_server/test/src/computer/folding_computer_test.dart b/pkg/analysis_server/test/src/computer/folding_computer_test.dart index 8b8fcb449fc..22eecea6647 100644 --- a/pkg/analysis_server/test/src/computer/folding_computer_test.dart +++ b/pkg/analysis_server/test/src/computer/folding_computer_test.dart @@ -44,18 +44,14 @@ class FoldingComputerTest extends AbstractContextTest { Map expected, { Set? onlyVerify, }) { - var expectedRegions = - expected.entries.map((entry) { - var range = code.ranges[entry.key].sourceRange; - return FoldingRegion(entry.value, range.offset, range.length); - }).toSet(); + var expectedRegions = expected.entries.map((entry) { + var range = code.ranges[entry.key].sourceRange; + return FoldingRegion(entry.value, range.offset, range.length); + }).toSet(); - var actualRegions = - onlyVerify == null - ? regions.toSet() - : regions - .where((region) => onlyVerify.contains(region.kind)) - .toSet(); + var actualRegions = onlyVerify == null + ? regions.toSet() + : regions.where((region) => onlyVerify.contains(region.kind)).toSet(); expect(actualRegions, expectedRegions); } diff --git a/pkg/analysis_server/test/src/computer/import_elements_computer_test.dart b/pkg/analysis_server/test/src/computer/import_elements_computer_test.dart index 5dfc976b487..e3d4c331f7f 100644 --- a/pkg/analysis_server/test/src/computer/import_elements_computer_test.dart +++ b/pkg/analysis_server/test/src/computer/import_elements_computer_test.dart @@ -111,9 +111,8 @@ void f() { var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -132,9 +131,8 @@ import 'package:pkg/foo.dart'; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -153,9 +151,8 @@ import 'package:pkg/foo.dart' as foo; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -175,9 +172,8 @@ import 'package:pkg/foo.dart' as foo; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -195,9 +191,8 @@ import 'package:pkg/foo.dart' show A, B, C hide D; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -215,9 +210,8 @@ import 'package:pkg/foo.dart' show B, A; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -237,9 +231,8 @@ import 'package:pkg/foo.dart' as foo show B, A; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -255,9 +248,8 @@ import 'package:pkg/foo.dart'; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -273,9 +265,8 @@ import 'package:pkg/foo.dart' as foo; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -303,9 +294,8 @@ class A { var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -330,9 +320,8 @@ import 'package:pkg/foo.dart'; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -350,9 +339,8 @@ import 'package:pkg/foo.dart' hide B, C; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -370,9 +358,8 @@ import 'package:pkg/foo.dart' hide A, B; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -390,9 +377,8 @@ import 'package:pkg/foo.dart' hide A, C; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -410,9 +396,8 @@ import 'package:pkg/foo.dart' hide A, C hide A, C; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -430,9 +415,8 @@ import 'package:pkg/foo.dart' hide B, C hide D, F hide G, H; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -450,9 +434,8 @@ import 'package:pkg/foo.dart' hide B hide C; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -470,9 +453,8 @@ import 'package:pkg/foo.dart' hide A hide B; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -490,9 +472,8 @@ import 'package:pkg/foo.dart' hide A hide C; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' @@ -510,9 +491,8 @@ import 'package:pkg/foo.dart'; var fooFile = newFile('$workspaceRootPath/pkg/lib/foo.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await createBuilder(''' diff --git a/pkg/analysis_server/test/src/computer/imported_elements_computer_test.dart b/pkg/analysis_server/test/src/computer/imported_elements_computer_test.dart index 149c9ea0300..dfcbcfa27a1 100644 --- a/pkg/analysis_server/test/src/computer/imported_elements_computer_test.dart +++ b/pkg/analysis_server/test/src/computer/imported_elements_computer_test.dart @@ -223,9 +223,8 @@ class B { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' @@ -249,9 +248,8 @@ class Foo { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' @@ -275,9 +273,8 @@ class Foo { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' @@ -299,9 +296,8 @@ String foo() => ''; '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' @@ -323,9 +319,8 @@ String foo = ''; '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' @@ -347,9 +342,8 @@ String foo = ''; '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' @@ -373,9 +367,8 @@ class Foo { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' @@ -400,9 +393,8 @@ class Foo { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: '$workspaceRootPath/foo'), ); var content = ''' diff --git a/pkg/analysis_server/test/src/computer/selection_range_computer_test.dart b/pkg/analysis_server/test/src/computer/selection_range_computer_test.dart index 9fdebae3e3c..3eb344ec632 100644 --- a/pkg/analysis_server/test/src/computer/selection_range_computer_test.dart +++ b/pkg/analysis_server/test/src/computer/selection_range_computer_test.dart @@ -639,15 +639,12 @@ void f() { /// Checks the text of [regions] against [expected]. void _expectRegions(List? regions, List expected) { - var actual = - regions! - .map( - (region) => code.code.substring( - region.offset, - region.offset + region.length, - ), - ) - .toList(); + var actual = regions! + .map( + (region) => + code.code.substring(region.offset, region.offset + region.length), + ) + .toList(); expect(actual, equals(expected.map(normalizeSource))); } diff --git a/pkg/analysis_server/test/src/computer/type_hierarchy_computer_test.dart b/pkg/analysis_server/test/src/computer/type_hierarchy_computer_test.dart index 28db9a71d9b..d4413dce350 100644 --- a/pkg/analysis_server/test/src/computer/type_hierarchy_computer_test.dart +++ b/pkg/analysis_server/test/src/computer/type_hierarchy_computer_test.dart @@ -364,10 +364,9 @@ class ^E extends D {} while (target != null) { names.add(target.displayName); var supertypes = await findSupertypes(target); - target = - (supertypes != null && supertypes.isNotEmpty) - ? supertypes.single - : null; + target = (supertypes != null && supertypes.isNotEmpty) + ? supertypes.single + : null; } expect(names, ['E', 'D', 'C', 'B', 'A', 'Object']); diff --git a/pkg/analysis_server/test/src/lsp/lsp_packet_transformer_test.dart b/pkg/analysis_server/test/src/lsp/lsp_packet_transformer_test.dart index 7486a2a4bcf..2ba8792ac59 100644 --- a/pkg/analysis_server/test/src/lsp/lsp_packet_transformer_test.dart +++ b/pkg/analysis_server/test/src/lsp/lsp_packet_transformer_test.dart @@ -12,10 +12,9 @@ void main() { test('transforms data received as individual bytes', () async { var payload = '{ json payload }'; var lspPacket = makeLspPacket(payload); - var output = - await Stream.fromIterable([ - lspPacket, - ]).transform(LspPacketTransformer()).toList(); + var output = await Stream.fromIterable([ + lspPacket, + ]).transform(LspPacketTransformer()).toList(); expect(output, equals([payload])); }); @@ -26,10 +25,9 @@ void main() { // where all the bytes for a single LSP packet don't arrive in one // item to the stream. var dataPackets = lspPacket.map((b) => [b]); - var output = - await Stream.fromIterable( - dataPackets, - ).transform(LspPacketTransformer()).toList(); + var output = await Stream.fromIterable( + dataPackets, + ).transform(LspPacketTransformer()).toList(); expect(output, equals([payload])); }); @@ -37,10 +35,9 @@ void main() { // This file is saved as UTF8. var payload = '{ json payload 🎉 }'; var lspPacket = makeLspPacket(payload); - var output = - await Stream.fromIterable([ - lspPacket, - ]).transform(LspPacketTransformer()).toList(); + var output = await Stream.fromIterable([ + lspPacket, + ]).transform(LspPacketTransformer()).toList(); expect(output, equals([payload])); }); @@ -50,10 +47,9 @@ void main() { payload, 'application/vscode-jsonrpc; charset=utf-8', ); - var output = - await Stream.fromIterable([ - lspPacket, - ]).transform(LspPacketTransformer()).toList(); + var output = await Stream.fromIterable([ + lspPacket, + ]).transform(LspPacketTransformer()).toList(); expect(output, equals([payload])); }); @@ -63,20 +59,18 @@ void main() { payload, 'application/vscode-jsonrpc; charset=utf8', ); - var output = - await Stream.fromIterable([ - lspPacket, - ]).transform(LspPacketTransformer()).toList(); + var output = await Stream.fromIterable([ + lspPacket, + ]).transform(LspPacketTransformer()).toList(); expect(output, equals([payload])); }); test('accepts no encoding', () async { var payload = '{ json payload 🎉 }'; var lspPacket = makeLspPacket(payload, 'application/vscode-jsonrpc;'); - var output = - await Stream.fromIterable([ - lspPacket, - ]).transform(LspPacketTransformer()).toList(); + var output = await Stream.fromIterable([ + lspPacket, + ]).transform(LspPacketTransformer()).toList(); expect(output, equals([payload])); }); diff --git a/pkg/analysis_server/test/src/plugin/plugin_isolate_test.dart b/pkg/analysis_server/test/src/plugin/plugin_isolate_test.dart index 5584ddb12d1..61b9ba60220 100644 --- a/pkg/analysis_server/test/src/plugin/plugin_isolate_test.dart +++ b/pkg/analysis_server/test/src/plugin/plugin_isolate_test.dart @@ -173,8 +173,10 @@ class PluginSessionTest with ResourceProviderMixin { } void test_handleNotification() { - var notification = - AnalysisErrorsParams('/test.dart', []).toNotification(); + var notification = AnalysisErrorsParams( + '/test.dart', + [], + ).toNotification(); expect(notificationManager.notifications, hasLength(0)); session.handleNotification(notification); expect(notificationManager.notifications, hasLength(1)); diff --git a/pkg/analysis_server/test/src/plugin/plugin_locator_test.dart b/pkg/analysis_server/test/src/plugin/plugin_locator_test.dart index 96ada4288f5..fe2d1f8b284 100644 --- a/pkg/analysis_server/test/src/plugin/plugin_locator_test.dart +++ b/pkg/analysis_server/test/src/plugin/plugin_locator_test.dart @@ -63,10 +63,9 @@ class PluginLocatorTest with ResourceProviderMixin { } void _createDefaultDir() { - defaultDirPath = - newFolder( - '/package/${PluginLocator.toolsFolderName}/${PluginLocator.defaultPluginFolderName}', - ).path; + defaultDirPath = newFolder( + '/package/${PluginLocator.toolsFolderName}/${PluginLocator.defaultPluginFolderName}', + ).path; } void _createPubspec(String content) { diff --git a/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart b/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart index 5842297b58f..60d4a8bb00b 100644 --- a/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart +++ b/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart @@ -243,8 +243,9 @@ class PluginManagerFromDiskTest extends PluginTestSupport { var pluginIsolates = manager.pluginsForContextRoot(contextRoot); expect(pluginIsolates, hasLength(2)); - var paths = - pluginIsolates.map((isolate) => isolate.pluginId).toList(); + var paths = pluginIsolates + .map((isolate) => isolate.pluginId) + .toList(); expect(paths, unorderedEquals([plugin1Path, plugin2Path])); await manager.stopAll(); @@ -429,8 +430,9 @@ class PluginManagerTest with ResourceProviderMixin, _ContextRoot { newFolder('/workspaceRoot/blaze-genfiles'); String newPackage(String packageName, [List? dependencies]) { - var packageRoot = - newFolder('/workspaceRoot/third_party/dart/$packageName').path; + var packageRoot = newFolder( + '/workspaceRoot/third_party/dart/$packageName', + ).path; newFile('$packageRoot/lib/$packageName.dart', ''); var buffer = StringBuffer(); if (dependencies != null) { diff --git a/pkg/analysis_server/test/src/plugin/plugin_watcher_test.dart b/pkg/analysis_server/test/src/plugin/plugin_watcher_test.dart index 8a62585ae19..3038c80fde5 100644 --- a/pkg/analysis_server/test/src/plugin/plugin_watcher_test.dart +++ b/pkg/analysis_server/test/src/plugin/plugin_watcher_test.dart @@ -51,9 +51,8 @@ analyzer: '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'foo', rootPath: convertPath('/foo')), + config: PackageConfigFileBuilder() + ..add(name: 'foo', rootPath: convertPath('/foo')), ); var driver = driverFor(testFile); diff --git a/pkg/analysis_server/test/src/services/completion/yaml/analysis_options_generator_test.dart b/pkg/analysis_server/test/src/services/completion/yaml/analysis_options_generator_test.dart index b8ea1b2231f..2f48c72c7db 100644 --- a/pkg/analysis_server/test/src/services/completion/yaml/analysis_options_generator_test.dart +++ b/pkg/analysis_server/test/src/services/completion/yaml/analysis_options_generator_test.dart @@ -94,11 +94,10 @@ analyzer: errors: ^ '''); - var duplicateCompletions = - groupBy( - results.map((result) => result.completion), - (result) => result, - ).entries.where((entry) => entry.value.length > 1).keys; + var duplicateCompletions = groupBy( + results.map((result) => result.completion), + (result) => result, + ).entries.where((entry) => entry.value.length > 1).keys; expect(duplicateCompletions, isEmpty); } diff --git a/pkg/analysis_server/test/src/services/completion/yaml/pubspec_generator_test.dart b/pkg/analysis_server/test/src/services/completion/yaml/pubspec_generator_test.dart index 85a9990e9ff..43aeb0dc26a 100644 --- a/pkg/analysis_server/test/src/services/completion/yaml/pubspec_generator_test.dart +++ b/pkg/analysis_server/test/src/services/completion/yaml/pubspec_generator_test.dart @@ -365,8 +365,8 @@ dependencies: ] } '''; - processRunner.startHandler = - (executable, args, {dir, env}) => MockProcess(1, 0, json, ''); + processRunner.startHandler = (executable, args, {dir, env}) => + MockProcess(1, 0, json, ''); pubPackageService.beginCachePreloads([convertPath('/home/test/$fileName')]); await pumpEventQueue(times: 500); diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_await_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_await_test.dart index 5a80a7f6293..9a039a3f5fe 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/add_await_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/add_await_test.dart @@ -162,8 +162,8 @@ void f() async { await doSomething() } ''', - errorFilter: - (error) => error.diagnosticCode != ParserErrorCode.expectedToken, + errorFilter: (error) => + error.diagnosticCode != ParserErrorCode.expectedToken, ); } @@ -325,9 +325,8 @@ Future baz() async { variable = await bar(); } ''', - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.invalidAssignment, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.invalidAssignment, ); } @@ -340,9 +339,8 @@ void baz() { } '''); await assertNoFix( - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.invalidAssignment, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.invalidAssignment, ); } @@ -362,9 +360,8 @@ Future baz() async { String variable = await bar(); } ''', - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.invalidAssignment, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.invalidAssignment, ); } } diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_diagnostic_property_reference_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_diagnostic_property_reference_test.dart index 7dbe546d0fa..95f9b58bf97 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/add_diagnostic_property_reference_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/add_diagnostic_property_reference_test.dart @@ -658,9 +658,8 @@ class C extends Widget with Diagnosticable { } } ''', - errorFilter: - (error) => - error.diagnosticCode != CompileTimeErrorCode.undefinedClass, + errorFilter: (error) => + error.diagnosticCode != CompileTimeErrorCode.undefinedClass, ); } @@ -693,9 +692,8 @@ class C extends Widget with Diagnosticable { } } ''', - errorFilter: - (error) => - error.diagnosticCode != CompileTimeErrorCode.undefinedClass, + errorFilter: (error) => + error.diagnosticCode != CompileTimeErrorCode.undefinedClass, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_extension_override_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_extension_override_test.dart index 844cf426500..e8a86285d14 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/add_extension_override_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/add_extension_override_test.dart @@ -49,10 +49,9 @@ void f(String str) { } ''', matchFixMessage: "Add an extension override for 'StringExt1'", - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, ); await assertHasFixesWithoutApplying( @@ -61,10 +60,9 @@ void f(String str) { "Add an extension override for 'StringExt1'", "Add an extension override for 'StringExt2'", ], - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, ); } @@ -203,10 +201,9 @@ extension E2 on A { } ''', matchFixMessage: "Add an extension override for 'E2'", - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, ); } @@ -239,10 +236,9 @@ extension E2 on A { } ''', matchFixMessage: "Add an extension override for 'E2'", - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, ); } @@ -279,10 +275,9 @@ extension E2 on A { } ''', matchFixMessage: "Add an extension override for 'E2'", - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, ); } @@ -388,10 +383,9 @@ void f(String str) { } ''', matchFixMessage: "Add an extension override for 'StringExt1'", - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, ); await assertHasFixesWithoutApplying( @@ -400,10 +394,9 @@ void f(String str) { "Add an extension override for 'StringExt1'", "Add an extension override for 'StringExt2'", ], - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.ambiguousExtensionMemberAccessTwo, ); } } diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_late_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_late_test.dart index 2ab749cbe53..be62e696d8e 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/add_late_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/add_late_test.dart @@ -136,9 +136,8 @@ class C { } } ''', - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.assignmentToFinal, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.assignmentToFinal, ); } @@ -175,9 +174,8 @@ void f(C c) { c.s = ''; } ''', - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.assignmentToFinal, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.assignmentToFinal, ); } @@ -199,9 +197,8 @@ class C { } } ''', - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.assignmentToFinal, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.assignmentToFinal, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_missing_parameter_required_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_missing_parameter_required_test.dart index 45ed2fb11a2..d68fb0dbcc1 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/add_missing_parameter_required_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/add_missing_parameter_required_test.dart @@ -170,9 +170,8 @@ class AddMissingParameterRequiredTest_Workspace var a = newFile('/home/aaa/lib/a.dart', 'void test() {}'); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: '$workspaceRootPath/aaa'), ); _workspace = DartChangeWorkspace([await session, await sessionFor(a)]); @@ -192,9 +191,8 @@ void f() { newFile('/home/bbb/lib/b.dart', 'void test() {}'); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb'), + config: PackageConfigFileBuilder() + ..add(name: 'bbb', rootPath: '$workspaceRootPath/bbb'), ); await resolveTestCode(''' diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_missing_switch_cases_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_missing_switch_cases_test.dart index 2d9d34741fa..2a6b053e14c 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/add_missing_switch_cases_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/add_missing_switch_cases_test.dart @@ -249,10 +249,9 @@ int f(E x) { }; } ''', - errorFilter: - (e) => - e.diagnosticCode == - CompileTimeErrorCode.nonExhaustiveSwitchExpression, + errorFilter: (e) => + e.diagnosticCode == + CompileTimeErrorCode.nonExhaustiveSwitchExpression, ); } @@ -519,10 +518,8 @@ void f(E e) { } } ''', - errorFilter: - (e) => - e.diagnosticCode == - CompileTimeErrorCode.nonExhaustiveSwitchStatement, + errorFilter: (e) => + e.diagnosticCode == CompileTimeErrorCode.nonExhaustiveSwitchStatement, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_null_check_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_null_check_test.dart index 1e9b7a8d55e..e1c26f40862 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/add_null_check_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/add_null_check_test.dart @@ -389,10 +389,8 @@ void g() { } '''); await assertNoFix( - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == - CompileTimeErrorCode.invalidAssignment, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.invalidAssignment, ); } @@ -568,10 +566,9 @@ void f (List? args) { } '''); await assertNoFix( - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode != - CompileTimeErrorCode.listElementTypeNotAssignable, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode != + CompileTimeErrorCode.listElementTypeNotAssignable, ); } @@ -619,10 +616,9 @@ f(List? args) { }); } ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode != - CompileTimeErrorCode.yieldEachOfInvalidType, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode != + CompileTimeErrorCode.yieldEachOfInvalidType, ); } @@ -642,10 +638,9 @@ g() { } } ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == - CompileTimeErrorCode.uncheckedUseOfNullableValueInYieldEach, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == + CompileTimeErrorCode.uncheckedUseOfNullableValueInYieldEach, ); } @@ -665,10 +660,9 @@ class C { } } ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode != - CompileTimeErrorCode.yieldEachOfInvalidType, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode != + CompileTimeErrorCode.yieldEachOfInvalidType, ); } @@ -684,10 +678,9 @@ Iterable f(List? args) sync* { yield* args!; } ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode != - CompileTimeErrorCode.yieldEachOfInvalidType, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode != + CompileTimeErrorCode.yieldEachOfInvalidType, ); } } diff --git a/pkg/analysis_server/test/src/services/correction/fix/ambiguous_import_fix_test.dart b/pkg/analysis_server/test/src/services/correction/fix/ambiguous_import_fix_test.dart index 2e80f866c72..f14e018883d 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/ambiguous_import_fix_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/ambiguous_import_fix_test.dart @@ -564,9 +564,8 @@ void f() { } ''', matchFixMessage: "Hide others to use 'N' from 'lib2.dart'", - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.ambiguousImport, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.ambiguousImport, ); } @@ -593,9 +592,8 @@ void f() { } ''', matchFixMessage: "Hide others to use 'N' from 'lib2.dart' as l", - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.ambiguousImport, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.ambiguousImport, ); } @@ -863,9 +861,8 @@ void f(N? n, O? o) { print(n); } ''', - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.ambiguousImport, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.ambiguousImport, matchFixMessage: "Remove show to use 'N' from 'lib2.dart'", ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/change_to_test.dart b/pkg/analysis_server/test/src/services/correction/fix/change_to_test.dart index 3b026549fae..3a2be5de7dd 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/change_to_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/change_to_test.dart @@ -493,8 +493,8 @@ void f(A a) { a.foo += 2; } ''', - errorFilter: - (e) => e.diagnosticCode == CompileTimeErrorCode.undefinedGetter, + errorFilter: (e) => + e.diagnosticCode == CompileTimeErrorCode.undefinedGetter, ); } @@ -520,8 +520,8 @@ void f() { A.foo += 2; } ''', - errorFilter: - (e) => e.diagnosticCode == CompileTimeErrorCode.undefinedGetter, + errorFilter: (e) => + e.diagnosticCode == CompileTimeErrorCode.undefinedGetter, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart b/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart index 43b13f235a6..99bc46e50d7 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart @@ -198,10 +198,9 @@ void f(List list) { } } ''', - errorFilter: - (error) => - error.diagnosticCode.name == - LintNames.avoid_function_literals_in_foreach_calls, + errorFilter: (error) => + error.diagnosticCode.name == + LintNames.avoid_function_literals_in_foreach_calls, ); } @@ -227,10 +226,9 @@ void f(List list) { } } ''', - errorFilter: - (error) => - error.diagnosticCode.name == - LintNames.avoid_function_literals_in_foreach_calls, + errorFilter: (error) => + error.diagnosticCode.name == + LintNames.avoid_function_literals_in_foreach_calls, ); } @@ -260,10 +258,9 @@ void f(core.List> list) { } } ''', - errorFilter: - (error) => - error.diagnosticCode.name == - LintNames.avoid_function_literals_in_foreach_calls, + errorFilter: (error) => + error.diagnosticCode.name == + LintNames.avoid_function_literals_in_foreach_calls, ); } @@ -309,10 +306,9 @@ void f(List list) { } '''); await assertNoFix( - errorFilter: - (error) => - error.diagnosticCode.name == - LintNames.avoid_function_literals_in_foreach_calls, + errorFilter: (error) => + error.diagnosticCode.name == + LintNames.avoid_function_literals_in_foreach_calls, ); } @@ -358,10 +354,9 @@ void f(List list) { } } ''', - errorFilter: - (error) => - error.diagnosticCode.name == - LintNames.avoid_function_literals_in_foreach_calls, + errorFilter: (error) => + error.diagnosticCode.name == + LintNames.avoid_function_literals_in_foreach_calls, ); } @@ -385,10 +380,9 @@ void f(List list) { } } ''', - errorFilter: - (error) => - error.diagnosticCode.name == - LintNames.avoid_function_literals_in_foreach_calls, + errorFilter: (error) => + error.diagnosticCode.name == + LintNames.avoid_function_literals_in_foreach_calls, ); } @@ -399,10 +393,9 @@ void f(List list) { } '''); await assertNoFix( - errorFilter: - (error) => - error.diagnosticCode.name == - LintNames.avoid_function_literals_in_foreach_calls, + errorFilter: (error) => + error.diagnosticCode.name == + LintNames.avoid_function_literals_in_foreach_calls, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/convert_into_getter_test.dart b/pkg/analysis_server/test/src/services/correction/fix/convert_into_getter_test.dart index e8a05be623a..304de113136 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/convert_into_getter_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/convert_into_getter_test.dart @@ -35,10 +35,9 @@ extension E on int { int get a => null; } ''', - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.extensionDeclaresInstanceField, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.extensionDeclaresInstanceField, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/convert_to_relative_import_test.dart b/pkg/analysis_server/test/src/services/correction/fix/convert_to_relative_import_test.dart index ceadf159312..cfc19f537a5 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/convert_to_relative_import_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/convert_to_relative_import_test.dart @@ -92,9 +92,8 @@ import 'package:test/foo'; ''' import 'foo'; ''', - errorFilter: - (error) => - error.diagnosticCode != CompileTimeErrorCode.uriDoesNotExist, + errorFilter: (error) => + error.diagnosticCode != CompileTimeErrorCode.uriDoesNotExist, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/create_constructor_test.dart b/pkg/analysis_server/test/src/services/correction/fix/create_constructor_test.dart index 031dad9b414..abaa973f6d4 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/create_constructor_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/create_constructor_test.dart @@ -40,8 +40,7 @@ class CreateConstructorTest extends FixProcessorTest { FixKind get kind => DartFixKind.CREATE_CONSTRUCTOR; Future test_inLibrary_insteadOfSyntheticDefault() async { - var a = - newFile('$testPackageLibPath/a.dart', ''' + var a = newFile('$testPackageLibPath/a.dart', ''' /// $_text200 class A {} ''').path; @@ -61,8 +60,7 @@ class A { } Future test_inLibrary_insteadOfSyntheticDefault_dotShorthand() async { - var a = - newFile('$testPackageLibPath/a.dart', ''' + var a = newFile('$testPackageLibPath/a.dart', ''' /// $_text200 class A {} ''').path; @@ -82,8 +80,7 @@ class A { } Future test_inLibrary_named() async { - var a = - newFile('$testPackageLibPath/a.dart', ''' + var a = newFile('$testPackageLibPath/a.dart', ''' /// $_text200 class A {} ''').path; @@ -103,8 +100,7 @@ class A { } Future test_inLibrary_named_dotShorthand() async { - var a = - newFile('$testPackageLibPath/a.dart', ''' + var a = newFile('$testPackageLibPath/a.dart', ''' /// $_text200 class A {} ''').path; diff --git a/pkg/analysis_server/test/src/services/correction/fix/create_extension_member_test.dart b/pkg/analysis_server/test/src/services/correction/fix/create_extension_member_test.dart index c870564eb82..b8b30b7b227 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/create_extension_member_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/create_extension_member_test.dart @@ -923,9 +923,8 @@ extension E on int { int foo() {} } ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, ); } @@ -942,15 +941,12 @@ extension E on A { } '''); await assertNoFix( - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, ); await assertNoFix( - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == - CompileTimeErrorCode.invalidAssignment, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.invalidAssignment, ); } @@ -1009,9 +1005,8 @@ extension E on int { int foo() {} } ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, ); } @@ -1024,9 +1019,8 @@ extension E on int { } '''); await assertNoFix( - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, ); } @@ -1048,9 +1042,8 @@ extension E on int { int foo() {} } ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, ); } @@ -1069,9 +1062,8 @@ extension E on B { } '''); await assertNoFix( - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == CompileTimeErrorCode.undefinedMethod, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/create_local_variable_test.dart b/pkg/analysis_server/test/src/services/correction/fix/create_local_variable_test.dart index 1a9a7403fcf..40a61f98d08 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/create_local_variable_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/create_local_variable_test.dart @@ -238,9 +238,8 @@ class C { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'pkg', rootPath: '$workspaceRootPath/pkg'), ); await resolveTestCode(''' diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/code_fragment_parser_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/code_fragment_parser_test.dart index d31b542c372..75831f9df13 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/code_fragment_parser_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/code_fragment_parser_test.dart @@ -46,11 +46,10 @@ abstract class AbstractCodeFragmentParserTest { List? variables, }) { var diagnosticListener = GatheringDiagnosticListener(); - var expression = - _parser( - diagnosticListener, - variables: variables, - ).parseCondition(content, 0)!; + var expression = _parser( + diagnosticListener, + variables: variables, + ).parseCondition(content, 0)!; diagnosticListener.assertNoErrors(); return expression; } diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/collection_use_case_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/collection_use_case_test.dart index beb9884d12f..e02dbd80859 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/collection_use_case_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/collection_use_case_test.dart @@ -28,9 +28,8 @@ extension IterableNullableExtension on Iterable { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); addPackageDataFile(''' @@ -79,9 +78,8 @@ extension IterableNullableExtension on Iterable { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); addPackageDataFile(''' diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test.dart index 97b61ae6c30..a46ce761bc6 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test.dart @@ -651,10 +651,9 @@ class NoProducerOverlapsTest { var bulkFixForLintCodes = registeredFixGenerators.lintProducers.entries .where( (e) => e.value.any( - (generator) => - generator( - context: StubCorrectionProducerContext.instance, - ).canBeAppliedAcrossFiles, + (generator) => generator( + context: StubCorrectionProducerContext.instance, + ).canBeAppliedAcrossFiles, ), ) .map((e) => e.key); @@ -663,10 +662,9 @@ class NoProducerOverlapsTest { .entries .where( (e) => e.value.any( - (generator) => - generator( - context: StubCorrectionProducerContext.instance, - ).canBeAppliedAcrossFiles, + (generator) => generator( + context: StubCorrectionProducerContext.instance, + ).canBeAppliedAcrossFiles, ), ) .map((e) => e.key.uniqueName); @@ -2341,9 +2339,8 @@ class _DataDrivenTest extends BulkFixProcessorTest { void setPackageContent(String content) { newFile('$workspaceRootPath/p/lib/lib.dart', content); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test_support.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test_support.dart index 54fa68c7b8e..9bf3d329ee6 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test_support.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/data_driven_test_support.dart @@ -67,9 +67,8 @@ mixin DataDrivenFixProcessorTestMixin on AbstractSingleUnitTest { void setPackageContent(String content) { newFile('$workspaceRootPath/p/lib/lib.dart', content); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/element_matcher_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/element_matcher_test.dart index 00e70499a72..615324da5df 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/element_matcher_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/element_matcher_test.dart @@ -675,9 +675,8 @@ String s = ''; var packageRootPath = '$workspaceRootPath/other'; newFile('$packageRootPath/lib/other.dart', ''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'other', rootPath: packageRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'other', rootPath: packageRootPath), ); await resolveTestCode(''' diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/platform_use_case_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/platform_use_case_test.dart index 01b547ee994..23f53f84c2e 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/platform_use_case_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/platform_use_case_test.dart @@ -30,10 +30,9 @@ class PlatformUseCaseTest extends DataDrivenFixProcessorTest { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p') - ..add(name: 'p2', rootPath: '$workspaceRootPath/p2'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p') + ..add(name: 'p2', rootPath: '$workspaceRootPath/p2'), ); addPackageDataFile(''' @@ -88,9 +87,8 @@ class HostPlatform { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); addPackageDataFile(''' @@ -146,9 +144,8 @@ class NativePlatform { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); addPackageDataFile(''' @@ -204,9 +201,8 @@ class NativePlatform { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); addSdkDataFile(''' @@ -257,9 +253,8 @@ class HostPlatform { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); addSdkDataFile(''' diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/replaced_by_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/replaced_by_test.dart index 44378f7b8ef..57d04edf1ab 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/replaced_by_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/replaced_by_test.dart @@ -1133,13 +1133,13 @@ void g() { var import = "import '$importUri'$prefixDeclaration;"; // TODO(asashour): inserting imports should remove initial blank lines - var oldImport = - isOldRemoved - ? '' - : ''' + var oldImport = isOldRemoved + ? '' + : ''' $import '''; - var newImport = ''' + var newImport = + ''' $import${isOldRemoved ? '\n' : ''} '''; diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/test_use_case_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/test_use_case_test.dart index 7a13a36bb14..c8c3208fa82 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/test_use_case_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/test_use_case_test.dart @@ -26,10 +26,9 @@ void expect(actual, matcher) {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'matcher', rootPath: '$workspaceRootPath/matcher') - ..add(name: 'p', rootPath: '$workspaceRootPath/p'), + config: PackageConfigFileBuilder() + ..add(name: 'matcher', rootPath: '$workspaceRootPath/matcher') + ..add(name: 'p', rootPath: '$workspaceRootPath/p'), ); addPackageDataFile(''' diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/transform_set_manager_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/transform_set_manager_test.dart index 054b8ca7160..20b5281fbc7 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/transform_set_manager_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/transform_set_manager_test.dart @@ -33,9 +33,8 @@ class TransformSetManagerTest extends AbstractContextTest { _addDataFile('p1-1.0'); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p1', rootPath: '$workspaceRootPath/p1-1.0'), + config: PackageConfigFileBuilder() + ..add(name: 'p1', rootPath: '$workspaceRootPath/p1-1.0'), ); newFile('/home/test/pubspec.yaml', ''); @@ -63,9 +62,8 @@ class TransformSetManagerTest extends AbstractContextTest { _addDataFileIn('$folder/deep/dive/two.yaml', 'p1'); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p1', rootPath: '$workspaceRootPath/p1'), + config: PackageConfigFileBuilder() + ..add(name: 'p1', rootPath: '$workspaceRootPath/p1'), ); newFile('/home/test/pubspec.yaml', ''); @@ -108,10 +106,9 @@ class TransformSetManagerTest extends AbstractContextTest { _addDataFile('p2'); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'p1', rootPath: '$workspaceRootPath/p1') - ..add(name: 'p2', rootPath: '$workspaceRootPath/p2'), + config: PackageConfigFileBuilder() + ..add(name: 'p1', rootPath: '$workspaceRootPath/p1') + ..add(name: 'p2', rootPath: '$workspaceRootPath/p2'), ); newFile('/home/test/pubspec.yaml', ''); diff --git a/pkg/analysis_server/test/src/services/correction/fix/fix_processor.dart b/pkg/analysis_server/test/src/services/correction/fix/fix_processor.dart index 703bcb805b7..44afc6fc4c6 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/fix_processor.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/fix_processor.dart @@ -336,12 +336,11 @@ abstract class FixProcessorLintTest extends FixProcessorTest { /// Returns the [LintCode] for the [lintCode] (which is actually a name). Future lintCodeByName(String name) async { var diagnostics = testAnalysisResult.diagnostics; - var lintCodeSet = - diagnostics - .map((d) => d.diagnosticCode) - .whereType() - .where((lintCode) => lintCode.name == name) - .toSet(); + var lintCodeSet = diagnostics + .map((d) => d.diagnosticCode) + .whereType() + .where((lintCode) => lintCode.name == name) + .toSet(); if (lintCodeSet.length != 1) { fail('Expected exactly one LintCode, actually: $lintCodeSet'); } @@ -628,8 +627,9 @@ abstract class FixProcessorTest extends BaseFixProcessorTest { List fixes, int expectedNumberOfFixesForKind, ) { - var actualNumberOfFixesForKind = - fixes.where((fix) => fix.kind == kind).length; + var actualNumberOfFixesForKind = fixes + .where((fix) => fix.kind == kind) + .length; if (actualNumberOfFixesForKind != expectedNumberOfFixesForKind) { fail( 'Expected $expectedNumberOfFixesForKind fixes of kind $kind,' diff --git a/pkg/analysis_server/test/src/services/correction/fix/import_library_project_test.dart b/pkg/analysis_server/test/src/services/correction/fix/import_library_project_test.dart index 637b3d45895..f4a40b51159 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/import_library_project_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/import_library_project_test.dart @@ -713,8 +713,8 @@ void f() { Test(); } ''', - errorFilter: - (e) => e.diagnosticCode == CompileTimeErrorCode.undefinedFunction, + errorFilter: (e) => + e.diagnosticCode == CompileTimeErrorCode.undefinedFunction, ); } @@ -724,9 +724,8 @@ class Test {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), ); newPubspecYamlFile('/home/test', r''' @@ -759,9 +758,8 @@ extension E on int { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), ); newPubspecYamlFile('/home/test', r''' @@ -790,9 +788,8 @@ class Test {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), ); newPubspecYamlFile('/home/test', r''' @@ -1282,8 +1279,8 @@ dependencies: '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path), ); await resolveTestCode(''' @@ -1310,8 +1307,8 @@ dev_dependencies: '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path), ); await resolveTestCode(''' @@ -1332,8 +1329,8 @@ name: test '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path), ); await resolveTestCode(''' @@ -1804,8 +1801,8 @@ dependencies: '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: aaaRoot.path), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: aaaRoot.path), ); } } @@ -2244,8 +2241,8 @@ extension IntExtension on int { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder()..add(name: 'aaa', rootPath: pkgRootPath), + config: PackageConfigFileBuilder() + ..add(name: 'aaa', rootPath: pkgRootPath), ); updateTestPubspecFile(''' @@ -2277,9 +2274,8 @@ class Test {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), ); newPubspecYamlFile('/home/test', r''' @@ -2311,9 +2307,8 @@ class Test {} '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), ); newPubspecYamlFile('/home/test', r''' @@ -2347,9 +2342,8 @@ extension E on int { '''); writeTestPackageConfig( - config: - PackageConfigFileBuilder() - ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), + config: PackageConfigFileBuilder() + ..add(name: 'my_pkg', rootPath: '$packagesRootPath/my_pkg'), ); newPubspecYamlFile('/home/test', r''' diff --git a/pkg/analysis_server/test/src/services/correction/fix/insert_body_test.dart b/pkg/analysis_server/test/src/services/correction/fix/insert_body_test.dart index 00d7dd23ab4..05f9acee811 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/insert_body_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/insert_body_test.dart @@ -126,9 +126,8 @@ enum E ''' enum E {}''', - errorFilter: - (error) => - error.diagnosticCode != CompileTimeErrorCode.enumWithoutConstants, + errorFilter: (error) => + error.diagnosticCode != CompileTimeErrorCode.enumWithoutConstants, ); } } diff --git a/pkg/analysis_server/test/src/services/correction/fix/remove_const_test.dart b/pkg/analysis_server/test/src/services/correction/fix/remove_const_test.dart index e4471a25e3a..e94d51ec4f5 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/remove_const_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/remove_const_test.dart @@ -65,10 +65,9 @@ void f(int i) { } '''); await assertNoFix( - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.constConstructorParamTypeMismatch, + errorFilter: (error) => + error.diagnosticCode == + CompileTimeErrorCode.constConstructorParamTypeMismatch, ); } @@ -172,10 +171,8 @@ class B {} var v = [const A(), B()]; ''', // TODO(FMorschel): CONST_WITH_NON_CONST should not be probably triggered - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.nonConstantListElement, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.nonConstantListElement, ); } @@ -199,11 +196,9 @@ Object f() { return [const A(), B(), [const A(), B()]]; } ''', - errorFilter: - (error) => - error.offset == parsedTestCode.positions[0].offset && - error.diagnosticCode == - CompileTimeErrorCode.nonConstantListElement, + errorFilter: (error) => + error.offset == parsedTestCode.positions[0].offset && + error.diagnosticCode == CompileTimeErrorCode.nonConstantListElement, ); await assertHasFix( r''' @@ -215,11 +210,9 @@ Object f() { return [const A(), B(), [const A(), B()]]; } ''', - errorFilter: - (error) => - error.offset == parsedTestCode.positions[1].offset && - error.diagnosticCode == - CompileTimeErrorCode.nonConstantListElement, + errorFilter: (error) => + error.offset == parsedTestCode.positions[1].offset && + error.diagnosticCode == CompileTimeErrorCode.nonConstantListElement, ); } @@ -243,11 +236,9 @@ Object f() { return [const A(), B(), const [A(), A()]]; } ''', - errorFilter: - (error) => - error.offset == parsedTestCode.position.offset && - error.diagnosticCode == - CompileTimeErrorCode.nonConstantListElement, + errorFilter: (error) => + error.offset == parsedTestCode.position.offset && + error.diagnosticCode == CompileTimeErrorCode.nonConstantListElement, ); } @@ -270,10 +261,8 @@ final x = [const A(), A.nonConst()]; // TODO(FMorschel): CONST_WITH_NON_CONST and // CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE should not be triggered and // NON_CONSTANT_LIST_ELEMENT should have the position for the element - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.nonConstantListElement, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.nonConstantListElement, ); } } @@ -426,9 +415,8 @@ class B {} var v = {1: const A(), 2: B()}; ''', // TODO(FMorschel): CONST_WITH_NON_CONST should not be probably triggered - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.nonConstantMapValue, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.nonConstantMapValue, ); } @@ -449,9 +437,8 @@ class A { final v = {1: const A(), 2: A.nonConst()}; ''', // TODO(FMorschel): CONST_WITH_NON_CONST should not be probably triggered - errorFilter: - (error) => - error.diagnosticCode == CompileTimeErrorCode.nonConstantMapValue, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.nonConstantMapValue, ); } } @@ -513,10 +500,8 @@ class B {} var v = {const A(), B()}; ''', // TODO(FMorschel): CONST_WITH_NON_CONST should not be probably triggered - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.nonConstantSetElement, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.nonConstantSetElement, ); } @@ -537,10 +522,8 @@ class A { final v = {const A(), A.nonConst()}; ''', // TODO(FMorschel): CONST_WITH_NON_CONST should not be probably triggered - errorFilter: - (error) => - error.diagnosticCode == - CompileTimeErrorCode.nonConstantSetElement, + errorFilter: (error) => + error.diagnosticCode == CompileTimeErrorCode.nonConstantSetElement, ); } } diff --git a/pkg/analysis_server/test/src/services/correction/fix/remove_dead_code_test.dart b/pkg/analysis_server/test/src/services/correction/fix/remove_dead_code_test.dart index 38418fb964b..19d43f77a6d 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/remove_dead_code_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/remove_dead_code_test.dart @@ -1162,10 +1162,9 @@ void f(int i, int j) => i; /// Error filter ignoring warnings that frequently occur in conjunction with /// code that is dead due to sound flow analysis. - bool _ignoreNullSafetyWarnings(Diagnostic diagnostic) => - !const { - 'DEAD_NULL_AWARE_EXPRESSION', - 'INVALID_NULL_AWARE_OPERATOR', - 'UNNECESSARY_NULL_COMPARISON', - }.contains(diagnostic.diagnosticCode.name); + bool _ignoreNullSafetyWarnings(Diagnostic diagnostic) => !const { + 'DEAD_NULL_AWARE_EXPRESSION', + 'INVALID_NULL_AWARE_OPERATOR', + 'UNNECESSARY_NULL_COMPARISON', + }.contains(diagnostic.diagnosticCode.name); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/remove_name_from_declaration_clause_test.dart b/pkg/analysis_server/test/src/services/correction/fix/remove_name_from_declaration_clause_test.dart index a530db9974c..367cd3375fc 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/remove_name_from_declaration_clause_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/remove_name_from_declaration_clause_test.dart @@ -330,8 +330,8 @@ import 'dart:ffi'; final class S extends Struct {} final class C {} ''', - errorFilter: - (error) => error.diagnosticCode == FfiCode.subtypeOfStructClassInWith, + errorFilter: (error) => + error.diagnosticCode == FfiCode.subtypeOfStructClassInWith, ); } } diff --git a/pkg/analysis_server/test/src/services/correction/fix/remove_unused_element_test.dart b/pkg/analysis_server/test/src/services/correction/fix/remove_unused_element_test.dart index b79add4e4dd..63a5ec8d70d 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/remove_unused_element_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/remove_unused_element_test.dart @@ -179,9 +179,8 @@ enum _MyEnum {A, B, C} await assertHasFix( r''' ''', - errorFilter: - (diagnostic) => - diagnostic.diagnosticCode == WarningCode.unusedElement, + errorFilter: (diagnostic) => + diagnostic.diagnosticCode == WarningCode.unusedElement, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/remove_unused_local_variable_test.dart b/pkg/analysis_server/test/src/services/correction/fix/remove_unused_local_variable_test.dart index 890e4da7390..45a04fa64ba 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/remove_unused_local_variable_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/remove_unused_local_variable_test.dart @@ -269,10 +269,8 @@ void f() { void f() { } ''', - errorFilter: - (e) => - e.diagnosticCode != - CompileTimeErrorCode.referencedBeforeDeclaration, + errorFilter: (e) => + e.diagnosticCode != CompileTimeErrorCode.referencedBeforeDeclaration, ); } } diff --git a/pkg/analysis_server/test/src/services/correction/fix/replace_cascade_with_dot_test.dart b/pkg/analysis_server/test/src/services/correction/fix/replace_cascade_with_dot_test.dart index 0c2c060750e..d2025e2a0f6 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/replace_cascade_with_dot_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/replace_cascade_with_dot_test.dart @@ -54,10 +54,9 @@ class A { } } ''', - errorFilter: - (e) => - e.diagnosticCode.name == - LintNames.avoid_single_cascade_in_expression_statements, + errorFilter: (e) => + e.diagnosticCode.name == + LintNames.avoid_single_cascade_in_expression_statements, ); } @@ -98,10 +97,9 @@ f() { E(3).g; } ''', - errorFilter: - (e) => - e.diagnosticCode.name == - LintNames.avoid_single_cascade_in_expression_statements, + errorFilter: (e) => + e.diagnosticCode.name == + LintNames.avoid_single_cascade_in_expression_statements, ); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/replace_with_decorated_box_test.dart b/pkg/analysis_server/test/src/services/correction/fix/replace_with_decorated_box_test.dart index b17dd6cd1b0..03a6c613a27 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/replace_with_decorated_box_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/replace_with_decorated_box_test.dart @@ -342,8 +342,8 @@ void f() { } ''', allowFixAllFixes: true, - errorFilter: - (error) => error.offset == testCode.indexOf('Container( // 1'), + errorFilter: (error) => + error.offset == testCode.indexOf('Container( // 1'), ); await assertHasFix( @@ -364,8 +364,8 @@ void f() { } ''', allowFixAllFixes: true, - errorFilter: - (error) => error.offset == testCode.indexOf('Container( // 2'), + errorFilter: (error) => + error.offset == testCode.indexOf('Container( // 2'), ); await assertHasFix( @@ -386,8 +386,8 @@ void f() { } ''', allowFixAllFixes: true, - errorFilter: - (error) => error.offset == testCode.indexOf('Container( // 3'), + errorFilter: (error) => + error.offset == testCode.indexOf('Container( // 3'), ); } diff --git a/pkg/analysis_server/test/src/services/flutter/constants.dart b/pkg/analysis_server/test/src/services/flutter/constants.dart index 3bf64d29280..443a62a9f84 100644 --- a/pkg/analysis_server/test/src/services/flutter/constants.dart +++ b/pkg/analysis_server/test/src/services/flutter/constants.dart @@ -2,7 +2,8 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -final alignmentEditor = ''' +final alignmentEditor = + ''' "editor": { "kind": "ENUM_LIKE", "enumItems": $alignmentEnumItems diff --git a/pkg/analysis_server/test/src/services/flutter/widget_descriptions_test.dart b/pkg/analysis_server/test/src/services/flutter/widget_descriptions_test.dart index 3ee76369929..dbf1941e730 100644 --- a/pkg/analysis_server/test/src/services/flutter/widget_descriptions_test.dart +++ b/pkg/analysis_server/test/src/services/flutter/widget_descriptions_test.dart @@ -244,8 +244,9 @@ void f() { '''); var property = await getWidgetProperty('Text(', 'overflow'); - var json = - property.toJson(clientUriConverter: null).cast(); + var json = property + .toJson(clientUriConverter: null) + .cast(); expect( json['editor']['enumItems'][0]['documentation'], startsWith('Clip the overflowing'), diff --git a/pkg/analysis_server/test/src/services/refactoring/move_top_level_to_file_test.dart b/pkg/analysis_server/test/src/services/refactoring/move_top_level_to_file_test.dart index 22b551de8aa..675baf58c57 100644 --- a/pkg/analysis_server/test/src/services/refactoring/move_top_level_to_file_test.dart +++ b/pkg/analysis_server/test/src/services/refactoring/move_top_level_to_file_test.dart @@ -2041,13 +2041,15 @@ class B {} var otherFilePath = '$projectFolderPath/lib/other.dart'; var otherFileContent = declarations; - var originalSource = ''' + var originalSource = + ''' import 'package:test/other.dart' as other; ${code.markedCode} '''; - var expected = ''' + var expected = + ''' >>>>>>>>>> lib/main.dart import 'package:test/other.dart' as other; >>>>>>>>>> lib/moving.dart created diff --git a/pkg/analysis_server/test/src/utilities/extensions/range_factory_test.dart b/pkg/analysis_server/test/src/utilities/extensions/range_factory_test.dart index bdb25b3169f..9fbf4f11585 100644 --- a/pkg/analysis_server/test/src/utilities/extensions/range_factory_test.dart +++ b/pkg/analysis_server/test/src/utilities/extensions/range_factory_test.dart @@ -97,14 +97,12 @@ abstract class BaseRangeFactoryTest extends AbstractSingleUnitTest { reason: 'Specify exactly one of endsBefore/endsAfter', ); - var offset = - startsBefore != null - ? testCode.indexOf(startsBefore) - : testCode.indexOf(startsAfter!) + startsAfter.length; - var end = - endsBefore != null - ? testCode.indexOf(endsBefore) - : testCode.indexOf(endsAfter!) + endsAfter.length; + var offset = startsBefore != null + ? testCode.indexOf(startsBefore) + : testCode.indexOf(startsAfter!) + startsAfter.length; + var end = endsBefore != null + ? testCode.indexOf(endsBefore) + : testCode.indexOf(endsAfter!) + endsAfter.length; expect(offset, greaterThanOrEqualTo(0)); expect(end, greaterThanOrEqualTo(0)); diff --git a/pkg/analysis_server/test/src/utilities/import_analyzer_test.dart b/pkg/analysis_server/test/src/utilities/import_analyzer_test.dart index 86d1fbf2c04..4457f976647 100644 --- a/pkg/analysis_server/test/src/utilities/import_analyzer_test.dart +++ b/pkg/analysis_server/test/src/utilities/import_analyzer_test.dart @@ -988,12 +988,11 @@ abstract class ImportAnalyzerTest extends PubPackageAnalysisServerTest { createDefaultFiles(); var testCode = TestCode.parse(code); var pathToInclude = newFile(testFilePath, testCode.code).path; - var context = - AnalysisContextCollection( - includedPaths: [pathToInclude], - resourceProvider: resourceProvider, - sdkPath: sdkRoot.path, - ).contexts[0]; + var context = AnalysisContextCollection( + includedPaths: [pathToInclude], + resourceProvider: resourceProvider, + sdkPath: sdkRoot.path, + ).contexts[0]; var result = await context.currentSession.getResolvedLibrary(pathToInclude) as ResolvedLibraryResult; diff --git a/pkg/analysis_server/test/src/utilities/selection_coverage_test.dart b/pkg/analysis_server/test/src/utilities/selection_coverage_test.dart index d5a74aa8fa6..5a578473de7 100644 --- a/pkg/analysis_server/test/src/utilities/selection_coverage_test.dart +++ b/pkg/analysis_server/test/src/utilities/selection_coverage_test.dart @@ -135,15 +135,14 @@ class SelectionCoverageTest { for (var member in declaration.members) { if (member is MethodDeclaration && member.name.lexeme.startsWith('visit')) { - var visitedClass = - member - .parameters - ?.parameters - .first - .declaredFragment - ?.element - .type - .element; + var visitedClass = member + .parameters + ?.parameters + .first + .declaredFragment + ?.element + .type + .element; if (visitedClass is ClassElement) { var visitor = VisitMethodVisitor(); member.body.accept(visitor); diff --git a/pkg/analysis_server/test/src/utilities/selection_test.dart b/pkg/analysis_server/test/src/utilities/selection_test.dart index 96544cea564..704b97c433a 100644 --- a/pkg/analysis_server/test/src/utilities/selection_test.dart +++ b/pkg/analysis_server/test/src/utilities/selection_test.dart @@ -1444,8 +1444,10 @@ nodesInRange var range = testCode.range.sourceRange; await resolveTestCode(testCode.code); - var selection = - testUnit.select(offset: range.offset, length: range.length)!; + var selection = testUnit.select( + offset: range.offset, + length: range.length, + )!; return _CodeSelection(testCode: testCode, selection: selection); } diff --git a/pkg/analysis_server/test/stress/replay/replay.dart b/pkg/analysis_server/test/stress/replay/replay.dart index a051f85ee57..20066bbadf5 100644 --- a/pkg/analysis_server/test/stress/replay/replay.dart +++ b/pkg/analysis_server/test/stress/replay/replay.dart @@ -223,14 +223,15 @@ class Driver { List _getBreakOffsets(String text) { var breakOffsets = []; var featureSet = FeatureSet.latestLanguageVersion(); - var scanner = Scanner( - _TestSource(), - CharSequenceReader(text), - error.DiagnosticListener.nullListener, - )..configureFeatures( - featureSetForOverriding: featureSet, - featureSet: featureSet, - ); + var scanner = + Scanner( + _TestSource(), + CharSequenceReader(text), + error.DiagnosticListener.nullListener, + )..configureFeatures( + featureSetForOverriding: featureSet, + featureSet: featureSet, + ); var token = scanner.tokenize(); // TODO(brianwilkerson): Randomize. Sometimes add zero (0) as a break point. while (!token.isEof) { @@ -293,11 +294,10 @@ class Driver { repositoryPath = path.normalize(arguments[0]); repository = GitRepository(repositoryPath, logger: logger); - analysisRoots = - arguments - .sublist(1) - .map((String analysisRoot) => path.normalize(analysisRoot)) - .toList(); + analysisRoots = arguments + .sublist(1) + .map((String analysisRoot) => path.normalize(analysisRoot)) + .toList(); for (var analysisRoot in analysisRoots) { if (repositoryPath != analysisRoot && !path.isWithin(repositoryPath, analysisRoot)) { diff --git a/pkg/analysis_server/test/tool/lsp_spec/json_test.dart b/pkg/analysis_server/test/tool/lsp_spec/json_test.dart index f9f13647c4c..0715c7f1a40 100644 --- a/pkg/analysis_server/test/tool/lsp_spec/json_test.dart +++ b/pkg/analysis_server/test/tool/lsp_spec/json_test.dart @@ -87,7 +87,8 @@ void main() { ], ); var output = json.encode(codeAction.toJson()); - var expected = '''{ + var expected = + '''{ "code":"test_err", "message":"err!!", "range":{ @@ -108,7 +109,8 @@ void main() { ], "severity":1, "source":"/tmp/source.dart" - }'''.replaceAll(RegExp('[ \n]'), ''); + }''' + .replaceAll(RegExp('[ \n]'), ''); expect(output, equals(expected)); }); @@ -134,13 +136,15 @@ void main() { kind: FoldingRangeKind.Comment, ); var output = json.encode(foldingRange.toJson()); - var expected = '''{ + var expected = + '''{ "endCharacter":4, "endLine":3, "kind":"comment", "startCharacter":2, "startLine":1 - }'''.replaceAll(RegExp('[ \n]'), ''); + }''' + .replaceAll(RegExp('[ \n]'), ''); expect(output, equals(expected)); }); diff --git a/pkg/analysis_server/test/utils/message_scheduler_test_view.dart b/pkg/analysis_server/test/utils/message_scheduler_test_view.dart index 0b92aab8b2b..6ea4d741bc3 100644 --- a/pkg/analysis_server/test/utils/message_scheduler_test_view.dart +++ b/pkg/analysis_server/test/utils/message_scheduler_test_view.dart @@ -16,10 +16,9 @@ class MessageSchedulerTestView implements MessageSchedulerListener { @override void addPendingMessage(ScheduledMessage message) { - var messageType = - message is LspMessage - ? message.message.runtimeType - : message.runtimeType; + var messageType = message is LspMessage + ? message.message.runtimeType + : message.runtimeType; messageLog.add('Incoming $messageType: ${message.toString()}'); } diff --git a/pkg/analysis_server/test/verify_sorted_test.dart b/pkg/analysis_server/test/verify_sorted_test.dart index 5c0670916a0..ddc6e226513 100644 --- a/pkg/analysis_server/test/verify_sorted_test.dart +++ b/pkg/analysis_server/test/verify_sorted_test.dart @@ -54,10 +54,9 @@ void buildTests({ var pkgRootPath = provider.pathContext.normalize(packageRoot); packagePath = _toPlatformPath(pkgRootPath, packagePath); - excludedPaths = - excludedPaths.map((e) { - return _toPlatformPath(packagePath, e); - }).toList(); + excludedPaths = excludedPaths.map((e) { + return _toPlatformPath(packagePath, e); + }).toList(); var collection = AnalysisContextCollection( includedPaths: [packagePath], diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/benchmark_utils.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/benchmark_utils.dart index f921918e64b..dabe1ecbab1 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/benchmark_utils.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/benchmark_utils.dart @@ -84,7 +84,8 @@ String foo(int i) { return nextFile.foo(i-1); }'''; } - var content = ''' + var content = + ''' $import $export @@ -103,7 +104,8 @@ String get$i() { } var mainFileUri = copyToDir.resolve('main.dart'); - var mainFileContent = """ + var mainFileContent = + """ import '${getFilenameFor(1)}'; void main(List arguments) { @@ -112,7 +114,8 @@ void main(List arguments) { """; File.fromUri(mainFileUri).writeAsStringSync(mainFileContent); var typing = ' ge'; - var mainFileTypingContent = """ + var mainFileTypingContent = + """ import '${getFilenameFor(1)}'; void main(List arguments) { @@ -122,7 +125,8 @@ $typing var typingAtOffset = mainFileTypingContent.indexOf(typing) + typing.length; var typingError = 'getFooBarBaz'; - var mainFileTypingErrorContent = """ + var mainFileTypingErrorContent = + """ import '${getFilenameFor(1)}'; void main(List arguments) { diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/files/copy_me/copy_me.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/files/copy_me/copy_me.dart index b78abd7c157..6fd69d84d3f 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/files/copy_me/copy_me.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/files/copy_me/copy_me.dart @@ -1177,8 +1177,9 @@ abstract class AbstractScanner { appendPrecedenceToken(TokenType.PERIOD); return next; } - TokenType tokenType = - hasSeparators ? TokenType.DOUBLE_WITH_SEPARATORS : TokenType.DOUBLE; + TokenType tokenType = hasSeparators + ? TokenType.DOUBLE_WITH_SEPARATORS + : TokenType.DOUBLE; appendSubstringToken(tokenType, start, /* asciiOnly = */ true); return next; } @@ -1247,10 +1248,9 @@ abstract class AbstractScanner { if (previousWasSeparator) { throw "removed"; } - TokenType tokenType = - hasSeparators - ? TokenType.HEXADECIMAL_WITH_SEPARATORS - : TokenType.HEXADECIMAL; + TokenType tokenType = hasSeparators + ? TokenType.HEXADECIMAL_WITH_SEPARATORS + : TokenType.HEXADECIMAL; appendSubstringToken(tokenType, start, /* asciiOnly = */ true); return next; } @@ -1712,8 +1712,9 @@ abstract class AbstractScanner { advance(); return tokenizeFractionPart(nextnext, start, hasSeparators); } else { - TokenType tokenType = - hasSeparators ? TokenType.INT_WITH_SEPARATORS : TokenType.INT; + TokenType tokenType = hasSeparators + ? TokenType.INT_WITH_SEPARATORS + : TokenType.INT; appendSubstringToken(tokenType, start, /* asciiOnly = */ true); return next; } @@ -1721,8 +1722,9 @@ abstract class AbstractScanner { if (previousWasSeparator) { throw "removed"; } - TokenType tokenType = - hasSeparators ? TokenType.INT_WITH_SEPARATORS : TokenType.INT; + TokenType tokenType = hasSeparators + ? TokenType.INT_WITH_SEPARATORS + : TokenType.INT; appendSubstringToken(tokenType, start, /* asciiOnly = */ true); return next; } diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_get_fixes_on_error.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_get_fixes_on_error.dart index 495cbee561c..5fc04e474e1 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_get_fixes_on_error.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_get_fixes_on_error.dart @@ -67,14 +67,13 @@ class LegacyGetFixesOnErrorBenchmark extends DartLanguageServerBenchmark { // It's done analyzing: Ask for fixes on the error. for (int i = 0; i < 5; i++) { Stopwatch stopwatch = Stopwatch()..start(); - var result = - await (await send( - LegacyMessages.getFixes( - largestIdSeen + 1, - runDetails.mainFile.uri, - runDetails.typingErrorAtOffset, - ), - ))!.completer.future; + var result = await (await send( + LegacyMessages.getFixes( + largestIdSeen + 1, + runDetails.mainFile.uri, + runDetails.typingErrorAtOffset, + ), + ))!.completer.future; stopwatch.stop(); var error = result['result']['fixes'].first['error']['type']; if (error != 'COMPILE_TIME_ERROR') throw 'Expected COMPILE_TIME_ERROR'; diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_files_in_flutter_set_subscriptions.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_files_in_flutter_set_subscriptions.dart index bf373e15a91..c4657d123da 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_files_in_flutter_set_subscriptions.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_files_in_flutter_set_subscriptions.dart @@ -75,14 +75,13 @@ class LegacyManyFilesInFlutterSetSubscriptionsBenchmark // ...and ask for completion. var firstCompletionStopwatch = Stopwatch()..start(); - var completion1Result = - await (await send( - LegacyMessages.getSuggestions2( - largestIdSeen + 1, - runDetails.mainFile.uri, - runDetails.typingAtOffset, - ), - ))!.completer.future; + var completion1Result = await (await send( + LegacyMessages.getSuggestions2( + largestIdSeen + 1, + runDetails.mainFile.uri, + runDetails.typingAtOffset, + ), + ))!.completer.future; firstCompletionStopwatch.stop(); List completion1Items = completion1Result['result']['suggestions'] as List; @@ -128,14 +127,13 @@ class LegacyManyFilesInFlutterSetSubscriptionsBenchmark ))!.completer.future.then((_) => getAssistsStopwatch.stop()); // The user tabs back into the main file and ask for completion again. - Future> completionFuture = - (await send( - LegacyMessages.getSuggestions2( - largestIdSeen + 1, - runDetails.mainFile.uri, - runDetails.typingAtOffset, - ), - ))!.completer.future; + Future> completionFuture = (await send( + LegacyMessages.getSuggestions2( + largestIdSeen + 1, + runDetails.mainFile.uri, + runDetails.typingAtOffset, + ), + ))!.completer.future; Stopwatch stopwatch = Stopwatch()..start(); var completionResponse = await completionFuture; diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_get_fixes_and_get_assists_requests.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_get_fixes_and_get_assists_requests.dart index d907c4acbcf..a8b7911db80 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_get_fixes_and_get_assists_requests.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_get_fixes_and_get_assists_requests.dart @@ -85,14 +85,13 @@ class LegacyManyGetFixesAndGetAssisstRequestsBenchmark ); // Ask for completion - Future> completionFuture = - (await send( - LegacyMessages.getSuggestions2( - largestIdSeen + 1, - runDetails.mainFile.uri, - runDetails.typingAtOffset, - ), - ))!.completer.future; + Future> completionFuture = (await send( + LegacyMessages.getSuggestions2( + largestIdSeen + 1, + runDetails.mainFile.uri, + runDetails.typingAtOffset, + ), + ))!.completer.future; Stopwatch stopwatch = Stopwatch()..start(); var completionResponse = await completionFuture; diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_hover_requests.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_hover_requests.dart index 24b6b7230f6..1f45cc2a3e5 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_hover_requests.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_many_hover_requests.dart @@ -74,14 +74,13 @@ class LegacyManyHoverRequestsBenchmark extends DartLanguageServerBenchmark { ); // Ask for completion - Future> completionFuture = - (await send( - LegacyMessages.getSuggestions2( - largestIdSeen + 1, - runDetails.mainFile.uri, - runDetails.typingAtOffset, - ), - ))!.completer.future; + Future> completionFuture = (await send( + LegacyMessages.getSuggestions2( + largestIdSeen + 1, + runDetails.mainFile.uri, + runDetails.typingAtOffset, + ), + ))!.completer.future; Stopwatch stopwatch = Stopwatch()..start(); var completionResponse = await completionFuture; diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_typing_temporary_missing_end_brace.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_typing_temporary_missing_end_brace.dart index 182cfdf781e..a6fc45cab7d 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_typing_temporary_missing_end_brace.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_typing_temporary_missing_end_brace.dart @@ -107,14 +107,13 @@ class LegacyTypingTemporaryMissingEndBraceBenchmark ); // Ask for completion - Future> completionFuture = - (await send( - LegacyMessages.getSuggestions2( - largestIdSeen + 1, - runDetails.orderedFileCopies.last.uri, - completionOffset, - ), - ))!.completer.future; + Future> completionFuture = (await send( + LegacyMessages.getSuggestions2( + largestIdSeen + 1, + runDetails.orderedFileCopies.last.uri, + completionOffset, + ), + ))!.completer.future; stopwatch = Stopwatch()..start(); var completionResponse = await completionFuture; diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_with_plugin_that_times_out.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_with_plugin_that_times_out.dart index 4af5e0dd17b..8e8ce2caa45 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_with_plugin_that_times_out.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/legacy_with_plugin_that_times_out.dart @@ -75,14 +75,13 @@ class LegacyWithPluginThatTimesOutBencmark extends DartLanguageServerBenchmark { // ...and ask for completion. var firstCompletionStopwatch = Stopwatch()..start(); - var completionResult = - await (await send( - LegacyMessages.getSuggestions2( - largestIdSeen + 1, - runDetails.mainFile.uri, - runDetails.typingAtOffset, - ), - ))!.completer.future; + var completionResult = await (await send( + LegacyMessages.getSuggestions2( + largestIdSeen + 1, + runDetails.mainFile.uri, + runDetails.typingAtOffset, + ), + ))!.completer.future; firstCompletionStopwatch.stop(); List completionItems = completionResult['result']['suggestions'] as List; diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_completion_after_change.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_completion_after_change.dart index 2d7b1a56947..6a2a0e8542e 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_completion_after_change.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_completion_after_change.dart @@ -109,15 +109,14 @@ class LspCompletionAfterChange extends DartLanguageServerBenchmark { insert: 'ge', ), ); - Future> completionFuture = - (await send( - LspMessages.completion( - runDetails.mainFile.uri, - largestIdSeen + 1, - line: 3, - character: 4 /* after the 'ge' just typed */, - ), - ))!.completer.future; + Future> completionFuture = (await send( + LspMessages.completion( + runDetails.mainFile.uri, + largestIdSeen + 1, + line: 3, + character: 4 /* after the 'ge' just typed */, + ), + ))!.completer.future; Stopwatch stopwatch = Stopwatch()..start(); var completionResponse = await completionFuture; diff --git a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_with_plugin_that_times_out.dart b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_with_plugin_that_times_out.dart index 28bbf51a07e..b37ff3a9b98 100644 --- a/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_with_plugin_that_times_out.dart +++ b/pkg/analysis_server/tool/benchmark_tools/big_chain_benchmark/lsp_with_plugin_that_times_out.dart @@ -75,15 +75,14 @@ class LspWithPluginThatTimesOutBencmark extends DartLanguageServerBenchmark { // ...and ask for completion. var firstCompletionStopwatch = Stopwatch()..start(); - var completionResult = - await (await send( - LspMessages.completion( - runDetails.mainFile.uri, - largestIdSeen + 1, - line: 3, - character: 4 /* after the 'ge' just typed */, - ), - ))!.completer.future; + var completionResult = await (await send( + LspMessages.completion( + runDetails.mainFile.uri, + largestIdSeen + 1, + line: 3, + character: 4 /* after the 'ge' just typed */, + ), + ))!.completer.future; firstCompletionStopwatch.stop(); List completionItems = completionResult['result']['items'] as List; diff --git a/pkg/analysis_server/tool/benchmark_tools/language_server_benchmark.dart b/pkg/analysis_server/tool/benchmark_tools/language_server_benchmark.dart index 05e63346af1..7118734c984 100644 --- a/pkg/analysis_server/tool/benchmark_tools/language_server_benchmark.dart +++ b/pkg/analysis_server/tool/benchmark_tools/language_server_benchmark.dart @@ -368,8 +368,9 @@ abstract class DartLanguageServerBenchmark { _printedVmServiceStuff = true; } if (header.startsWith('Content-Length:')) { - String contentLength = - header.substring('Content-Length:'.length).trim(); + String contentLength = header + .substring('Content-Length:'.length) + .trim(); _headerContentLength = int.parse(contentLength); break; } @@ -400,10 +401,9 @@ abstract class DartLanguageServerBenchmark { (!_lsp && message['event'] == 'server.status')) { dynamic params = message['params']; if (params is Map) { - dynamic isAnalyzing = - _lsp - ? params['isAnalyzing'] - : params['analysis']?['isAnalyzing']; + dynamic isAnalyzing = _lsp + ? params['isAnalyzing'] + : params['analysis']?['isAnalyzing']; if (isAnalyzing is bool) { _analyzingCompleter.complete(isAnalyzing); _analyzingCompleter = Completer(); diff --git a/pkg/analysis_server/tool/benchmark_tools/run_utils.dart b/pkg/analysis_server/tool/benchmark_tools/run_utils.dart index 26b305512bf..a2afec1281b 100644 --- a/pkg/analysis_server/tool/benchmark_tools/run_utils.dart +++ b/pkg/analysis_server/tool/benchmark_tools/run_utils.dart @@ -48,8 +48,11 @@ Future runHelper( bool jsonOutput = false; for (String arg in args) { if (arg.startsWith('--sizes=')) { - sizeOptions = - arg.substring('--sizes='.length).split(',').map(int.parse).toList(); + sizeOptions = arg + .substring('--sizes='.length) + .split(',') + .map(int.parse) + .toList(); } else if (arg.startsWith('--verbosity=')) { verbosity = int.parse(arg.substring('--verbosity='.length)); } else if (arg == '--json') { diff --git a/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_assist_other_file_could_add_late.dart b/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_assist_other_file_could_add_late.dart index 1af383a9908..7ae6cddcfe1 100644 --- a/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_assist_other_file_could_add_late.dart +++ b/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_assist_other_file_could_add_late.dart @@ -100,17 +100,18 @@ class LspAssistLate extends DartLanguageServerBenchmark { Future timeAssist(int lineNumber, int column) async { var codeActionStopwatch = Stopwatch()..start(); - var codeActionFuture = (await send( - LspMessages.codeAction( - largestIdSeen + 1, - runDetails.mainFile.uri, - line: lineNumber, - character: column, - ), - ))!.completer.future.then((result) { - codeActionStopwatch.stop(); - return result; - }); + var codeActionFuture = + (await send( + LspMessages.codeAction( + largestIdSeen + 1, + runDetails.mainFile.uri, + line: lineNumber, + character: column, + ), + ))!.completer.future.then((result) { + codeActionStopwatch.stop(); + return result; + }); await codeActionFuture; return codeActionStopwatch.elapsed; } diff --git a/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_many_assist_calls.dart b/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_many_assist_calls.dart index 16204b605e1..712e4c43282 100644 --- a/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_many_assist_calls.dart +++ b/pkg/analysis_server/tool/benchmark_tools/single_benchmarks/lsp_many_assist_calls.dart @@ -109,17 +109,18 @@ class LspManyAssistCalls extends DartLanguageServerBenchmark { Future timeAssist(int lineNumber, int column) async { var codeActionStopwatch = Stopwatch()..start(); - var codeActionFuture = (await send( - LspMessages.codeAction( - largestIdSeen + 1, - runDetails.mainFile.uri, - line: lineNumber, - character: column, - ), - ))!.completer.future.then((result) { - codeActionStopwatch.stop(); - return result; - }); + var codeActionFuture = + (await send( + LspMessages.codeAction( + largestIdSeen + 1, + runDetails.mainFile.uri, + line: lineNumber, + character: column, + ), + ))!.completer.future.then((result) { + codeActionStopwatch.stop(); + return result; + }); await codeActionFuture; return codeActionStopwatch.elapsed; } diff --git a/pkg/analysis_server/tool/bulk_fix/supported_lints.dart b/pkg/analysis_server/tool/bulk_fix/supported_lints.dart index 16c11e08c30..7b8d87bfa9a 100644 --- a/pkg/analysis_server/tool/bulk_fix/supported_lints.dart +++ b/pkg/analysis_server/tool/bulk_fix/supported_lints.dart @@ -11,10 +11,9 @@ void main() { var bulkFixCodes = registeredFixGenerators.lintProducers.entries .where( (e) => e.value.any( - (generator) => - generator( - context: StubCorrectionProducerContext.instance, - ).canBeAppliedAcrossFiles, + (generator) => generator( + context: StubCorrectionProducerContext.instance, + ).canBeAppliedAcrossFiles, ), ) .map((e) => e.key); diff --git a/pkg/analysis_server/tool/code_completion/benchmark/flutter.dart b/pkg/analysis_server/tool/code_completion/benchmark/flutter.dart index d55870edef2..b8515b4d9bb 100644 --- a/pkg/analysis_server/tool/code_completion/benchmark/flutter.dart +++ b/pkg/analysis_server/tool/code_completion/benchmark/flutter.dart @@ -76,15 +76,16 @@ Future _runForever({ var budget = CompletionBudget(Duration(seconds: 30)); List suggestions = []; for (var i = 0; i < 10; i++) { - suggestions = await DartCompletionManager( - budget: budget, - notImportedSuggestions: NotImportedSuggestions(), - ).computeSuggestions( - dartRequest, - OperationPerformanceImpl(''), - maxSuggestions: -1, - useFilter: false, - ); + suggestions = + await DartCompletionManager( + budget: budget, + notImportedSuggestions: NotImportedSuggestions(), + ).computeSuggestions( + dartRequest, + OperationPerformanceImpl(''), + maxSuggestions: -1, + useFilter: false, + ); } var responseTime = timer.elapsedMilliseconds; diff --git a/pkg/analysis_server/tool/code_completion/code_metrics.dart b/pkg/analysis_server/tool/code_completion/code_metrics.dart index a83af77c219..d82072fb80e 100644 --- a/pkg/analysis_server/tool/code_completion/code_metrics.dart +++ b/pkg/analysis_server/tool/code_completion/code_metrics.dart @@ -1331,10 +1331,10 @@ class CodeShapeMetricsComputer { /// column occupied by the map. List _convertMap(String context, Map map) { var columns = []; - var entries = - map.entries.toList()..sort((first, second) { - return second.value.compareTo(first.value); - }); + var entries = map.entries.toList() + ..sort((first, second) { + return second.value.compareTo(first.value); + }); var total = 0; for (var entry in entries) { total += entry.value; diff --git a/pkg/analysis_server/tool/code_completion/completion_metrics.dart b/pkg/analysis_server/tool/code_completion/completion_metrics.dart index 8d23676346d..a3ad607100d 100644 --- a/pkg/analysis_server/tool/code_completion/completion_metrics.dart +++ b/pkg/analysis_server/tool/code_completion/completion_metrics.dart @@ -133,8 +133,9 @@ Future main(List args) async { if (result.wasParsed('mapFile')) { var mapFile = provider.getFile(result['mapFile'] as String); - var map = - computer.targetMetrics.map((metrics) => metrics.toJson()).toList(); + var map = computer.targetMetrics + .map((metrics) => metrics.toJson()) + .toList(); mapFile.writeAsStringSync(json.encode(map)); } else { computer.printResults(); @@ -477,12 +478,9 @@ class CompletionMetrics { ]); for (var entry in (map['worstResults'] as Map).entries) { var group = CompletionGroup.values[int.parse(entry.key)]; - var results = - (entry.value as List) - .map( - (map) => CompletionResult.fromJson(map as Map), - ) - .toList(); + var results = (entry.value as List) + .map((map) => CompletionResult.fromJson(map as Map)) + .toList(); metrics.worstResults[group] = results; } return metrics; @@ -605,10 +603,11 @@ class CompletionMetrics { 'charsBeforeTopFive': charsBeforeTopFive.toJson(), 'insertionLengthTheoretical': insertionLengthTheoretical.toJson(), 'missingCompletionLocations': missingCompletionLocations.toList(), - 'missingCompletionLocationTables': - missingCompletionLocationTables.toList(), - 'slowestResults': - slowestResults.map((result) => result.toJson()).toList(), + 'missingCompletionLocationTables': missingCompletionLocationTables + .toList(), + 'slowestResults': slowestResults + .map((result) => result.toJson()) + .toList(), 'worstResults': worstResults.map( (key, value) => MapEntry( key.index.toString(), @@ -957,11 +956,10 @@ class CompletionQualityMetricsComputer extends CompletionMetricsComputer { var features = listener.featureMap[suggestion] ?? MetricsSuggestionListener.noFeatures; - topSuggestions = - suggestions - .sublist(0, math.min(10, suggestions.length)) - .map((suggestion) => SuggestionData(suggestion, features)) - .toList(); + topSuggestions = suggestions + .sublist(0, math.min(10, suggestions.length)) + .map((suggestion) => SuggestionData(suggestion, features)) + .toList(); precedingRelevanceCounts = {}; for (var i = 0; i < rank - 1; i++) { var relevance = suggestions[i].relevanceScore; @@ -1218,9 +1216,8 @@ class CompletionQualityMetricsComputer extends CompletionMetricsComputer { if (options.printMissedCompletionDetails) { printHeading(2, 'Missed Completions'); var needsBlankLine = false; - var entries = - metrics.missedCompletions.entries.toList() - ..sort((first, second) => first.key.compareTo(second.key)); + var entries = metrics.missedCompletions.entries.toList() + ..sort((first, second) => first.key.compareTo(second.key)); for (var entry in entries) { if (needsBlankLine) { print(''); @@ -1285,11 +1282,10 @@ class CompletionQualityMetricsComputer extends CompletionMetricsComputer { toRow(targetMetrics.map((metrics) => metrics.successfulMrrComputer)), blankRow, ]; - var elementKinds = - targetMetrics - .expand((metrics) => metrics.groupMrrComputers.keys) - .toSet() - .toList(); + var elementKinds = targetMetrics + .expand((metrics) => metrics.groupMrrComputers.keys) + .toSet() + .toList(); elementKinds.sort((first, second) => first.name.compareTo(second.name)); for (var kind in elementKinds) { table.add( @@ -1304,11 +1300,10 @@ class CompletionQualityMetricsComputer extends CompletionMetricsComputer { } if (options.printMrrByLocation) { table.add(blankRow); - var locations = - targetMetrics - .expand((metrics) => metrics.locationMrrComputers.keys) - .toSet() - .toList(); + var locations = targetMetrics + .expand((metrics) => metrics.locationMrrComputers.keys) + .toSet() + .toList(); locations.sort(); for (var location in locations) { table.add( @@ -1404,9 +1399,8 @@ class CompletionQualityMetricsComputer extends CompletionMetricsComputer { if (options.printShadowedCompletionDetails) { printHeading(2, 'Shadowed Completions'); var needsBlankLine = false; - var entries = - metrics.shadowedCompletions.entries.toList() - ..sort((first, second) => first.key.compareTo(second.key)); + var entries = metrics.shadowedCompletions.entries.toList() + ..sort((first, second) => first.key.compareTo(second.key)); for (var entry in entries) { if (needsBlankLine) { print(''); @@ -1429,10 +1423,9 @@ class CompletionQualityMetricsComputer extends CompletionMetricsComputer { /// are in the top [maxSlowestResults] slowest results, are included. void printSlowestResults(CompletionMetrics metrics) { var p90ElapsedMs = metrics.percentileCompletionMS.p90; - var slowestResults = - metrics.slowestResults - .where((element) => element.elapsedMS >= p90ElapsedMs) - .toList(); + var slowestResults = metrics.slowestResults + .where((element) => element.elapsedMS >= p90ElapsedMs) + .toList(); print(''); printHeading(2, 'The slowest completion results to compute'); for (var result in slowestResults) { @@ -1515,15 +1508,16 @@ class CompletionQualityMetricsComputer extends CompletionMetricsComputer { NotImportedSuggestions notImportedSuggestions, ) async { var budget = CompletionBudget(Duration(seconds: 30)); - var collector = await DartCompletionManager( - budget: budget, - listener: listener, - notImportedSuggestions: notImportedSuggestions, - ).computeFinalizedCandidateSuggestions( - request: dartRequest, - performance: performance, - maxSuggestions: -1, - ); + var collector = + await DartCompletionManager( + budget: budget, + listener: listener, + notImportedSuggestions: notImportedSuggestions, + ).computeFinalizedCandidateSuggestions( + request: dartRequest, + performance: performance, + maxSuggestions: -1, + ); return collector.suggestions; } @@ -1675,13 +1669,13 @@ class CompletionResult { var actualSuggestion = SuggestionData.fromJson( map['actualSuggestion'] as Map, ); - var topSuggestions = - (map['topSuggestions'] as List) - .map((map) => SuggestionData.fromJson(map as Map)) - .toList(); - var precedingRelevanceCounts = (map['precedingRelevanceCounts'] - as Map) - .map((key, value) => MapEntry(int.parse(key), value as int)); + var topSuggestions = (map['topSuggestions'] as List) + .map((map) => SuggestionData.fromJson(map as Map)) + .toList(); + var precedingRelevanceCounts = + (map['precedingRelevanceCounts'] as Map).map( + (key, value) => MapEntry(int.parse(key), value as int), + ); var expectedCompletion = ExpectedCompletion.fromJson( map['expectedCompletion'] as Map, ); @@ -1761,8 +1755,9 @@ class CompletionResult { 'place': place.toJson(), 'actualSuggestion': actualSuggestion.toJson(), if (topSuggestions != null) - 'topSuggestions': - topSuggestions!.map((suggestion) => suggestion.toJson()).toList(), + 'topSuggestions': topSuggestions! + .map((suggestion) => suggestion.toJson()) + .toList(), if (precedingRelevanceCounts != null) 'precedingRelevanceCounts': precedingRelevanceCounts!.map( (key, value) => MapEntry(key.toString(), value), diff --git a/pkg/analysis_server/tool/code_completion/corpus.dart b/pkg/analysis_server/tool/code_completion/corpus.dart index 824d6cf10af..38deb93c369 100644 --- a/pkg/analysis_server/tool/code_completion/corpus.dart +++ b/pkg/analysis_server/tool/code_completion/corpus.dart @@ -66,10 +66,9 @@ final _appDir = path.join( 'apps', ); -final _homeDir = - Platform.isWindows - ? Platform.environment['LOCALAPPDATA']! - : Platform.environment['HOME']!; +final _homeDir = Platform.isWindows + ? Platform.environment['LOCALAPPDATA']! + : Platform.environment['HOME']!; final _packageConfig = path.join('.dart_tool', 'package_config.json'); diff --git a/pkg/analysis_server/tool/code_completion/metrics_util.dart b/pkg/analysis_server/tool/code_completion/metrics_util.dart index 235937d860c..7df32414160 100644 --- a/pkg/analysis_server/tool/code_completion/metrics_util.dart +++ b/pkg/analysis_server/tool/code_completion/metrics_util.dart @@ -383,8 +383,8 @@ class PercentileComputer { _counts = Uint32List.fromList((map['counts'] as List).cast()); valueCount = map['valueCount'] as int; aboveValueMaxCount = map['aboveValueMaxCount'] as int; - aboveValueMaxSamples = - (map['aboveValueMaxSamples'] as List).cast(); + aboveValueMaxSamples = (map['aboveValueMaxSamples'] as List) + .cast(); maxValue = map['maxValue'] as int; } diff --git a/pkg/analysis_server/tool/code_completion/relevance_metrics.dart b/pkg/analysis_server/tool/code_completion/relevance_metrics.dart index 73404f392b7..205ae4fed8e 100644 --- a/pkg/analysis_server/tool/code_completion/relevance_metrics.dart +++ b/pkg/analysis_server/tool/code_completion/relevance_metrics.dart @@ -1533,10 +1533,9 @@ class RelevanceDataCollector extends RecursiveAstVisitor { @override void visitVariableDeclaration(VariableDeclaration node) { - var keywords = - node.parent?.parent is FieldDeclaration - ? [Keyword.COVARIANT, ...expressionKeywords] - : expressionKeywords; + var keywords = node.parent?.parent is FieldDeclaration + ? [Keyword.COVARIANT, ...expressionKeywords] + : expressionKeywords; _recordDataForNode( 'VariableDeclaration (initializer)', node.initializer, @@ -2270,10 +2269,10 @@ class RelevanceMetricsComputer { if (map == null) { return columns; } - var entries = - map.entries.toList()..sort((first, second) { - return second.value.compareTo(first.value); - }); + var entries = map.entries.toList() + ..sort((first, second) { + return second.value.compareTo(first.value); + }); var total = 0; for (var entry in entries) { total += entry.value; @@ -2326,9 +2325,8 @@ class RelevanceMetricsComputer { StringSink sink, Map> contextMap, ) { - var entries = - contextMap.entries.toList() - ..sort((first, second) => first.key.compareTo(second.key)); + var entries = contextMap.entries.toList() + ..sort((first, second) => first.key.compareTo(second.key)); for (var i = 0; i < entries.length; i++) { if (i > 0) { sink.writeln(); @@ -2403,9 +2401,8 @@ class RelevanceMetricsComputer { StringSink sink, Map percentageMap, ) { - var entries = - percentageMap.entries.toList() - ..sort((first, second) => first.key.compareTo(second.key)); + var entries = percentageMap.entries.toList() + ..sort((first, second) => first.key.compareTo(second.key)); for (var entry in entries) { var name = entry.key; var data = entry.value; diff --git a/pkg/analysis_server/tool/code_completion/relevance_table_generator.dart b/pkg/analysis_server/tool/code_completion/relevance_table_generator.dart index 251c4f7f185..ce6f5f52abf 100644 --- a/pkg/analysis_server/tool/code_completion/relevance_table_generator.dart +++ b/pkg/analysis_server/tool/code_completion/relevance_table_generator.dart @@ -1413,10 +1413,9 @@ class RelevanceDataCollector extends RecursiveAstVisitor { @override void visitVariableDeclaration(VariableDeclaration node) { - var keywords = - node.parent?.parent is FieldDeclaration - ? [Keyword.COVARIANT, ...expressionKeywords] - : expressionKeywords; + var keywords = node.parent?.parent is FieldDeclaration + ? [Keyword.COVARIANT, ...expressionKeywords] + : expressionKeywords; _recordDataForNode( 'VariableDeclaration_initializer', node.initializer, @@ -1729,9 +1728,8 @@ const defaultElementKindRelevance = { '''); var byKind = data._byKind; - var entries = - byKind.entries.toList() - ..sort((first, second) => first.key.compareTo(second.key)); + var entries = byKind.entries.toList() + ..sort((first, second) => first.key.compareTo(second.key)); for (var entry in entries) { var completionLocation = entry.key; var counts = entry.value; @@ -1739,9 +1737,8 @@ const defaultElementKindRelevance = { var totalCount = _totalCount(counts); // TODO(brianwilkerson): If two element kinds have the same count they // ought to have the same probability. This doesn't correctly do that. - var entries = - counts.entries.toList() - ..sort((first, second) => first.value.compareTo(second.value)); + var entries = counts.entries.toList() + ..sort((first, second) => first.value.compareTo(second.value)); sink.write(" '"); sink.write(completionLocation); @@ -1807,9 +1804,8 @@ const defaultKeywordRelevance = { '''); var byKind = data._byKind; - var entries = - byKind.entries.toList() - ..sort((first, second) => first.key.compareTo(second.key)); + var entries = byKind.entries.toList() + ..sort((first, second) => first.key.compareTo(second.key)); for (var entry in entries) { var completionLocation = entry.key; var counts = entry.value; @@ -1817,9 +1813,8 @@ const defaultKeywordRelevance = { var totalCount = _totalCount(counts); // TODO(brianwilkerson): If two keywords have the same count they ought to // have the same probability. This doesn't correctly do that. - var entries = - counts.entries.toList() - ..sort((first, second) => first.value.compareTo(second.value)); + var entries = counts.entries.toList() + ..sort((first, second) => first.value.compareTo(second.value)); sink.write(" '"); sink.write(completionLocation); diff --git a/pkg/analysis_server/tool/code_completion/visitors.dart b/pkg/analysis_server/tool/code_completion/visitors.dart index 33cb9b127e0..986514acff7 100644 --- a/pkg/analysis_server/tool/code_completion/visitors.dart +++ b/pkg/analysis_server/tool/code_completion/visitors.dart @@ -49,22 +49,20 @@ class ExpectedCompletion { var lineNumber = map['lineNumber'] as int; var columnNumber = map['columnNumber'] as int; var completionString = map['completionString'] as String; - var kind = - map['kind'] != null - ? protocol.CompletionSuggestionKind.fromJson( - jsonDecoder, - '', - map['kind'] as String, - ) - : null; - var elementKind = - map['elementKind'] != null - ? protocol.ElementKind.fromJson( - jsonDecoder, - '', - map['elementKind'] as String, - ) - : null; + var kind = map['kind'] != null + ? protocol.CompletionSuggestionKind.fromJson( + jsonDecoder, + '', + map['kind'] as String, + ) + : null; + var elementKind = map['elementKind'] != null + ? protocol.ElementKind.fromJson( + jsonDecoder, + '', + map['elementKind'] as String, + ) + : null; return ExpectedCompletion.specialCompletionString( filePath, _SyntacticEntity(offset), diff --git a/pkg/analysis_server/tool/codebase/failing_tests.dart b/pkg/analysis_server/tool/codebase/failing_tests.dart index 04d087bd6af..c4d2b0a7041 100644 --- a/pkg/analysis_server/tool/codebase/failing_tests.dart +++ b/pkg/analysis_server/tool/codebase/failing_tests.dart @@ -132,11 +132,10 @@ class FailingTestAnnotationTracker extends RecursiveAstVisitor { @override void visitAnnotation(Annotation node) { if (node.name.name == 'FailingTest' || node.name.name == 'SkippedTest') { - var issue = - node.arguments?.arguments - .whereType() - .where((arg) => arg.name.label.name == 'issue') - .firstOrNull; + var issue = node.arguments?.arguments + .whereType() + .where((arg) => arg.name.label.name == 'issue') + .firstOrNull; var issueUrl = (issue?.expression as SimpleStringLiteral?)?.value; if (issueUrl != null && issueUrl.startsWith('https://github.com/')) { var issueUri = Uri.parse(issueUrl); diff --git a/pkg/analysis_server/tool/generate_testing_package.dart b/pkg/analysis_server/tool/generate_testing_package.dart index 76f65d33a0e..f68db682837 100644 --- a/pkg/analysis_server/tool/generate_testing_package.dart +++ b/pkg/analysis_server/tool/generate_testing_package.dart @@ -18,33 +18,32 @@ import 'package:test_descriptor/test_descriptor.dart' as d; void main(List args) async { // TODO(srawlins): Support multiple packages which depend on each other, in a // DAG similar to the import graph. - var argParser = - ArgParser() - ..addOption( - 'library-count', - defaultsTo: '1', - help: 'the number of libraries', - ) - ..addOption( - 'class-count', - defaultsTo: '1', - help: 'the number of classes per library', - ) - ..addOption( - 'method-count', - defaultsTo: '1', - help: 'the number of methods per class', - ) - ..addOption( - 'parameter-count', - defaultsTo: '1', - help: 'the number of parameters per method', - ) - ..addFlag('use-barrel-file', help: 'Whether to add a barrel import') - ..addFlag( - 'use-json-serializable', - help: 'Whether to declare @JsonSerializable classes', - ); + var argParser = ArgParser() + ..addOption( + 'library-count', + defaultsTo: '1', + help: 'the number of libraries', + ) + ..addOption( + 'class-count', + defaultsTo: '1', + help: 'the number of classes per library', + ) + ..addOption( + 'method-count', + defaultsTo: '1', + help: 'the number of methods per class', + ) + ..addOption( + 'parameter-count', + defaultsTo: '1', + help: 'the number of parameters per method', + ) + ..addFlag('use-barrel-file', help: 'Whether to add a barrel import') + ..addFlag( + 'use-json-serializable', + help: 'Whether to declare @JsonSerializable classes', + ); var argResults = argParser.parse(args); var libraryCount = int.parse(argResults['library-count'] as String); var classCount = int.parse(argResults['class-count'] as String); @@ -82,8 +81,9 @@ void main(List args) async { // TODO(srawlins): Make the "connectedness" of the import graph // configurable. var importGraphTier = (log(lIndex) / ln2).ceil(); - var importIndexStep = - importGraphTier == 0 ? -1 : (lIndex - 1) ~/ importGraphTier; + var importIndexStep = importGraphTier == 0 + ? -1 + : (lIndex - 1) ~/ importGraphTier; var content = StringBuffer(); if (useJsonSerializable) { content.writeln("import 'package:json_annotation/json_annotation.dart';"); @@ -182,21 +182,19 @@ String import(String uri) => "import '$uri';"; /// With [useJsonSerializable], several packages are added to the dependencies /// in order to test using build_runner. String pubspec({required bool useJsonSerializable}) { - var dependencies = - useJsonSerializable - ? ''' + var dependencies = useJsonSerializable + ? ''' dependencies: json_annotation: any json_serializable: any ''' - : ''; - var devDependencies = - useJsonSerializable - ? ''' + : ''; + var devDependencies = useJsonSerializable + ? ''' dev_dependencies: build_runner: any ''' - : ''; + : ''; return ''' name: test_package version: 0.0.1 diff --git a/pkg/analysis_server/tool/instrumentation/page/log_page.dart b/pkg/analysis_server/tool/instrumentation/page/log_page.dart index ba920db4dd7..ba65971ac35 100644 --- a/pkg/analysis_server/tool/instrumentation/page/log_page.dart +++ b/pkg/analysis_server/tool/instrumentation/page/log_page.dart @@ -230,8 +230,9 @@ function selectEntryGroup(pageStart) { void _writeLeftColumn(StringSink sink) { var length = entries.length; var pageLength = this.pageLength; - var pageEnd = - pageLength == null ? length : math.min(pageStart + pageLength, length); + var pageEnd = pageLength == null + ? length + : math.min(pageStart + pageLength, length); // // Write the header of the column. // diff --git a/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart b/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart index 701dcbb318c..5a81c8c07ba 100644 --- a/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart +++ b/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart @@ -289,16 +289,15 @@ String _memberNameForType(TypeBase type) { type = resolveTypeAlias(type); } - var dartType = - type is NullableType - ? '${type.dartType}?' - : type is UnionType - ? type.types.map(_memberNameForType).join() - : type is ArrayType - ? 'List${_memberNameForType(type.elementType)}' - : type is MapType - ? 'Map${_memberNameForType(type.indexType)}${_memberNameForType(type.valueType)}' - : type.dartType; + var dartType = type is NullableType + ? '${type.dartType}?' + : type is UnionType + ? type.types.map(_memberNameForType).join() + : type is ArrayType + ? 'List${_memberNameForType(type.elementType)}' + : type is MapType + ? 'Map${_memberNameForType(type.indexType)}${_memberNameForType(type.valueType)}' + : type.dartType; return capitalize(dartType.replaceAll('?', 'Nullable')); } @@ -335,16 +334,16 @@ String _sortContent(String content) { /// Subtypes will be sorted such that types with the most required fields appear /// first to ensure `fromJson` constructors delegate to the most specific type. void _sortSubtypes() { - int requiredFieldCount(String interfaceName) => - _interfaces[interfaceName]!.members - .whereType() - .where((field) => !field.allowsUndefined && !field.allowsNull) - .length; - int optionalFieldCount(String interfaceName) => - _interfaces[interfaceName]!.members - .whereType() - .where((field) => field.allowsUndefined || field.allowsNull) - .length; + int requiredFieldCount(String interfaceName) => _interfaces[interfaceName]! + .members + .whereType() + .where((field) => !field.allowsUndefined && !field.allowsNull) + .length; + int optionalFieldCount(String interfaceName) => _interfaces[interfaceName]! + .members + .whereType() + .where((field) => field.allowsUndefined || field.allowsNull) + .length; for (var entry in _subtypes.entries) { var subtypes = entry.value; subtypes.sort((subtype1, subtype2) { @@ -414,10 +413,9 @@ void _writeCanParseMethod(IndentableStringBuffer buffer, Interface interface) { // In order to consider this valid for parsing, all fields that must not be // undefined must be present and also type check for the correct type. // Any fields that are optional but present, must still type check. - var fields = - _getAllFields( - interface, - ).whereNot((f) => isNullableAnyType(f.type)).toList(); + var fields = _getAllFields( + interface, + ).whereNot((f) => isNullableAnyType(f.type)).toList(); for (var i = 0; i < fields.length; i++) { var field = fields[i]; var type = field.type; @@ -558,14 +556,16 @@ void _writeConstructor(IndentableStringBuffer buffer, Interface interface) { !field.allowsUndefined && !isNullableAnyType(field.type); var requiredKeyword = isRequired ? 'required' : ''; - var valueCode = - isLiteral ? ' = ${(field.type as LiteralType).valueAsLiteral}' : ''; + var valueCode = isLiteral + ? ' = ${(field.type as LiteralType).valueAsLiteral}' + : ''; return '$requiredKeyword this.${field.name}$valueCode, '; }).join(), ) ..write('})'); - var fieldsWithValidation = - allFields.where((f) => f.type is LiteralType).toList(); + var fieldsWithValidation = allFields + .where((f) => f.type is LiteralType) + .toList(); if (fieldsWithValidation.isNotEmpty) { buffer ..writeIndentedln(' {') @@ -751,12 +751,12 @@ void _writeFromJsonCode( var nullOperator = allowsNull ? '?' : ''; var cast = requiresCast && - // LSPAny - !isNullableAnyType(type) && - // LSPObject marked as optional - !(isObjectType(type) && allowsNull) - ? ' as ${type.dartTypeWithTypeArgs}$nullOperator' - : ''; + // LSPAny + !isNullableAnyType(type) && + // LSPObject marked as optional + !(isObjectType(type) && allowsNull) + ? ' as ${type.dartTypeWithTypeArgs}$nullOperator' + : ''; if (_isSimpleType(type)) { buffer.write('$valueCode$cast'); @@ -1020,8 +1020,9 @@ void _writeInterface(IndentableStringBuffer buffer, Interface interface) { buffer ..writeIndented(interface.abstract ? 'abstract ' : '') ..write('class ${interface.name} '); - var allBaseTypes = - interface.baseTypes.map((t) => t.dartTypeWithTypeArgs).toList(); + var allBaseTypes = interface.baseTypes + .map((t) => t.dartTypeWithTypeArgs) + .toList(); allBaseTypes.add('ToJsonable'); if (allBaseTypes.isNotEmpty) { buffer.writeIndented('implements ${allBaseTypes.join(', ')} '); diff --git a/pkg/analysis_server/tool/lsp_spec/generate_all.dart b/pkg/analysis_server/tool/lsp_spec/generate_all.dart index b78dbb7d534..d1bd5a8b8ee 100644 --- a/pkg/analysis_server/tool/lsp_spec/generate_all.dart +++ b/pkg/analysis_server/tool/lsp_spec/generate_all.dart @@ -49,16 +49,14 @@ const argDownload = 'download'; const argHelp = 'help'; -final argParser = - ArgParser() - ..addFlag(argHelp, hide: true) - ..addFlag( - argDownload, - negatable: false, - abbr: 'd', - help: - 'Download the latest version of the LSP spec before generating types', - ); +final argParser = ArgParser() + ..addFlag(argHelp, hide: true) + ..addFlag( + argDownload, + negatable: false, + abbr: 'd', + help: 'Download the latest version of the LSP spec before generating types', + ); final String languageServerProtocolPackagePath = path.join( sdkRootPath, @@ -67,9 +65,8 @@ final String languageServerProtocolPackagePath = path.join( 'language_server_protocol', ); -final String licenseComment = LineSplitter.split( - File(localLicensePath).readAsStringSync(), - ) +final String +licenseComment = LineSplitter.split(File(localLicensePath).readAsStringSync()) .skipWhile( (line) => line != @@ -83,8 +80,9 @@ final String localLicensePath = '$languageServerProtocolPackagePath/LICENSE'; final String localSpecPath = '$languageServerProtocolPackagePath/lsp_meta_model.json'; -final String sdkRootPath = - File(Platform.script.toFilePath()).parent.parent.parent.parent.parent.path; +final String sdkRootPath = File( + Platform.script.toFilePath(), +).parent.parent.parent.parent.parent.path; final Uri specLicenseUri = Uri.parse( 'https://microsoft.github.io/language-server-protocol/License-code.txt', @@ -117,7 +115,8 @@ ${licenseResp.body} '''); } -String generatedFileHeader(int year, {bool importCustom = false}) => ''' +String generatedFileHeader(int year, {bool importCustom = false}) => + ''' $licenseComment // This file has been automatically generated. Please do not edit it manually. @@ -165,12 +164,11 @@ List getCustomClasses() { bool canBeNull = false, bool canBeUndefined = false, }) { - var fieldType = - array - ? ArrayType(TypeReference(type)) - : literal - ? LiteralType(TypeReference.string, type) - : TypeReference(type); + var fieldType = array + ? ArrayType(TypeReference(type)) + : literal + ? LiteralType(TypeReference.string, type) + : TypeReference(type); return Field( name: name, diff --git a/pkg/analysis_server/tool/lsp_spec/meta_model_cleaner.dart b/pkg/analysis_server/tool/lsp_spec/meta_model_cleaner.dart index cf113b8482a..d0d3cd581a7 100644 --- a/pkg/analysis_server/tool/lsp_spec/meta_model_cleaner.dart +++ b/pkg/analysis_server/tool/lsp_spec/meta_model_cleaner.dart @@ -164,15 +164,13 @@ class LspMetaModelCleaner { name: interface.name, comment: _cleanComment(interface.comment), isProposed: interface.isProposed, - baseTypes: - interface.baseTypes - .where((type) => _includeTypeInOutput(type.name)) - .toList(), - members: - interface.members - .where(_includeEntityInOutput) - .map((member) => _cleanMember(interface.name, member)) - .toList(), + baseTypes: interface.baseTypes + .where((type) => _includeTypeInOutput(type.name)) + .toList(), + members: interface.members + .where(_includeEntityInOutput) + .map((member) => _cleanMember(interface.name, member)) + .toList(), ); } @@ -192,11 +190,10 @@ class LspMetaModelCleaner { comment: _cleanComment(namespace.comment), isProposed: namespace.isProposed, typeOfValues: namespace.typeOfValues, - members: - namespace.members - .where(_includeEntityInOutput) - .map((member) => _cleanMember(namespace.name, member)) - .toList(), + members: namespace.members + .where(_includeEntityInOutput) + .map((member) => _cleanMember(namespace.name, member)) + .toList(), ); } @@ -227,12 +224,11 @@ class LspMetaModelCleaner { /// Key on `dartType` to ensure we combine different types that will map down /// to the same type. TypeBase _cleanUnionType(UnionType type) { - var uniqueTypes = - Map.fromEntries( - type.types - .where(_allowTypeInUnions) - .map((t) => MapEntry(t.uniqueTypeIdentifier, t)), - ).values.toList(); + var uniqueTypes = Map.fromEntries( + type.types + .where(_allowTypeInUnions) + .map((t) => MapEntry(t.uniqueTypeIdentifier, t)), + ).values.toList(); // If our list includes something that maps to Object? as well as other // types, we should just treat the whole thing as Object? as we get no value @@ -256,10 +252,9 @@ class LspMetaModelCleaner { return LiteralUnionType(uniqueTypes.cast()); } else if (uniqueTypes.any(isNullType)) { var remainingTypes = uniqueTypes.whereNot(isNullType).toList(); - var nonNullType = - remainingTypes.length == 1 - ? remainingTypes.single - : UnionType(remainingTypes); + var nonNullType = remainingTypes.length == 1 + ? remainingTypes.single + : UnionType(remainingTypes); return NullableType(nonNullType); } else { return UnionType(uniqueTypes); @@ -288,18 +283,18 @@ class LspMetaModelCleaner { return improvedTypeName != null ? improvedTypeName.endsWith('[]') - ? ArrayType( - TypeReference( - improvedTypeName.substring(0, improvedTypeName.length - 2), - ), - ) - : improvedTypeName.endsWith('?') - ? NullableType( - TypeReference( - improvedTypeName.substring(0, improvedTypeName.length - 1), - ), - ) - : TypeReference(improvedTypeName) + ? ArrayType( + TypeReference( + improvedTypeName.substring(0, improvedTypeName.length - 2), + ), + ) + : improvedTypeName.endsWith('?') + ? NullableType( + TypeReference( + improvedTypeName.substring(0, improvedTypeName.length - 1), + ), + ) + : TypeReference(improvedTypeName) : null; } diff --git a/pkg/analysis_server/tool/lsp_spec/meta_model_reader.dart b/pkg/analysis_server/tool/lsp_spec/meta_model_reader.dart index ef1942d0cbb..36803ad17ea 100644 --- a/pkg/analysis_server/tool/lsp_spec/meta_model_reader.dart +++ b/pkg/analysis_server/tool/lsp_spec/meta_model_reader.dart @@ -92,8 +92,10 @@ class LspMetaModelReader { ); } - var methodConstants = - methods.cast>().map(toConstant).toList(); + var methodConstants = methods + .cast>() + .map(toConstant) + .toList(); if (methodConstants.isEmpty) { return null; @@ -195,10 +197,9 @@ class LspMetaModelReader { var inlineTypeName = _generateTypeName(parentName, fieldName ?? ''); // First record the definition of the anonymous type itself. - var members = - (model['value']['properties'] as List) - .map((p) => _extractMember(inlineTypeName, p)) - .toList(); + var members = (model['value']['properties'] as List) + .map((p) => _extractMember(inlineTypeName, p)) + .toList(); _addType(Interface.inline(inlineTypeName, members)); // Then return its name. @@ -211,27 +212,22 @@ class LspMetaModelReader { _typeNames.add(parentName); var itemTypes = model['items'] as List; - var types = - itemTypes.map((item) { - var generatedName = _generateAvailableTypeName( - parentName, - fieldName, - ); - return _extractType(generatedName, null, item); - }).toList(); + var types = itemTypes.map((item) { + var generatedName = _generateAvailableTypeName(parentName, fieldName); + return _extractType(generatedName, null, item); + }).toList(); return UnionType(types); } else if (model['kind'] == 'tuple') { // We currently just map tuples to an array of any of the types. The // LSP 3.17 spec only has one tuple which is `[number, number]`. var itemTypes = model['items'] as List; - var types = - itemTypes.mapIndexed((index, item) { - var suffix = index + 1; - var name = fieldName ?? ''; - var thisName = '$name$suffix'; - return _extractType(parentName, thisName, item); - }).toList(); + var types = itemTypes.mapIndexed((index, item) { + var suffix = index + 1; + var name = fieldName ?? ''; + var thisName = '$name$suffix'; + return _extractType(parentName, thisName, item); + }).toList(); return ArrayType(UnionType(types)); } else { throw 'Unable to extract type from $model'; @@ -253,8 +249,9 @@ class LspMetaModelReader { if (suffixIndex > 20) { throw 'Failed to generate an available name for $name'; } - generatedName = - requiresSuffix || suffixIndex > 1 ? '$name$suffixIndex' : name; + generatedName = requiresSuffix || suffixIndex > 1 + ? '$name$suffixIndex' + : name; suffixIndex++; } while (_typeNames.contains(generatedName)); return generatedName; @@ -313,10 +310,9 @@ class LspMetaModelReader { var namePrefix = method.split('/').map(capitalize).join(); var documentation = model['documentation'] as String?; - var paramsDoc = - documentation != null - ? 'Parameters for ${_camelCase(documentation)}' - : null; + var paramsDoc = documentation != null + ? 'Parameters for ${_camelCase(documentation)}' + : null; _createUnionAlias('${namePrefix}Params', model['params'], paramsDoc); } @@ -326,15 +322,13 @@ class LspMetaModelReader { var namePrefix = method.split('/').map(capitalize).join(); var documentation = model['documentation'] as String?; - var paramsDoc = - documentation != null - ? 'Parameters for ${_camelCase(documentation)}' - : null; + var paramsDoc = documentation != null + ? 'Parameters for ${_camelCase(documentation)}' + : null; - var resultDoc = - documentation != null - ? 'Result for ${_camelCase(documentation)}' - : null; + var resultDoc = documentation != null + ? 'Result for ${_camelCase(documentation)}' + : null; _createUnionAlias('${namePrefix}Params', model['params'], paramsDoc); _createUnionAlias('${namePrefix}Result', model['result'], resultDoc); diff --git a/pkg/analysis_server/tool/lsp_test_with_parameters.dart b/pkg/analysis_server/tool/lsp_test_with_parameters.dart index 2c4f66431ef..8aed81699be 100644 --- a/pkg/analysis_server/tool/lsp_test_with_parameters.dart +++ b/pkg/analysis_server/tool/lsp_test_with_parameters.dart @@ -229,8 +229,9 @@ void listenToStdout(List event) { List headers = headerRaw.split('\r\n'); for (String header in headers) { if (header.startsWith('Content-Length:')) { - String contentLength = - header.substring('Content-Length:'.length).trim(); + String contentLength = header + .substring('Content-Length:'.length) + .trim(); headerContentLength = int.parse(contentLength); break; } diff --git a/pkg/analysis_server/tool/spec/codegen_dart_notification_handler.dart b/pkg/analysis_server/tool/spec/codegen_dart_notification_handler.dart index cf848456db7..213e07fa59e 100644 --- a/pkg/analysis_server/tool/spec/codegen_dart_notification_handler.dart +++ b/pkg/analysis_server/tool/spec/codegen_dart_notification_handler.dart @@ -24,11 +24,10 @@ GeneratedFile clientTarget() { String _capitalize(String name) => '${name.substring(0, 1).toUpperCase()}${name.substring(1)}'; -List _generateDartDoc(Element html) => - html.children - .where((Element elem) => elem.name == 'p') - .map((Element elem) => innerText(elem).trim()) - .toList(); +List _generateDartDoc(Element html) => html.children + .where((Element elem) => elem.name == 'p') + .map((Element elem) => innerText(elem).trim()) + .toList(); String _generateNotificationMethodName(String domainName, String event) => 'on${_capitalize(domainName)}${_capitalize(event)}'; diff --git a/pkg/analysis_server/tool/spec/codegen_dart_protocol.dart b/pkg/analysis_server/tool/spec/codegen_dart_protocol.dart index 64a3243c62e..30d54d41f67 100644 --- a/pkg/analysis_server/tool/spec/codegen_dart_protocol.dart +++ b/pkg/analysis_server/tool/spec/codegen_dart_protocol.dart @@ -209,14 +209,12 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { return false; } - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', { ${clientUriConverterKind.namedParameterString} }' - : ''; - var namedArguments = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', ${clientUriConverterKind.namedArgumentString}' - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? ', { ${clientUriConverterKind.namedParameterString} }' + : ''; + var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none + ? ', ${clientUriConverterKind.namedArgumentString}' + : ''; var args = ['$inputType $inputName']; args.addAll(extraArgs); @@ -295,20 +293,18 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Emit the toJson() code for an empty class. void emitEmptyToJsonMember() { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? '{ ${clientUriConverterKind.namedParameterString} }' - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? '{ ${clientUriConverterKind.namedParameterString} }' + : ''; writeln('@override'); writeln('Map toJson($namedParameters) => {};'); } /// Emit a class to encapsulate an enum. void emitEnum(String className, TypeEnum type, ImpliedType impliedType) { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? '{ ${clientUriConverterKind.namedParameterString} }' - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? '{ ${clientUriConverterKind.namedParameterString} }' + : ''; docComment( toHtmlVisitor.collectHtml(() { @@ -369,10 +365,9 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { TypeEnum type, ImpliedType impliedType, ) { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', { ${clientUriConverterKind.namedParameterString} }' - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? ', { ${clientUriConverterKind.namedParameterString} }' + : ''; writeln( 'factory $className.fromJson(JsonDecoder jsonDecoder, String jsonPath, Object? json$namedParameters) {', ); @@ -505,8 +500,8 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none - ? 'clientUriConverter: null' - : ''; + ? 'clientUriConverter: null' + : ''; writeln('@override'); writeln('String toString() => json.encode(toJson($namedArguments));'); writeln(); @@ -596,14 +591,12 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { TypeObject type, ImpliedType impliedType, ) { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', { ${clientUriConverterKind.namedParameterString} }' - : ''; - var namedArguments = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', ${clientUriConverterKind.namedArgumentString}' - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? ', { ${clientUriConverterKind.namedParameterString} }' + : ''; + var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none + ? ', ${clientUriConverterKind.namedArgumentString}' + : ''; var humanReadableNameString = _literalString(impliedType.humanReadableName); if (className == 'RefactoringFeedback') { @@ -913,18 +906,16 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Emit the toJson() code for an object class. void emitToJsonMember(TypeObject type) { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? '{ ${clientUriConverterKind.namedParameterString} }' - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? '{ ${clientUriConverterKind.namedParameterString} }' + : ''; writeln('@override'); writeln('Map toJson($namedParameters) {'); indent(() { - var resultMapName = - type.fields.any((field) => field.name == 'result') - ? 'result_' - : 'result'; + var resultMapName = type.fields.any((field) => field.name == 'result') + ? 'result_' + : 'result'; writeln('var $resultMapName = {};'); for (var field in type.fields) { var fieldNameString = _literalString(field.name); @@ -956,14 +947,12 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Emit the toNotification() code for a class, if appropriate. Returns true /// if code was emitted. bool emitToNotificationMember(ImpliedType impliedType) { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? '{ ${clientUriConverterKind.namedParameterString} }' - : ''; - var namedArguments = - clientUriConverterKind != CodegenUriConverterKind.none - ? clientUriConverterKind.namedArgumentString - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? '{ ${clientUriConverterKind.namedParameterString} }' + : ''; + var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none + ? clientUriConverterKind.namedArgumentString + : ''; if (impliedType.kind == 'notificationParams') { writeln('Notification toNotification($namedParameters) {'); @@ -971,8 +960,9 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { var eventString = _literalString( (impliedType.apiNode as Notification).longEvent, ); - var jsonPart = - impliedType.type != null ? 'toJson($namedArguments)' : 'null'; + var jsonPart = impliedType.type != null + ? 'toJson($namedArguments)' + : 'null'; writeln('return Notification($eventString, $jsonPart);'); }); writeln('}'); @@ -984,14 +974,12 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Emit the toRequest() code for a class, if appropriate. Returns true if /// code was emitted. bool emitToRequestMember(ImpliedType impliedType) { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', { ${clientUriConverterKind.namedParameterString} }' - : ''; - var namedArguments = - clientUriConverterKind != CodegenUriConverterKind.none - ? clientUriConverterKind.namedArgumentString - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? ', { ${clientUriConverterKind.namedParameterString} }' + : ''; + var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none + ? clientUriConverterKind.namedArgumentString + : ''; if (impliedType.kind == 'requestParams') { writeln('@override'); @@ -1017,14 +1005,12 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Emit the toResponse() code for a class, if appropriate. Returns true if /// code was emitted. bool emitToResponseMember(ImpliedType impliedType) { - var namedParameters = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', { ${clientUriConverterKind.namedParameterString} }' - : ''; - var namedArguments = - clientUriConverterKind != CodegenUriConverterKind.none - ? clientUriConverterKind.namedArgumentString - : ''; + var namedParameters = clientUriConverterKind != CodegenUriConverterKind.none + ? ', { ${clientUriConverterKind.namedParameterString} }' + : ''; + var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none + ? clientUriConverterKind.namedArgumentString + : ''; if (impliedType.kind == 'requestResult') { writeln('@override'); @@ -1060,10 +1046,9 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Compute the code necessary to translate [type] from JSON. FromJsonCode fromJsonCode(TypeDecl type) { - var namedArguments = - clientUriConverterKind != CodegenUriConverterKind.none - ? ', ${clientUriConverterKind.namedArgumentString}' - : ''; + var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none + ? ', ${clientUriConverterKind.namedArgumentString}' + : ''; if (type is TypeReference) { var referencedDefinition = api.types[type.typeName]; @@ -1184,11 +1169,10 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Return a list of the classes to be emitted. List getClassesToEmit() { - var types = - impliedTypes.values.where((ImpliedType type) { - var node = type.apiNode; - return !(node is TypeDefinition && node.isExternal); - }).toList(); + var types = impliedTypes.values.where((ImpliedType type) { + var node = type.apiNode; + return !(node is TypeDefinition && node.isExternal); + }).toList(); types.sort( (first, second) => capitalize(first.camelName).compareTo(capitalize(second.camelName)), @@ -1210,10 +1194,9 @@ class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator { /// Compute the code necessary to convert [type] to JSON. ToJsonCode toJsonCode(TypeDecl type) { - var namedArguments = - clientUriConverterKind != CodegenUriConverterKind.none - ? clientUriConverterKind.namedArgumentString - : ''; + var namedArguments = clientUriConverterKind != CodegenUriConverterKind.none + ? clientUriConverterKind.namedArgumentString + : ''; var resolvedType = resolveTypeReferenceChain(type); if (type is TypeReference && @@ -1374,10 +1357,9 @@ class FromJsonFunction extends FromJsonCode { bool get isIdentity => false; @override - String asSnippet(String jsonPath, String json) => - castType == null - ? '$asClosure($jsonPath, $json)' - : '$asClosure($jsonPath, $json as $castType)'; + String asSnippet(String jsonPath, String json) => castType == null + ? '$asClosure($jsonPath, $json)' + : '$asClosure($jsonPath, $json as $castType)'; } /// Representation of FromJsonCode for the identity transformation. diff --git a/pkg/analysis_server/tool/spec/codegen_matchers.dart b/pkg/analysis_server/tool/spec/codegen_matchers.dart index ff8bf606b5e..4cb258f1468 100644 --- a/pkg/analysis_server/tool/spec/codegen_matchers.dart +++ b/pkg/analysis_server/tool/spec/codegen_matchers.dart @@ -155,10 +155,9 @@ class CodegenMatchersVisitor extends HierarchicalApiVisitor with CodeGenerator { (TypeObjectField field) => !field.optional, ); outputObjectFields(requiredFields); - var optionalFields = - typeObject.fields - .where((TypeObjectField field) => field.optional) - .toList(); + var optionalFields = typeObject.fields + .where((TypeObjectField field) => field.optional) + .toList(); if (optionalFields.isNotEmpty) { write(', optionalFields: '); outputObjectFields(optionalFields); diff --git a/pkg/analysis_server/tool/spec/to_html.dart b/pkg/analysis_server/tool/spec/to_html.dart index 5a69fe4da16..9e6d535f15e 100644 --- a/pkg/analysis_server/tool/spec/to_html.dart +++ b/pkg/analysis_server/tool/spec/to_html.dart @@ -123,7 +123,8 @@ a:focus, a:hover { list-style-type: none; } -'''.trim(); +''' + .trim(); final GeneratedFile target = GeneratedFile('analysis_server/doc/api.html', ( pkgRoot,