Skip to content

Commit 3f104a2

Browse files
nshahanCommit Bot
authored and
Commit Bot
committed
[ddc] Migrate command to null safety
Revert small diffs introduced in earlier migrations to avoid an import of command.dart before it was migrated. Issue: #46617 Change-Id: Ia728fd727417fd4fdf8c454a0044e096e9de5756 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/248948 Reviewed-by: Anna Gringauze <[email protected]> Commit-Queue: Nicholas Shahan <[email protected]>
1 parent 6366fdd commit 3f104a2

File tree

3 files changed

+72
-71
lines changed

3 files changed

+72
-71
lines changed

pkg/dev_compiler/lib/src/kernel/command.dart

Lines changed: 68 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5-
// @dart = 2.9
6-
75
import 'dart:async';
86
import 'dart:convert' show json;
97
import 'dart:io';
@@ -46,8 +44,8 @@ const _binaryName = 'dartdevc -k';
4644
/// The result may also contain a [previousResult], which can be passed back in
4745
/// for batch/worker executions to attempt to existing state.
4846
Future<CompilerResult> compile(ParsedArguments args,
49-
{fe.InitializedCompilerState compilerState,
50-
Map<Uri, List<int>> inputDigests}) {
47+
{fe.InitializedCompilerState? compilerState,
48+
Map<Uri, List<int>>? inputDigests}) {
5149
if (compilerState != null && !args.isBatchOrWorker) {
5250
throw ArgumentError(
5351
'previousResult requires --batch or --bazel_worker mode/');
@@ -83,10 +81,10 @@ String _usageMessage(ArgParser ddcArgParser) =>
8381
'${ddcArgParser.usage}';
8482

8583
Future<CompilerResult> _compile(List<String> args,
86-
{fe.InitializedCompilerState compilerState,
84+
{fe.InitializedCompilerState? compilerState,
8785
bool isWorker = false,
8886
bool useIncrementalCompiler = false,
89-
Map<Uri, List<int>> inputDigests}) async {
87+
Map<Uri, List<int>>? inputDigests}) async {
9088
// TODO(jmesserly): refactor options to share code with dartdevc CLI.
9189
var argParser = ArgParser(allowTrailingOptions: true)
9290
..addFlag('help',
@@ -98,7 +96,9 @@ Future<CompilerResult> _compile(List<String> args,
9896
defaultsTo: false,
9997
hide: true)
10098
..addFlag('track-widget-creation',
101-
help: 'Enable inspecting of Flutter widgets.', hide: true)
99+
help: 'Enable inspecting of Flutter widgets.',
100+
defaultsTo: false,
101+
hide: true)
102102
// TODO(jmesserly): add verbose help to show hidden options
103103
..addOption('dart-sdk-summary',
104104
help: 'The path to the Dart SDK summary file.', hide: true)
@@ -198,9 +198,10 @@ Future<CompilerResult> _compile(List<String> args,
198198

199199
var summaryPaths = options.summaryModules.keys.toList();
200200
var summaryModules = Map.fromIterables(
201-
summaryPaths.map(sourcePathToUri), options.summaryModules.values);
202-
var sdkSummaryPath = argResults['dart-sdk-summary'] as String;
203-
var librarySpecPath = argResults['libraries-file'] as String;
201+
summaryPaths.map(sourcePathToUri).cast<Uri>(),
202+
options.summaryModules.values);
203+
var sdkSummaryPath = argResults['dart-sdk-summary'] as String?;
204+
var librarySpecPath = argResults['libraries-file'] as String?;
204205
if (sdkSummaryPath == null) {
205206
sdkSummaryPath =
206207
defaultSdkSummaryPath(soundNullSafety: options.soundNullSafety);
@@ -246,7 +247,8 @@ Future<CompilerResult> _compile(List<String> args,
246247
// TODO(jmesserly): conceptually CFE should not need a .packages file to
247248
// resolve package URIs that are in the input summaries, but it seems to.
248249
// This needs further investigation.
249-
var packageFile = argResults['packages'] as String ?? _findPackagesFilePath();
250+
var packageFile =
251+
argResults['packages'] as String? ?? _findPackagesFilePath();
250252

251253
var succeeded = true;
252254
void diagnosticMessageHandler(fe.DiagnosticMessage message) {
@@ -259,14 +261,13 @@ Future<CompilerResult> _compile(List<String> args,
259261
var explicitExperimentalFlags = fe.parseExperimentalFlags(options.experiments,
260262
onError: stderr.writeln, onWarning: print);
261263

262-
var trackWidgetCreation =
263-
argResults['track-widget-creation'] as bool ?? false;
264+
var trackWidgetCreation = argResults['track-widget-creation'] as bool;
264265

265266
var compileSdk = argResults['compile-sdk'] == true;
266267
var oldCompilerState = compilerState;
267-
List<Component> doneAdditionalDills;
268-
fe.IncrementalCompiler incrementalCompiler;
269-
fe.WorkerInputComponent cachedSdkInput;
268+
var doneAdditionalDills = <Component>[];
269+
fe.IncrementalCompiler? incrementalCompiler;
270+
fe.WorkerInputComponent? cachedSdkInput;
270271
var recordUsedInputs = argResults['used-inputs-file'] != null;
271272
var additionalDills = summaryModules.keys.toList();
272273

@@ -291,18 +292,17 @@ Future<CompilerResult> _compile(List<String> args,
291292
// If digests weren't given and if not in worker mode, create fake data and
292293
// ensure we don't have a previous state (as that wouldn't be safe with
293294
// fake input digests).
294-
if (!isWorker && (inputDigests == null || inputDigests.isEmpty)) {
295+
inputDigests ??= {};
296+
if (!isWorker && inputDigests.isEmpty) {
295297
oldCompilerState = null;
296-
inputDigests ??= {};
298+
297299
if (!compileSdk) {
298300
inputDigests[sourcePathToUri(sdkSummaryPath)] = const [0];
299301
}
300302
for (var uri in summaryModules.keys) {
301303
inputDigests[uri] = const [0];
302304
}
303305
}
304-
305-
doneAdditionalDills = List<Component>(summaryModules.length);
306306
compilerState = await fe.initializeIncrementalCompiler(
307307
oldCompilerState,
308308
{
@@ -329,7 +329,7 @@ Future<CompilerResult> _compile(List<String> args,
329329
options.soundNullSafety ? fe.NnbdMode.Strong : fe.NnbdMode.Weak);
330330
incrementalCompiler = compilerState.incrementalCompiler;
331331
cachedSdkInput =
332-
compilerState.workerInputCache[sourcePathToUri(sdkSummaryPath)];
332+
compilerState.workerInputCache![sourcePathToUri(sdkSummaryPath)];
333333
}
334334

335335
// TODO(jmesserly): is there a cleaner way to do this?
@@ -338,20 +338,20 @@ Future<CompilerResult> _compile(List<String> args,
338338
// `initializeCompiler`. Also we should be able to pass down Components for
339339
// SDK and summaries.
340340
//
341-
fe.DdcResult result;
341+
fe.DdcResult? result;
342342
if (!useIncrementalCompiler) {
343343
result = await fe.compile(compilerState, inputs, diagnosticMessageHandler);
344344
} else {
345345
compilerState.options.onDiagnostic = diagnosticMessageHandler;
346-
var incrementalCompilerResult = await incrementalCompiler.computeDelta(
346+
var incrementalCompilerResult = await incrementalCompiler!.computeDelta(
347347
entryPoints: inputs,
348348
fullComponent: true,
349349
trackNeededDillLibraries: recordUsedInputs);
350350
result = fe.DdcResult(
351351
incrementalCompilerResult.component,
352-
cachedSdkInput.component,
352+
cachedSdkInput!.component,
353353
doneAdditionalDills,
354-
incrementalCompilerResult.classHierarchy,
354+
incrementalCompilerResult.classHierarchy!,
355355
incrementalCompilerResult.neededDillLibraries);
356356
}
357357
compilerState.options.onDiagnostic = null; // See http://dartbug.com/36983.
@@ -393,7 +393,7 @@ Future<CompilerResult> _compile(List<String> args,
393393
kernel.BinaryPrinter(sink).writeComponentFile(component);
394394
outFiles.add(sink.flush().then((_) => sink.close()));
395395
}
396-
String fullDillUri;
396+
String? fullDillUri;
397397
if (argResults['experimental-output-compiled-kernel'] as bool) {
398398
if (outPaths.length > 1) {
399399
print(
@@ -433,7 +433,7 @@ Future<CompilerResult> _compile(List<String> args,
433433
final summaryToModule = Map<Component, String>.identity();
434434
for (var i = 0; i < result.additionalDills.length; i++) {
435435
var additionalDill = result.additionalDills[i];
436-
var moduleImport = summaryModules[additionalDills[i]];
436+
var moduleImport = summaryModules[additionalDills[i]]!;
437437
for (var l in additionalDill.libraries) {
438438
assert(!importToSummary.containsKey(l));
439439
importToSummary[l] = additionalDill;
@@ -487,12 +487,12 @@ Future<CompilerResult> _compile(List<String> args,
487487
if (recordUsedInputs) {
488488
var usedOutlines = <Uri>{};
489489
if (useIncrementalCompiler) {
490-
var neededDillLibraries = result.neededDillLibraries;
491-
compilerState.incrementalCompiler.updateNeededDillLibrariesWithHierarchy(
490+
var neededDillLibraries = result.neededDillLibraries!;
491+
compilerState.incrementalCompiler!.updateNeededDillLibrariesWithHierarchy(
492492
neededDillLibraries, result.classHierarchy);
493493
for (var lib in neededDillLibraries) {
494494
if (lib.importUri.isScheme('dart')) continue;
495-
var uri = compilerState.libraryToInputDill[lib.importUri];
495+
var uri = compilerState.libraryToInputDill![lib.importUri];
496496
if (uri == null) {
497497
throw StateError('Library ${lib.importUri} was recorded as used, '
498498
'but was not in the list of known libraries.');
@@ -650,20 +650,20 @@ class JSCode {
650650
///
651651
/// The source paths will initially be absolute paths. They can be adjusted
652652
/// using [placeSourceMap].
653-
final Map sourceMap;
653+
final Map? sourceMap;
654654

655655
/// Module and library information
656656
///
657657
/// The [metadata] is a contract between compiler and the debugger,
658658
/// helping the debugger map between libraries, modules, source paths.
659659
/// see: https://goto.google.com/dart-web-debugger-metadata
660-
final ModuleMetadata metadata;
660+
final ModuleMetadata? metadata;
661661

662662
/// Module debug symbols.
663663
///
664664
/// The [symbols] is a contract between compiler and the debugger,
665665
/// helping the debugger map between dart and JS objects.
666-
final ModuleSymbols symbols;
666+
final ModuleSymbols? symbols;
667667

668668
JSCode(this.code, this.sourceMap, {this.symbols, this.metadata});
669669
}
@@ -677,18 +677,18 @@ JSCode jsProgramToCode(js_ast.Program moduleTree, ModuleFormat format,
677677
bool inlineSourceMap = false,
678678
bool emitDebugMetadata = false,
679679
bool emitDebugSymbols = false,
680-
String jsUrl,
681-
String mapUrl,
682-
String fullDillUri,
683-
String sourceMapBase,
684-
String customScheme,
685-
String multiRootOutputPath,
686-
ProgramCompiler compiler,
687-
Component component}) {
680+
String? jsUrl,
681+
String? mapUrl,
682+
String? fullDillUri,
683+
String? sourceMapBase,
684+
String? customScheme,
685+
String? multiRootOutputPath,
686+
ProgramCompiler? compiler,
687+
Component? component}) {
688688
var opts = js_ast.JavaScriptPrintingOptions(
689689
allowKeywordsInProperties: true, allowSingleLineIfStatements: true);
690690
js_ast.SimpleJavaScriptPrintingContext printer;
691-
SourceMapBuilder sourceMap;
691+
SourceMapBuilder? sourceMap;
692692
if (buildSourceMap) {
693693
var sourceMapContext = SourceMapPrintingContext();
694694
sourceMap = sourceMapContext.sourceMap;
@@ -702,9 +702,9 @@ JSCode jsProgramToCode(js_ast.Program moduleTree, ModuleFormat format,
702702
tree.accept(js_ast.Printer(opts, printer,
703703
localNamer: js_ast.TemporaryNamer(tree, nameListener)));
704704

705-
Map builtMap;
705+
Map? builtMap;
706706
if (buildSourceMap && sourceMap != null) {
707-
builtMap = placeSourceMap(sourceMap.build(jsUrl), mapUrl, customScheme,
707+
builtMap = placeSourceMap(sourceMap.build(jsUrl!), mapUrl!, customScheme,
708708
multiRootOutputPath: multiRootOutputPath, sourceMapBase: sourceMapBase);
709709
var jsDir = p.dirname(p.fromUri(jsUrl));
710710
var relative = p.relative(p.fromUri(mapUrl), from: jsDir);
@@ -733,19 +733,19 @@ JSCode jsProgramToCode(js_ast.Program moduleTree, ModuleFormat format,
733733
// our runtime metrics gathering would obtain this information from the
734734
// compilation server, not the browser. We don't yet have the infra for that.
735735
var compileTimeStatistics = {
736-
'dartSize': component != null ? _computeDartSize(component) : null,
736+
'dartSize': _computeDartSize(component!),
737737
'sourceMapSize': encodedMap.length
738738
};
739739
text = text.replaceFirst(
740740
SharedCompiler.metricsLocationID, '$compileTimeStatistics');
741741

742742
var debugMetadata = emitDebugMetadata
743-
? _emitMetadata(moduleTree, component, mapUrl, jsUrl, fullDillUri)
743+
? _emitMetadata(moduleTree, component, mapUrl!, jsUrl!, fullDillUri)
744744
: null;
745745

746746
var debugSymbols = emitDebugSymbols
747747
? _emitSymbols(
748-
compiler, moduleTree.name, nameListener.identifierNames, component)
748+
compiler!, moduleTree.name!, nameListener!.identifierNames, component)
749749
: null;
750750

751751
return JSCode(text, builtMap, symbols: debugSymbols, metadata: debugMetadata);
@@ -759,17 +759,26 @@ JSCode jsProgramToCode(js_ast.Program moduleTree, ModuleFormat format,
759759
/// names used when outputting the JavaScript.
760760
ModuleSymbols _emitSymbols(ProgramCompiler compiler, String moduleName,
761761
Map<js_ast.Identifier, String> identifierNames, Component component) {
762+
/// Returns the name selected in the final Javascript for [id].
763+
String lookupName(js_ast.Identifier id) {
764+
var name = identifierNames[id];
765+
if (name == null) {
766+
throw Exception('No recorded naming decision found for Identifier with '
767+
'name: ${id.name}');
768+
}
769+
return name;
770+
}
771+
762772
var classJsNames = <Class, String>{
763-
for (var e in compiler.classIdentifiers.entries)
764-
e.key: identifierNames[e.value],
773+
for (var e in compiler.classIdentifiers.entries) e.key: lookupName(e.value),
765774
};
766775
var procedureJsNames = <Procedure, String>{
767776
for (var e in compiler.procedureIdentifiers.entries)
768-
e.key: identifierNames[e.value],
777+
e.key: lookupName(e.value),
769778
};
770779
var variableJsNames = <VariableDeclaration, String>{
771780
for (var e in compiler.variableIdentifiers.entries)
772-
e.key: identifierNames[e.value],
781+
e.key: lookupName(e.value),
773782
};
774783

775784
return ModuleSymbolsCollector(moduleName, classJsNames, compiler.memberNames,
@@ -778,10 +787,10 @@ ModuleSymbols _emitSymbols(ProgramCompiler compiler, String moduleName,
778787
}
779788

780789
ModuleMetadata _emitMetadata(js_ast.Program program, Component component,
781-
String sourceMapUri, String moduleUri, String fullDillUri) {
790+
String sourceMapUri, String moduleUri, String? fullDillUri) {
782791
var metadata = ModuleMetadata(
783-
program.name,
784-
loadFunctionName(program.name),
792+
program.name!,
793+
loadFunctionName(program.name!),
785794
sourceMapUri,
786795
moduleUri,
787796
fullDillUri,
@@ -803,7 +812,7 @@ Map<String, String> parseAndRemoveDeclaredVariables(List<String> args) {
803812
var declaredVariables = <String, String>{};
804813
for (var i = 0; i < args.length;) {
805814
var arg = args[i];
806-
String rest;
815+
String? rest;
807816
const defineFlag = '--define';
808817
if (arg.startsWith('-D') && arg.length > 2) {
809818
rest = arg.substring(2);
@@ -835,7 +844,7 @@ Map<String, String> parseAndRemoveDeclaredVariables(List<String> args) {
835844

836845
/// The default path of the kernel summary for the Dart SDK given the
837846
/// [soundNullSafety] mode.
838-
String defaultSdkSummaryPath({bool soundNullSafety}) {
847+
String defaultSdkSummaryPath({required bool soundNullSafety}) {
839848
var outlineDill = soundNullSafety ? 'ddc_outline_sound.dill' : 'ddc_sdk.dill';
840849
return p.join(getSdkPath(), 'lib', '_internal', outlineDill);
841850
}
@@ -850,7 +859,7 @@ String getSdkPath() => p.dirname(p.dirname(Platform.resolvedExecutable));
850859
///
851860
/// Checks for a `.dart_tool/package_config.json` file in the current working
852861
/// directory, or in any parent directory.
853-
String _findPackagesFilePath() {
862+
String? _findPackagesFilePath() {
854863
// TODO(jmesserly): this was copied from package:package_config/discovery.dart
855864
// Unfortunately the relevant function is not public. CFE APIs require a URI
856865
// to the .packages file, rather than letting us provide the package map data.
@@ -872,9 +881,9 @@ String _findPackagesFilePath() {
872881
}
873882

874883
/// Inputs must be absolute paths. Returns null if no prefixing path is found.
875-
String _longestPrefixingPath(Uri baseUri, List<Uri> prefixingPaths) {
884+
String? _longestPrefixingPath(Uri baseUri, List<Uri> prefixingPaths) {
876885
var basePath = baseUri.path;
877-
return prefixingPaths.fold(null, (String previousValue, Uri element) {
886+
return prefixingPaths.fold(null, (String? previousValue, Uri element) {
878887
if (basePath.startsWith(element.path) &&
879888
(previousValue == null || previousValue.length < element.path.length)) {
880889
return element.path;

pkg/dev_compiler/test/nullable_inference_test.dart

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import 'dart:async';
66
import 'dart:io';
77

8+
import 'package:dev_compiler/src/kernel/command.dart' show getSdkPath;
89
import 'package:dev_compiler/src/kernel/js_typerep.dart';
910
import 'package:dev_compiler/src/kernel/nullable_inference.dart';
1011
import 'package:dev_compiler/src/kernel/target.dart';
@@ -18,8 +19,6 @@ import 'package:kernel/type_environment.dart';
1819
import 'package:path/path.dart' as p;
1920
import 'package:test/test.dart';
2021

21-
import 'shared_test_options.dart' show getSdkPath;
22-
2322
const AstTextStrategy astTextStrategy = AstTextStrategy(
2423
includeLibraryNamesInTypes: true,
2524
includeLibraryNamesInMembers: true,
@@ -657,17 +656,13 @@ Future<CompileResult> kernelCompile(String code) async {
657656
var sdkUri = Uri.file('/memory/dart_sdk.dill');
658657
var sdkFile = _fileSystem.entityForUri(sdkUri);
659658
if (!await sdkFile.exists()) {
660-
// TODO(46617) Call getSdkPath() from command.dart instead.
661-
var sdkPath = getSdkPath();
662-
var outlineDill = p.join(sdkPath, 'lib', '_internal', 'ddc_sdk.dill');
659+
var outlineDill = p.join(getSdkPath(), 'lib', '_internal', 'ddc_sdk.dill');
663660
sdkFile.writeAsBytesSync(File(outlineDill).readAsBytesSync());
664661
}
665662
var librariesUri = Uri.file('/memory/libraries.json');
666663
var librariesFile = _fileSystem.entityForUri(librariesUri);
667664
if (!await librariesFile.exists()) {
668-
// TODO(46617) Call getSdkPath() from command.dart instead.
669-
var sdkPath = getSdkPath();
670-
var librariesJson = p.join(sdkPath, 'lib', 'libraries.json');
665+
var librariesJson = p.join(getSdkPath(), 'lib', 'libraries.json');
671666
librariesFile.writeAsBytesSync(File(librariesJson).readAsBytesSync());
672667
}
673668
var packagesUri = Uri.file('/memory/.packages');

0 commit comments

Comments
 (0)