Version 2.14.0-12.0.dev
Merge commit 'fa1a28bf6504b617de81832ba6062c6389727865' into 'dev'
diff --git a/pkg/analysis_server/lib/protocol/protocol.dart b/pkg/analysis_server/lib/protocol/protocol.dart
index 8eef995..e9d5c9d 100644
--- a/pkg/analysis_server/lib/protocol/protocol.dart
+++ b/pkg/analysis_server/lib/protocol/protocol.dart
@@ -270,7 +270,7 @@
/// this handler, return `null` so that other handlers will be given a chance
/// to handle it. Otherwise, return the response that should be passed back to
/// the client.
- Response handleRequest(Request request);
+ Response? handleRequest(Request request);
}
/// A response to a request.
diff --git a/pkg/analysis_server/lib/src/analysis_server.dart b/pkg/analysis_server/lib/src/analysis_server.dart
index 77193b3..a9dde60 100644
--- a/pkg/analysis_server/lib/src/analysis_server.dart
+++ b/pkg/analysis_server/lib/src/analysis_server.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:async';
import 'dart:collection';
import 'dart:core';
@@ -76,7 +74,7 @@
/// A list of the request handlers used to handle the requests sent to this
/// server.
- List<RequestHandler> handlers;
+ late List<RequestHandler> handlers;
/// A set of the [ServerService]s to send notifications for.
Set<ServerService> serverServices = HashSet<ServerService>();
@@ -98,23 +96,24 @@
WidgetDescriptions flutterWidgetDescriptions = WidgetDescriptions();
/// The [Completer] that completes when analysis is complete.
- Completer _onAnalysisCompleteCompleter;
+ Completer<void>? _onAnalysisCompleteCompleter;
/// The controller that is notified when analysis is started.
- StreamController<bool> _onAnalysisStartedController;
+ final StreamController<bool> _onAnalysisStartedController =
+ StreamController.broadcast();
/// If the "analysis.analyzedFiles" notification is currently being subscribed
/// to (see [generalAnalysisServices]), and at least one such notification has
/// been sent since the subscription was enabled, the set of analyzed files
/// that was delivered in the most recently sent notification. Otherwise
/// `null`.
- Set<String> prevAnalyzedFiles;
+ Set<String>? prevAnalyzedFiles;
/// The controller for [onAnalysisSetChanged].
final StreamController _onAnalysisSetChangedController =
StreamController.broadcast(sync: true);
- final DetachableFileSystemManager detachableFileSystemManager;
+ final DetachableFileSystemManager? detachableFileSystemManager;
/// Initialize a newly created server to receive requests from and send
/// responses to the given [channel].
@@ -130,9 +129,9 @@
DartSdkManager sdkManager,
CrashReportingAttachmentsBuilder crashReportingAttachmentsBuilder,
InstrumentationService instrumentationService, {
- http.Client httpClient,
- RequestStatisticsHelper requestStatistics,
- DiagnosticServer diagnosticServer,
+ http.Client? httpClient,
+ RequestStatisticsHelper? requestStatistics,
+ DiagnosticServer? diagnosticServer,
this.detachableFileSystemManager,
// Disable to avoid using this in unit tests.
bool enableBazelWatcher = false,
@@ -155,11 +154,9 @@
analysisDriverScheduler.status.listen(sendStatusNotificationNew);
analysisDriverScheduler.start();
- _onAnalysisStartedController = StreamController.broadcast();
onAnalysisStarted.first.then((_) {
onAnalysisComplete.then((_) {
- performanceAfterStartup = ServerPerformance();
- performance = performanceAfterStartup;
+ performance = performanceAfterStartup = ServerPerformance();
});
});
var notification =
@@ -181,15 +178,15 @@
}
/// The analytics instance; note, this object can be `null`.
- telemetry.Analytics get analytics => options.analytics;
+ telemetry.Analytics? get analytics => options.analytics;
/// The [Future] that completes when analysis is complete.
- Future get onAnalysisComplete {
+ Future<void> get onAnalysisComplete {
if (isAnalysisComplete()) {
return Future.value();
}
- _onAnalysisCompleteCompleter ??= Completer();
- return _onAnalysisCompleteCompleter.future;
+ var completer = _onAnalysisCompleteCompleter ??= Completer<void>();
+ return completer.future;
}
/// The stream that is notified when the analysis set is changed - this might
@@ -217,7 +214,7 @@
/// Return the cached analysis result for the file with the given [path].
/// If there is no cached result, return `null`.
- ResolvedUnitResult getCachedResolvedUnit(String path) {
+ ResolvedUnitResult? getCachedResolvedUnit(String path) {
if (!file_paths.isDart(resourceProvider.pathContext, path)) {
return null;
}
@@ -247,9 +244,7 @@
} catch (exception, stackTrace) {
var error =
RequestError(RequestErrorCode.SERVER_ERROR, exception.toString());
- if (stackTrace != null) {
- error.stackTrace = stackTrace.toString();
- }
+ error.stackTrace = stackTrace.toString();
var response = Response(request.id, error: error);
channel.sendResponse(response);
return;
@@ -338,7 +333,7 @@
exceptions.add(ServerException(
message,
exception,
- stackTrace is StackTrace ? stackTrace : null,
+ stackTrace is StackTrace ? stackTrace : StackTrace.current,
fatal,
));
}
@@ -349,8 +344,9 @@
if (status.isAnalyzing) {
_onAnalysisStartedController.add(true);
}
- if (_onAnalysisCompleteCompleter != null && !status.isAnalyzing) {
- _onAnalysisCompleteCompleter.complete();
+ var onAnalysisCompleteCompleter = _onAnalysisCompleteCompleter;
+ if (onAnalysisCompleteCompleter != null && !status.isAnalyzing) {
+ onAnalysisCompleteCompleter.complete();
_onAnalysisCompleteCompleter = null;
}
// Perform on-idle actions.
@@ -391,7 +387,8 @@
try {
contextManager.setRoots(includedPaths, excludedPaths);
} on UnimplementedError catch (e) {
- throw RequestFailure(Response.unsupportedFeature(requestId, e.message));
+ throw RequestFailure(Response.unsupportedFeature(
+ requestId, e.message ?? 'Unsupported feature.'));
}
analysisDriverScheduler.transitionToAnalyzingToIdleIfNoFilesToAnalyze();
}
@@ -451,11 +448,10 @@
pubApi.close();
- if (options.analytics != null) {
- options.analytics
- .waitForLastPing(timeout: Duration(milliseconds: 200))
- .then((_) {
- options.analytics.close();
+ var analytics = options.analytics;
+ if (analytics != null) {
+ analytics.waitForLastPing(timeout: Duration(milliseconds: 200)).then((_) {
+ analytics.close();
});
}
@@ -476,7 +472,7 @@
_onAnalysisSetChangedController.add(null);
changes.forEach((file, change) {
// Prepare the old overlay contents.
- String oldContents;
+ String? oldContents;
try {
if (resourceProvider.hasOverlay(file)) {
oldContents = resourceProvider.getFile(file).readAsStringSync();
@@ -484,7 +480,7 @@
} catch (_) {}
// Prepare the new contents.
- String newContents;
+ String? newContents;
if (change is AddContentOverlay) {
newContents = change.content;
} else if (change is ChangeContentOverlay) {
@@ -604,27 +600,27 @@
/// Various IDE options.
class AnalysisServerOptions {
- String newAnalysisDriverLog;
+ String? newAnalysisDriverLog;
- String clientId;
- String clientVersion;
+ String? clientId;
+ String? clientVersion;
/// Base path where to cache data.
- String cacheFolder;
+ String? cacheFolder;
/// The analytics instance; note, this object can be `null`, and should be
/// accessed via a null-aware operator.
- telemetry.Analytics analytics;
+ telemetry.Analytics? analytics;
/// The crash report sender instance; note, this object can be `null`, and
/// should be accessed via a null-aware operator.
- CrashReportSender crashReportSender;
+ CrashReportSender? crashReportSender;
/// An optional set of configuration overrides specified by the SDK.
///
/// These overrides can provide new values for configuration settings, and are
/// generally used in specific SDKs (like the internal google3 one).
- SdkConfiguration configurationOverrides;
+ SdkConfiguration? configurationOverrides;
/// Whether to use the Language Server Protocol.
bool useLanguageServerProtocol = false;
@@ -644,7 +640,7 @@
ServerContextManagerCallbacks(this.analysisServer, this.resourceProvider);
- NotificationManager get _notificationManager =>
+ AbstractNotificationManager get _notificationManager =>
analysisServer.notificationManager;
@override
@@ -683,7 +679,7 @@
@override
void listenAnalysisDriver(nd.AnalysisDriver analysisDriver) {
analysisDriver.results.listen((result) {
- var path = result.path;
+ var path = result.path!;
filesToFlush.add(path);
if (analysisServer.isAnalyzed(path)) {
_notificationManager.recordAnalysisErrors(NotificationManager.serverId,
@@ -844,7 +840,7 @@
int slowRequestCount = 0;
/// Log timing information for a request.
- void logRequestTiming(int clientRequestTime) {
+ void logRequestTiming(int? clientRequestTime) {
++requestCount;
if (clientRequestTime != null) {
var latency = DateTime.now().millisecondsSinceEpoch - clientRequestTime;
diff --git a/pkg/analysis_server/lib/src/analysis_server_abstract.dart b/pkg/analysis_server/lib/src/analysis_server_abstract.dart
index 109b9c7..1cb9178 100644
--- a/pkg/analysis_server/lib/src/analysis_server_abstract.dart
+++ b/pkg/analysis_server/lib/src/analysis_server_abstract.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:core';
import 'dart:io' as io;
import 'dart:io';
@@ -47,6 +45,7 @@
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/services/available_declarations.dart';
import 'package:analyzer/src/util/file_paths.dart' as file_paths;
+import 'package:collection/collection.dart';
import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
@@ -61,7 +60,7 @@
/// The [ContextManager] that handles the mapping from analysis roots to
/// context directories.
- ContextManager contextManager;
+ late ContextManager contextManager;
/// The object used to manage sending a subset of notifications to the client.
/// The subset of notifications are those to which plugins may contribute.
@@ -69,25 +68,25 @@
AbstractNotificationManager notificationManager;
/// The object used to manage the execution of plugins.
- PluginManager pluginManager;
+ late PluginManager pluginManager;
/// The object used to manage the SDK's known to this server.
final DartSdkManager sdkManager;
/// The [SearchEngine] for this server, may be `null` if indexing is disabled.
- SearchEngine searchEngine;
+ SearchEngine? searchEngine;
- ByteStore byteStore;
+ late ByteStore byteStore;
- nd.AnalysisDriverScheduler analysisDriverScheduler;
+ late nd.AnalysisDriverScheduler analysisDriverScheduler;
- DeclarationsTracker declarationsTracker;
- DeclarationsTrackerData declarationsTrackerData;
+ DeclarationsTracker? declarationsTracker;
+ DeclarationsTrackerData? declarationsTrackerData;
/// The DiagnosticServer for this AnalysisServer. If available, it can be used
/// to start an http diagnostics server or return the port for an existing
/// server.
- final DiagnosticServer diagnosticServer;
+ final DiagnosticServer? diagnosticServer;
/// A [RecentBuffer] of the most recent exceptions encountered by the analysis
/// server.
@@ -98,25 +97,25 @@
/// Performance information after initial analysis is complete
/// or `null` if the initial analysis is not yet complete
- ServerPerformance performanceAfterStartup;
+ ServerPerformance? performanceAfterStartup;
/// A client for making requests to the pub.dev API.
final PubApi pubApi;
/// A service for fetching pub.dev package details.
- PubPackageService pubPackageService;
+ late PubPackageService pubPackageService;
/// The class into which performance information is currently being recorded.
/// During startup, this will be the same as [performanceDuringStartup]
/// and after startup is complete, this switches to [performanceAfterStartup].
- ServerPerformance performance;
+ late ServerPerformance performance;
/// Performance information before initial analysis is complete.
final ServerPerformance performanceDuringStartup = ServerPerformance();
- RequestStatisticsHelper requestStatistics;
+ RequestStatisticsHelper? requestStatistics;
- PerformanceLog analysisPerformanceLogger;
+ PerformanceLog? analysisPerformanceLogger;
/// The set of the files that are currently priority.
final Set<String> priorityFiles = <String>{};
@@ -139,10 +138,10 @@
this.crashReportingAttachmentsBuilder,
ResourceProvider baseResourceProvider,
this.instrumentationService,
- http.Client httpClient,
+ http.Client? httpClient,
this.notificationManager, {
this.requestStatistics,
- bool enableBazelWatcher,
+ bool enableBazelWatcher = false,
}) : resourceProvider = OverlayResourceProvider(baseResourceProvider),
pubApi = PubApi(instrumentationService, httpClient,
Platform.environment['PUB_HOSTED_URL']) {
@@ -158,22 +157,22 @@
instrumentationService);
var pluginWatcher = PluginWatcher(resourceProvider, pluginManager);
- {
- var name = options.newAnalysisDriverLog;
- StringSink sink = NullStringSink();
- if (name != null) {
- if (name == 'stdout') {
- sink = io.stdout;
- } else if (name.startsWith('file:')) {
- var path = name.substring('file:'.length);
- sink = FileStringSink(path);
- }
+ var name = options.newAnalysisDriverLog;
+ StringSink sink = NullStringSink();
+ if (name != null) {
+ if (name == 'stdout') {
+ sink = io.stdout;
+ } else if (name.startsWith('file:')) {
+ var path = name.substring('file:'.length);
+ sink = FileStringSink(path);
}
- if (requestStatistics != null) {
- sink = TeeStringSink(sink, requestStatistics.perfLoggerStringSink);
- }
- analysisPerformanceLogger = PerformanceLog(sink);
}
+ final requestStatistics = this.requestStatistics;
+ if (requestStatistics != null) {
+ sink = TeeStringSink(sink, requestStatistics.perfLoggerStringSink);
+ }
+ final analysisPerformanceLogger =
+ this.analysisPerformanceLogger = PerformanceLog(sink);
byteStore = createByteStore(resourceProvider);
@@ -182,10 +181,11 @@
driverWatcher: pluginWatcher);
if (options.featureSet.completion) {
- declarationsTracker = DeclarationsTracker(byteStore, resourceProvider);
- declarationsTrackerData = DeclarationsTrackerData(declarationsTracker);
+ var tracker = declarationsTracker =
+ DeclarationsTracker(byteStore, resourceProvider);
+ declarationsTrackerData = DeclarationsTrackerData(tracker);
analysisDriverScheduler.outOfBandWorker =
- CompletionLibrariesWorker(declarationsTracker);
+ CompletionLibrariesWorker(tracker);
}
contextManager = ContextManagerImpl(
@@ -218,7 +218,7 @@
void addContextsToDeclarationsTracker() {
declarationsTracker?.discardContexts();
for (var driver in driverMap.values) {
- declarationsTracker?.addContext(driver.analysisContext);
+ declarationsTracker?.addContext(driver.analysisContext!);
driver.resetUriResolution();
}
}
@@ -232,8 +232,7 @@
const memoryCacheSize = 128 * M;
if (resourceProvider is OverlayResourceProvider) {
- OverlayResourceProvider overlay = resourceProvider;
- resourceProvider = overlay.baseProvider;
+ resourceProvider = resourceProvider.baseProvider;
}
if (resourceProvider is PhysicalResourceProvider) {
var stateLocation = resourceProvider.getStateLocation('.analysis-driver');
@@ -249,22 +248,20 @@
/// Return an analysis driver to which the file with the given [path] is
/// added if one exists, otherwise a driver in which the file was analyzed if
/// one exists, otherwise the first driver, otherwise `null`.
- nd.AnalysisDriver getAnalysisDriver(String path) {
+ nd.AnalysisDriver? getAnalysisDriver(String path) {
var drivers = driverMap.values.toList();
if (drivers.isNotEmpty) {
// Sort the drivers so that more deeply nested contexts will be checked
// before enclosing contexts.
drivers.sort((first, second) {
- var firstRoot = first.analysisContext.contextRoot.root.path;
- var secondRoot = second.analysisContext.contextRoot.root.path;
+ var firstRoot = first.analysisContext!.contextRoot.root.path;
+ var secondRoot = second.analysisContext!.contextRoot.root.path;
return secondRoot.length - firstRoot.length;
});
- var driver = drivers.firstWhere(
- (driver) => driver.analysisContext.contextRoot.isAnalyzed(path),
- orElse: () => null);
- driver ??= drivers.firstWhere(
- (driver) => driver.knownFiles.contains(path),
- orElse: () => null);
+ var driver = drivers.firstWhereOrNull(
+ (driver) => driver.analysisContext!.contextRoot.isAnalyzed(path));
+ driver ??= drivers
+ .firstWhereOrNull((driver) => driver.knownFiles.contains(path));
driver ??= drivers.first;
return driver;
}
@@ -281,7 +278,7 @@
/// Return a [Future] that completes with the [Element] at the given
/// [offset] of the given [file], or with `null` if there is no node at the
/// [offset] or the node does not have an element.
- Future<Element> getElementAtOffset(String file, int offset) async {
+ Future<Element?> getElementAtOffset(String file, int offset) async {
if (!priorityFiles.contains(file)) {
var driver = getAnalysisDriver(file);
if (driver == null) {
@@ -293,8 +290,7 @@
return null;
}
- var element = findElementByNameOffset(
- (unitElementResult as UnitElementResult).element, offset);
+ var element = findElementByNameOffset(unitElementResult.element, offset);
if (element != null) {
return element;
}
@@ -306,7 +302,7 @@
/// Return the [Element] of the given [node], or `null` if [node] is `null` or
/// does not have an element.
- Element getElementOfNode(AstNode node) {
+ Element? getElementOfNode(AstNode? node) {
if (node == null) {
return null;
}
@@ -329,7 +325,7 @@
/// Return a [Future] that completes with the resolved [AstNode] at the
/// given [offset] of the given [file], or with `null` if there is no node as
/// the [offset].
- Future<AstNode> getNodeAtOffset(String file, int offset) async {
+ Future<AstNode?> getNodeAtOffset(String file, int offset) async {
var result = await getResolvedUnit(file);
var unit = result?.unit;
if (unit != null) {
@@ -339,18 +335,18 @@
}
/// Return the unresolved unit for the file with the given [path].
- ParsedUnitResult getParsedUnit(String path) {
+ ParsedUnitResult? getParsedUnit(String path) {
if (!file_paths.isDart(resourceProvider.pathContext, path)) {
return null;
}
- return getAnalysisDriver(path)?.currentSession?.getParsedUnit(path);
+ return getAnalysisDriver(path)?.currentSession.getParsedUnit(path);
}
/// Return the resolved unit for the file with the given [path]. The file is
/// analyzed in one of the analysis drivers to which the file was added,
/// otherwise in the first driver, otherwise `null` is returned.
- Future<ResolvedUnitResult> getResolvedUnit(String path,
+ Future<ResolvedUnitResult?>? getResolvedUnit(String path,
{bool sendCachedToStream = false}) {
if (!file_paths.isDart(resourceProvider.pathContext, path)) {
return null;
@@ -366,6 +362,7 @@
.then((value) => value is ResolvedUnitResult ? value : null)
.catchError((e, st) {
instrumentationService.logException(e, st);
+ // ignore: invalid_return_type_for_catch_error
return null;
});
}
@@ -427,10 +424,10 @@
/// Return the path to the location of the byte store on disk, or `null` if
/// there is no on-disk byte store.
- String _getByteStorePath() {
+ String? _getByteStorePath() {
ResourceProvider provider = resourceProvider;
if (provider is OverlayResourceProvider) {
- provider = (provider as OverlayResourceProvider).baseProvider;
+ provider = provider.baseProvider;
}
if (provider is PhysicalResourceProvider) {
var stateLocation = provider.getStateLocation('.analysis-driver');
diff --git a/pkg/analysis_server/lib/src/domain_abstract.dart b/pkg/analysis_server/lib/src/domain_abstract.dart
index e88d541..e7079c1 100644
--- a/pkg/analysis_server/lib/src/domain_abstract.dart
+++ b/pkg/analysis_server/lib/src/domain_abstract.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
@@ -41,24 +39,26 @@
/// waiting for plugins to respond.
Future<List<plugin.Response>> waitForResponses(
Map<PluginInfo, Future<plugin.Response>> futures,
- {plugin.RequestParams requestParameters,
+ {plugin.RequestParams? requestParameters,
int timeout = 500}) async {
// TODO(brianwilkerson) requestParameters might need to be required.
var endTime = DateTime.now().millisecondsSinceEpoch + timeout;
var responses = <plugin.Response>[];
- for (var pluginInfo in futures.keys) {
- var future = futures[pluginInfo];
+ for (var entry in futures.entries) {
+ var pluginInfo = entry.key;
+ var future = entry.value;
try {
var startTime = DateTime.now().millisecondsSinceEpoch;
var response = await future
.timeout(Duration(milliseconds: math.max(endTime - startTime, 0)));
- if (response.error != null) {
+ var error = response.error;
+ if (error != null) {
// TODO(brianwilkerson) Report the error to the plugin manager.
server.instrumentationService.logPluginError(
pluginInfo.data,
- response.error.code.name,
- response.error.message,
- response.error.stackTrace);
+ error.code.name,
+ error.message,
+ error.stackTrace ?? StackTrace.current.toString());
} else {
responses.add(response);
}
@@ -67,7 +67,7 @@
server.instrumentationService.logPluginTimeout(
pluginInfo.data,
JsonEncoder()
- .convert(requestParameters?.toRequest('-')?.toJson() ?? {}));
+ .convert(requestParameters?.toRequest('-').toJson() ?? {}));
} catch (exception, stackTrace) {
// TODO(brianwilkerson) Report the exception to the plugin manager.
server.instrumentationService
diff --git a/pkg/analysis_server/lib/src/domain_analysis.dart b/pkg/analysis_server/lib/src/domain_analysis.dart
index c557341..2e2bc5d 100644
--- a/pkg/analysis_server/lib/src/domain_analysis.dart
+++ b/pkg/analysis_server/lib/src/domain_analysis.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:core';
import 'package:analysis_server/protocol/protocol_constants.dart';
@@ -40,7 +38,7 @@
var result = await server.getResolvedUnit(file);
- if (result?.state != ResultState.VALID) {
+ if (result == null || result.state != ResultState.VALID) {
server.sendResponse(Response.getErrorsInvalidFile(request));
return;
}
@@ -61,21 +59,19 @@
// Prepare the resolved units.
var result = await server.getResolvedUnit(file);
- if (result == null) {
+ if (result is! ResolvedUnitResult) {
server.sendResponse(Response.fileNotAnalyzed(request, file));
return;
}
- var unit = result?.unit;
+ var unit = result.unit!;
// Prepare the hovers.
var hovers = <HoverInformation>[];
- if (unit != null) {
- var hoverInformation = DartUnitHoverComputer(
- server.getDartdocDirectiveInfoFor(result), unit, params.offset)
- .compute();
- if (hoverInformation != null) {
- hovers.add(hoverInformation);
- }
+ var computer = DartUnitHoverComputer(
+ server.getDartdocDirectiveInfoFor(result), unit, params.offset);
+ var hoverInformation = computer.compute();
+ if (hoverInformation != null) {
+ hovers.add(hoverInformation);
}
// Send the response.
@@ -95,7 +91,7 @@
// Prepare the resolved unit.
//
var result = await server.getResolvedUnit(file);
- if (result?.state != ResultState.VALID) {
+ if (result == null || result.state != ResultState.VALID) {
server.sendResponse(Response.getImportedElementsInvalidFile(request));
return;
}
@@ -109,7 +105,7 @@
elements = <ImportedElements>[];
} else {
elements =
- ImportedElementsComputer(result.unit, params.offset, params.length)
+ ImportedElementsComputer(result.unit!, params.offset, params.length)
.compute();
}
@@ -162,15 +158,15 @@
plugin.AnalysisGetNavigationParams(file, offset, length);
var pluginFutures = server.pluginManager.broadcastRequest(
requestParams,
- contextRoot: driver.analysisContext.contextRoot,
+ contextRoot: driver.analysisContext!.contextRoot,
);
//
// Compute navigation data generated by server.
//
var allResults = <AnalysisNavigationParams>[];
var result = await server.getResolvedUnit(file);
- if (result?.state == ResultState.VALID) {
- var unit = result?.unit;
+ if (result != null && result.state == ResultState.VALID) {
+ var unit = result.unit!;
var collector = NavigationCollectorImpl();
computeDartNavigation(
server.resourceProvider, collector, unit, offset, length);
@@ -182,15 +178,12 @@
// Add the navigation data produced by plugins to the server-generated
// navigation data.
//
- if (pluginFutures != null) {
- var responses = await waitForResponses(pluginFutures,
- requestParameters: requestParams);
- for (var response in responses) {
- var result =
- plugin.AnalysisGetNavigationResult.fromResponse(response);
- allResults.add(AnalysisNavigationParams(
- file, result.regions, result.targets, result.files));
- }
+ var responses = await waitForResponses(pluginFutures,
+ requestParameters: requestParams);
+ for (var response in responses) {
+ var result = plugin.AnalysisGetNavigationResult.fromResponse(response);
+ allResults.add(AnalysisNavigationParams(
+ file, result.regions, result.targets, result.files));
}
//
// Return the result.
@@ -238,13 +231,13 @@
// Prepare the resolved units.
var result = await server.getResolvedUnit(file);
- if (result?.state != ResultState.VALID) {
+ if (result == null || result.state != ResultState.VALID) {
server.sendResponse(Response.getSignatureInvalidFile(request));
return;
}
// Ensure the offset provided is a valid location in the file.
- final unit = result.unit;
+ final unit = result.unit!;
final computer = DartUnitSignatureComputer(
server.getDartdocDirectiveInfoFor(result), unit, params.offset);
if (!computer.offsetIsValid) {
@@ -263,7 +256,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
try {
var requestName = request.method;
if (requestName == ANALYSIS_REQUEST_GET_ERRORS) {
@@ -344,9 +337,10 @@
}
}
- if (server.detachableFileSystemManager != null) {
+ var detachableFileSystemManager = server.detachableFileSystemManager;
+ if (detachableFileSystemManager != null) {
// TODO(scheglov) remove the last argument
- server.detachableFileSystemManager
+ detachableFileSystemManager
.setAnalysisRoots(request.id, includedPathList, excludedPathList, {});
} else {
server.setAnalysisRoots(request.id, includedPathList, excludedPathList);
@@ -444,14 +438,16 @@
var params = AnalysisUpdateOptionsParams.fromRequest(request);
var newOptions = params.options;
var updaters = <OptionUpdater>[];
- if (newOptions.generateHints != null) {
+ var generateHints = newOptions.generateHints;
+ if (generateHints != null) {
updaters.add((engine.AnalysisOptionsImpl options) {
- options.hint = newOptions.generateHints;
+ options.hint = generateHints;
});
}
- if (newOptions.generateLints != null) {
+ var generateLints = newOptions.generateLints;
+ if (generateLints != null) {
updaters.add((engine.AnalysisOptionsImpl options) {
- options.lint = newOptions.generateLints;
+ options.lint = generateLints;
});
}
server.updateOptions(updaters);
diff --git a/pkg/analysis_server/lib/src/domain_analytics.dart b/pkg/analysis_server/lib/src/domain_analytics.dart
index 9a8f1aa..e3fe532 100644
--- a/pkg/analysis_server/lib/src/domain_analytics.dart
+++ b/pkg/analysis_server/lib/src/domain_analytics.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:core';
import 'package:analysis_server/protocol/protocol.dart';
@@ -19,12 +17,13 @@
AnalyticsDomainHandler(this.server);
- Analytics get analytics => server.analytics;
+ Analytics? get analytics => server.analytics;
String get _clientId => server.options.clientId ?? 'client';
Response handleEnable(Request request) {
var params = AnalyticsEnableParams.fromRequest(request);
+ final analytics = this.analytics;
if (analytics != null) {
analytics.enabled = params.value;
}
@@ -37,7 +36,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
var requestName = request.method;
if (requestName == ANALYTICS_REQUEST_IS_ENABLED) {
@@ -54,6 +53,7 @@
}
Response handleSendEvent(Request request) {
+ final analytics = this.analytics;
if (analytics == null) {
return AnalyticsSendEventResult().toResponse(request.id);
}
@@ -64,6 +64,7 @@
}
Response handleSendTiming(Request request) {
+ final analytics = this.analytics;
if (analytics == null) {
return AnalyticsSendTimingResult().toResponse(request.id);
}
diff --git a/pkg/analysis_server/lib/src/domain_completion.dart b/pkg/analysis_server/lib/src/domain_completion.dart
index 8a9ff43..4fe65b8 100644
--- a/pkg/analysis_server/lib/src/domain_completion.dart
+++ b/pkg/analysis_server/lib/src/domain_completion.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:async';
import 'package:analysis_server/protocol/protocol.dart';
@@ -46,7 +44,7 @@
int _nextCompletionId = 0;
/// Code completion performance for the last completion operation.
- CompletionPerformance performance;
+ CompletionPerformance? performance;
/// A list of code completion performance measurements for the latest
/// completion operation up to [performanceListMaxLength] measurements.
@@ -54,7 +52,7 @@
RecentBuffer<CompletionPerformance>(performanceListMaxLength);
/// The current request being processed or `null` if none.
- CompletionRequestImpl _currentRequest;
+ CompletionRequestImpl? _currentRequest;
/// The identifiers of the latest `getSuggestionDetails` request.
/// We use it to abort previous requests.
@@ -72,15 +70,15 @@
OperationPerformanceImpl perf,
CompletionRequestImpl request,
CompletionGetSuggestionsParams params,
- Set<ElementKind> includedElementKinds,
- Set<String> includedElementNames,
- List<IncludedSuggestionRelevanceTag> includedSuggestionRelevanceTags,
+ Set<ElementKind>? includedElementKinds,
+ Set<String>? includedElementNames,
+ List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags,
) async {
//
// Allow plugins to start computing fixes.
//
- Map<PluginInfo, Future<plugin.Response>> pluginFutures;
- plugin.CompletionGetSuggestionsParams requestParams;
+ Map<PluginInfo, Future<plugin.Response>>? pluginFutures;
+ plugin.CompletionGetSuggestionsParams? requestParams;
var file = params.file;
var offset = params.offset;
var driver = server.getAnalysisDriver(file);
@@ -88,37 +86,35 @@
requestParams = plugin.CompletionGetSuggestionsParams(file, offset);
pluginFutures = server.pluginManager.broadcastRequest(
requestParams,
- contextRoot: driver.analysisContext.contextRoot,
+ contextRoot: driver.analysisContext!.contextRoot,
);
}
//
// Compute completions generated by server.
//
var suggestions = <CompletionSuggestion>[];
- if (request.result != null) {
- const COMPUTE_SUGGESTIONS_TAG = 'computeSuggestions';
- await perf.runAsync(COMPUTE_SUGGESTIONS_TAG, (perf) async {
- var manager = DartCompletionManager(
- dartdocDirectiveInfo: server.getDartdocDirectiveInfoFor(
- request.result,
- ),
- includedElementKinds: includedElementKinds,
- includedElementNames: includedElementNames,
- includedSuggestionRelevanceTags: includedSuggestionRelevanceTags,
- );
+ const COMPUTE_SUGGESTIONS_TAG = 'computeSuggestions';
+ await perf.runAsync(COMPUTE_SUGGESTIONS_TAG, (perf) async {
+ var manager = DartCompletionManager(
+ dartdocDirectiveInfo: server.getDartdocDirectiveInfoFor(
+ request.result,
+ ),
+ includedElementKinds: includedElementKinds,
+ includedElementNames: includedElementNames,
+ includedSuggestionRelevanceTags: includedSuggestionRelevanceTags,
+ );
- var contributorTag = 'computeSuggestions - ${manager.runtimeType}';
- await perf.runAsync(contributorTag, (performance) async {
- try {
- suggestions.addAll(
- await manager.computeSuggestions(performance, request),
- );
- } on AbortCompletion {
- suggestions.clear();
- }
- });
+ var contributorTag = 'computeSuggestions - ${manager.runtimeType}';
+ await perf.runAsync(contributorTag, (performance) async {
+ try {
+ suggestions.addAll(
+ await manager.computeSuggestions(performance, request),
+ );
+ } on AbortCompletion {
+ suggestions.clear();
+ }
});
- }
+ });
// TODO (danrubel) if request is obsolete (processAnalysisRequest returns
// false) then send empty results
@@ -131,7 +127,7 @@
for (var response in responses) {
var result =
plugin.CompletionGetSuggestionsResult.fromResponse(response);
- if (result.results != null && result.results.isNotEmpty) {
+ if (result.results.isNotEmpty) {
if (suggestions.isEmpty) {
request.replacementOffset = result.replacementOffset;
request.replacementLength = result.replacementLength;
@@ -181,7 +177,13 @@
}
var libraryId = params.id;
- var library = server.declarationsTracker.getLibrary(libraryId);
+ var declarationsTracker = server.declarationsTracker;
+ if (declarationsTracker == null) {
+ server.sendResponse(Response.unsupportedFeature(
+ request.id, 'Completion is not enabled.'));
+ return;
+ }
+ var library = declarationsTracker.getLibrary(libraryId);
if (library == null) {
server.sendResponse(Response.invalidParameter(
request,
@@ -206,6 +208,10 @@
while (id == _latestGetSuggestionDetailsId && timer.elapsed < timeout) {
try {
var analysisDriver = server.getAnalysisDriver(file);
+ if (analysisDriver == null) {
+ server.sendResponse(Response.fileNotAnalyzed(request, 'libraryId'));
+ return;
+ }
var session = analysisDriver.currentSession;
var completion = params.label;
@@ -236,7 +242,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
if (!server.options.featureSet.completion) {
return Response.invalidParameter(
request,
@@ -245,7 +251,7 @@
);
}
- return runZonedGuarded(() {
+ return runZonedGuarded<Response?>(() {
var requestName = request.method;
if (requestName == COMPLETION_REQUEST_GET_SUGGESTION_DETAILS) {
@@ -275,7 +281,7 @@
/// Process a `completion.getSuggestions` request.
Future<void> processRequest(Request request) async {
- performance = CompletionPerformance();
+ final performance = this.performance = CompletionPerformance();
await performance.runRequestOperation((perf) async {
// extract and validate params
@@ -304,12 +310,25 @@
null,
);
return;
+ } else if (!file.endsWith('.dart')) {
+ // Return the response without results.
+ var completionId = (_nextCompletionId++).toString();
+ server.sendResponse(CompletionGetSuggestionsResult(completionId)
+ .toResponse(request.id));
+ // Send a notification with results.
+ sendCompletionNotification(
+ completionId, offset, 0, [], null, null, null, null);
+ return;
}
var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit == null) {
+ server.sendResponse(Response.fileNotAnalyzed(request, 'params.offset'));
+ return;
+ }
server.requestStatistics?.addItemTimeNow(request, 'resolvedUnit');
- if (resolvedUnit?.state == ResultState.VALID) {
- if (offset < 0 || offset > resolvedUnit.content.length) {
+ if (resolvedUnit.state == ResultState.VALID) {
+ if (offset < 0 || offset > resolvedUnit.content!.length) {
server.sendResponse(Response.invalidParameter(
request,
'params.offset',
@@ -318,7 +337,13 @@
return;
}
- recordRequest(performance, file, resolvedUnit.content, offset);
+ recordRequest(performance, file, resolvedUnit.content!, offset);
+ }
+ var declarationsTracker = server.declarationsTracker;
+ if (declarationsTracker == null) {
+ server.sendResponse(Response.unsupportedFeature(
+ request.id, 'Completion is not enabled.'));
+ return;
}
var completionRequest =
CompletionRequestImpl(resolvedUnit, offset, performance);
@@ -333,9 +358,9 @@
// If the client opted into using available suggestion sets,
// create the kinds set, so signal the completion manager about opt-in.
- Set<ElementKind> includedElementKinds;
- Set<String> includedElementNames;
- List<IncludedSuggestionRelevanceTag> includedSuggestionRelevanceTags;
+ Set<ElementKind>? includedElementKinds;
+ Set<String>? includedElementNames;
+ List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags;
if (subscriptions.contains(CompletionService.AVAILABLE_SUGGESTION_SETS)) {
includedElementKinds = <ElementKind>{};
includedElementNames = <String>{};
@@ -352,15 +377,15 @@
includedElementNames,
includedSuggestionRelevanceTags,
);
- String libraryFile;
+ String? libraryFile;
var includedSuggestionSets = <IncludedSuggestionSet>[];
- if (includedElementKinds != null && resolvedUnit != null) {
+ if (includedElementKinds != null && includedElementNames != null) {
libraryFile = resolvedUnit.libraryElement.source.fullName;
server.sendNotification(
createExistingImportsNotification(resolvedUnit),
);
computeIncludedSetList(
- server.declarationsTracker,
+ declarationsTracker,
resolvedUnit,
includedSuggestionSets,
includedElementNames,
@@ -405,11 +430,11 @@
String completionId,
int replacementOffset,
int replacementLength,
- Iterable<CompletionSuggestion> results,
- String libraryFile,
- List<IncludedSuggestionSet> includedSuggestionSets,
- List<ElementKind> includedElementKinds,
- List<IncludedSuggestionRelevanceTag> includedSuggestionRelevanceTags,
+ List<CompletionSuggestion> results,
+ String? libraryFile,
+ List<IncludedSuggestionSet>? includedSuggestionSets,
+ List<ElementKind>? includedElementKinds,
+ List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags,
) {
server.sendNotification(
CompletionResultsParams(
@@ -426,7 +451,7 @@
);
}
- void setNewRequest(CompletionRequest completionRequest) {
+ void setNewRequest(CompletionRequestImpl completionRequest) {
_abortCurrentRequest();
_currentRequest = completionRequest;
}
@@ -438,33 +463,35 @@
subscriptions.clear();
subscriptions.addAll(params.subscriptions);
- if (subscriptions.contains(CompletionService.AVAILABLE_SUGGESTION_SETS)) {
- var data = server.declarationsTrackerData;
- var soFarLibraries = data.startListening((change) {
+ var data = server.declarationsTrackerData;
+ if (data != null) {
+ if (subscriptions.contains(CompletionService.AVAILABLE_SUGGESTION_SETS)) {
+ var soFarLibraries = data.startListening((change) {
+ server.sendNotification(
+ createCompletionAvailableSuggestionsNotification(
+ change.changed,
+ change.removed,
+ ),
+ );
+ });
server.sendNotification(
createCompletionAvailableSuggestionsNotification(
- change.changed,
- change.removed,
+ soFarLibraries,
+ [],
),
);
- });
- server.sendNotification(
- createCompletionAvailableSuggestionsNotification(
- soFarLibraries,
- [],
- ),
- );
- } else {
- server.declarationsTrackerData.stopListening();
+ } else {
+ data.stopListening();
+ }
}
-
return CompletionSetSubscriptionsResult().toResponse(request.id);
}
/// Abort the current completion request, if any.
void _abortCurrentRequest() {
- if (_currentRequest != null) {
- _currentRequest.abort();
+ var currentRequest = _currentRequest;
+ if (currentRequest != null) {
+ currentRequest.abort();
_currentRequest = null;
}
}
diff --git a/pkg/analysis_server/lib/src/domain_diagnostic.dart b/pkg/analysis_server/lib/src/domain_diagnostic.dart
index 6e7b6ab..f11ad7f 100644
--- a/pkg/analysis_server/lib/src/domain_diagnostic.dart
+++ b/pkg/analysis_server/lib/src/domain_diagnostic.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:core';
import 'package:analysis_server/protocol/protocol.dart';
@@ -40,7 +38,7 @@
Future handleGetServerPort(Request request) async {
try {
// Open a port (or return the existing one).
- var port = await server.diagnosticServer.getServerPort();
+ var port = await server.diagnosticServer!.getServerPort();
server.sendResponse(
DiagnosticGetServerPortResult(port).toResponse(request.id));
} catch (error) {
@@ -49,7 +47,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
try {
var requestName = request.method;
if (requestName == DIAGNOSTIC_REQUEST_GET_DIAGNOSTICS) {
diff --git a/pkg/analysis_server/lib/src/domain_execution.dart b/pkg/analysis_server/lib/src/domain_execution.dart
index f1fec6e..9a79bf1 100644
--- a/pkg/analysis_server/lib/src/domain_execution.dart
+++ b/pkg/analysis_server/lib/src/domain_execution.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:collection';
import 'dart:core';
@@ -72,7 +70,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
try {
var requestName = request.method;
if (requestName == EXECUTION_REQUEST_CREATE_CONTEXT) {
diff --git a/pkg/analysis_server/lib/src/domain_kythe.dart b/pkg/analysis_server/lib/src/domain_kythe.dart
index 14ac442..b03acbb 100644
--- a/pkg/analysis_server/lib/src/domain_kythe.dart
+++ b/pkg/analysis_server/lib/src/domain_kythe.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:core';
import 'package:analysis_server/protocol/protocol.dart';
@@ -38,52 +36,44 @@
var requestParams = plugin.KytheGetKytheEntriesParams(file);
var pluginFutures = server.pluginManager.broadcastRequest(
requestParams,
- contextRoot: driver.analysisContext.contextRoot,
+ contextRoot: driver.analysisContext!.contextRoot,
);
//
// Compute entries generated by server.
//
var allResults = <KytheGetKytheEntriesResult>[];
var result = await server.getResolvedUnit(file);
- if (result?.state == ResultState.VALID) {
+ if (result != null && result.state == ResultState.VALID) {
var entries = <KytheEntry>[];
// TODO(brianwilkerson) Figure out how to get the list of files.
var files = <String>[];
- result.unit.accept(KytheDartVisitor(server.resourceProvider, entries,
- file, InheritanceManager3(), result.content));
+ result.unit!.accept(KytheDartVisitor(server.resourceProvider, entries,
+ file, InheritanceManager3(), result.content!));
allResults.add(KytheGetKytheEntriesResult(entries, files));
}
//
// Add the entries produced by plugins to the server-generated entries.
//
- if (pluginFutures != null) {
- var responses = await waitForResponses(pluginFutures,
- requestParameters: requestParams);
- for (var response in responses) {
- var result = plugin.KytheGetKytheEntriesResult.fromResponse(response);
- allResults
- .add(KytheGetKytheEntriesResult(result.entries, result.files));
- }
+ var responses = await waitForResponses(pluginFutures,
+ requestParameters: requestParams);
+ for (var response in responses) {
+ var result = plugin.KytheGetKytheEntriesResult.fromResponse(response);
+ allResults
+ .add(KytheGetKytheEntriesResult(result.entries, result.files));
}
//
// Return the result.
//
var merger = ResultMerger();
var mergedResults = merger.mergeKytheEntries(allResults);
- if (mergedResults == null) {
- server.sendResponse(
- KytheGetKytheEntriesResult(<KytheEntry>[], <String>[])
- .toResponse(request.id));
- } else {
- server.sendResponse(KytheGetKytheEntriesResult(
- mergedResults.entries, mergedResults.files)
- .toResponse(request.id));
- }
+ server.sendResponse(
+ KytheGetKytheEntriesResult(mergedResults.entries, mergedResults.files)
+ .toResponse(request.id));
}
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
try {
var requestName = request.method;
if (requestName == KYTHE_REQUEST_GET_KYTHE_ENTRIES) {
diff --git a/pkg/analysis_server/lib/src/domain_server.dart b/pkg/analysis_server/lib/src/domain_server.dart
index 44a8b4b..5dca197 100644
--- a/pkg/analysis_server/lib/src/domain_server.dart
+++ b/pkg/analysis_server/lib/src/domain_server.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/protocol/protocol.dart';
import 'package:analysis_server/protocol/protocol_constants.dart';
import 'package:analysis_server/protocol/protocol_generated.dart';
@@ -25,7 +23,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
try {
var requestName = request.method;
if (requestName == SERVER_REQUEST_GET_VERSION) {
diff --git a/pkg/analysis_server/lib/src/edit/edit_dartfix.dart b/pkg/analysis_server/lib/src/edit/edit_dartfix.dart
index e94f0f5..78b2d09 100644
--- a/pkg/analysis_server/lib/src/edit/edit_dartfix.dart
+++ b/pkg/analysis_server/lib/src/edit/edit_dartfix.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/protocol/protocol.dart';
import 'package:analysis_server/protocol/protocol_generated.dart';
import 'package:analysis_server/src/analysis_server.dart';
@@ -18,6 +16,7 @@
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl;
import 'package:analyzer/src/generated/source.dart' show SourceKind;
+import 'package:collection/collection.dart';
class EditDartFix
with FixCodeProcessor, FixErrorProcessor, FixLintProcessor
@@ -31,9 +30,7 @@
DartFixListener listener;
- EditDartFix(this.server, this.request) {
- listener = DartFixListener(server);
- }
+ EditDartFix(this.server, this.request) : listener = DartFixListener(server);
Future<Response> compute() async {
final params = EditDartfixParams.fromRequest(request);
@@ -46,9 +43,10 @@
}
}
}
- if (params.includedFixes != null) {
- for (var key in params.includedFixes) {
- var info = allFixes.firstWhere((i) => i.key == key, orElse: () => null);
+ var includedFixes = params.includedFixes;
+ if (includedFixes != null) {
+ for (var key in includedFixes) {
+ var info = allFixes.firstWhereOrNull((i) => i.key == key);
if (info != null) {
fixInfo.add(info);
} else {
@@ -57,9 +55,10 @@
}
}
}
- if (params.excludedFixes != null) {
- for (var key in params.excludedFixes) {
- var info = allFixes.firstWhere((i) => i.key == key, orElse: () => null);
+ var excludedFixes = params.excludedFixes;
+ if (excludedFixes != null) {
+ for (var key in excludedFixes) {
+ var info = allFixes.firstWhereOrNull((i) => i.key == key);
if (info != null) {
fixInfo.remove(info);
} else {
@@ -114,15 +113,15 @@
if (res is Folder) {
fixFolders.add(res);
} else {
- fixFiles.add(res);
+ fixFiles.add(res as File);
}
}
- String changedPath;
+ String? changedPath;
contextManager.driverMap.values.forEach((driver) {
// Setup a listener to remember the resource that changed during analysis
// so it can be reported if there is an InconsistentAnalysisException.
- driver.onCurrentSessionAboutToBeDiscarded = (String path) {
+ driver.onCurrentSessionAboutToBeDiscarded = (String? path) {
changedPath = path;
};
});
@@ -153,7 +152,7 @@
).toResponse(request.id);
}
- Folder findPkgFolder(Folder start) {
+ Folder? findPkgFolder(Folder start) {
for (var folder in start.withAncestors) {
if (folder.getChild('analysis_options.yaml').exists ||
folder.getChild('pubspec.yaml').exists) {
@@ -194,16 +193,14 @@
/// Return `true` if the path in within the set of `included` files
/// or is within an `included` directory.
bool isIncluded(String filePath) {
- if (filePath != null) {
- for (var file in fixFiles) {
- if (file.path == filePath) {
- return true;
- }
+ for (var file in fixFiles) {
+ if (file.path == filePath) {
+ return true;
}
- for (var folder in fixFolders) {
- if (folder.contains(filePath)) {
- return true;
- }
+ }
+ for (var folder in fixFolders) {
+ if (folder.contains(filePath)) {
+ return true;
}
}
return false;
@@ -217,26 +214,25 @@
for (var path in pathsToProcess) {
if (pathsProcessed.contains(path)) continue;
var driver = server.getAnalysisDriver(path);
- switch (await driver.getSourceKind(path)) {
- case SourceKind.PART:
- // Parts will either be found in a library, below, or if the library
- // isn't [isIncluded], will be picked up in the final loop.
- continue;
- break;
- case SourceKind.LIBRARY:
- var result = await driver.getResolvedLibrary2(path);
- if (result is ResolvedLibraryResult) {
- for (var unit in result.units) {
- if (pathsToProcess.contains(unit.path) &&
- !pathsProcessed.contains(unit.path)) {
- await process(unit);
- pathsProcessed.add(unit.path);
+ if (driver != null) {
+ switch (await driver.getSourceKind(path)) {
+ case SourceKind.PART:
+ // Parts will either be found in a library, below, or if the library
+ // isn't [isIncluded], will be picked up in the final loop.
+ continue;
+ case SourceKind.LIBRARY:
+ var result = await driver.getResolvedLibrary2(path);
+ if (result is ResolvedLibraryResult) {
+ for (var unit in result.units!) {
+ if (pathsToProcess.contains(unit.path) &&
+ !pathsProcessed.contains(unit.path)) {
+ await process(unit);
+ pathsProcessed.add(unit.path!);
+ }
}
+ break;
}
- }
- break;
- default:
- break;
+ }
}
}
diff --git a/pkg/analysis_server/lib/src/edit/edit_domain.dart b/pkg/analysis_server/lib/src/edit/edit_domain.dart
index fec4a3f..01eed28 100644
--- a/pkg/analysis_server/lib/src/edit/edit_domain.dart
+++ b/pkg/analysis_server/lib/src/edit/edit_domain.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:async';
import 'package:analysis_server/plugin/edit/assist/assist_core.dart';
@@ -75,20 +73,21 @@
/// that handles requests in the edit domain.
class EditDomainHandler extends AbstractRequestHandler {
/// The [SearchEngine] for this server.
- SearchEngine searchEngine;
+ SearchEngine? searchEngine;
/// The workspace for rename refactorings.
- RefactoringWorkspace refactoringWorkspace;
+ RefactoringWorkspace? refactoringWorkspace;
/// The object used to manage uncompleted refactorings.
- _RefactoringManager refactoringManager;
+ _RefactoringManager? refactoringManager;
/// Initialize a newly created handler to handle requests for the given
/// [server].
EditDomainHandler(AnalysisServer server) : super(server) {
- searchEngine = server.searchEngine;
- refactoringWorkspace =
- RefactoringWorkspace(server.driverMap.values, searchEngine);
+ var search = searchEngine = server.searchEngine;
+ refactoringWorkspace = search == null
+ ? null
+ : RefactoringWorkspace(server.driverMap.values, search);
_newRefactoringManager();
}
@@ -156,8 +155,8 @@
return Response.formatInvalidFile(request);
}
- var start = params.selectionOffset;
- var length = params.selectionLength;
+ int? start = params.selectionOffset;
+ int? length = params.selectionLength;
// No need to preserve 0,0 selection
if (start == 0 && length == 0) {
@@ -219,7 +218,7 @@
} else {
pluginFutures = server.pluginManager.broadcastRequest(
requestParams,
- contextRoot: driver.analysisContext.contextRoot,
+ contextRoot: driver.analysisContext!.contextRoot,
);
}
@@ -279,13 +278,13 @@
} else {
pluginFutures = server.pluginManager.broadcastRequest(
requestParams,
- contextRoot: driver.analysisContext.contextRoot,
+ contextRoot: driver.analysisContext!.contextRoot,
);
}
//
// Compute fixes associated with server-generated errors.
//
- List<AnalysisErrorFixes> errorFixesList;
+ List<AnalysisErrorFixes>? errorFixesList;
while (errorFixesList == null) {
try {
errorFixesList = await _computeServerErrorFixes(request, file, offset);
@@ -322,7 +321,7 @@
return;
}
- SourceChange change;
+ SourceChange? change;
var result = await server.getResolvedUnit(file);
if (result != null) {
@@ -333,7 +332,7 @@
);
var processor = PostfixCompletionProcessor(context);
var completion = await processor.compute();
- change = completion?.change;
+ change = completion.change;
}
change ??= SourceChange('', edits: []);
@@ -350,7 +349,7 @@
return;
}
- SourceChange change;
+ SourceChange? change;
var result = await server.getResolvedUnit(file);
if (result != null) {
@@ -367,7 +366,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
try {
var requestName = request.method;
if (requestName == EDIT_REQUEST_FORMAT) {
@@ -433,14 +432,16 @@
var result = await server.getResolvedUnit(file);
if (result == null) {
server.sendResponse(Response.importElementsInvalidFile(request));
+ return;
}
var libraryUnit = result.libraryElement.definingCompilationUnit;
- if (libraryUnit != result.unit.declaredElement) {
+ if (libraryUnit != result.unit!.declaredElement) {
// The file in the request is a part of a library. We need to pass the
// defining compilation unit to the computer, not the part.
result = await server.getResolvedUnit(libraryUnit.source.fullName);
if (result == null) {
server.sendResponse(Response.importElementsInvalidFile(request));
+ return;
}
}
//
@@ -516,8 +517,8 @@
return;
}
var fileStamp = -1;
- var code = result.content;
- var unit = result.unit;
+ var code = result.content!;
+ var unit = result.unit!;
var errors = result.errors;
// check if there are scan/parse errors in the file
var numScanParseErrors = _getNumberOfScanParseErrors(errors);
@@ -584,6 +585,9 @@
return errorFixesList;
}
var driver = server.getAnalysisDriver(file);
+ if (driver == null) {
+ return errorFixesList;
+ }
var session = driver.currentSession;
var sourceFactory = driver.sourceFactory;
var errors = analyzeAnalysisOptions(
@@ -598,8 +602,8 @@
if (fixes.isNotEmpty) {
fixes.sort(Fix.SORT_BY_RELEVANCE);
var lineInfo = LineInfo.fromContent(content);
- ResolvedUnitResult result = engine.ResolvedUnitResultImpl(
- session, file, null, true, content, lineInfo, false, null, errors);
+ ResolvedUnitResult result = engine.ResolvedUnitResultImpl(session, file,
+ Uri.file(file), true, content, lineInfo, false, null, errors);
var serverError = newAnalysisError_fromEngine(result, error);
var errorFixes = AnalysisErrorFixes(serverError);
errorFixesList.add(errorFixes);
@@ -628,10 +632,13 @@
var context = DartFixContextImpl(
server.instrumentationService, workspace, result, error, (name) {
var tracker = server.declarationsTracker;
+ if (tracker == null) {
+ return const [];
+ }
var provider = TopLevelDeclarationsProvider(tracker);
return provider.get(
result.session.analysisContext,
- result.path,
+ result.path!,
name,
);
});
@@ -648,7 +655,7 @@
error.errorCode: ${error.errorCode}
''';
throw CaughtExceptionWithFiles(exception, stackTrace, {
- file: result.content,
+ file: result.content!,
'parameters': parametersFile,
});
}
@@ -681,11 +688,12 @@
}
var document =
parseFragment(content, container: MANIFEST_TAG, generateSpans: true);
- if (document == null) {
+ var validator = ManifestValidator(manifestFile.createSource());
+ var driver = server.getAnalysisDriver(file);
+ if (driver == null) {
return errorFixesList;
}
- var validator = ManifestValidator(manifestFile.createSource());
- var session = server.getAnalysisDriver(file).currentSession;
+ var session = driver.currentSession;
var errors = validator.validate(content, true);
for (var error in errors) {
var generator = ManifestFixGenerator(error, content, document);
@@ -693,8 +701,8 @@
if (fixes.isNotEmpty) {
fixes.sort(Fix.SORT_BY_RELEVANCE);
var lineInfo = LineInfo.fromContent(content);
- ResolvedUnitResult result = engine.ResolvedUnitResultImpl(
- session, file, null, true, content, lineInfo, false, null, errors);
+ ResolvedUnitResult result = engine.ResolvedUnitResultImpl(session, file,
+ Uri.file(file), true, content, lineInfo, false, null, errors);
var serverError = newAnalysisError_fromEngine(result, error);
var errorFixes = AnalysisErrorFixes(serverError);
errorFixesList.add(errorFixes);
@@ -716,14 +724,18 @@
if (content == null) {
return errorFixesList;
}
- var sourceFactory = server.getAnalysisDriver(file).sourceFactory;
+ var driver = server.getAnalysisDriver(file);
+ if (driver == null) {
+ return errorFixesList;
+ }
+ var sourceFactory = driver.sourceFactory;
var pubspec = _getOptions(sourceFactory, content);
if (pubspec == null) {
return errorFixesList;
}
var validator =
PubspecValidator(server.resourceProvider, pubspecFile.createSource());
- var session = server.getAnalysisDriver(file).currentSession;
+ var session = driver.currentSession;
var errors = validator.validate(pubspec.nodes);
for (var error in errors) {
var generator = PubspecFixGenerator(error, content, pubspec);
@@ -731,8 +743,8 @@
if (fixes.isNotEmpty) {
fixes.sort(Fix.SORT_BY_RELEVANCE);
var lineInfo = LineInfo.fromContent(content);
- ResolvedUnitResult result = engine.ResolvedUnitResultImpl(
- session, file, null, true, content, lineInfo, false, null, errors);
+ ResolvedUnitResult result = engine.ResolvedUnitResultImpl(session, file,
+ Uri.file(file), true, content, lineInfo, false, null, errors);
var serverError = newAnalysisError_fromEngine(result, error);
var errorFixes = AnalysisErrorFixes(serverError);
errorFixesList.add(errorFixes);
@@ -775,7 +787,7 @@
length: $length
''';
throw CaughtExceptionWithFiles(exception, stackTrace, {
- file: result.content,
+ file: result.content!,
'parameters': parametersFile,
});
}
@@ -804,6 +816,10 @@
}
Response _getAvailableRefactorings(Request request) {
+ if (searchEngine == null) {
+ var result = EditGetAvailableRefactoringsResult([]);
+ return result.toResponse(request.id);
+ }
_getAvailableRefactoringsImpl(request);
return Response.DELAYED_RESPONSE;
}
@@ -821,6 +837,7 @@
// add refactoring kinds
var kinds = <RefactoringKind>[];
// Check nodes.
+ final searchEngine = this.searchEngine;
{
var resolvedUnit = await server.getResolvedUnit(file);
if (resolvedUnit != null) {
@@ -829,15 +846,19 @@
.isAvailable()) {
kinds.add(RefactoringKind.EXTRACT_LOCAL_VARIABLE);
}
- // Try EXTRACT_METHOD.
- if (ExtractMethodRefactoring(searchEngine, resolvedUnit, offset, length)
- .isAvailable()) {
- kinds.add(RefactoringKind.EXTRACT_METHOD);
- }
- // Try EXTRACT_WIDGETS.
- if (ExtractWidgetRefactoring(searchEngine, resolvedUnit, offset, length)
- .isAvailable()) {
- kinds.add(RefactoringKind.EXTRACT_WIDGET);
+ if (searchEngine != null) {
+ // Try EXTRACT_METHOD.
+ if (ExtractMethodRefactoring(
+ searchEngine, resolvedUnit, offset, length)
+ .isAvailable()) {
+ kinds.add(RefactoringKind.EXTRACT_METHOD);
+ }
+ // Try EXTRACT_WIDGETS.
+ if (ExtractWidgetRefactoring(
+ searchEngine, resolvedUnit, offset, length)
+ .isAvailable()) {
+ kinds.add(RefactoringKind.EXTRACT_WIDGET);
+ }
}
}
}
@@ -849,7 +870,7 @@
var element = server.getElementOfNode(node);
if (element != null) {
// try CONVERT_METHOD_TO_GETTER
- if (element is ExecutableElement) {
+ if (element is ExecutableElement && searchEngine != null) {
Refactoring refactoring = ConvertMethodToGetterRefactoring(
searchEngine, resolvedUnit.session, element);
var status = await refactoring.checkInitialConditions();
@@ -858,7 +879,8 @@
}
}
// try RENAME
- {
+ final refactoringWorkspace = this.refactoringWorkspace;
+ if (refactoringWorkspace != null) {
var renameRefactoring = RenameRefactoring.create(
refactoringWorkspace, resolvedUnit, element);
if (renameRefactoring != null) {
@@ -873,7 +895,7 @@
server.sendResponse(result.toResponse(request.id));
}
- YamlMap _getOptions(SourceFactory sourceFactory, String content) {
+ YamlMap? _getOptions(SourceFactory sourceFactory, String content) {
var optionsProvider = AnalysisOptionsProvider(sourceFactory);
try {
return optionsProvider.getOptionsFromString(content);
@@ -883,6 +905,10 @@
}
Response _getRefactoring(Request request) {
+ final refactoringManager = this.refactoringManager;
+ if (refactoringManager == null) {
+ return Response.unsupportedFeature(request.id, 'Search is not enabled.');
+ }
if (refactoringManager.hasPendingRequest) {
refactoringManager.cancel();
_newRefactoringManager();
@@ -893,12 +919,15 @@
/// Initializes [refactoringManager] with a new instance.
void _newRefactoringManager() {
- refactoringManager = _RefactoringManager(server, refactoringWorkspace);
+ final refactoringWorkspace = this.refactoringWorkspace;
+ if (refactoringWorkspace != null) {
+ refactoringManager = _RefactoringManager(server, refactoringWorkspace);
+ }
}
/// Return the contents of the [file], or `null` if the file does not exist or
/// cannot be read.
- String _safelyRead(File file) {
+ String? _safelyRead(File file) {
try {
return file.readAsStringSync();
} on FileSystemException {
@@ -933,20 +962,20 @@
final AnalysisServer server;
final RefactoringWorkspace refactoringWorkspace;
final SearchEngine searchEngine;
- StreamSubscription subscriptionToReset;
+ StreamSubscription? subscriptionToReset;
- RefactoringKind kind;
- String file;
- int offset;
- int length;
- Refactoring refactoring;
- RefactoringFeedback feedback;
- RefactoringStatus initStatus;
- RefactoringStatus optionsStatus;
- RefactoringStatus finalStatus;
+ RefactoringKind? kind;
+ String? file;
+ int? offset;
+ int? length;
+ Refactoring? refactoring;
+ RefactoringFeedback? feedback;
+ late RefactoringStatus initStatus;
+ late RefactoringStatus optionsStatus;
+ late RefactoringStatus finalStatus;
- Request request;
- EditGetRefactoringResult result;
+ Request? request;
+ EditGetRefactoringResult? result;
_RefactoringManager(this.server, this.refactoringWorkspace)
: searchEngine = refactoringWorkspace.searchEngine {
@@ -975,8 +1004,9 @@
/// Cancels processing of the current request and cleans up.
void cancel() {
- if (request != null) {
- server.sendResponse(Response.refactoringRequestCancelled(request));
+ var currentRequest = request;
+ if (currentRequest != null) {
+ server.sendResponse(Response.refactoringRequestCancelled(currentRequest));
request = null;
}
_reset();
@@ -985,20 +1015,18 @@
void getRefactoring(Request _request) {
// prepare for processing the request
request = _request;
- result = EditGetRefactoringResult(
+ final result = this.result = EditGetRefactoringResult(
EMPTY_PROBLEM_LIST, EMPTY_PROBLEM_LIST, EMPTY_PROBLEM_LIST);
// process the request
var params = EditGetRefactoringParams.fromRequest(_request);
var file = params.file;
- if (server.sendResponseErrorIfInvalidFilePath(request, file)) {
+ if (server.sendResponseErrorIfInvalidFilePath(_request, file)) {
return;
}
- if (params.kind != null) {
- server.options.analytics
- ?.sendEvent('refactor', params.kind.name.toLowerCase());
- }
+ server.options.analytics
+ ?.sendEvent('refactor', params.kind.name.toLowerCase());
runZonedGuarded(() async {
await _init(params.kind, file, params.offset, params.length);
@@ -1031,6 +1059,7 @@
throw 'A simulated refactoring exception - final.';
}
// validation and create change
+ final refactoring = this.refactoring!;
finalStatus = await refactoring.checkFinalConditions();
_checkForReset_afterFinalConditions();
if (_hasFatalError) {
@@ -1086,6 +1115,99 @@
}
}
+ Future<void> _createRefactoringFromKind(
+ String file, int offset, int length) async {
+ if (kind == RefactoringKind.CONVERT_GETTER_TO_METHOD) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ var node = NodeLocator(offset).searchWithin(resolvedUnit.unit);
+ var element = server.getElementOfNode(node);
+ if (element != null) {
+ if (element is PropertyAccessorElement) {
+ refactoring = ConvertGetterToMethodRefactoring(
+ searchEngine, resolvedUnit.session, element);
+ }
+ }
+ }
+ } else if (kind == RefactoringKind.CONVERT_METHOD_TO_GETTER) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ var node = NodeLocator(offset).searchWithin(resolvedUnit.unit);
+ var element = server.getElementOfNode(node);
+ if (element != null) {
+ if (element is ExecutableElement) {
+ refactoring = ConvertMethodToGetterRefactoring(
+ searchEngine, resolvedUnit.session, element);
+ }
+ }
+ }
+ } else if (kind == RefactoringKind.EXTRACT_LOCAL_VARIABLE) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ refactoring = ExtractLocalRefactoring(resolvedUnit, offset, length);
+ feedback = ExtractLocalVariableFeedback(<String>[], <int>[], <int>[],
+ coveringExpressionOffsets: <int>[],
+ coveringExpressionLengths: <int>[]);
+ }
+ } else if (kind == RefactoringKind.EXTRACT_METHOD) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ refactoring = ExtractMethodRefactoring(
+ searchEngine, resolvedUnit, offset, length);
+ feedback = ExtractMethodFeedback(offset, length, '', <String>[], false,
+ <RefactoringMethodParameter>[], <int>[], <int>[]);
+ }
+ } else if (kind == RefactoringKind.EXTRACT_WIDGET) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ refactoring = ExtractWidgetRefactoring(
+ searchEngine, resolvedUnit, offset, length);
+ feedback = ExtractWidgetFeedback();
+ }
+ } else if (kind == RefactoringKind.INLINE_LOCAL_VARIABLE) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ refactoring = InlineLocalRefactoring(
+ searchEngine,
+ resolvedUnit,
+ offset,
+ );
+ }
+ } else if (kind == RefactoringKind.INLINE_METHOD) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ refactoring = InlineMethodRefactoring(
+ searchEngine,
+ resolvedUnit,
+ offset,
+ );
+ }
+ } else if (kind == RefactoringKind.MOVE_FILE) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ refactoring = MoveFileRefactoring(
+ server.resourceProvider, refactoringWorkspace, resolvedUnit, file);
+ }
+ } else if (kind == RefactoringKind.RENAME) {
+ var resolvedUnit = await server.getResolvedUnit(file);
+ if (resolvedUnit != null) {
+ var node = NodeLocator(offset).searchWithin(resolvedUnit.unit);
+ var element = server.getElementOfNode(node);
+ if (node != null && element != null) {
+ final renameElement =
+ RenameRefactoring.getElementToRename(node, element);
+ if (renameElement != null) {
+ // do create the refactoring
+ refactoring = RenameRefactoring.create(
+ refactoringWorkspace, resolvedUnit, renameElement.element);
+ feedback = RenameFeedback(
+ renameElement.offset, renameElement.length, 'kind', 'oldName');
+ }
+ }
+ }
+ }
+ }
+
/// Initializes this context to perform a refactoring with the specified
/// parameters. The existing [Refactoring] is reused or created as needed.
Future _init(
@@ -1108,102 +1230,8 @@
throw 'A simulated refactoring exception - init.';
}
// create a new Refactoring instance
- if (kind == RefactoringKind.CONVERT_GETTER_TO_METHOD) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- var node = NodeLocator(offset).searchWithin(resolvedUnit.unit);
- var element = server.getElementOfNode(node);
- if (element != null) {
- if (element is ExecutableElement) {
- refactoring = ConvertGetterToMethodRefactoring(
- searchEngine, resolvedUnit.session, element);
- }
- }
- }
- }
- if (kind == RefactoringKind.CONVERT_METHOD_TO_GETTER) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- var node = NodeLocator(offset).searchWithin(resolvedUnit.unit);
- var element = server.getElementOfNode(node);
- if (element != null) {
- if (element is ExecutableElement) {
- refactoring = ConvertMethodToGetterRefactoring(
- searchEngine, resolvedUnit.session, element);
- }
- }
- }
- }
- if (kind == RefactoringKind.EXTRACT_LOCAL_VARIABLE) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- refactoring = ExtractLocalRefactoring(resolvedUnit, offset, length);
- feedback = ExtractLocalVariableFeedback(<String>[], <int>[], <int>[],
- coveringExpressionOffsets: <int>[],
- coveringExpressionLengths: <int>[]);
- }
- }
- if (kind == RefactoringKind.EXTRACT_METHOD) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- refactoring = ExtractMethodRefactoring(
- searchEngine, resolvedUnit, offset, length);
- feedback = ExtractMethodFeedback(offset, length, '', <String>[], false,
- <RefactoringMethodParameter>[], <int>[], <int>[]);
- }
- }
- if (kind == RefactoringKind.EXTRACT_WIDGET) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- refactoring = ExtractWidgetRefactoring(
- searchEngine, resolvedUnit, offset, length);
- feedback = ExtractWidgetFeedback();
- }
- }
- if (kind == RefactoringKind.INLINE_LOCAL_VARIABLE) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- refactoring = InlineLocalRefactoring(
- searchEngine,
- resolvedUnit,
- offset,
- );
- }
- }
- if (kind == RefactoringKind.INLINE_METHOD) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- refactoring = InlineMethodRefactoring(
- searchEngine,
- resolvedUnit,
- offset,
- );
- }
- }
- if (kind == RefactoringKind.MOVE_FILE) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- refactoring = MoveFileRefactoring(
- server.resourceProvider, refactoringWorkspace, resolvedUnit, file);
- }
- }
- if (kind == RefactoringKind.RENAME) {
- var resolvedUnit = await server.getResolvedUnit(file);
- if (resolvedUnit != null) {
- var node = NodeLocator(offset).searchWithin(resolvedUnit.unit);
- var element = server.getElementOfNode(node);
- if (node != null && element != null) {
- final renameElement =
- RenameRefactoring.getElementToRename(node, element);
-
- // do create the refactoring
- refactoring = RenameRefactoring.create(
- refactoringWorkspace, resolvedUnit, renameElement.element);
- feedback = RenameFeedback(
- renameElement.offset, renameElement.length, 'kind', 'oldName');
- }
- }
- }
+ await _createRefactoringFromKind(file, offset, length);
+ final refactoring = this.refactoring;
if (refactoring == null) {
initStatus = RefactoringStatus.fatal('Unable to create a refactoring');
return;
@@ -1212,8 +1240,7 @@
initStatus = await refactoring.checkInitialConditions();
_checkForReset_afterInitialConditions();
if (refactoring is ExtractLocalRefactoring) {
- ExtractLocalRefactoring refactoring = this.refactoring;
- ExtractLocalVariableFeedback feedback = this.feedback;
+ var feedback = this.feedback as ExtractLocalVariableFeedback;
feedback.names = refactoring.names;
feedback.offsets = refactoring.offsets;
feedback.lengths = refactoring.lengths;
@@ -1221,35 +1248,27 @@
refactoring.coveringExpressionOffsets;
feedback.coveringExpressionLengths =
refactoring.coveringExpressionLengths;
- }
- if (refactoring is ExtractMethodRefactoring) {
- ExtractMethodRefactoring refactoring = this.refactoring;
- ExtractMethodFeedback feedback = this.feedback;
+ } else if (refactoring is ExtractMethodRefactoring) {
+ var feedback = this.feedback as ExtractMethodFeedback;
feedback.canCreateGetter = refactoring.canCreateGetter;
feedback.returnType = refactoring.returnType;
feedback.names = refactoring.names;
feedback.parameters = refactoring.parameters;
feedback.offsets = refactoring.offsets;
feedback.lengths = refactoring.lengths;
- }
- if (refactoring is InlineLocalRefactoring) {
- InlineLocalRefactoring refactoring = this.refactoring;
+ } else if (refactoring is InlineLocalRefactoring) {
if (!initStatus.hasFatalError) {
feedback = InlineLocalVariableFeedback(
- refactoring.variableName, refactoring.referenceCount);
+ refactoring.variableName ?? '', refactoring.referenceCount);
}
- }
- if (refactoring is InlineMethodRefactoring) {
- InlineMethodRefactoring refactoring = this.refactoring;
+ } else if (refactoring is InlineMethodRefactoring) {
if (!initStatus.hasFatalError) {
feedback = InlineMethodFeedback(
- refactoring.methodName, refactoring.isDeclaration,
+ refactoring.methodName ?? '', refactoring.isDeclaration,
className: refactoring.className);
}
- }
- if (refactoring is RenameRefactoring) {
- RenameRefactoring refactoring = this.refactoring;
- RenameFeedback feedback = this.feedback;
+ } else if (refactoring is RenameRefactoring) {
+ var feedback = this.feedback as RenameFeedback;
feedback.elementKindName = refactoring.elementKindName;
feedback.oldName = refactoring.oldName;
}
@@ -1278,10 +1297,15 @@
void _sendResultResponse() {
// ignore if was cancelled
+ final request = this.request;
if (request == null) {
return;
}
// set feedback
+ final result = this.result;
+ if (result == null) {
+ return;
+ }
result.feedback = feedback;
// set problems
result.initialProblems = initStatus.problems;
@@ -1290,54 +1314,42 @@
// send the response
server.sendResponse(result.toResponse(request.id));
// done with this request
- request = null;
- result = null;
+ this.request = null;
+ this.result = null;
}
RefactoringStatus _setOptions(EditGetRefactoringParams params) {
+ final refactoring = this.refactoring;
if (refactoring is ExtractLocalRefactoring) {
- ExtractLocalRefactoring extractRefactoring = refactoring;
- ExtractLocalVariableOptions extractOptions = params.options;
- extractRefactoring.name = extractOptions.name;
- extractRefactoring.extractAll = extractOptions.extractAll;
- return extractRefactoring.checkName();
- }
- if (refactoring is ExtractMethodRefactoring) {
- ExtractMethodRefactoring extractRefactoring = refactoring;
- ExtractMethodOptions extractOptions = params.options;
- extractRefactoring.createGetter = extractOptions.createGetter;
- extractRefactoring.extractAll = extractOptions.extractAll;
- extractRefactoring.name = extractOptions.name;
- if (extractOptions.parameters != null) {
- extractRefactoring.parameters = extractOptions.parameters;
- }
- extractRefactoring.returnType = extractOptions.returnType;
- return extractRefactoring.checkName();
- }
- if (refactoring is ExtractWidgetRefactoring) {
- ExtractWidgetRefactoring extractRefactoring = refactoring;
- ExtractWidgetOptions extractOptions = params.options;
- extractRefactoring.name = extractOptions.name;
- return extractRefactoring.checkName();
- }
- if (refactoring is InlineMethodRefactoring) {
- InlineMethodRefactoring inlineRefactoring = refactoring;
- InlineMethodOptions inlineOptions = params.options;
- inlineRefactoring.deleteSource = inlineOptions.deleteSource;
- inlineRefactoring.inlineAll = inlineOptions.inlineAll;
+ var extractOptions = params.options as ExtractLocalVariableOptions;
+ refactoring.name = extractOptions.name;
+ refactoring.extractAll = extractOptions.extractAll;
+ return refactoring.checkName();
+ } else if (refactoring is ExtractMethodRefactoring) {
+ var extractOptions = params.options as ExtractMethodOptions;
+ refactoring.createGetter = extractOptions.createGetter;
+ refactoring.extractAll = extractOptions.extractAll;
+ refactoring.name = extractOptions.name;
+ refactoring.parameters = extractOptions.parameters;
+ refactoring.returnType = extractOptions.returnType;
+ return refactoring.checkName();
+ } else if (refactoring is ExtractWidgetRefactoring) {
+ var extractOptions = params.options as ExtractWidgetOptions;
+ refactoring.name = extractOptions.name;
+ return refactoring.checkName();
+ } else if (refactoring is InlineMethodRefactoring) {
+ var inlineOptions = params.options as InlineMethodOptions;
+ refactoring.deleteSource = inlineOptions.deleteSource;
+ refactoring.inlineAll = inlineOptions.inlineAll;
return RefactoringStatus();
- }
- if (refactoring is MoveFileRefactoring) {
- MoveFileRefactoring moveRefactoring = refactoring;
- MoveFileOptions moveOptions = params.options;
- moveRefactoring.newFile = moveOptions.newFile;
+ } else if (refactoring is MoveFileRefactoring) {
+ var moveOptions = params.options as MoveFileOptions;
+ refactoring.newFile = moveOptions.newFile;
return RefactoringStatus();
- }
- if (refactoring is RenameRefactoring) {
- RenameRefactoring renameRefactoring = refactoring;
- RenameOptions renameOptions = params.options;
- renameRefactoring.newName = renameOptions.newName;
- return renameRefactoring.checkNewName();
+ } else if (refactoring is RenameRefactoring) {
+ var renameOptions = params.options as RenameOptions;
+ refactoring.newName = renameOptions.newName;
+ return refactoring.checkNewName();
}
return RefactoringStatus();
}
diff --git a/pkg/analysis_server/lib/src/edit/fix/dartfix_info.dart b/pkg/analysis_server/lib/src/edit/fix/dartfix_info.dart
index 6335d65..0d4ac07 100644
--- a/pkg/analysis_server/lib/src/edit/fix/dartfix_info.dart
+++ b/pkg/analysis_server/lib/src/edit/fix/dartfix_info.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/protocol/protocol_generated.dart'
show DartFix, EditDartfixParams;
import 'package:analysis_server/src/edit/edit_dartfix.dart';
@@ -553,12 +551,12 @@
this.fixKind,
String description, {
bool isPedantic = false,
- }) : super(lintName, description, null, isPedantic: isPedantic);
+ }) : super(lintName, description, (_, __, ___) {}, isPedantic: isPedantic);
@override
void setup(DartFixRegistrar registrar, DartFixListener listener,
EditDartfixParams params) {
registrar.registerLintTask(
- Registry.ruleRegistry[lintName], FixLintTask(listener));
+ Registry.ruleRegistry[lintName]!, FixLintTask(listener));
}
}
diff --git a/pkg/analysis_server/lib/src/edit/fix/dartfix_listener.dart b/pkg/analysis_server/lib/src/edit/fix/dartfix_listener.dart
index 556cc38..42868cd 100644
--- a/pkg/analysis_server/lib/src/edit/fix/dartfix_listener.dart
+++ b/pkg/analysis_server/lib/src/edit/fix/dartfix_listener.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/protocol/protocol_generated.dart';
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analyzer/dart/analysis/results.dart';
@@ -37,7 +35,7 @@
}
/// Record a recommendation to be sent to the client.
- void addRecommendation(String description, [Location location]) {
+ void addRecommendation(String description, [Location? location]) {
otherSuggestions.add(DartFixSuggestion(description, location: location));
}
@@ -81,11 +79,11 @@
/// Return the [Location] representing the specified offset and length
/// in the given compilation unit.
Location locationFor(ResolvedUnitResult result, int offset, int length) {
- var lineInfo = result.unit.lineInfo;
+ var lineInfo = result.unit!.lineInfo!;
var startLocation = lineInfo.getLocation(offset);
var endLocation = lineInfo.getLocation(offset + length);
return Location(
- result.path,
+ result.path!,
offset,
length,
startLocation.lineNumber,
diff --git a/pkg/analysis_server/lib/src/edit/fix/dartfix_registrar.dart b/pkg/analysis_server/lib/src/edit/fix/dartfix_registrar.dart
index f1c8b44..07652c0 100644
--- a/pkg/analysis_server/lib/src/edit/fix/dartfix_registrar.dart
+++ b/pkg/analysis_server/lib/src/edit/fix/dartfix_registrar.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/src/edit/fix/dartfix_info.dart';
import 'package:analysis_server/src/edit/fix/fix_code_task.dart';
import 'package:analysis_server/src/edit/fix/fix_error_task.dart';
diff --git a/pkg/analysis_server/lib/src/edit/fix/fix_code_task.dart b/pkg/analysis_server/lib/src/edit/fix/fix_code_task.dart
index cca1834..a4243a9 100644
--- a/pkg/analysis_server/lib/src/edit/fix/fix_code_task.dart
+++ b/pkg/analysis_server/lib/src/edit/fix/fix_code_task.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'dart:math' show max;
import 'package:analysis_server/src/edit/edit_dartfix.dart';
diff --git a/pkg/analysis_server/lib/src/edit/fix/fix_error_task.dart b/pkg/analysis_server/lib/src/edit/fix/fix_error_task.dart
index 5f7ec39..2896407 100644
--- a/pkg/analysis_server/lib/src/edit/fix/fix_error_task.dart
+++ b/pkg/analysis_server/lib/src/edit/fix/fix_error_task.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/protocol/protocol_generated.dart';
import 'package:analysis_server/src/edit/edit_dartfix.dart';
import 'package:analysis_server/src/edit/fix/dartfix_listener.dart';
diff --git a/pkg/analysis_server/lib/src/edit/fix/fix_lint_task.dart b/pkg/analysis_server/lib/src/edit/fix/fix_lint_task.dart
index d7564a9..2aac75e 100644
--- a/pkg/analysis_server/lib/src/edit/fix/fix_lint_task.dart
+++ b/pkg/analysis_server/lib/src/edit/fix/fix_lint_task.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/src/edit/edit_dartfix.dart';
import 'package:analysis_server/src/edit/fix/dartfix_listener.dart';
import 'package:analysis_server/src/edit/fix/fix_error_task.dart';
diff --git a/pkg/analysis_server/lib/src/edit/fix/prefer_mixin_fix.dart b/pkg/analysis_server/lib/src/edit/fix/prefer_mixin_fix.dart
index f9ef2a5..10c0214 100644
--- a/pkg/analysis_server/lib/src/edit/fix/prefer_mixin_fix.dart
+++ b/pkg/analysis_server/lib/src/edit/fix/prefer_mixin_fix.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/protocol/protocol_generated.dart';
import 'package:analysis_server/src/edit/fix/dartfix_listener.dart';
import 'package:analysis_server/src/edit/fix/dartfix_registrar.dart';
@@ -30,9 +28,12 @@
int get numPhases => 0;
Future<void> convertClassToMixin(Element elem) async {
- var result = await listener.server.getResolvedUnit(elem.source?.fullName);
+ var result = await listener.server.getResolvedUnit(elem.source!.fullName);
+ if (result == null) {
+ return;
+ }
- for (var declaration in result.unit.declarations) {
+ for (var declaration in result.unit!.declarations) {
if (declaration is ClassOrMixinDeclaration &&
declaration.name.name == elem.name) {
var processor = AssistProcessor(
@@ -74,10 +75,13 @@
@override
Future<void> fixError(ResolvedUnitResult result, AnalysisError error) async {
var node = NodeLocator(error.offset).searchWithin(result.unit);
+ if (node == null) {
+ return;
+ }
var type = node.thisOrAncestorOfType<TypeName>();
if (type != null) {
var element = type.name.staticElement;
- if (element.source?.fullName != null) {
+ if (element != null && element.source?.fullName != null) {
classesToConvert.add(element);
}
} else {
@@ -97,7 +101,7 @@
static void task(DartFixRegistrar registrar, DartFixListener listener,
EditDartfixParams params) {
var task = PreferMixinFix(listener);
- registrar.registerLintTask(Registry.ruleRegistry['prefer_mixin'], task);
+ registrar.registerLintTask(Registry.ruleRegistry['prefer_mixin']!, task);
registrar.registerCodeTask(task);
}
}
diff --git a/pkg/analysis_server/lib/src/flutter/flutter_domain.dart b/pkg/analysis_server/lib/src/flutter/flutter_domain.dart
index 6996ece..6ec33cc 100644
--- a/pkg/analysis_server/lib/src/flutter/flutter_domain.dart
+++ b/pkg/analysis_server/lib/src/flutter/flutter_domain.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/protocol/protocol_constants.dart';
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/domain_abstract.dart';
@@ -29,12 +27,13 @@
var resolvedUnit = await server.getResolvedUnit(file);
if (resolvedUnit == null) {
- // TODO(scheglov) report error
+ server.sendResponse(Response.fileNotAnalyzed(request, file));
+ return;
}
var computer = server.flutterWidgetDescriptions;
- FlutterGetWidgetDescriptionResult result;
+ FlutterGetWidgetDescriptionResult? result;
try {
result = await computer.getDescription(
resolvedUnit,
@@ -72,7 +71,7 @@
}
@override
- Response handleRequest(Request request) {
+ Response? handleRequest(Request request) {
try {
var requestName = request.method;
if (requestName == FLUTTER_REQUEST_GET_WIDGET_DESCRIPTION) {
@@ -101,18 +100,19 @@
params.value,
);
- if (result.errorCode != null) {
+ var errorCode = result.errorCode;
+ if (errorCode != null) {
server.sendResponse(
Response(
request.id,
- error: RequestError(result.errorCode, ''),
+ error: RequestError(errorCode, ''),
),
);
}
server.sendResponse(
FlutterSetWidgetPropertyValueResult(
- result.change,
+ result.change!,
).toResponse(request.id),
);
}
diff --git a/pkg/analysis_server/lib/src/flutter/flutter_notifications.dart b/pkg/analysis_server/lib/src/flutter/flutter_notifications.dart
index a18cb7d..36e5272 100644
--- a/pkg/analysis_server/lib/src/flutter/flutter_notifications.dart
+++ b/pkg/analysis_server/lib/src/flutter/flutter_notifications.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/flutter/flutter_outline_computer.dart';
import 'package:analysis_server/src/protocol_server.dart' as protocol;
@@ -17,7 +15,7 @@
var outline = computer.compute();
// send notification
var params = protocol.FlutterOutlineParams(
- resolvedUnit.path,
+ resolvedUnit.path!,
outline,
);
server.sendNotification(params.toNotification());
diff --git a/pkg/analysis_server/lib/src/operation/operation_analysis.dart b/pkg/analysis_server/lib/src/operation/operation_analysis.dart
index f612320..be6d158 100644
--- a/pkg/analysis_server/lib/src/operation/operation_analysis.dart
+++ b/pkg/analysis_server/lib/src/operation/operation_analysis.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/computer/computer_closingLabels.dart';
import 'package:analysis_server/src/computer/computer_folding.dart';
@@ -79,7 +77,7 @@
void sendAnalysisNotificationFlushResults(
AnalysisServer server, List<String> files) {
_sendNotification(server, () {
- if (files != null && files.isNotEmpty) {
+ if (files.isNotEmpty) {
var params = protocol.AnalysisFlushResultsParams(files);
server.sendNotification(params.toNotification());
}
@@ -99,14 +97,15 @@
AnalysisServer server, ResolvedUnitResult resolvedUnit) {
_sendNotification(server, () {
protocol.FileKind fileKind;
- if (resolvedUnit.unit.directives.any((d) => d is PartOfDirective)) {
+ var unit = resolvedUnit.unit!;
+ if (unit.directives.any((d) => d is PartOfDirective)) {
fileKind = protocol.FileKind.PART;
} else {
fileKind = protocol.FileKind.LIBRARY;
}
// compute library name
- var libraryName = _computeLibraryName(resolvedUnit.unit);
+ var libraryName = _computeLibraryName(unit);
// compute Outline
var outline = DartUnitOutlineComputer(
@@ -116,7 +115,7 @@
// send notification
var params = protocol.AnalysisOutlineParams(
- resolvedUnit.path, fileKind, outline,
+ resolvedUnit.path!, fileKind, outline,
libraryName: libraryName);
server.sendNotification(params.toNotification());
});
@@ -131,15 +130,18 @@
});
}
-String _computeLibraryName(CompilationUnit unit) {
+String? _computeLibraryName(CompilationUnit unit) {
for (var directive in unit.directives) {
- if (directive is LibraryDirective && directive.name != null) {
+ if (directive is LibraryDirective) {
return directive.name.name;
}
}
for (var directive in unit.directives) {
- if (directive is PartOfDirective && directive.libraryName != null) {
- return directive.libraryName.name;
+ if (directive is PartOfDirective) {
+ var libraryName = directive.libraryName;
+ if (libraryName != null) {
+ return libraryName.name;
+ }
}
}
return null;
diff --git a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
index 1820f9e..08f8fb6 100644
--- a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
+++ b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
@@ -202,7 +202,7 @@
/// Start a new isolate that is running the plugin. Return the state object
/// used to interact with the plugin, or `null` if the plugin could not be
/// run.
- Future<PluginSession?> start(String byteStorePath, String sdkPath) async {
+ Future<PluginSession?> start(String? byteStorePath, String sdkPath) async {
if (currentSession != null) {
throw StateError('Cannot start a plugin that is already running.');
}
@@ -261,7 +261,7 @@
/// The absolute path of the directory containing the on-disk byte store, or
/// `null` if there is no on-disk store.
- final String byteStorePath;
+ final String? byteStorePath;
/// The absolute path of the directory containing the SDK.
final String sdkPath;
@@ -918,11 +918,11 @@
/// Start a new isolate that is running this plugin. The plugin will be sent
/// the given [byteStorePath]. Return `true` if the plugin is compatible and
/// running.
- Future<bool> start(String byteStorePath, String sdkPath) async {
+ Future<bool> start(String? byteStorePath, String sdkPath) async {
if (channel != null) {
throw StateError('Cannot start a plugin that is already running.');
}
- if (byteStorePath.isEmpty) {
+ if (byteStorePath == null || byteStorePath.isEmpty) {
throw StateError('Missing byte store path');
}
if (!isCompatible) {
diff --git a/pkg/analysis_server/lib/src/search/search_domain.dart b/pkg/analysis_server/lib/src/search/search_domain.dart
index 1317e40..0ee46f1 100644
--- a/pkg/analysis_server/lib/src/search/search_domain.dart
+++ b/pkg/analysis_server/lib/src/search/search_domain.dart
@@ -2,8 +2,7 @@
// 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.
-// @dart = 2.9
-
+import 'package:analysis_server/protocol/protocol.dart';
import 'package:analysis_server/protocol/protocol_constants.dart';
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/protocol_server.dart' as protocol;
@@ -20,7 +19,7 @@
final AnalysisServer server;
/// The [SearchEngine] for this server.
- final SearchEngine searchEngine;
+ final SearchEngine? searchEngine;
/// The next search response id.
int _nextSearchId = 0;
@@ -29,20 +28,26 @@
/// [server].
SearchDomainHandler(this.server) : searchEngine = server.searchEngine;
- Future findElementReferences(protocol.Request request) async {
+ Future<void> findElementReferences(protocol.Request request) async {
+ final searchEngine = this.searchEngine;
+ if (searchEngine == null) {
+ server.sendResponse(
+ Response.unsupportedFeature(request.id, 'Search has been disabled.'));
+ return;
+ }
var params =
protocol.SearchFindElementReferencesParams.fromRequest(request);
var file = params.file;
// prepare element
var element = await server.getElementAtOffset(file, params.offset);
if (element is ImportElement) {
- element = (element as ImportElement).prefix;
+ element = element.prefix;
}
if (element is FieldFormalParameterElement) {
- element = (element as FieldFormalParameterElement).field;
+ element = element.field;
}
if (element is PropertyAccessorElement) {
- element = (element as PropertyAccessorElement).variable;
+ element = element.variable;
}
// respond
var searchId = (_nextSearchId++).toString();
@@ -61,6 +66,12 @@
}
Future findMemberDeclarations(protocol.Request request) async {
+ final searchEngine = this.searchEngine;
+ if (searchEngine == null) {
+ server.sendResponse(
+ Response.unsupportedFeature(request.id, 'Search has been disabled.'));
+ return;
+ }
var params =
protocol.SearchFindMemberDeclarationsParams.fromRequest(request);
await server.onAnalysisComplete;
@@ -74,6 +85,12 @@
}
Future findMemberReferences(protocol.Request request) async {
+ final searchEngine = this.searchEngine;
+ if (searchEngine == null) {
+ server.sendResponse(
+ Response.unsupportedFeature(request.id, 'Search has been disabled.'));
+ return;
+ }
var params = protocol.SearchFindMemberReferencesParams.fromRequest(request);
await server.onAnalysisComplete;
// respond
@@ -86,6 +103,12 @@
}
Future findTopLevelDeclarations(protocol.Request request) async {
+ final searchEngine = this.searchEngine;
+ if (searchEngine == null) {
+ server.sendResponse(
+ Response.unsupportedFeature(request.id, 'Search has been disabled.'));
+ return;
+ }
var params =
protocol.SearchFindTopLevelDeclarationsParams.fromRequest(request);
try {
@@ -112,10 +135,11 @@
var params =
protocol.SearchGetElementDeclarationsParams.fromRequest(request);
- RegExp regExp;
- if (params.pattern != null) {
+ RegExp? regExp;
+ var pattern = params.pattern;
+ if (pattern != null) {
try {
- regExp = RegExp(params.pattern);
+ regExp = RegExp(pattern);
} on FormatException catch (exception) {
server.sendResponse(protocol.Response.invalidParameter(
request, 'pattern', exception.message));
@@ -157,6 +181,11 @@
}
var tracker = server.declarationsTracker;
+ if (tracker == null) {
+ server.sendResponse(Response.unsupportedFeature(
+ request.id, 'Completion is not enabled.'));
+ return;
+ }
var files = <String>{};
var remainingMaxResults = params.maxResults;
var declarations = search.WorkspaceSymbols(tracker).declarations(
@@ -188,6 +217,12 @@
/// Implement the `search.getTypeHierarchy` request.
Future getTypeHierarchy(protocol.Request request) async {
+ final searchEngine = this.searchEngine;
+ if (searchEngine == null) {
+ server.sendResponse(
+ Response.unsupportedFeature(request.id, 'Search has been disabled.'));
+ return;
+ }
var params = protocol.SearchGetTypeHierarchyParams.fromRequest(request);
var file = params.file;
// prepare element
@@ -215,7 +250,7 @@
}
@override
- protocol.Response handleRequest(protocol.Request request) {
+ protocol.Response? handleRequest(protocol.Request request) {
try {
var requestName = request.method;
if (requestName == SEARCH_REQUEST_FIND_ELEMENT_REFERENCES) {
diff --git a/pkg/analysis_server/lib/src/search/workspace_symbols.dart b/pkg/analysis_server/lib/src/search/workspace_symbols.dart
index ec02b7e..71d3b9b 100644
--- a/pkg/analysis_server/lib/src/search/workspace_symbols.dart
+++ b/pkg/analysis_server/lib/src/search/workspace_symbols.dart
@@ -2,8 +2,6 @@
// 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.
-import 'dart:collection';
-
import 'package:analyzer/source/line_info.dart';
import 'package:analyzer/src/services/available_declarations.dart';
import 'package:analyzer/src/services/available_declarations.dart' as ad;
@@ -61,7 +59,7 @@
WorkspaceSymbols(this.tracker);
List<Declaration> declarations(
- RegExp? regExp, int? maxResults, LinkedHashSet<String> files,
+ RegExp? regExp, int? maxResults, Set<String> files,
{String? onlyForFile}) {
_doTrackerWork();
diff --git a/pkg/analysis_server/lib/src/server/detachable_filesystem_manager.dart b/pkg/analysis_server/lib/src/server/detachable_filesystem_manager.dart
index 1bad242..d32ca39 100644
--- a/pkg/analysis_server/lib/src/server/detachable_filesystem_manager.dart
+++ b/pkg/analysis_server/lib/src/server/detachable_filesystem_manager.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/src/analysis_server.dart';
/// A class that can be used to configure an analysis server instance to better
diff --git a/pkg/analysis_server/lib/src/server/error_notifier.dart b/pkg/analysis_server/lib/src/server/error_notifier.dart
index f329c92..a533aae 100644
--- a/pkg/analysis_server/lib/src/server/error_notifier.dart
+++ b/pkg/analysis_server/lib/src/server/error_notifier.dart
@@ -2,8 +2,6 @@
// 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.
-// @dart = 2.9
-
import 'package:analysis_server/src/analysis_server_abstract.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
@@ -11,25 +9,30 @@
/// An instrumentation service to show instrumentation errors as error
/// notifications to the user.
class ErrorNotifier extends NoopInstrumentationService {
- AbstractAnalysisServer server;
+ late AbstractAnalysisServer server;
@override
- void logException(dynamic exception,
- [StackTrace stackTrace,
- List<InstrumentationServiceAttachment> attachments = const []]) {
+ void logException(
+ Object exception, [
+ StackTrace? stackTrace,
+ List<InstrumentationServiceAttachment>? attachments,
+ ]) {
if (exception is SilentException) {
// Silent exceptions should not be reported to the user.
return;
}
var message = 'Internal error';
- if (exception is CaughtException && exception.message != null) {
- // TODO(mfairhurst): Use the outermost exception once crash reporting is
- // fixed and this becomes purely user-facing.
- exception = exception.rootCaughtException;
- // TODO(mfairhurst): Use the outermost message rather than the innermost
- // exception as its own message.
- message = exception.message;
+ if (exception is CaughtException) {
+ var message = exception.message;
+ if (message != null) {
+ // TODO(mfairhurst): Use the outermost exception once crash reporting is
+ // fixed and this becomes purely user-facing.
+ exception = exception.rootCaughtException;
+ // TODO(mfairhurst): Use the outermost message rather than the innermost
+ // exception as its own message.
+ message = message;
+ }
}
server.sendServerErrorNotification(message, exception, stackTrace,
diff --git a/pkg/analyzer/lib/src/dart/analysis/driver.dart b/pkg/analyzer/lib/src/dart/analysis/driver.dart
index 83112cd..7aebf77 100644
--- a/pkg/analyzer/lib/src/dart/analysis/driver.dart
+++ b/pkg/analyzer/lib/src/dart/analysis/driver.dart
@@ -2038,7 +2038,9 @@
/// Notify that there is a change to the [driver], it it might need to
/// perform some work.
- void notify(AnalysisDriverGeneric driver) {
+ void notify(AnalysisDriverGeneric? driver) {
+ // TODO(brianwilkerson) Consider removing the parameter, given that it isn't
+ // referenced in the body.
_hasWork.notify();
_statusSupport.preTransitionToAnalyzing();
}
diff --git a/tools/VERSION b/tools/VERSION
index 2c09787e..f8228e6 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -27,5 +27,5 @@
MAJOR 2
MINOR 14
PATCH 0
-PRERELEASE 11
+PRERELEASE 12
PRERELEASE_PATCH 0
\ No newline at end of file