From 5cd284f5c326490e874aae7f7e2cf473a15be457 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Tue, 31 May 2022 13:50:00 -0700 Subject: [PATCH 01/12] Remove dead code --- frontend_server_common/CHANGELOG.md | 3 + frontend_server_common/lib/src/asset.dart | 64 ----- frontend_server_common/lib/src/devfs.dart | 62 ++--- .../lib/src/devfs_content.dart | 230 ------------------ .../lib/src/frontend_server_client.dart | 10 - .../lib/src/resident_runner.dart | 11 - frontend_server_common/lib/src/utilities.dart | 1 - 7 files changed, 27 insertions(+), 354 deletions(-) delete mode 100644 frontend_server_common/lib/src/asset.dart delete mode 100644 frontend_server_common/lib/src/devfs_content.dart diff --git a/frontend_server_common/CHANGELOG.md b/frontend_server_common/CHANGELOG.md index 51d1510cd..a2a8ac29e 100644 --- a/frontend_server_common/CHANGELOG.md +++ b/frontend_server_common/CHANGELOG.md @@ -1,3 +1,6 @@ +## 0.1.1 +- Remove dead code + ## 0.1.0 - Initial version diff --git a/frontend_server_common/lib/src/asset.dart b/frontend_server_common/lib/src/asset.dart deleted file mode 100644 index e08128db0..000000000 --- a/frontend_server_common/lib/src/asset.dart +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2020 The Dart Authors. 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 - -// Note: this is a copy from flutter tools, updated to work with dwds tests, -// most functionality removed - -import 'dart:async'; - -import 'devfs_content.dart'; - -const AssetBundleFactory _manifestFactory = _MockManifestAssetBundleFactory(); - -const String defaultManifestPath = 'pubspec.yaml'; - -/// Injected factory class for spawning [AssetBundle] instances. -abstract class AssetBundleFactory { - static AssetBundleFactory get defaultInstance => _manifestFactory; - - /// Creates a new [AssetBundle]. - AssetBundle createBundle(); -} - -abstract class AssetBundle { - Map get entries; - - /// Returns 0 for success; non-zero for failure. - Future build({ - String manifestPath = defaultManifestPath, - String assetDirPath, - String packagesPath, - bool includeDefaultFonts = true, - bool reportLicensedPackages = false, - }); -} - -class _MockManifestAssetBundleFactory implements AssetBundleFactory { - const _MockManifestAssetBundleFactory(); - - @override - AssetBundle createBundle() => _MockManifestAssetBundle(); -} - -class _MockManifestAssetBundle implements AssetBundle { - /// Constructs an [_MockManifestAssetBundle] that gathers the set of assets from the - /// pubspec.yaml manifest. - _MockManifestAssetBundle(); - - @override - final Map entries = {}; - - @override - Future build({ - String manifestPath = defaultManifestPath, - String assetDirPath, - String packagesPath, - bool includeDefaultFonts = true, - bool reportLicensedPackages = false, - }) async { - return 0; - } -} diff --git a/frontend_server_common/lib/src/devfs.dart b/frontend_server_common/lib/src/devfs.dart index 2fa2027a8..323c92fc1 100644 --- a/frontend_server_common/lib/src/devfs.dart +++ b/frontend_server_common/lib/src/devfs.dart @@ -10,22 +10,17 @@ import 'dart:io'; import 'package:dwds/dwds.dart'; import 'package:file/file.dart'; -import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as p; -import 'asset.dart'; import 'asset_server.dart'; import 'bootstrap.dart'; -import 'devfs_content.dart'; import 'frontend_server_client.dart'; import 'utilities.dart'; final String dartWebSdkPath = p.join(dartSdkPath, 'lib', 'dev_compiler'); -Logger _logger = Logger('WebDevFs'); - class WebDevFS { WebDevFS({ this.fileSystem, @@ -71,7 +66,6 @@ class WebDevFS { Future update({ String mainPath, - AssetBundle bundle, String dillOutputPath, @required ResidentCompiler generator, List invalidatedFiles, @@ -101,17 +95,8 @@ class WebDevFS { soundNullSafety ? dartSdkSourcemapSound : dartSdkSourcemap; assetServer.writeFile('/dart_sdk.js', sdk.readAsStringSync()); assetServer.writeFile('/dart_sdk.js.map', sdkSourceMap.readAsStringSync()); - // TODO(jonahwilliams): refactor the asset code in this and the regular devfs to - // be shared. - if (bundle != null) { - await writeBundle( - fileSystem.directory(p.joinAll(['build', 'assets'])), - bundle.entries, - ); - } generator.reset(); - var compilerOutput = await generator.recompile( Uri.parse('org-dartlang-app:///$mainPath'), invalidatedFiles, outputPath: p.join(dillOutputPath, 'app.dill'), @@ -191,6 +176,30 @@ class WebDevFS { )); } +class UpdateFSReport { + final bool _success; + final int _invalidatedSourcesCount; + final int _syncedBytes; + + UpdateFSReport({ + bool success = false, + int invalidatedSourcesCount = 0, + int syncedBytes = 0, + }) : _success = success, + _invalidatedSourcesCount = invalidatedSourcesCount, + _syncedBytes = syncedBytes; + + bool get success => _success; + int get invalidatedSourcesCount => _invalidatedSourcesCount; + int get syncedBytes => _syncedBytes; + + /// JavaScript modules produced by the incremental compiler in `dartdevc` + /// mode. + /// + /// Only used for JavaScript compilation. + List invalidatedModules; +} + String _filePathToUriFragment(String path) { if (Platform.isWindows) { var startWithSlash = path.startsWith('/'); @@ -203,26 +212,3 @@ String _filePathToUriFragment(String path) { } return path; } - -Future writeBundle( - Directory bundleDir, Map assetEntries) async { - if (bundleDir.existsSync()) { - try { - bundleDir.deleteSync(recursive: true); - } on FileSystemException catch (e, s) { - _logger.warning( - 'Failed to clean up asset directory ${bundleDir.path}.\n' - 'To clean build artifacts, use the command "flutter clean".', - e, - s); - } - } - bundleDir.createSync(recursive: true); - - await Future.wait(assetEntries.entries - .map>((MapEntry entry) async { - var file = fileSystem.file(fileSystem.path.join(bundleDir.path, entry.key)); - file.parent.createSync(recursive: true); - await file.writeAsBytes(await entry.value.contentsAsBytes()); - })); -} diff --git a/frontend_server_common/lib/src/devfs_content.dart b/frontend_server_common/lib/src/devfs_content.dart deleted file mode 100644 index 3b09c15c7..000000000 --- a/frontend_server_common/lib/src/devfs_content.dart +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2020 The Dart Authors. 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 - -// Note: this is a copy from flutter tools, updated to work with dwds tests - -import 'dart:async'; -import 'dart:convert'; - -import 'package:file/file.dart'; -import 'package:logging/logging.dart'; - -import 'utilities.dart'; - -Logger _logger = Logger('DevFsContent'); - -/// Common superclass for content copied to the device. -abstract class DevFSContent { - /// Return true if this is the first time this method is called - /// or if the entry has been modified since this method was last called. - bool get isModified; - - /// Return true if this is the first time this method is called - /// or if the entry has been modified after the given time - /// or if the given time is null. - bool isModifiedAfter(DateTime time); - - int get size; - - Future> contentsAsBytes(); - - Stream> contentsAsStream(); - - /// Return the list of files this content depends on. - List get fileDependencies => []; -} - -// File content to be copied to the device. -class DevFSFileContent extends DevFSContent { - DevFSFileContent(this.file); - - final FileSystemEntity file; - File _linkTarget; - FileStat _fileStat; - - File _getFile() { - if (_linkTarget != null) { - return _linkTarget; - } - if (file is Link) { - // The link target. - return fileSystem.file(file.resolveSymbolicLinksSync()); - } - return file as File; - } - - void _stat() { - if (_linkTarget != null) { - // Stat the cached symlink target. - var fileStat = _linkTarget.statSync(); - if (fileStat.type == FileSystemEntityType.notFound) { - _linkTarget = null; - } else { - _fileStat = fileStat; - return; - } - } - var fileStat = file.statSync(); - _fileStat = - fileStat.type == FileSystemEntityType.notFound ? null : fileStat; - if (_fileStat != null && _fileStat.type == FileSystemEntityType.link) { - // Resolve, stat the symlink target. - var resolved = file.resolveSymbolicLinksSync(); - var linkTarget = fileSystem.file(resolved); - // Stat the link target. - var fileStat = linkTarget.statSync(); - if (fileStat.type == FileSystemEntityType.notFound) { - _fileStat = null; - _linkTarget = null; - } - } - if (_fileStat == null) { - _logger.severe( - 'Unable to get status of file "${file.path}": file not found.'); - } - } - - @override - List get fileDependencies => [_getFile().path]; - - @override - bool get isModified { - var _oldFileStat = _fileStat; - _stat(); - if (_oldFileStat == null && _fileStat == null) { - return false; - } - return _oldFileStat == null || - _fileStat == null || - _fileStat.modified.isAfter(_oldFileStat.modified); - } - - @override - bool isModifiedAfter(DateTime time) { - var _oldFileStat = _fileStat; - _stat(); - if (_oldFileStat == null && _fileStat == null) { - return false; - } - return time == null || - _oldFileStat == null || - _fileStat == null || - _fileStat.modified.isAfter(time); - } - - @override - int get size { - if (_fileStat == null) { - _stat(); - } - // Can still be null if the file wasn't found. - return _fileStat?.size ?? 0; - } - - @override - Future> contentsAsBytes() => _getFile().readAsBytes(); - - @override - Stream> contentsAsStream() => _getFile().openRead(); -} - -/// Byte content to be copied to the device. -class DevFSByteContent extends DevFSContent { - DevFSByteContent(this._bytes); - - List _bytes; - - bool _isModified = true; - DateTime _modificationTime = DateTime.now(); - - List get bytes => _bytes; - - set bytes(List value) { - _bytes = value; - _isModified = true; - _modificationTime = DateTime.now(); - } - - /// Return true only once so that the content is written to the device only once. - @override - bool get isModified { - var modified = _isModified; - _isModified = false; - return modified; - } - - @override - bool isModifiedAfter(DateTime time) { - return time == null || _modificationTime.isAfter(time); - } - - @override - int get size => _bytes.length; - - @override - Future> contentsAsBytes() async => _bytes; - - @override - Stream> contentsAsStream() => - Stream>.fromIterable(>[_bytes]); -} - -/// String content to be copied to the device. -class DevFSStringContent extends DevFSByteContent { - DevFSStringContent(String string) - : _string = string, - super(utf8.encode(string)); - - String _string; - - String get string => _string; - - set string(String value) { - _string = value; - super.bytes = utf8.encode(_string); - } - - @override - set bytes(List value) { - string = utf8.decode(value); - } -} - -// Basic statistics for DevFS update operation. -class UpdateFSReport { - UpdateFSReport({ - bool success = false, - int invalidatedSourcesCount = 0, - int syncedBytes = 0, - }) { - _success = success; - _invalidatedSourcesCount = invalidatedSourcesCount; - _syncedBytes = syncedBytes; - } - - bool get success => _success; - int get invalidatedSourcesCount => _invalidatedSourcesCount; - int get syncedBytes => _syncedBytes; - - /// JavaScript modules produced by the incremental compiler in `dartdevc` - /// mode. - /// - /// Only used for JavaScript compilation. - List invalidatedModules; - - void incorporateResults(UpdateFSReport report) { - if (!report._success) { - _success = false; - } - _invalidatedSourcesCount += report._invalidatedSourcesCount; - _syncedBytes += report._syncedBytes; - invalidatedModules ??= report.invalidatedModules; - } - - bool _success; - int _invalidatedSourcesCount; - int _syncedBytes; -} diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index 68f9a236b..57daa5da3 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -262,11 +262,6 @@ abstract class ResidentCompiler { CompilerMessageConsumer compilerMessageConsumer, }) = DefaultResidentCompiler; - // TODO(jonahwilliams): find a better way to configure additional file system - // roots from the runner. - // See: https://github.com/flutter/flutter/issues/50494 - void addFileSystemRoot(String root); - /// If invoked for the first time, it compiles Dart script identified by /// [mainUri], [invalidatedFiles] list is ignored. /// On successive runs [invalidatedFiles] indicates which files need to be @@ -338,11 +333,6 @@ class DefaultResidentCompiler implements ResidentCompiler { final String platformDill; final bool verbose; - @override - void addFileSystemRoot(String root) { - fileSystemRoots.add(root); - } - /// The path to the root of the Dart SDK used to compile. final String sdkRoot; diff --git a/frontend_server_common/lib/src/resident_runner.dart b/frontend_server_common/lib/src/resident_runner.dart index f5329ebe9..81c90c3cf 100644 --- a/frontend_server_common/lib/src/resident_runner.dart +++ b/frontend_server_common/lib/src/resident_runner.dart @@ -13,9 +13,7 @@ import 'package:dwds/dwds.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; -import 'asset.dart'; import 'devfs.dart'; -import 'devfs_content.dart'; import 'frontend_server_client.dart'; import 'utilities.dart'; @@ -56,7 +54,6 @@ class ResidentWebRunner { ResidentCompiler generator; ExpressionCompiler expressionCompiler; - AssetBundle assetBundle; WebDevFS devFS; Uri uri; Iterable modules; @@ -64,8 +61,6 @@ class ResidentWebRunner { Future run(String hostname, int port, String root) async { hostname ??= 'localhost'; - assetBundle = AssetBundleFactory.defaultInstance.createBundle(); - devFS = WebDevFS( fileSystem: fileSystem, hostname: hostname, @@ -90,14 +85,8 @@ class ResidentWebRunner { } Future _updateDevFS() async { - var result = await assetBundle.build(); - if (result != 0) { - return UpdateFSReport(success: false); - } - var report = await devFS.update( mainPath: mainPath, - bundle: assetBundle, dillOutputPath: outputPath, generator: generator, invalidatedFiles: []); diff --git a/frontend_server_common/lib/src/utilities.dart b/frontend_server_common/lib/src/utilities.dart index 9ca429eff..801cc600b 100644 --- a/frontend_server_common/lib/src/utilities.dart +++ b/frontend_server_common/lib/src/utilities.dart @@ -20,6 +20,5 @@ final String _sdkDir = (() { })(); final String dartSdkPath = _sdkDir; -final String dartPath = p.join(_sdkDir, 'bin', 'dart'); const fs.FileSystem fileSystem = LocalFileSystem(); From ede7871599b286950c5abfdae00ff040dd178f99 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Tue, 31 May 2022 14:11:52 -0700 Subject: [PATCH 02/12] Remove abstract ResidentCompiler class --- .../lib/src/frontend_server_client.dart | 106 +++++------------- 1 file changed, 28 insertions(+), 78 deletions(-) diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index 57daa5da3..9d3f92050 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -164,9 +164,9 @@ abstract class _CompilationRequest { Completer completer; - Future _run(DefaultResidentCompiler compiler); + Future _run(ResidentCompiler compiler); - Future run(DefaultResidentCompiler compiler) async { + Future run(ResidentCompiler compiler) async { completer.complete(await _run(compiler)); } } @@ -186,7 +186,7 @@ class _RecompileRequest extends _CompilationRequest { PackageConfig packageConfig; @override - Future _run(DefaultResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._recompile(this); } @@ -209,7 +209,7 @@ class _CompileExpressionRequest extends _CompilationRequest { bool isStatic; @override - Future _run(DefaultResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._compileExpression(this); } @@ -234,7 +234,7 @@ class _CompileExpressionToJsRequest extends _CompilationRequest { String expression; @override - Future _run(DefaultResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._compileExpressionToJs(this); } @@ -242,7 +242,7 @@ class _RejectRequest extends _CompilationRequest { _RejectRequest(Completer completer) : super(completer); @override - Future _run(DefaultResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._reject(); } @@ -251,70 +251,8 @@ class _RejectRequest extends _CompilationRequest { /// /// The wrapper is intended to stay resident in memory as user changes, reloads, /// restarts the Flutter app. -abstract class ResidentCompiler { - factory ResidentCompiler( - String sdkRoot, { - String packageConfigPath, - List fileSystemRoots, - String fileSystemScheme, - String platformDill, - bool verbose, - CompilerMessageConsumer compilerMessageConsumer, - }) = DefaultResidentCompiler; - - /// If invoked for the first time, it compiles Dart script identified by - /// [mainUri], [invalidatedFiles] list is ignored. - /// On successive runs [invalidatedFiles] indicates which files need to be - /// recompiled. If [mainUri] is null, previously used [mainUri] entry - /// point that is used for recompilation. - /// Binary file name is returned if compilation was successful, otherwise - /// null is returned. - Future recompile(Uri mainUri, List invalidatedFiles, - {@required String outputPath, @required PackageConfig packageConfig}); - - Future compileExpression( - String expression, - List definitions, - List typeDefinitions, - String libraryUri, - String klass, - bool isStatic, - ); - - Future compileExpressionToJs( - String libraryUri, - int line, - int column, - Map jsModules, - Map jsFrameValues, - String moduleName, - String expression); - - /// Should be invoked when results of compilation are accepted by the client. - /// - /// Either [accept] or [reject] should be called after every [recompile] call. - void accept(); - - /// Should be invoked when results of compilation are rejected by the client. - /// - /// Either [accept] or [reject] should be called after every [recompile] call. - Future reject(); - - /// Should be invoked when frontend server compiler should forget what was - /// accepted previously so that next call to [recompile] produces complete - /// kernel file. - void reset(); - - /// stop the service normally - Future shutdown(); - - /// kill the service - Future kill(); -} - -@visibleForTesting -class DefaultResidentCompiler implements ResidentCompiler { - DefaultResidentCompiler( +class ResidentCompiler { + ResidentCompiler( String sdkRoot, { this.packageConfigPath, this.fileSystemRoots, @@ -343,7 +281,13 @@ class DefaultResidentCompiler implements ResidentCompiler { final StreamController<_CompilationRequest> _controller = StreamController<_CompilationRequest>(); - @override + /// If invoked for the first time, it compiles Dart script identified by + /// [mainUri], [invalidatedFiles] list is ignored. + /// On successive runs [invalidatedFiles] indicates which files need to be + /// recompiled. If [mainUri] is null, previously used [mainUri] entry + /// point that is used for recompilation. + /// Binary file name is returned if compilation was successful, otherwise + /// null is returned. Future recompile(Uri mainUri, List invalidatedFiles, {@required String outputPath, @required PackageConfig packageConfig}) async { @@ -475,7 +419,7 @@ class DefaultResidentCompiler implements ResidentCompiler { return _stdoutHandler.compilerOutput.future; } - @override + /// Compile dart expression to kernel. Future compileExpression( String expression, List definitions, @@ -518,7 +462,7 @@ class DefaultResidentCompiler implements ResidentCompiler { return _stdoutHandler.compilerOutput.future; } - @override + /// Compiles dart expression to JavaScript. Future compileExpressionToJs( String libraryUri, int line, @@ -567,7 +511,9 @@ class DefaultResidentCompiler implements ResidentCompiler { return _stdoutHandler.compilerOutput.future; } - @override + /// Should be invoked when results of compilation are accepted by the client. + /// + /// Either [accept] or [reject] should be called after every [recompile] call. void accept() { if (_compileRequestNeedsConfirmation) { _server.stdin.writeln('accept'); @@ -576,7 +522,9 @@ class DefaultResidentCompiler implements ResidentCompiler { _compileRequestNeedsConfirmation = false; } - @override + /// Should be invoked when results of compilation are rejected by the client. + /// + /// Either [accept] or [reject] should be called after every [recompile] call. Future reject() { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); @@ -598,7 +546,9 @@ class DefaultResidentCompiler implements ResidentCompiler { return _stdoutHandler.compilerOutput.future; } - @override + /// Should be invoked when frontend server compiler should forget what was + /// accepted previously so that next call to [recompile] produces complete + /// kernel file. void reset() { _server?.stdin?.writeln('reset'); _logger.info('<- reset'); @@ -610,7 +560,7 @@ class DefaultResidentCompiler implements ResidentCompiler { return _server.exitCode; } - @override + /// stop the service normally Future shutdown() async { // Server was never successfully created. if (_server == null) { @@ -619,7 +569,7 @@ class DefaultResidentCompiler implements ResidentCompiler { return quit(); } - @override + /// kill the service Future kill() async { if (_server == null) { return 0; From e5faeec894b8e4c56bfbcb71241d419c55a4c879 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Tue, 31 May 2022 16:22:05 -0700 Subject: [PATCH 03/12] Migrate events and utilities to null safety --- dwds/lib/src/events.dart | 19 +++++++-------- dwds/lib/src/utilities/conversions.dart | 31 ++++++++++++++----------- 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/dwds/lib/src/events.dart b/dwds/lib/src/events.dart index c1178cbed..886f00d38 100644 --- a/dwds/lib/src/events.dart +++ b/dwds/lib/src/events.dart @@ -2,19 +2,17 @@ // 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:vm_service/vm_service.dart'; class DwdsStats { /// The time when the user starts the debugger. - DateTime _debuggerStart; + late DateTime _debuggerStart; DateTime get debuggerStart => _debuggerStart; /// The time when dwds launches DevTools. - DateTime _devToolsStart; + late DateTime _devToolsStart; DateTime get devToolsStart => _devToolsStart; /// Records and returns weither the debugger is ready. @@ -25,7 +23,8 @@ class DwdsStats { return wasReady; } - void updateLoadTime({DateTime debuggerStart, DateTime devToolsStart}) { + void updateLoadTime( + {required DateTime debuggerStart, required DateTime devToolsStart}) { _debuggerStart = debuggerStart; _devToolsStart = devToolsStart; } @@ -66,14 +65,14 @@ class DwdsEvent { DwdsEvent.devtoolsLaunch() : this(DwdsEventKind.devtoolsLaunch, {}); - DwdsEvent.evaluate(String expression, Response result) + DwdsEvent.evaluate(String expression, Response? result) : this(DwdsEventKind.evaluate, { 'expression': expression, 'success': result != null && result is InstanceRef, if (result != null && result is ErrorRef) 'error': result, }); - DwdsEvent.evaluateInFrame(String expression, Response result) + DwdsEvent.evaluateInFrame(String expression, Response? result) : this(DwdsEventKind.evaluateInFrame, { 'expression': expression, 'success': result != null && result is InstanceRef, @@ -140,13 +139,13 @@ Stream get eventStream => _eventController.stream; /// and appends time and exception details to it if /// available. Future captureElapsedTime( - Future Function() function, DwdsEvent Function(T result) event) async { + Future Function() function, DwdsEvent Function(T? result) event) async { var stopwatch = Stopwatch()..start(); - T result; + T? result; try { return result = await function(); } catch (e) { - emitEvent(event(result) + emitEvent(event(null) ..addException(e) ..addElapsedTime(stopwatch.elapsedMilliseconds)); rethrow; diff --git a/dwds/lib/src/utilities/conversions.dart b/dwds/lib/src/utilities/conversions.dart index 05465fc0f..be5a22d88 100644 --- a/dwds/lib/src/utilities/conversions.dart +++ b/dwds/lib/src/utilities/conversions.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 - /// Functions for converting between the different object references we use. import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; @@ -58,16 +56,15 @@ RemoteObject remoteObjectFor(String dartId) { data['value'] = _stringFromDartId(dartId); } else if (isDoubleId(dartId)) { data['type'] = 'number'; - data['value'] = _doubleFromDartId(dartId); + data['value'] = _doubleFromDartId(dartId)!; } else if (isIntId(dartId)) { data['type'] = 'number'; - data['value'] = _intFromDartId(dartId); + data['value'] = _intFromDartId(dartId)!; } else if (isBoolId(dartId)) { data['type'] = 'boolean'; data['value'] = _boolFromDartId(dartId); } else if (dartId == _nullId) { data['type'] = 'undefined'; - data['value'] = null; } else { data['type'] = 'object'; } @@ -78,7 +75,7 @@ RemoteObject remoteObjectFor(String dartId) { /// /// This will work for simple values, RemoteObject, and Maps representations of /// RemoteObjects. -String dartIdFor(Object argument) { +String dartIdFor(Object? argument) { if (argument == null) { return _nullId; } @@ -95,10 +92,10 @@ String dartIdFor(Object argument) { return '$_prefixForStringIds$argument'; } if (argument is RemoteObject) { - return argument.objectId; + return argument.objectId ?? null.toString(); } if (argument is Map) { - var id = argument['objectId'] as String; + var id = argument['objectId'] as String?; if (id == null) { throw ArgumentError.value(argument, 'objectId', 'No objectId found'); } @@ -136,17 +133,23 @@ bool isDoubleId(String dartId) => dartId.startsWith(_prefixForDoubleIds); bool isLibraryId(String dartId) => _uriPrefixes.any(dartId.startsWith); /// A Map representing a RemoteObject for a primitive object. -Map _callArgumentForPrimitive(Object primitive) { - return {'type': _jsTypeOf(primitive), 'value': primitive}; +Map _callArgumentForPrimitive(Object? primitive) { + return { + 'type': _jsTypeOf(primitive), + if (primitive != null) 'value': primitive, + }; } /// A Map representing a RemoteObject from an actual RemoteObject. Map _callArgumentForRemote(RemoteObject remote) { - return {'type': 'object', 'objectId': remote.objectId}; + return { + 'type': 'object', + if (remote.objectId != null) 'objectId': remote.objectId!, + }; } /// The JS type name to use in a RemoteObject reference to [object]. -String _jsTypeOf(Object object) { +String _jsTypeOf(Object? object) { if (object == null) return 'undefined'; if (object is String) return 'string'; if (object is num) return 'num'; @@ -162,11 +165,11 @@ String _stringFromDartId(String dartIdForString) => dartIdForString.substring(_prefixForStringIds.length); /// Convert [dartIdForInt] to its corresponding int. -int _intFromDartId(String dartIdForInt) => +int? _intFromDartId(String dartIdForInt) => int.tryParse(dartIdForInt.substring(_prefixForIntIds.length)); /// Convert [dartIdForDouble] to its corresponding double. -double _doubleFromDartId(String dartIdForDouble) => +double? _doubleFromDartId(String dartIdForDouble) => double.tryParse(dartIdForDouble.substring(_prefixForDoubleIds.length)); /// Convert [dartIdForBool] to its corresponding boolean. From ea9360c8e872d01474f1228d63611419553443ad Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Thu, 2 Jun 2022 17:23:45 -0700 Subject: [PATCH 04/12] Migrate some of dwds files to null safety --- dwds/CHANGELOG.md | 3 ++ dwds/lib/asset_reader.dart | 5 +++ dwds/lib/dwds.dart | 5 +-- dwds/lib/expression_compiler.dart | 6 +++ dwds/lib/src/debugging/debugger.dart | 1 + dwds/lib/src/debugging/execution_context.dart | 22 +++++----- dwds/lib/src/debugging/metadata/class.dart | 2 +- dwds/lib/src/debugging/remote_debugger.dart | 10 ++--- dwds/lib/src/debugging/webkit_debugger.dart | 12 +++-- dwds/lib/src/handlers/socket_connections.dart | 11 ++--- dwds/lib/src/readers/asset_reader.dart | 8 ++-- dwds/lib/src/servers/extension_debugger.dart | 2 +- .../src/services/chrome_debug_exception.dart | 37 ++++++++++++++++ .../src/services/chrome_proxy_service.dart | 34 -------------- .../lib/src/services/expression_compiler.dart | 7 +-- .../services/expression_compiler_service.dart | 3 +- dwds/lib/src/sockets.dart | 5 +-- dwds/lib/src/utilities/batched_stream.dart | 9 ++-- dwds/lib/src/utilities/ddc_names.dart | 4 +- dwds/lib/src/utilities/objects.dart | 18 ++++---- dwds/lib/src/utilities/sdk_configuration.dart | 44 +++++++++---------- dwds/lib/src/utilities/shared.dart | 29 ++++++------ dwds/pubspec.yaml | 2 +- 23 files changed, 138 insertions(+), 141 deletions(-) create mode 100644 dwds/lib/asset_reader.dart create mode 100644 dwds/lib/expression_compiler.dart create mode 100644 dwds/lib/src/services/chrome_debug_exception.dart diff --git a/dwds/CHANGELOG.md b/dwds/CHANGELOG.md index 7b78c142e..20ac79153 100644 --- a/dwds/CHANGELOG.md +++ b/dwds/CHANGELOG.md @@ -1,3 +1,6 @@ +## 14.0.4-dev +- Port some `dwds` files to null safety. + ## 14.0.3 - Make data types null safe. - Update `package:vm_service` to 8.3.0. diff --git a/dwds/lib/asset_reader.dart b/dwds/lib/asset_reader.dart new file mode 100644 index 000000000..e542e64ae --- /dev/null +++ b/dwds/lib/asset_reader.dart @@ -0,0 +1,5 @@ +// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file +// 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. + +export 'src/readers/asset_reader.dart' show AssetReader, UrlEncoder; diff --git a/dwds/lib/dwds.dart b/dwds/lib/dwds.dart index 5c17a527d..88a925b23 100644 --- a/dwds/lib/dwds.dart +++ b/dwds/lib/dwds.dart @@ -40,12 +40,12 @@ export 'src/loaders/frontend_server_require.dart' export 'src/loaders/legacy.dart' show LegacyStrategy; export 'src/loaders/require.dart' show RequireStrategy; export 'src/loaders/strategy.dart' show LoadStrategy, ReloadConfiguration; -export 'src/readers/asset_reader.dart' show AssetReader; +export 'src/readers/asset_reader.dart' show AssetReader, UrlEncoder; export 'src/readers/frontend_server_asset_reader.dart' show FrontendServerAssetReader; export 'src/readers/proxy_server_asset_reader.dart' show ProxyServerAssetReader; export 'src/servers/devtools.dart'; -export 'src/services/chrome_proxy_service.dart' show ChromeDebugException; +export 'src/services/chrome_debug_exception.dart' show ChromeDebugException; export 'src/services/expression_compiler.dart' show ExpressionCompilationResult, ExpressionCompiler, ModuleInfo; export 'src/services/expression_compiler_service.dart' @@ -54,7 +54,6 @@ export 'src/utilities/sdk_configuration.dart' show SdkConfiguration, SdkConfigurationProvider; typedef ConnectionProvider = Future Function(); -typedef UrlEncoder = Future Function(String url); /// The Dart Web Debug Service. class Dwds { diff --git a/dwds/lib/expression_compiler.dart b/dwds/lib/expression_compiler.dart new file mode 100644 index 000000000..1bce79920 --- /dev/null +++ b/dwds/lib/expression_compiler.dart @@ -0,0 +1,6 @@ +// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file +// 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. + +export 'src/services/expression_compiler.dart' + show ExpressionCompilationResult, ExpressionCompiler, ModuleInfo; diff --git a/dwds/lib/src/debugging/debugger.dart b/dwds/lib/src/debugging/debugger.dart index dd9e02426..b44e6f3b1 100644 --- a/dwds/lib/src/debugging/debugger.dart +++ b/dwds/lib/src/debugging/debugger.dart @@ -16,6 +16,7 @@ import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' import '../loaders/strategy.dart'; import '../services/chrome_proxy_service.dart'; +import '../services/chrome_debug_exception.dart'; import '../utilities/conversions.dart'; import '../utilities/dart_uri.dart'; import '../utilities/domain.dart'; diff --git a/dwds/lib/src/debugging/execution_context.dart b/dwds/lib/src/debugging/execution_context.dart index e04bb58d2..64b9a3af2 100644 --- a/dwds/lib/src/debugging/execution_context.dart +++ b/dwds/lib/src/debugging/execution_context.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:async/async.dart'; @@ -22,13 +20,13 @@ class RemoteDebuggerExecutionContext extends ExecutionContext { final _logger = Logger('RemoteDebuggerExecutionContext'); // Contexts that may contain a Dart application. - StreamQueue _contexts; + late StreamQueue _contexts; - int _id; + int? _id; @override Future get id async { - if (_id != null) return _id; + if (_id != null) return _id!; _logger.fine('Looking for Dart execution context...'); while (await _contexts.hasNext .timeout(const Duration(milliseconds: 50), onTimeout: () => false)) { @@ -40,7 +38,7 @@ class RemoteDebuggerExecutionContext extends ExecutionContext { 'expression': r'window["$dartAppInstanceId"];', 'contextId': context, }); - if (result.result['result']['value'] != null) { + if (result.result?['result']?['value'] != null) { _logger.fine('Found valid execution context: $context'); _id = context; break; @@ -54,18 +52,18 @@ class RemoteDebuggerExecutionContext extends ExecutionContext { if (_id == null) { throw StateError('No context with the running Dart application.'); } - return _id; + return _id!; } RemoteDebuggerExecutionContext(this._id, this._remoteDebugger) { - var contextController = StreamController(); + var contextController = StreamController(); _remoteDebugger .eventStream('Runtime.executionContextsCleared', (e) => e) .listen((_) => _id = null); - _remoteDebugger - .eventStream('Runtime.executionContextCreated', - (e) => int.parse(e.params['context']['id'].toString())) - .listen(contextController.add); + _remoteDebugger.eventStream('Runtime.executionContextCreated', (e) { + var id = e.params?['context']?['id']?.toString(); + return id == null ? null : int.parse(id); + }).listen(contextController.add); _contexts = StreamQueue(contextController.stream); } } diff --git a/dwds/lib/src/debugging/metadata/class.dart b/dwds/lib/src/debugging/metadata/class.dart index 5c2a0de35..85245b665 100644 --- a/dwds/lib/src/debugging/metadata/class.dart +++ b/dwds/lib/src/debugging/metadata/class.dart @@ -11,7 +11,7 @@ import '../../debugging/classes.dart'; import '../../debugging/inspector.dart'; import '../../debugging/remote_debugger.dart'; import '../../loaders/strategy.dart'; -import '../../services/chrome_proxy_service.dart'; +import '../../services/chrome_debug_exception.dart'; /// Meta data for a remote Dart class in Chrome. class ClassMetaData { diff --git a/dwds/lib/src/debugging/remote_debugger.dart b/dwds/lib/src/debugging/remote_debugger.dart index 6520c8e27..8a2da79d4 100644 --- a/dwds/lib/src/debugging/remote_debugger.dart +++ b/dwds/lib/src/debugging/remote_debugger.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:webkit_inspection_protocol/webkit_inspection_protocol.dart'; class TargetCrashedEvent extends WipEvent { @@ -31,7 +29,7 @@ abstract class RemoteDebugger { Stream get onClose; Future sendCommand(String command, - {Map params}); + {Map? params}); Future disable(); @@ -47,18 +45,18 @@ abstract class RemoteDebugger { Future removeBreakpoint(String breakpointId); - Future stepInto({Map params}); + Future stepInto({Map? params}); Future stepOut(); - Future stepOver({Map params}); + Future stepOver({Map? params}); Future enablePage(); Future pageReload(); Future evaluate(String expression, - {bool returnByValue, int contextId}); + {bool? returnByValue, int? contextId}); Future evaluateOnCallFrame( String callFrameId, String expression); diff --git a/dwds/lib/src/debugging/webkit_debugger.dart b/dwds/lib/src/debugging/webkit_debugger.dart index e9b474b04..98b2dc546 100644 --- a/dwds/lib/src/debugging/webkit_debugger.dart +++ b/dwds/lib/src/debugging/webkit_debugger.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:webkit_inspection_protocol/webkit_inspection_protocol.dart'; import 'remote_debugger.dart'; @@ -15,7 +13,7 @@ class WebkitDebugger implements RemoteDebugger { /// Null until [close] is called. /// /// All subsequent calls to [close] will return this future. - Future _closed; + Future? _closed; WebkitDebugger(this._wipDebugger); @@ -29,7 +27,7 @@ class WebkitDebugger implements RemoteDebugger { @override Future sendCommand(String command, - {Map params}) => + {Map? params}) => _wipDebugger.sendCommand(command, params: params); @override @@ -60,14 +58,14 @@ class WebkitDebugger implements RemoteDebugger { _wipDebugger.removeBreakpoint(breakpointId); @override - Future stepInto({Map params}) => + Future stepInto({Map? params}) => _wipDebugger.stepInto(params: params); @override Future stepOut() => _wipDebugger.stepOut(); @override - Future stepOver({Map params}) => + Future stepOver({Map? params}) => _wipDebugger.stepOver(params: params); @override @@ -78,7 +76,7 @@ class WebkitDebugger implements RemoteDebugger { @override Future evaluate(String expression, - {bool returnByValue, int contextId}) { + {bool? returnByValue, int? contextId}) { return _wipDebugger.connection.runtime .evaluate(expression, returnByValue: returnByValue); } diff --git a/dwds/lib/src/handlers/socket_connections.dart b/dwds/lib/src/handlers/socket_connections.dart index 330a4e4ba..752fe385c 100644 --- a/dwds/lib/src/handlers/socket_connections.dart +++ b/dwds/lib/src/handlers/socket_connections.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:async/async.dart'; @@ -56,7 +54,7 @@ class SseSocketHandler extends SocketHandler { final SseHandler _sseHandler; final StreamController _connectionsStream = StreamController(); - StreamQueue _connectionsStreamQueue; + StreamQueue? _connectionsStreamQueue; SseSocketHandler(this._sseHandler) { unawaited(() async { @@ -90,8 +88,7 @@ class WebSocketConnection extends SocketConnection { StreamSink get sink => _channel.sink; @override - Stream get stream => - _channel.stream.map((dynamic o) => o?.toString()); + Stream get stream => _channel.stream.map((dynamic o) => o.toString()); @override void shutdown() => _channel.sink.close(); @@ -100,10 +97,10 @@ class WebSocketConnection extends SocketConnection { /// An implemenation of [SocketHandler] that accepts WebSocket connections and /// wraps them in a [WebSocketConnection]. class WebSocketSocketHandler extends SocketHandler { - Handler _handler; + late Handler _handler; final StreamController _connectionsStream = StreamController(); - StreamQueue _connectionsStreamQueue; + StreamQueue? _connectionsStreamQueue; WebSocketSocketHandler() { _handler = webSocketHandler((WebSocketChannel channel) => diff --git a/dwds/lib/src/readers/asset_reader.dart b/dwds/lib/src/readers/asset_reader.dart index 5d8764185..55824fc99 100644 --- a/dwds/lib/src/readers/asset_reader.dart +++ b/dwds/lib/src/readers/asset_reader.dart @@ -2,20 +2,20 @@ // 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 +typedef UrlEncoder = Future Function(String url); /// A reader for Dart sources and related source maps. abstract class AssetReader { /// Returns the contents for a source map at the provided server path, or /// null if the resource does not exist. - Future sourceMapContents(String serverPath); + Future sourceMapContents(String serverPath); /// Returns the contents for a dart source at the provided server path, or /// null if the resource does not exist. - Future dartSourceContents(String serverPath); + Future dartSourceContents(String serverPath); /// Returns the contents for the merged metadata output at the provided path. - Future metadataContents(String serverPath); + Future metadataContents(String serverPath); /// Closes connections Future close(); diff --git a/dwds/lib/src/servers/extension_debugger.dart b/dwds/lib/src/servers/extension_debugger.dart index 854b2c704..830775655 100644 --- a/dwds/lib/src/servers/extension_debugger.dart +++ b/dwds/lib/src/servers/extension_debugger.dart @@ -16,7 +16,7 @@ import '../../data/serializers.dart'; import '../debugging/execution_context.dart'; import '../debugging/remote_debugger.dart'; import '../handlers/socket_connections.dart'; -import '../services/chrome_proxy_service.dart'; +import '../services/chrome_debug_exception.dart'; /// A remote debugger backed by the Dart Debug Extension with an SSE connection. class ExtensionDebugger implements RemoteDebugger { diff --git a/dwds/lib/src/services/chrome_debug_exception.dart b/dwds/lib/src/services/chrome_debug_exception.dart new file mode 100644 index 000000000..5fc41f92e --- /dev/null +++ b/dwds/lib/src/services/chrome_debug_exception.dart @@ -0,0 +1,37 @@ +// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file +// 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 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; + +class ChromeDebugException extends ExceptionDetails implements Exception { + /// Optional, additional information about the exception. + final Object? additionalDetails; + + /// Optional, the exact contents of the eval that was attempted. + final String? evalContents; + + ChromeDebugException(Map exceptionDetails, + {this.additionalDetails, this.evalContents}) + : super(exceptionDetails); + + @override + String toString() { + var description = StringBuffer() + ..writeln('Unexpected error from chrome devtools:'); + description.writeln('text: $text'); + if (exception != null) { + description.writeln('exception:'); + description.writeln(' description: ${exception?.description}'); + description.writeln(' type: ${exception?.type}'); + description.writeln(' value: ${exception?.value}'); + } + if (evalContents != null) { + description.writeln('attempted JS eval: `$evalContents`'); + } + if (additionalDetails != null) { + description.writeln('additional details:\n $additionalDetails'); + } + return description.toString(); + } +} diff --git a/dwds/lib/src/services/chrome_proxy_service.dart b/dwds/lib/src/services/chrome_proxy_service.dart index c8bc51ade..141c2e97b 100644 --- a/dwds/lib/src/services/chrome_proxy_service.dart +++ b/dwds/lib/src/services/chrome_proxy_service.dart @@ -1097,37 +1097,3 @@ const _stderrTypes = ['error']; /// The `type`s of [ConsoleAPIEvent]s that are treated as `stdout` logs. const _stdoutTypes = ['log', 'info', 'warning']; - -class ChromeDebugException extends ExceptionDetails implements Exception { - /// Optional, additional information about the exception. - final Object additionalDetails; - - /// Optional, the exact contents of the eval that was attempted. - final String evalContents; - - ChromeDebugException(Map exceptionDetails, - {this.additionalDetails, this.evalContents}) - : super(exceptionDetails); - - @override - String toString() { - var description = StringBuffer() - ..writeln('Unexpected error from chrome devtools:'); - if (text != null) { - description.writeln('text: $text'); - } - if (exception != null) { - description.writeln('exception:'); - description.writeln(' description: ${exception.description}'); - description.writeln(' type: ${exception.type}'); - description.writeln(' value: ${exception.value}'); - } - if (evalContents != null) { - description.writeln('attempted JS eval: `$evalContents`'); - } - if (additionalDetails != null) { - description.writeln('additional details:\n $additionalDetails'); - } - return description.toString(); - } -} diff --git a/dwds/lib/src/services/expression_compiler.dart b/dwds/lib/src/services/expression_compiler.dart index db3b55f18..4af38c114 100644 --- a/dwds/lib/src/services/expression_compiler.dart +++ b/dwds/lib/src/services/expression_compiler.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 - /// Result of compilation of dart expression to JavaScript class ExpressionCompilationResult { final bool isError; @@ -69,7 +67,10 @@ abstract class ExpressionCompiler { /// Initializes the compiler with null safety mode and module format. /// /// May be called multiple times and always before [updateDependencies]. - Future initialize({String moduleFormat, bool soundNullSafety}); + Future initialize({ + required String moduleFormat, + bool soundNullSafety = false, + }); } class ModuleInfo { diff --git a/dwds/lib/src/services/expression_compiler_service.dart b/dwds/lib/src/services/expression_compiler_service.dart index eb82bcc37..aac744211 100644 --- a/dwds/lib/src/services/expression_compiler_service.dart +++ b/dwds/lib/src/services/expression_compiler_service.dart @@ -261,7 +261,8 @@ class ExpressionCompilerService implements ExpressionCompiler { line, column, jsModules, jsFrameValues, moduleName, expression); @override - Future initialize({String moduleFormat, bool soundNullSafety}) async { + Future initialize( + {String moduleFormat, bool soundNullSafety = false}) async { if (_compiler.isCompleted) return; soundNullSafety ??= false; diff --git a/dwds/lib/src/sockets.dart b/dwds/lib/src/sockets.dart index c802c1584..016448f9f 100644 --- a/dwds/lib/src/sockets.dart +++ b/dwds/lib/src/sockets.dart @@ -2,8 +2,6 @@ // 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:sse/client/sse_client.dart'; @@ -37,8 +35,7 @@ class WebSocketClient extends SocketClient { @override StreamSink get sink => _channel.sink; @override - Stream get stream => - _channel.stream.map((dynamic o) => o?.toString()); + Stream get stream => _channel.stream.map((dynamic o) => o.toString()); @override void close() => _channel.sink.close(); diff --git a/dwds/lib/src/utilities/batched_stream.dart b/dwds/lib/src/utilities/batched_stream.dart index cfe837a92..eb5bdbf8f 100644 --- a/dwds/lib/src/utilities/batched_stream.dart +++ b/dwds/lib/src/utilities/batched_stream.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:async/async.dart'; @@ -14,10 +12,10 @@ class BatchedStreamController { final int _batchDelayMilliseconds; - StreamController _inputController; - StreamQueue _inputQueue; + late StreamController _inputController; + late StreamQueue _inputQueue; - StreamController> _outputController; + late StreamController> _outputController; final Completer _completer = Completer(); /// Create batched stream controller. @@ -30,7 +28,6 @@ class BatchedStreamController { _inputController = StreamController(); _inputQueue = StreamQueue(_inputController.stream); _outputController = StreamController>(); - unawaited(_batchAndSendEvents()); } diff --git a/dwds/lib/src/utilities/ddc_names.dart b/dwds/lib/src/utilities/ddc_names.dart index b5b5436bd..e55823be5 100644 --- a/dwds/lib/src/utilities/ddc_names.dart +++ b/dwds/lib/src/utilities/ddc_names.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:path/path.dart' as p; /// Transforms a path to a valid JS identifier. @@ -31,7 +29,7 @@ String toJSIdentifier(String name) { if (name.isEmpty) return r'$'; // Escape any invalid characters - StringBuffer buffer; + StringBuffer? buffer; for (var i = 0; i < name.length; i++) { var ch = name[i]; var needsEscape = ch == r'$' || _invalidCharInIdentifier.hasMatch(ch); diff --git a/dwds/lib/src/utilities/objects.dart b/dwds/lib/src/utilities/objects.dart index fbfd48c89..5d67a85c8 100644 --- a/dwds/lib/src/utilities/objects.dart +++ b/dwds/lib/src/utilities/objects.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:async'; -// @dart = 2.9 - /// A library for WebKit mirror objects and support code. These probably should /// get migrated into webkit_inspection_protocol over time. @@ -11,26 +9,26 @@ import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; /// Represents a property of an object. class Property { - final Map _map; + final Map? _map; - RemoteObject _remoteObjectValue; + RemoteObject? _remoteObjectValue; Property(this._map); - Map get map => _map; + Map? get map => _map; /// The remote object value in unwrapped form. /// /// Useful for getting access to properties of particular types of /// RemoteObject. - Object get rawValue => _map == null ? null : _map['value']; + Object? get rawValue => _map == null ? null : _map!['value']; /// Remote object value in case of primitive values or JSON values (if it was /// requested). (optional) - RemoteObject get value { - if (_remoteObjectValue != null) return _remoteObjectValue; + RemoteObject? get value { + if (_remoteObjectValue != null) return _remoteObjectValue!; if (rawValue == null) return null; - var val = _map['value']; + var val = _map!['value']; if (val is RemoteObject) { _remoteObjectValue = val; } else { @@ -56,7 +54,7 @@ class Property { /// The raw name of the property in JS. /// /// Will be of the form 'Symbol(_actualName)' for private fields. - String get rawName => _map['name'] as String; + String get rawName => _map!['name'] as String; @override String toString() => '$name $value'; diff --git a/dwds/lib/src/utilities/sdk_configuration.dart b/dwds/lib/src/utilities/sdk_configuration.dart index 114e18f66..4a83e37f7 100644 --- a/dwds/lib/src/utilities/sdk_configuration.dart +++ b/dwds/lib/src/utilities/sdk_configuration.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:io'; import 'package:file/file.dart'; @@ -11,7 +9,7 @@ import 'package:file/local.dart'; import 'package:path/path.dart' as p; class InvalidSdkConfigurationException implements Exception { - final String message; + final String? message; InvalidSdkConfigurationException([this.message]); @@ -38,11 +36,11 @@ abstract class SdkConfigurationProvider { /// Call [validate] method to make sure the files in the configuration /// layout exist before reading the files. class SdkConfiguration { - String sdkDirectory; - String unsoundSdkSummaryPath; - String soundSdkSummaryPath; - String librariesPath; - String compilerWorkerPath; + String? sdkDirectory; + String? unsoundSdkSummaryPath; + String? soundSdkSummaryPath; + String? librariesPath; + String? compilerWorkerPath; SdkConfiguration({ this.sdkDirectory, @@ -52,21 +50,21 @@ class SdkConfiguration { this.compilerWorkerPath, }); - static Uri _toUri(String path) => path == null ? null : p.toUri(path); - static Uri _toAbsoluteUri(String path) => + static Uri? _toUri(String? path) => path == null ? null : p.toUri(path); + static Uri? _toAbsoluteUri(String? path) => path == null ? null : p.toUri(p.absolute(path)); - Uri get sdkDirectoryUri => _toUri(sdkDirectory); - Uri get soundSdkSummaryUri => _toUri(soundSdkSummaryPath); - Uri get unsoundSdkSummaryUri => _toUri(unsoundSdkSummaryPath); - Uri get librariesUri => _toUri(librariesPath); + Uri? get sdkDirectoryUri => _toUri(sdkDirectory); + Uri? get soundSdkSummaryUri => _toUri(soundSdkSummaryPath); + Uri? get unsoundSdkSummaryUri => _toUri(unsoundSdkSummaryPath); + Uri? get librariesUri => _toUri(librariesPath); /// Note: has to be ///file: Uri to run in an isolate. - Uri get compilerWorkerUri => _toAbsoluteUri(compilerWorkerPath); + Uri? get compilerWorkerUri => _toAbsoluteUri(compilerWorkerPath); /// Throws [InvalidSdkConfigurationException] if configuration does not /// exist on disk. - void validate({FileSystem fileSystem}) { + void validate({FileSystem? fileSystem}) { fileSystem ??= const LocalFileSystem(); validateSdkDir(fileSystem: fileSystem); @@ -77,7 +75,7 @@ class SdkConfiguration { /// Throws [InvalidSdkConfigurationException] if SDK root does not /// exist on the disk. - void validateSdkDir({FileSystem fileSystem}) { + void validateSdkDir({FileSystem? fileSystem}) { fileSystem ??= const LocalFileSystem(); if (sdkDirectory == null || !fileSystem.directory(sdkDirectory).existsSync()) { @@ -86,7 +84,7 @@ class SdkConfiguration { } } - void validateSummaries({FileSystem fileSystem}) { + void validateSummaries({FileSystem? fileSystem}) { fileSystem ??= const LocalFileSystem(); if (unsoundSdkSummaryPath == null || @@ -102,7 +100,7 @@ class SdkConfiguration { } } - void validateLibrariesSpec({FileSystem fileSystem}) { + void validateLibrariesSpec({FileSystem? fileSystem}) { fileSystem ??= const LocalFileSystem(); if (librariesPath == null || !fileSystem.file(librariesPath).existsSync()) { @@ -111,7 +109,7 @@ class SdkConfiguration { } } - void validateCompilerWorker({FileSystem fileSystem}) { + void validateCompilerWorker({FileSystem? fileSystem}) { fileSystem ??= const LocalFileSystem(); if (compilerWorkerPath == null || @@ -124,10 +122,10 @@ class SdkConfiguration { /// Implementation for the default SDK configuration layout. class DefaultSdkConfigurationProvider extends SdkConfigurationProvider { - SdkConfiguration _configuration; - DefaultSdkConfigurationProvider(); + SdkConfiguration? _configuration; + /// Create and validate configuration matching the default SDK layout. @override Future get configuration async { @@ -146,6 +144,6 @@ class DefaultSdkConfigurationProvider extends SdkConfigurationProvider { p.join(binDir, 'snapshots', 'dartdevc.dart.snapshot'), ); } - return _configuration; + return _configuration!; } } diff --git a/dwds/lib/src/utilities/shared.dart b/dwds/lib/src/utilities/shared.dart index 613b64a6f..78a2663d9 100644 --- a/dwds/lib/src/utilities/shared.dart +++ b/dwds/lib/src/utilities/shared.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:io'; @@ -15,7 +13,7 @@ import 'package:vm_service/vm_service.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' as wip; -import '../../dwds.dart' show ChromeDebugException; +import 'package:dwds/src/services/chrome_debug_exception.dart'; VMRef toVMRef(VM vm) => VMRef(name: vm.name); @@ -28,11 +26,12 @@ String createId() { /// Returns `true` if [hostname] is bound to an IPv6 address. Future useIPv6ForHost(String hostname) async { final addresses = await InternetAddress.lookup(hostname); + if (addresses.isEmpty) return false; final address = addresses.firstWhere( (a) => a.type == InternetAddressType.IPv6, - orElse: () => null, + orElse: () => addresses.first, ); - return address != null; + return address.type == InternetAddressType.IPv6; } /// Returns a port that is probably, but not definitely, not in use. @@ -58,23 +57,23 @@ Future findUnusedPort() async { /// Retries a few times to recover from errors due to /// another thread or process opening the same port. /// Starts by trying to bind to [port] if specified. -Future startHttpServer(String hostname, {int port}) async { - HttpServer httpServer; +Future startHttpServer(String hostname, {int? port}) async { + HttpServer? httpServer; var retries = 5; var i = 0; port = port ?? await findUnusedPort(); while (i < retries) { i++; try { - httpServer = await HttpMultiServer.bind(hostname, port); + httpServer = await HttpMultiServer.bind(hostname, port!); } on SocketException { if (i == retries) rethrow; } - if (httpServer != null || i == retries) return httpServer; + if (httpServer != null || i == retries) return httpServer!; port = await findUnusedPort(); await Future.delayed(const Duration(milliseconds: 100)); } - return httpServer; + return httpServer!; } /// Handles [requests] using [handler]. @@ -90,12 +89,12 @@ void serveHttpRequests(Stream requests, Handler handler, /// Throws an [wip.ExceptionDetails] object if `exceptionDetails` is present on the /// result. -void handleErrorIfPresent(wip.WipResponse response, - {String evalContents, Object additionalDetails}) { - if (response == null) return; - if (response.result.containsKey('exceptionDetails')) { +void handleErrorIfPresent(wip.WipResponse? response, + {String? evalContents, Object? additionalDetails}) { + if (response == null || response.result == null) return; + if (response.result!.containsKey('exceptionDetails')) { throw ChromeDebugException( - response.result['exceptionDetails'] as Map, + response.result!['exceptionDetails'] as Map, evalContents: evalContents, additionalDetails: additionalDetails); } diff --git a/dwds/pubspec.yaml b/dwds/pubspec.yaml index 471750663..2694a79f6 100644 --- a/dwds/pubspec.yaml +++ b/dwds/pubspec.yaml @@ -1,6 +1,6 @@ name: dwds # Every time this changes you need to run `dart run build_runner build`. -version: 14.0.3 +version: 14.0.4-dev description: >- A service that proxies between the Chrome debug protocol and the Dart VM service protocol. From 0cda87016dc0abd185a482abbedb37797ecad288 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Thu, 2 Jun 2022 17:24:52 -0700 Subject: [PATCH 05/12] Migrate frontend_server_common to null safety --- .../lib/src/asset_server.dart | 64 +++--- frontend_server_common/lib/src/bootstrap.dart | 12 +- frontend_server_common/lib/src/devfs.dart | 40 ++-- .../lib/src/frontend_server_client.dart | 205 +++++++++--------- .../lib/src/resident_runner.dart | 19 +- frontend_server_common/lib/src/utilities.dart | 2 - 6 files changed, 167 insertions(+), 175 deletions(-) diff --git a/frontend_server_common/lib/src/asset_server.dart b/frontend_server_common/lib/src/asset_server.dart index 776e35e6a..c3dee872b 100644 --- a/frontend_server_common/lib/src/asset_server.dart +++ b/frontend_server_common/lib/src/asset_server.dart @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.9 - // Note: this is a copy from flutter tools, updated to work with dwds tests import 'dart:async'; @@ -11,7 +9,7 @@ import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; -import 'package:dwds/dwds.dart'; +import 'package:dwds/asset_reader.dart'; import 'package:file/file.dart'; import 'package:logging/logging.dart'; import 'package:mime/mime.dart' as mime; @@ -36,6 +34,23 @@ class TestAssetServer implements AssetReader { // makes no claims as to the structure of the data. static const String _defaultMimeType = 'application/octet-stream'; final FileSystem _fileSystem; + final String _root; + final HttpServer _httpServer; + final Map _files = {}; + final Map _sourcemaps = {}; + final Map _metadata = {}; + String? _mergedMetadata; + final PackageConfig _packageConfig; + final InternetAddress internetAddress; + + bool hasFile(String path) => _files.containsKey(path); + Uint8List getFile(String path) => _files[path]!; + + bool hasSourceMap(String path) => _sourcemaps.containsKey(path); + Uint8List getSourceMap(String path) => _sourcemaps[path]!; + + bool hasMetadata(String path) => _metadata.containsKey(path); + Uint8List getMetadata(String path) => _metadata[path]!; /// Start the web asset server on a [hostname] and [port]. /// @@ -56,19 +71,6 @@ class TestAssetServer implements AssetReader { return server; } - final String _root; - final HttpServer _httpServer; - final Map _files = {}; - final Map _sourcemaps = {}; - final Map _metadata = {}; - String _mergedMetadata; - final PackageConfig _packageConfig; - final InternetAddress internetAddress; - - Uint8List getFile(String path) => _files[path]; - - Uint8List getSourceMap(String path) => _sourcemaps[path]; - // handle requests for JavaScript source, dart sources maps, or asset files. Future handleRequest(shelf.Request request) async { var headers = {}; @@ -94,16 +96,16 @@ class TestAssetServer implements AssetReader { // If this is a JavaScript file, it must be in the in-memory cache. // Attempt to look up the file by URI. - if (_files.containsKey(requestPath)) { - final List bytes = getFile(requestPath); + if (hasFile(requestPath)) { + final bytes = getFile(requestPath); headers[HttpHeaders.contentLengthHeader] = bytes.length.toString(); headers[HttpHeaders.contentTypeHeader] = 'application/javascript'; return shelf.Response.ok(bytes, headers: headers); } // If this is a sourcemap file, then it might be in the in-memory cache. // Attempt to lookup the file by URI. - if (_sourcemaps.containsKey(requestPath)) { - final List bytes = getSourceMap(requestPath); + if (hasSourceMap(requestPath)) { + final bytes = getSourceMap(requestPath); headers[HttpHeaders.contentLengthHeader] = bytes.length.toString(); headers[HttpHeaders.contentTypeHeader] = 'application/json'; return shelf.Response.ok(bytes, headers: headers); @@ -118,7 +120,7 @@ class TestAssetServer implements AssetReader { // Attempt to determine the file's mime type. if this is not provided some // browsers will refuse to render images/show video et cetera. If the tool // cannot determine a mime type, fall back to application/octet-stream. - String mimeType; + String? mimeType; if (length >= 12) { mimeType = mime.lookupMimeType( file.path, @@ -154,10 +156,6 @@ class TestAssetServer implements AssetReader { var manifest = castStringKeyedMap(json.decode(manifestFile.readAsStringSync())); for (var filePath in manifest.keys) { - if (filePath == null) { - _logger.severe('Invalid manfiest file: $filePath'); - continue; - } var offsets = castStringKeyedMap(manifest[filePath]); var codeOffsets = (offsets['code'] as List).cast(); var sourcemapOffsets = @@ -253,7 +251,7 @@ class TestAssetServer implements AssetReader { } @override - Future dartSourceContents(String serverPath) { + Future dartSourceContents(String serverPath) async { var result = _resolveDartFile(serverPath); if (result.existsSync()) { return result.readAsString(); @@ -262,22 +260,22 @@ class TestAssetServer implements AssetReader { } @override - Future sourceMapContents(String serverPath) async { + Future sourceMapContents(String serverPath) async { var path = '/$serverPath'; - if (_sourcemaps.containsKey(path)) { - return utf8.decode(_sourcemaps[path]); + if (hasSourceMap(path)) { + return utf8.decode(getSourceMap(path)); } return null; } @override - Future metadataContents(String serverPath) async { + Future metadataContents(String serverPath) async { if (serverPath.endsWith('.ddc_merged_metadata')) { return _mergedMetadata; } var path = '/$serverPath'; - if (_metadata.containsKey(path)) { - return utf8.decode(_metadata[path]); + if (hasMetadata(path)) { + return utf8.decode(getMetadata(path)); } return null; } @@ -287,5 +285,5 @@ class TestAssetServer implements AssetReader { /// the same structure (`Map`) with the correct runtime types. Map castStringKeyedMap(dynamic untyped) { var map = untyped as Map; - return map?.cast(); + return map.cast(); } diff --git a/frontend_server_common/lib/src/bootstrap.dart b/frontend_server_common/lib/src/bootstrap.dart index f1a7e01b9..a5d1ba0c4 100644 --- a/frontend_server_common/lib/src/bootstrap.dart +++ b/frontend_server_common/lib/src/bootstrap.dart @@ -2,12 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.9 - // Note: this is a copy from flutter tools, updated to work with dwds tests -import 'package:meta/meta.dart'; - /// The JavaScript bootstrap script to support in-browser hot restart. /// /// The [requireUrl] loads our cached RequireJS script file. The [mapperUrl] @@ -18,9 +14,9 @@ import 'package:meta/meta.dart'; /// and is responsible for bootstrapping the RequireJS modules and attaching /// the hot reload hooks. String generateBootstrapScript({ - @required String requireUrl, - @required String mapperUrl, - @required String entrypoint, + required String requireUrl, + required String mapperUrl, + required String entrypoint, }) { return ''' "use strict"; @@ -53,7 +49,7 @@ document.head.appendChild(requireEl); /// the file `foo/bar/baz.dart` will generate a property named approximately /// `foo__bar__baz`. Rather than attempt to guess, we assume the first property of /// this object is the module. -String generateMainModule({@required String entrypoint}) { +String generateMainModule({required String entrypoint}) { return '''/* ENTRYPOINT_EXTENTION_MARKER */ // Create the main module loaded below. diff --git a/frontend_server_common/lib/src/devfs.dart b/frontend_server_common/lib/src/devfs.dart index 323c92fc1..6d1e82c3c 100644 --- a/frontend_server_common/lib/src/devfs.dart +++ b/frontend_server_common/lib/src/devfs.dart @@ -2,15 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.9 - // Note: this is a copy from flutter tools, updated to work with dwds tests import 'dart:io'; -import 'package:dwds/dwds.dart'; +import 'package:dwds/asset_reader.dart'; import 'package:file/file.dart'; -import 'package:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as p; @@ -23,26 +20,26 @@ final String dartWebSdkPath = p.join(dartSdkPath, 'lib', 'dev_compiler'); class WebDevFS { WebDevFS({ - this.fileSystem, - this.hostname, - this.port, - this.packageConfigPath, - this.root, - this.urlTunneller, - this.soundNullSafety, + required this.fileSystem, + required this.hostname, + required this.port, + required this.packageConfigPath, + required this.root, + required this.urlTunneller, + required this.soundNullSafety, }); final FileSystem fileSystem; - TestAssetServer assetServer; + late TestAssetServer assetServer; final String hostname; final int port; final String packageConfigPath; final String root; final UrlEncoder urlTunneller; final bool soundNullSafety; - Directory _savedCurrentDirectory; - List sources; - PackageConfig _packageConfig; + late Directory _savedCurrentDirectory; + List? sources; + late PackageConfig _packageConfig; Future create() async { _savedCurrentDirectory = fileSystem.currentDirectory; @@ -61,16 +58,15 @@ class WebDevFS { Future dispose() { fileSystem.currentDirectory = _savedCurrentDirectory; - return assetServer?.close(); + return assetServer.close(); } Future update({ - String mainPath, - String dillOutputPath, - @required ResidentCompiler generator, - List invalidatedFiles, + required String mainPath, + required String dillOutputPath, + required ResidentCompiler generator, + required List invalidatedFiles, }) async { - assert(generator != null); var outputDirectoryPath = fileSystem.file(mainPath).parent.path; var entryPoint = mainPath; @@ -197,7 +193,7 @@ class UpdateFSReport { /// mode. /// /// Only used for JavaScript compilation. - List invalidatedModules; + List? invalidatedModules; } String _filePathToUriFragment(String path) { diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index 9d3f92050..fe1d7653b 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -2,17 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.9 - // Note: this is a copy from flutter tools, updated to work with dwds tests import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import 'package:dwds/dwds.dart'; +import 'package:dwds/expression_compiler.dart'; import 'package:logging/logging.dart'; -import 'package:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as p; import 'package:usage/uuid/uuid.dart'; @@ -22,7 +19,7 @@ import 'utilities.dart'; Logger _logger = Logger('FrontendServerClient'); Logger _serverLogger = Logger('FrontendServer'); -void defaultConsumer(String message, {StackTrace stackTrace}) => +void defaultConsumer(String message, {StackTrace? stackTrace}) => stackTrace == null ? _serverLogger.info(message) : _serverLogger.severe(message, null, stackTrace); @@ -45,19 +42,19 @@ enum StdoutState { collectDiagnostic, collectDependencies } /// Handles stdin/stdout communication with the frontend server. class StdoutHandler { - StdoutHandler({@required this.consumer}) { + StdoutHandler({required this.consumer}) { reset(); } bool compilerMessageReceived = false; final CompilerMessageConsumer consumer; - String boundaryKey; + String? boundaryKey; StdoutState state = StdoutState.collectDiagnostic; - Completer compilerOutput; + late Completer compilerOutput; final List sources = []; - bool _suppressCompilerMessages; - bool _expectSources; + late bool _suppressCompilerMessages; + late bool _expectSources; bool _badState = false; void handler(String message) { @@ -104,20 +101,20 @@ class StdoutHandler { _badState = true; return; } - if (message.startsWith(boundaryKey)) { + if (message.startsWith(boundaryKey!)) { if (_expectSources) { if (state == StdoutState.collectDiagnostic) { state = StdoutState.collectDependencies; return; } } - if (message.length <= boundaryKey.length) { + if (message.length <= boundaryKey!.length) { compilerOutput.complete(null); return; } var spaceDelimiter = message.lastIndexOf(' '); compilerOutput.complete(CompilerOutput( - message.substring(boundaryKey.length + 1, spaceDelimiter), + message.substring(boundaryKey!.length + 1, spaceDelimiter), int.parse(message.substring(spaceDelimiter + 1).trim()), sources)); return; @@ -151,7 +148,7 @@ class StdoutHandler { {bool suppressCompilerMessages = false, bool expectSources = true}) { boundaryKey = null; compilerMessageReceived = false; - compilerOutput = Completer(); + compilerOutput = Completer(); _suppressCompilerMessages = suppressCompilerMessages; _expectSources = expectSources; state = StdoutState.collectDiagnostic; @@ -162,9 +159,9 @@ class StdoutHandler { abstract class _CompilationRequest { _CompilationRequest(this.completer); - Completer completer; + Completer completer; - Future _run(ResidentCompiler compiler); + Future _run(ResidentCompiler compiler); Future run(ResidentCompiler compiler) async { completer.complete(await _run(compiler)); @@ -173,7 +170,7 @@ abstract class _CompilationRequest { class _RecompileRequest extends _CompilationRequest { _RecompileRequest( - Completer completer, + Completer completer, this.mainUri, this.invalidatedFiles, this.outputPath, @@ -186,13 +183,13 @@ class _RecompileRequest extends _CompilationRequest { PackageConfig packageConfig; @override - Future _run(ResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._recompile(this); } class _CompileExpressionRequest extends _CompilationRequest { _CompileExpressionRequest( - Completer completer, + Completer completer, this.expression, this.definitions, this.typeDefinitions, @@ -204,18 +201,18 @@ class _CompileExpressionRequest extends _CompilationRequest { String expression; List definitions; List typeDefinitions; - String libraryUri; - String klass; - bool isStatic; + String? libraryUri; + String? klass; + bool? isStatic; @override - Future _run(ResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._compileExpression(this); } class _CompileExpressionToJsRequest extends _CompilationRequest { _CompileExpressionToJsRequest( - Completer completer, + Completer completer, this.libraryUri, this.line, this.column, @@ -234,15 +231,15 @@ class _CompileExpressionToJsRequest extends _CompilationRequest { String expression; @override - Future _run(ResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._compileExpressionToJs(this); } class _RejectRequest extends _CompilationRequest { - _RejectRequest(Completer completer) : super(completer); + _RejectRequest(Completer completer) : super(completer); @override - Future _run(ResidentCompiler compiler) async => + Future _run(ResidentCompiler compiler) async => compiler._reject(); } @@ -254,14 +251,13 @@ class _RejectRequest extends _CompilationRequest { class ResidentCompiler { ResidentCompiler( String sdkRoot, { - this.packageConfigPath, - this.fileSystemRoots, - this.fileSystemScheme, - this.platformDill, - this.verbose, + required this.packageConfigPath, + required this.fileSystemRoots, + required this.fileSystemScheme, + required this.platformDill, + this.verbose = false, CompilerMessageConsumer compilerMessageConsumer = defaultConsumer, - }) : assert(sdkRoot != null), - _stdoutHandler = StdoutHandler(consumer: compilerMessageConsumer), + }) : _stdoutHandler = StdoutHandler(consumer: compilerMessageConsumer), // This is a URI, not a file path, so the forward slash is correct even on Windows. sdkRoot = sdkRoot.endsWith('/') ? sdkRoot : '$sdkRoot/'; @@ -274,7 +270,7 @@ class ResidentCompiler { /// The path to the root of the Dart SDK used to compile. final String sdkRoot; - Process _server; + Process? _server; final StdoutHandler _stdoutHandler; bool _compileRequestNeedsConfirmation = false; @@ -288,21 +284,23 @@ class ResidentCompiler { /// point that is used for recompilation. /// Binary file name is returned if compilation was successful, otherwise /// null is returned. - Future recompile(Uri mainUri, List invalidatedFiles, - {@required String outputPath, - @required PackageConfig packageConfig}) async { - assert(outputPath != null); + Future recompile( + Uri mainUri, + List invalidatedFiles, { + required String outputPath, + required PackageConfig packageConfig, + }) async { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } - var completer = Completer(); + var completer = Completer(); _controller.add(_RecompileRequest( completer, mainUri, invalidatedFiles, outputPath, packageConfig)); return completer.future; } - Future _recompile(_RecompileRequest request) async { + Future _recompile(_RecompileRequest request) async { _stdoutHandler.reset(); final mainUri = @@ -316,7 +314,7 @@ class ResidentCompiler { } var inputKey = Uuid().generateV4(); - _server.stdin.writeln('recompile $mainUri$inputKey'); + _server!.stdin.writeln('recompile $mainUri$inputKey'); _logger.info('<- recompile $mainUri$inputKey'); for (var fileUri in request.invalidatedFiles) { String message; @@ -326,10 +324,10 @@ class ResidentCompiler { message = request.packageConfig.toPackageUri(fileUri)?.toString() ?? toMultiRootPath(fileUri, fileSystemScheme, fileSystemRoots); } - _server.stdin.writeln(message); + _server!.stdin.writeln(message); _logger.info(message); } - _server.stdin.writeln(inputKey); + _server!.stdin.writeln(inputKey); _logger.info('<- $inputKey'); return _stdoutHandler.compilerOutput.future; @@ -352,7 +350,7 @@ class ResidentCompiler { } } - Future _compile( + Future _compile( String scriptUri, String outputFilePath) async { var frontendServer = frontendServerExecutable; var args = [ @@ -364,20 +362,19 @@ class ResidentCompiler { '-Ddart.developer.causal_async_stacks=true', '--output-dill', outputFilePath, - if (packageConfigPath != null) ...[ + ...[ '--packages', packageConfigPath, ], - if (fileSystemRoots != null) - for (final String root in fileSystemRoots) ...[ - '--filesystem-root', - root, - ], - if (fileSystemScheme != null) ...[ + for (final String root in fileSystemRoots) ...[ + '--filesystem-root', + root, + ], + ...[ '--filesystem-scheme', fileSystemScheme, ], - if (platformDill != null) ...[ + ...[ '--platform', platformDill, ], @@ -390,7 +387,7 @@ class ResidentCompiler { var projectDirectory = p.dirname(p.dirname(packageConfigPath)); _server = await Process.start(Platform.resolvedExecutable, args, workingDirectory: projectDirectory); - _server.stdout + _server!.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen(_stdoutHandler.handler, onDone: () { @@ -402,25 +399,25 @@ class ResidentCompiler { } }); - _server.stderr + _server!.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen(_logger.info); - unawaited(_server.exitCode.then((int code) { + unawaited(_server!.exitCode.then((int code) { if (code != 0) { throw Exception('the Dart compiler exited unexpectedly.'); } })); - _server.stdin.writeln('compile $scriptUri'); + _server!.stdin.writeln('compile $scriptUri'); _logger.info('<- compile $scriptUri'); return _stdoutHandler.compilerOutput.future; } /// Compile dart expression to kernel. - Future compileExpression( + Future compileExpression( String expression, List definitions, List typeDefinitions, @@ -432,13 +429,13 @@ class ResidentCompiler { _controller.stream.listen(_handleCompilationRequest); } - var completer = Completer(); + var completer = Completer(); _controller.add(_CompileExpressionRequest(completer, expression, definitions, typeDefinitions, libraryUri, klass, isStatic)); return completer.future; } - Future _compileExpression( + Future _compileExpression( _CompileExpressionRequest request) async { _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false); @@ -447,23 +444,24 @@ class ResidentCompiler { if (_server == null) { return null; } + var server = _server!; var inputKey = Uuid().generateV4(); - _server.stdin.writeln('compile-expression $inputKey'); - _server.stdin.writeln(request.expression); - request.definitions?.forEach(_server.stdin.writeln); - _server.stdin.writeln(inputKey); - request.typeDefinitions?.forEach(_server.stdin.writeln); - _server.stdin.writeln(inputKey); - _server.stdin.writeln(request.libraryUri ?? ''); - _server.stdin.writeln(request.klass ?? ''); - _server.stdin.writeln(request.isStatic ?? false); + server.stdin.writeln('compile-expression $inputKey'); + server.stdin.writeln(request.expression); + request.definitions.forEach(server.stdin.writeln); + server.stdin.writeln(inputKey); + request.typeDefinitions.forEach(server.stdin.writeln); + server.stdin.writeln(inputKey); + server.stdin.writeln(request.libraryUri ?? ''); + server.stdin.writeln(request.klass ?? ''); + server.stdin.writeln(request.isStatic ?? false); return _stdoutHandler.compilerOutput.future; } /// Compiles dart expression to JavaScript. - Future compileExpressionToJs( + Future compileExpressionToJs( String libraryUri, int line, int column, @@ -475,13 +473,13 @@ class ResidentCompiler { _controller.stream.listen(_handleCompilationRequest); } - var completer = Completer(); + var completer = Completer(); _controller.add(_CompileExpressionToJsRequest(completer, libraryUri, line, column, jsModules, jsFrameValues, moduleName, expression)); return completer.future; } - Future _compileExpressionToJs( + Future _compileExpressionToJs( _CompileExpressionToJsRequest request) async { _stdoutHandler.reset( suppressCompilerMessages: !verbose, expectSources: false); @@ -491,22 +489,23 @@ class ResidentCompiler { if (_server == null) { return null; } + var server = _server!; var inputKey = Uuid().generateV4(); - _server.stdin.writeln('compile-expression-to-js $inputKey'); - _server.stdin.writeln(request.libraryUri ?? ''); - _server.stdin.writeln(request.line); - _server.stdin.writeln(request.column); - request.jsModules?.forEach((k, v) { - _server.stdin.writeln('$k:$v'); + server.stdin.writeln('compile-expression-to-js $inputKey'); + server.stdin.writeln(request.libraryUri); + server.stdin.writeln(request.line); + server.stdin.writeln(request.column); + request.jsModules.forEach((k, v) { + server.stdin.writeln('$k:$v'); }); - _server.stdin.writeln(inputKey); - request.jsFrameValues?.forEach((k, v) { - _server.stdin.writeln('$k:$v'); + server.stdin.writeln(inputKey); + request.jsFrameValues.forEach((k, v) { + server.stdin.writeln('$k:$v'); }); - _server.stdin.writeln(inputKey); - _server.stdin.writeln(request.moduleName ?? ''); - _server.stdin.writeln(request.expression ?? ''); + server.stdin.writeln(inputKey); + server.stdin.writeln(request.moduleName); + server.stdin.writeln(request.expression); return _stdoutHandler.compilerOutput.future; } @@ -516,7 +515,7 @@ class ResidentCompiler { /// Either [accept] or [reject] should be called after every [recompile] call. void accept() { if (_compileRequestNeedsConfirmation) { - _server.stdin.writeln('accept'); + _server!.stdin.writeln('accept'); _logger.info('<- accept'); } _compileRequestNeedsConfirmation = false; @@ -525,22 +524,22 @@ class ResidentCompiler { /// Should be invoked when results of compilation are rejected by the client. /// /// Either [accept] or [reject] should be called after every [recompile] call. - Future reject() { + Future reject() { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } - var completer = Completer(); + var completer = Completer(); _controller.add(_RejectRequest(completer)); return completer.future; } - Future _reject() { + Future _reject() { if (!_compileRequestNeedsConfirmation) { - return Future.value(null); + return Future.value(null); } _stdoutHandler.reset(expectSources: false); - _server.stdin.writeln('reject'); + _server!.stdin.writeln('reject'); _logger.info('<- reject'); _compileRequestNeedsConfirmation = false; return _stdoutHandler.compilerOutput.future; @@ -550,14 +549,18 @@ class ResidentCompiler { /// accepted previously so that next call to [recompile] produces complete /// kernel file. void reset() { - _server?.stdin?.writeln('reset'); + _server?.stdin.writeln('reset'); _logger.info('<- reset'); } Future quit() async { - _server.stdin.writeln('quit'); + _server?.stdin.writeln('quit'); _logger.info('<- quit'); - return _server.exitCode; + + if (_server == null) { + return 0; + } + return _server!.exitCode; } /// stop the service normally @@ -575,9 +578,9 @@ class ResidentCompiler { return 0; } - _logger.info('killing pid ${_server.pid}'); - _server.kill(); - return _server.exitCode; + _logger.info('killing pid ${_server!.pid}'); + _server!.kill(); + return _server!.exitCode; } } @@ -598,7 +601,7 @@ class TestExpressionCompiler implements ExpressionCompiler { var compilerOutput = await _generator.compileExpressionToJs(libraryUri, line, column, jsModules, jsFrameValues, moduleName, expression); - if (compilerOutput != null && compilerOutput.outputFilename != null) { + if (compilerOutput != null) { var content = utf8.decode( fileSystem.file(compilerOutput.outputFilename).readAsBytesSync()); return ExpressionCompilationResult( @@ -613,14 +616,16 @@ class TestExpressionCompiler implements ExpressionCompiler { true; @override - Future initialize({String moduleFormat, bool soundNullSafety}) async {} + Future initialize({ + required String moduleFormat, + bool soundNullSafety = false, + }) async {} } /// Convert a file URI into a multi-root scheme URI if provided, otherwise /// return unmodified. -@visibleForTesting String toMultiRootPath( - Uri fileUri, String scheme, List fileSystemRoots) { + Uri fileUri, String? scheme, List fileSystemRoots) { if (scheme == null || fileSystemRoots.isEmpty || fileUri.scheme != 'file') { return fileUri.toString(); } diff --git a/frontend_server_common/lib/src/resident_runner.dart b/frontend_server_common/lib/src/resident_runner.dart index 81c90c3cf..2d6fdc297 100644 --- a/frontend_server_common/lib/src/resident_runner.dart +++ b/frontend_server_common/lib/src/resident_runner.dart @@ -2,14 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.9 - // Note: this is a copy from flutter tools, updated to work with dwds tests, // and some functionality remioved (does not support hot reload yet) import 'dart:async'; -import 'package:dwds/dwds.dart'; +import 'package:dwds/asset_reader.dart'; +import 'package:dwds/expression_compiler.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; @@ -52,13 +51,13 @@ class ResidentWebRunner { final String fileSystemScheme; final bool soundNullSafety; - ResidentCompiler generator; - ExpressionCompiler expressionCompiler; - WebDevFS devFS; - Uri uri; - Iterable modules; + late ResidentCompiler generator; + late ExpressionCompiler expressionCompiler; + late WebDevFS devFS; + late Uri uri; + late Iterable modules; - Future run(String hostname, int port, String root) async { + Future run(String? hostname, int port, String root) async { hostname ??= 'localhost'; devFS = WebDevFS( @@ -78,7 +77,7 @@ class ResidentWebRunner { return 1; } - modules = report.invalidatedModules; + modules = report.invalidatedModules!; generator.accept(); return 0; diff --git a/frontend_server_common/lib/src/utilities.dart b/frontend_server_common/lib/src/utilities.dart index 801cc600b..859ab8ad8 100644 --- a/frontend_server_common/lib/src/utilities.dart +++ b/frontend_server_common/lib/src/utilities.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:io'; import 'package:file/file.dart' as fs; From 13deedff405727f7d9cbd609fdc9809fb28e0f30 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Mon, 13 Jun 2022 14:23:12 -0700 Subject: [PATCH 06/12] Fixed bad merge --- dwds/lib/src/utilities/conversions.dart | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dwds/lib/src/utilities/conversions.dart b/dwds/lib/src/utilities/conversions.dart index b2f84bfd3..5117fef8e 100644 --- a/dwds/lib/src/utilities/conversions.dart +++ b/dwds/lib/src/utilities/conversions.dart @@ -56,15 +56,16 @@ RemoteObject remoteObjectFor(String dartId) { data['value'] = _stringFromDartId(dartId); } else if (isDoubleId(dartId)) { data['type'] = 'number'; - data['value'] = _doubleFromDartId(dartId)!; + data['value'] = _doubleFromDartId(dartId); } else if (isIntId(dartId)) { data['type'] = 'number'; - data['value'] = _intFromDartId(dartId)!; + data['value'] = _intFromDartId(dartId); } else if (isBoolId(dartId)) { data['type'] = 'boolean'; data['value'] = _boolFromDartId(dartId); } else if (dartId == _nullId) { data['type'] = 'undefined'; + data['value'] = null; } else { data['type'] = 'object'; } From a0e9fc629a292e01a9dffac5e3367a50abdecbce Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Mon, 13 Jun 2022 14:24:11 -0700 Subject: [PATCH 07/12] Fixed analyzer warning --- dwds/lib/src/utilities/sdk_configuration.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dwds/lib/src/utilities/sdk_configuration.dart b/dwds/lib/src/utilities/sdk_configuration.dart index 03f5f46b2..0439e01e6 100644 --- a/dwds/lib/src/utilities/sdk_configuration.dart +++ b/dwds/lib/src/utilities/sdk_configuration.dart @@ -120,8 +120,7 @@ class SdkConfiguration { class DefaultSdkConfigurationProvider extends SdkConfigurationProvider { DefaultSdkConfigurationProvider(); - // ignore: prefer_final_fields - late SdkConfiguration _configuration = _create(); + late final SdkConfiguration _configuration = _create(); /// Create and validate configuration matching the default SDK layout. @override From 78262b584ae42a1ed898982986f0f425ce29cbb1 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Fri, 17 Jun 2022 14:58:16 -0700 Subject: [PATCH 08/12] Address CR comments --- .../lib/src/asset_server.dart | 8 +++---- .../lib/src/frontend_server_client.dart | 24 +++++++++++-------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/frontend_server_common/lib/src/asset_server.dart b/frontend_server_common/lib/src/asset_server.dart index 6bb1f0532..d84a67314 100644 --- a/frontend_server_common/lib/src/asset_server.dart +++ b/frontend_server_common/lib/src/asset_server.dart @@ -31,7 +31,7 @@ class TestAssetServer implements AssetReader { final FileSystem _fileSystem; final HttpServer _httpServer; final Map _files = {}; - final Map _sourcemaps = {}; + final Map _sourceMaps = {}; final Map _metadata = {}; String? _mergedMetadata; final PackageConfig _packageConfig; @@ -48,8 +48,8 @@ class TestAssetServer implements AssetReader { bool hasFile(String path) => _files.containsKey(path); Uint8List getFile(String path) => _files[path]!; - bool hasSourceMap(String path) => _sourcemaps.containsKey(path); - Uint8List getSourceMap(String path) => _sourcemaps[path]!; + bool hasSourceMap(String path) => _sourceMaps.containsKey(path); + Uint8List getSourceMap(String path) => _sourceMaps[path]!; bool hasMetadata(String path) => _metadata.containsKey(path); Uint8List getMetadata(String path) => _metadata[path]!; @@ -196,7 +196,7 @@ class TestAssetServer implements AssetReader { sourcemapStart, sourcemapEnd - sourcemapStart, ); - _sourcemaps['$filePath.map'] = sourcemapView; + _sourceMaps['$filePath.map'] = sourcemapView; var metadataStart = metadataOffsets[0]; var metadataEnd = metadataOffsets[1]; diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index f5c81a930..48eaffb4f 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -313,9 +313,10 @@ class ResidentCompiler { if (_server == null) { return _compile(mainUri, request.outputPath); } + var server = _server!; var inputKey = Uuid().generateV4(); - _server!.stdin.writeln('recompile $mainUri$inputKey'); + server.stdin.writeln('recompile $mainUri$inputKey'); _logger.info('<- recompile $mainUri$inputKey'); for (var fileUri in request.invalidatedFiles) { String message; @@ -325,10 +326,10 @@ class ResidentCompiler { message = request.packageConfig.toPackageUri(fileUri)?.toString() ?? _toMultiRootPath(fileUri, fileSystemScheme, fileSystemRoots); } - _server!.stdin.writeln(message); + server.stdin.writeln(message); _logger.info(message); } - _server!.stdin.writeln(inputKey); + server.stdin.writeln(inputKey); _logger.info('<- $inputKey'); return _stdoutHandler.compilerOutput.future; @@ -388,7 +389,9 @@ class ResidentCompiler { final workingDirectory = projectDirectory.toFilePath(); _server = await Process.start(Platform.resolvedExecutable, args, workingDirectory: workingDirectory); - _server!.stdout + + var server = _server!; + server.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen(_stdoutHandler.handler, onDone: () { @@ -400,18 +403,18 @@ class ResidentCompiler { } }); - _server!.stderr + server.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen(_logger.info); - unawaited(_server!.exitCode.then((int code) { + unawaited(server.exitCode.then((int code) { if (code != 0) { throw Exception('the Dart compiler exited unexpectedly.'); } })); - _server!.stdin.writeln('compile $scriptUri'); + server.stdin.writeln('compile $scriptUri'); _logger.info('<- compile $scriptUri'); return _stdoutHandler.compilerOutput.future; @@ -579,9 +582,10 @@ class ResidentCompiler { return 0; } - _logger.info('killing pid ${_server!.pid}'); - _server!.kill(); - return _server!.exitCode; + var server = _server!; + _logger.info('killing pid ${server.pid}'); + server.kill(); + return server.exitCode; } } From 4bc8265cc41a0d739fe13ffbc72fea2655333497 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Tue, 21 Jun 2022 18:05:05 -0700 Subject: [PATCH 09/12] Addressed CR comments --- frontend_server_common/lib/src/frontend_server_client.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index 48eaffb4f..238284c86 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -553,6 +553,9 @@ class ResidentCompiler { /// accepted previously so that next call to [recompile] produces complete /// kernel file. void reset() { + // TODO(annagrin): make sure this works when we support hot restart in + // tests using frontend server - for example, throw an error if the + // server is not available. _server?.stdin.writeln('reset'); _logger.info('<- reset'); } From 03321002179740746fd55338c605f53736644601 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Tue, 21 Jun 2022 18:23:58 -0700 Subject: [PATCH 10/12] Format --- frontend_server_common/lib/src/frontend_server_client.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index 238284c86..975c1892d 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -554,7 +554,7 @@ class ResidentCompiler { /// kernel file. void reset() { // TODO(annagrin): make sure this works when we support hot restart in - // tests using frontend server - for example, throw an error if the + // tests using frontend server - for example, throw an error if the // server is not available. _server?.stdin.writeln('reset'); _logger.info('<- reset'); From d42ad43e8a0e2382317ddaf6a6334c5041abb2e3 Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Wed, 22 Jun 2022 13:45:56 -0700 Subject: [PATCH 11/12] Address CR comments --- frontend_server_common/lib/src/asset_server.dart | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/frontend_server_common/lib/src/asset_server.dart b/frontend_server_common/lib/src/asset_server.dart index d84a67314..62e4afce9 100644 --- a/frontend_server_common/lib/src/asset_server.dart +++ b/frontend_server_common/lib/src/asset_server.dart @@ -33,7 +33,7 @@ class TestAssetServer implements AssetReader { final Map _files = {}; final Map _sourceMaps = {}; final Map _metadata = {}; - String? _mergedMetadata; + late String _mergedMetadata; final PackageConfig _packageConfig; final InternetAddress internetAddress; @@ -329,5 +329,6 @@ String _parseBasePathFromIndexHtml(String index) { } final contents = file.readAsStringSync(); final matches = RegExp(r'').allMatches(contents); - return (matches.isEmpty ? null : matches.first.group(1)) ?? ''; + if (matches.isEmpty) return ''; + return matches.first.group(1) ?? ''; } From 96f8a50f23fab4e1875ef460fe79daa0d7e4db2a Mon Sep 17 00:00:00 2001 From: Anna Gringauze Date: Wed, 22 Jun 2022 17:24:51 -0700 Subject: [PATCH 12/12] Address CR comments, make fields of StdoutHandler private --- .../lib/src/frontend_server_client.dart | 52 ++++++++++--------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/frontend_server_common/lib/src/frontend_server_client.dart b/frontend_server_common/lib/src/frontend_server_client.dart index 975c1892d..8f5a4a201 100644 --- a/frontend_server_common/lib/src/frontend_server_client.dart +++ b/frontend_server_common/lib/src/frontend_server_client.dart @@ -46,13 +46,14 @@ class StdoutHandler { reset(); } - bool compilerMessageReceived = false; final CompilerMessageConsumer consumer; - String? boundaryKey; - StdoutState state = StdoutState.collectDiagnostic; late Completer compilerOutput; - final List sources = []; + final List _sources = []; + + bool _compilerMessageReceived = false; + String? _boundaryKey; + StdoutState _state = StdoutState.collectDiagnostic; late bool _suppressCompilerMessages; late bool _expectSources; bool _badState = false; @@ -69,14 +70,14 @@ class StdoutHandler { return; } var kResultPrefix = 'result '; - if (boundaryKey == null && message.startsWith(kResultPrefix)) { - boundaryKey = message.substring(kResultPrefix.length); + if (_boundaryKey == null && message.startsWith(kResultPrefix)) { + _boundaryKey = message.substring(kResultPrefix.length); return; } // Invalid state, see commented issue below for more information. // NB: both the completeError and _badState flags are required to avoid // filling the console with exceptions. - if (boundaryKey == null) { + if (_boundaryKey == null) { // Throwing a synchronous exception via throwToolExit will fail to cancel // the stream. Instead use completeError so that the error is returned // from the awaited future that the compiler consumers are expecting. @@ -87,11 +88,11 @@ class StdoutHandler { 'frontend server client (in dwds tests).' '\n\n' 'Additional debugging information:\n' - ' StdoutState: $state\n' - ' compilerMessageReceived: $compilerMessageReceived\n' + ' StdoutState: $_state\n' + ' compilerMessageReceived: $_compilerMessageReceived\n' ' message: $message\n' ' _expectSources: $_expectSources\n' - ' sources: $sources\n'); + ' sources: $_sources\n'); // There are several event turns before the tool actually exits from a // tool exception. Normally, the stream should be cancelled to prevent // more events from entering the bad state, but because the error @@ -101,40 +102,41 @@ class StdoutHandler { _badState = true; return; } - if (message.startsWith(boundaryKey!)) { + final boundaryKey = _boundaryKey!; + if (message.startsWith(boundaryKey)) { if (_expectSources) { - if (state == StdoutState.collectDiagnostic) { - state = StdoutState.collectDependencies; + if (_state == StdoutState.collectDiagnostic) { + _state = StdoutState.collectDependencies; return; } } - if (message.length <= boundaryKey!.length) { + if (message.length <= boundaryKey.length) { compilerOutput.complete(null); return; } var spaceDelimiter = message.lastIndexOf(' '); compilerOutput.complete(CompilerOutput( - message.substring(boundaryKey!.length + 1, spaceDelimiter), + message.substring(boundaryKey.length + 1, spaceDelimiter), int.parse(message.substring(spaceDelimiter + 1).trim()), - sources)); + _sources)); return; } - if (state == StdoutState.collectDiagnostic) { + if (_state == StdoutState.collectDiagnostic) { if (!_suppressCompilerMessages) { - if (compilerMessageReceived == false) { + if (_compilerMessageReceived == false) { consumer('\nCompiler message:'); - compilerMessageReceived = true; + _compilerMessageReceived = true; } consumer(message); } } else { - assert(state == StdoutState.collectDependencies); + assert(_state == StdoutState.collectDependencies); switch (message[0]) { case '+': - sources.add(Uri.parse(message.substring(1))); + _sources.add(Uri.parse(message.substring(1))); break; case '-': - sources.remove(Uri.parse(message.substring(1))); + _sources.remove(Uri.parse(message.substring(1))); break; default: _logger.warning('Unexpected prefix for $message uri - ignoring'); @@ -146,12 +148,12 @@ class StdoutHandler { // with its own boundary key and new completer. void reset( {bool suppressCompilerMessages = false, bool expectSources = true}) { - boundaryKey = null; - compilerMessageReceived = false; + _boundaryKey = null; + _compilerMessageReceived = false; compilerOutput = Completer(); _suppressCompilerMessages = suppressCompilerMessages; _expectSources = expectSources; - state = StdoutState.collectDiagnostic; + _state = StdoutState.collectDiagnostic; } }