-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcompile.dart
1053 lines (962 loc) · 31.8 KB
/
compile.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 'dart:async';
import 'dart:io';
import 'package:args/args.dart';
import 'package:dart2native/generate.dart';
import 'package:front_end/src/api_prototype/compiler_options.dart'
show Verbosity;
import 'package:path/path.dart' as path;
import 'package:vm/target_os.dart'; // For possible --target-os values.
import '../core.dart';
import '../experiments.dart';
import '../native_assets.dart';
import '../sdk.dart';
import '../utils.dart';
import '../vm_interop_handler.dart';
const int genericErrorExitCode = 255;
const int compileErrorExitCode = 254;
class Option {
final String flag;
final String help;
final String? abbr;
final String? defaultsTo;
final bool? flagDefaultsTo;
final String? valueHelp;
final List<String>? allowed;
final Map<String, String>? allowedHelp;
const Option({
required this.flag,
required this.help,
this.abbr,
this.defaultsTo,
this.flagDefaultsTo,
this.valueHelp,
this.allowed,
this.allowedHelp,
});
}
bool checkFile(String sourcePath) {
if (!FileSystemEntity.isFileSync(sourcePath)) {
stderr.writeln('"$sourcePath" file not found.');
stderr.flush();
return false;
}
return true;
}
/// Checks to see if [destPath] is a file path that can be written to.
bool checkFileWriteable(String destPath) {
final file = File(destPath);
final exists = file.existsSync();
try {
file.writeAsStringSync(
'',
mode: FileMode.append,
flush: true,
);
// Don't leave empty files around.
if (!exists) {
file.deleteSync();
}
return true;
} on FileSystemException {
return false;
}
}
class CompileJSCommand extends CompileSubcommandCommand {
static const String cmdName = 'js';
/// Accept all flags so we can delegate arg parsing to dart2js internally.
@override
final ArgParser argParser = ArgParser.allowAnything();
CompileJSCommand({bool verbose = false})
: super(cmdName, 'Compile Dart to JavaScript.', verbose);
@override
String get invocation => '${super.invocation} <dart entry point>';
@override
FutureOr<int> run() async {
if (!Sdk.checkArtifactExists(sdk.librariesJson)) {
return genericErrorExitCode;
}
final args = argResults!;
var snapshot = sdk.dart2jsAotSnapshot;
var script = sdk.dartAotRuntime;
var useExecProcess = true;
if (!Sdk.checkArtifactExists(snapshot, logError: false)) {
// AOT snapshots cannot be generated on IA32, so we need this fallback
// branch until support for IA32 is dropped (https://dartbug.com/49969).
script = sdk.dart2jsSnapshot;
if (!Sdk.checkArtifactExists(script)) {
return genericErrorExitCode;
}
useExecProcess = false;
}
final dart2jsCommand = [
if (useExecProcess) snapshot,
'--libraries-spec=${sdk.librariesJson}',
'--cfe-invocation-modes=compile',
'--invoker=dart_cli',
// Add the remaining arguments.
if (args.rest.isNotEmpty) ...args.rest.sublist(0),
];
try {
VmInteropHandler.run(
script,
dart2jsCommand,
packageConfigOverride: null,
useExecProcess: useExecProcess,
);
return 0;
} catch (e, st) {
log.stderr('Error: JS compilation failed');
log.stderr(e.toString());
if (verbose) {
log.stderr(st.toString());
}
return compileErrorExitCode;
}
}
}
class CompileDDCCommand extends CompileSubcommandCommand {
static const String cmdName = 'js-dev';
/// Accept all flags so we can delegate arg parsing to ddc internally.
@override
final ArgParser argParser = ArgParser.allowAnything();
// This command is an internal developer command used by tools and is
// hidden in the help message.
CompileDDCCommand({bool verbose = false})
: super(
cmdName,
'Compile Dart to JavaScript using ddc.',
verbose,
hidden: true,
);
@override
String get invocation => '${super.invocation} <dart entry point>';
@override
FutureOr<int> run() async {
if (!Sdk.checkArtifactExists(sdk.librariesJson)) {
return genericErrorExitCode;
}
final args = argResults!;
var snapshot = sdk.ddcAotSnapshot;
var script = sdk.dartAotRuntime;
var useExecProcess = true;
if (!Sdk.checkArtifactExists(snapshot, logError: false)) {
// AOT snapshots cannot be generated on IA32, so we need this fallback
// branch until support for IA32 is dropped (https://dartbug.com/49969).
script = sdk.ddcSnapshot;
if (!Sdk.checkArtifactExists(script)) {
return genericErrorExitCode;
}
useExecProcess = false;
}
final ddcCommand = <String>[
if (useExecProcess) snapshot,
// Add the remaining arguments.
if (args.rest.isNotEmpty) ...args.rest.sublist(0),
];
try {
VmInteropHandler.run(
script,
ddcCommand,
packageConfigOverride: null,
useExecProcess: useExecProcess,
);
return 0;
} catch (e, st) {
log.stderr('Error: JS compilation failed');
log.stderr(e.toString());
if (verbose) {
log.stderr(st.toString());
}
return compileErrorExitCode;
}
}
}
class CompileKernelSnapshotCommand extends CompileSubcommandCommand {
static const commandName = 'kernel';
static const help = 'Compile Dart to a kernel snapshot.\n'
'To run the snapshot use: dart run <kernel file>';
CompileKernelSnapshotCommand({
bool verbose = false,
}) : super(commandName, help, verbose) {
argParser
..addOption(
outputFileOption.flag,
help: outputFileOption.help,
abbr: outputFileOption.abbr,
)
..addOption(
verbosityOption.flag,
help: verbosityOption.help,
abbr: verbosityOption.abbr,
defaultsTo: verbosityOption.defaultsTo,
allowed: verbosityOption.allowed,
allowedHelp: verbosityOption.allowedHelp,
)
..addOption(
packagesOption.flag,
abbr: packagesOption.abbr,
valueHelp: packagesOption.valueHelp,
help: packagesOption.help,
)
..addFlag(
'link-platform',
help: 'Includes the platform kernel in the resulting kernel file. '
"Required for use with 'dart compile exe' or 'dart compile aot-snapshot'.",
defaultsTo: true,
)
..addFlag(
'embed-sources',
help: 'Embed source files in the generated kernel component.',
defaultsTo: true,
)
..addMultiOption(
defineOption.flag,
help: defineOption.help,
abbr: defineOption.abbr,
valueHelp: defineOption.valueHelp,
)
..addFlag(
soundNullSafetyOption.flag,
help: soundNullSafetyOption.help,
defaultsTo: soundNullSafetyOption.flagDefaultsTo,
hide: true,
)
..addOption(
'depfile',
valueHelp: 'path',
help: 'Path to output Ninja depfile',
)
..addMultiOption(
'extra-gen-kernel-options',
help: 'Pass additional options to gen_kernel.',
hide: true,
valueHelp: 'opt1,opt2,...',
)
..addExperimentalFlags(verbose: verbose);
}
@override
FutureOr<int> run() async {
final args = argResults!;
if (args.rest.isEmpty) {
// This throws.
usageException('Missing Dart entry point.');
} else if (args.rest.length > 1) {
usageException('Unexpected arguments after Dart entry point.');
}
final String sourcePath = args.rest[0];
if (!checkFile(sourcePath)) {
return genericErrorExitCode;
}
// Determine output file name.
String? outputFile = args.option(outputFileOption.flag);
if (outputFile == null) {
final inputWithoutDart = sourcePath.endsWith('.dart')
? sourcePath.substring(0, sourcePath.length - 5)
: sourcePath;
outputFile = '$inputWithoutDart.dill';
}
log.stdout('Compiling $sourcePath to kernel file $outputFile.');
if (!checkFileWriteable(outputFile)) {
log.stderr('Unable to open file $outputFile for writing snapshot.');
return genericErrorExitCode;
}
final bool soundNullSafety = args.flag('sound-null-safety');
if (!soundNullSafety) {
log.stdout(
'Error: the flag --no-sound-null-safety is not supported in Dart 3.');
return compileErrorExitCode;
}
try {
await generateKernel(
sourceFile: sourcePath,
outputFile: outputFile,
defines: args.multiOption('define'),
packages: args.option('packages'),
enableExperiment: args.enabledExperiments.join(','),
linkPlatform: args.flag('link-platform'),
depFile: args.option('depfile'),
extraOptions: args.multiOption('extra-gen-kernel-options'),
embedSources: args.flag('embed-sources'),
verbose: verbose,
verbosity: args.option('verbosity')!,
);
return 0;
} catch (e, st) {
log.stderr(e.toString());
if (verbose) {
log.stderr(st.toString());
}
return compileErrorExitCode;
}
}
}
class CompileJitSnapshotCommand extends CompileSubcommandCommand {
static const help = 'Compile Dart to a JIT snapshot.\n'
'The executable will be run once to snapshot a warm JIT.\n'
'To run the snapshot use: dart run <JIT file>';
CompileJitSnapshotCommand({
bool verbose = false,
}) : super('jit-snapshot', help, verbose) {
argParser
..addOption(
outputFileOption.flag,
help: outputFileOption.help,
abbr: outputFileOption.abbr,
)
..addOption(
verbosityOption.flag,
help: verbosityOption.help,
abbr: verbosityOption.abbr,
defaultsTo: verbosityOption.defaultsTo,
allowed: verbosityOption.allowed,
allowedHelp: verbosityOption.allowedHelp,
)
..addOption(
packagesOption.flag,
abbr: packagesOption.abbr,
valueHelp: packagesOption.valueHelp,
help: packagesOption.help,
)
..addMultiOption(
defineOption.flag,
help: defineOption.help,
abbr: defineOption.abbr,
valueHelp: defineOption.valueHelp,
)
..addFlag(soundNullSafetyOption.flag,
help: soundNullSafetyOption.help,
defaultsTo: soundNullSafetyOption.flagDefaultsTo,
hide: true)
..addExperimentalFlags(verbose: verbose);
}
@override
String get invocation =>
'${super.invocation} <dart entry point> [<training arguments>]';
@override
ArgParser createArgParser() {
return ArgParser(
// Don't parse the training arguments for JIT snapshots.
allowTrailingOptions: false,
usageLineLength: dartdevUsageLineLength,
);
}
@override
FutureOr<int> run() async {
final args = argResults!;
if (args.rest.isEmpty) {
// This throws.
usageException('Missing Dart entry point.');
}
final String sourcePath = args.rest[0];
if (!checkFile(sourcePath)) {
return genericErrorExitCode;
}
// Determine output file name.
String? outputFile = args.option(outputFileOption.flag);
if (outputFile == null) {
final inputWithoutDart = sourcePath.endsWith('.dart')
? sourcePath.substring(0, sourcePath.length - 5)
: sourcePath;
outputFile = '$inputWithoutDart.jit';
}
if (!checkFileWriteable(outputFile)) {
log.stderr('Unable to open file $outputFile for writing snapshot.');
return genericErrorExitCode;
}
final enabledExperiments = args.enabledExperiments;
final defines = args.multiOption(defineOption.flag);
// Build arguments.
final buildArgs = <String>[];
buildArgs.add('--snapshot-kind=app-jit');
buildArgs.add('--snapshot=${path.canonicalize(outputFile)}');
final bool soundNullSafety = args.flag('sound-null-safety');
if (!soundNullSafety) {
log.stdout(
'Error: the flag --no-sound-null-safety is not supported in Dart 3.');
return compileErrorExitCode;
}
final String? packages = args.option(packagesOption.flag);
if (packages != null) {
buildArgs.add('--packages=$packages');
}
final String verbosity = args.option(verbosityOption.flag)!;
buildArgs.add('--verbosity=$verbosity');
if (enabledExperiments.isNotEmpty) {
buildArgs.add("--enable-experiment=${enabledExperiments.join(',')}");
}
if (verbose) {
buildArgs.add('-v');
}
for (final define in defines) {
buildArgs.add('-D$define');
}
buildArgs.add(path.canonicalize(sourcePath));
// Add the training arguments.
if (args.rest.length > 1) {
buildArgs.addAll(args.rest.sublist(1));
}
log.stdout('Compiling $sourcePath to jit-snapshot file $outputFile.');
// TODO(bkonyi): perform compilation in same process.
return await runProcess([sdk.dart, ...buildArgs]);
}
}
class CompileNativeCommand extends CompileSubcommandCommand {
static const String exeCmdName = 'exe';
static const String aotSnapshotCmdName = 'aot-snapshot';
final String commandName;
final Kind format;
final String help;
final bool nativeAssetsExperimentEnabled;
CompileNativeCommand({
required this.commandName,
required this.format,
required this.help,
bool verbose = false,
this.nativeAssetsExperimentEnabled = false,
}) : super(commandName, 'Compile Dart $help', verbose) {
argParser
..addOption(
outputFileOption.flag,
help: outputFileOption.help,
abbr: outputFileOption.abbr,
)
..addOption(
verbosityOption.flag,
help: verbosityOption.help,
abbr: verbosityOption.abbr,
defaultsTo: verbosityOption.defaultsTo,
allowed: verbosityOption.allowed,
allowedHelp: verbosityOption.allowedHelp,
)
..addMultiOption(
defineOption.flag,
help: defineOption.help,
abbr: defineOption.abbr,
valueHelp: defineOption.valueHelp,
)
..addFlag(
'enable-asserts',
negatable: false,
help: 'Enable assert statements.',
)
..addOption(
packagesOption.flag,
abbr: packagesOption.abbr,
valueHelp: packagesOption.valueHelp,
help: packagesOption.help,
)
..addFlag(soundNullSafetyOption.flag,
help: soundNullSafetyOption.help,
defaultsTo: soundNullSafetyOption.flagDefaultsTo,
hide: true)
..addOption(
'save-debugging-info',
abbr: 'S',
valueHelp: 'path',
help: '''
Remove debugging information from the output and save it separately to the specified file.
<path> can be relative or absolute.''',
)
..addOption(
'depfile',
valueHelp: 'path',
help: 'Path to output Ninja depfile',
)
..addMultiOption(
'extra-gen-snapshot-options',
help: 'Pass additional options to gen_snapshot.',
hide: true,
valueHelp: 'opt1,opt2,...',
)
..addMultiOption(
'extra-gen-kernel-options',
help: 'Pass additional options to gen_kernel.',
hide: true,
valueHelp: 'opt1,opt2,...',
)
..addOption('target-os',
help: 'Compile to a specific target operating system.',
allowed: TargetOS.names)
..addExperimentalFlags(verbose: verbose);
}
@override
String get invocation => '${super.invocation} <dart entry point>';
@override
FutureOr<int> run() async {
// AOT compilation isn't supported on ia32. Currently, generating an
// executable only supports AOT runtimes, so these commands are disabled.
if (Platform.version.contains('ia32')) {
stderr.write(
"'dart compile $commandName' is not supported on x86 architectures.\n");
return 64;
}
if (!Sdk.checkArtifactExists(genKernel) ||
!Sdk.checkArtifactExists(genSnapshot)) {
return 255;
}
final args = argResults!;
// We expect a single rest argument; the dart entry point.
if (args.rest.length != 1) {
// This throws.
usageException('Missing Dart entry point.');
}
final String sourcePath = args.rest[0];
if (!checkFile(sourcePath)) {
return genericErrorExitCode;
}
if (!args.flag('sound-null-safety')) {
log.stdout(
'Error: the flag --no-sound-null-safety is not supported in Dart 3.');
return compileErrorExitCode;
}
final packageConfig = await DartNativeAssetsBuilder.ensurePackageConfig(
Directory.current.uri,
);
if (packageConfig != null) {
final runPackageName = await DartNativeAssetsBuilder.findRootPackageName(
Directory.current.uri,
);
if (runPackageName != null) {
final builder = DartNativeAssetsBuilder(
packageConfigUri: packageConfig,
runPackageName: runPackageName,
verbose: verbose,
);
if (!nativeAssetsExperimentEnabled) {
if (await builder.warnOnNativeAssets()) {
return 255;
}
} else {
final assets = await builder.compileNativeAssetsJit();
if (assets == null) {
stderr.writeln('Native assets build failed.');
return 255;
}
if (assets.isNotEmpty) {
stderr.writeln(
"'dart compile' does currently not support native assets.");
return 255;
}
}
}
}
String? targetOS = args.option('target-os');
if (format != Kind.exe) {
assert(format == Kind.aot);
// If we're generating an AOT snapshot and not an executable, then
// targetOS is allowed to be null for a platform-independent snapshot
// or a different platform than the host.
} else if (targetOS == null) {
targetOS = Platform.operatingSystem;
} else if (targetOS != Platform.operatingSystem) {
stderr.writeln(
"'dart compile $commandName' does not support cross-OS compilation.");
stderr.writeln('Host OS: ${Platform.operatingSystem}');
stderr.writeln('Target OS: $targetOS');
return 128;
}
final tempDir = Directory.systemTemp.createTempSync();
try {
final kernelGenerator = KernelGenerator(
kind: format,
sourceFile: sourcePath,
outputFile: args.option('output'),
defines: args.multiOption(defineOption.flag),
packages: args.option('packages'),
enableExperiment: args.enabledExperiments.join(','),
enableAsserts: args.flag('enable-asserts'),
debugFile: args.option('save-debugging-info'),
verbose: verbose,
verbosity: args.option('verbosity')!,
targetOS: targetOS,
tempDir: tempDir,
depFile: args.option('depfile'),
);
final snapshotGenerator = await kernelGenerator.generate(
extraOptions: args.multiOption('extra-gen-kernel-options'),
);
await snapshotGenerator.generate(
extraOptions: args.multiOption('extra-gen-snapshot-options'),
);
return 0;
} catch (e, st) {
log.stderr('Error: AOT compilation failed');
log.stderr(e.toString());
if (verbose) {
log.stderr(st.toString());
}
return compileErrorExitCode;
} finally {
await tempDir.delete(recursive: true);
}
}
}
class CompileWasmCommand extends CompileSubcommandCommand {
static const String commandName = 'wasm';
static const String help = 'Compile Dart to a WebAssembly/WasmGC module.';
// The unique place where we store various flags for dart2wasm & binaryen.
//
// Other uses (e.g. pkg/dart2wasm/tool/compile_benchmark) will grep in this
// file for the flags. So please keep the formatting.
final List<String> binaryenFlags = _flagList('''
--all-features
--closed-world
--traps-never-happen
--type-unfinalizing
-Os
--type-ssa
--gufa
-Os
--type-merging
-Os
--type-finalizing
--minimize-rec-groups
'''); // end of binaryenFlags
final List<String> optimizationLevel0Flags = _flagList('''
--no-inlining
--no-minify
'''); // end of optimizationLevel0Flags
final List<String> optimizationLevel1Flags = _flagList('''
--inlining
--no-minify
'''); // end of optimizationLevel1Flags
final List<String> optimizationLevel2Flags = _flagList('''
--inlining
--minify
'''); // end of optimizationLevel2Flags
final List<String> optimizationLevel3Flags = _flagList('''
--inlining
--minify
--omit-implicit-checks
'''); // end of optimizationLevel3Flags
final List<String> optimizationLevel4Flags = _flagList('''
--inlining
--minify
--omit-implicit-checks
--omit-bounds-checks
'''); // end of optimizationLevel4Flags
static List<String> _flagList(String lines) => lines
.split('\n')
.map((line) => line.trim())
.where((line) => line.isNotEmpty)
.toList();
CompileWasmCommand({bool verbose = false})
: super(commandName, help, verbose) {
argParser
..addOption(
outputFileOption.flag,
help: outputFileOption.help,
abbr: outputFileOption.abbr,
)
..addFlag(
'minify',
negatable: true,
help: 'Minify names that are needed at runtime (such as class names). '
'Affects e.g. `<obj>.runtimeType.toString()`). If passed, this '
'takes precedence over the optimization-level option.',
hide: !verbose,
)
..addFlag(
'strip-wasm',
defaultsTo: true,
negatable: true,
help:
'Whether to strip the resulting wasm file of static symbol names.',
hide: !verbose,
)
..addFlag(
'print-wasm',
help: 'Print human-readable wasm debug output',
hide: !verbose,
negatable: false,
)
..addFlag(
'print-kernel',
help: 'Print human-readable Dart kernel debug output',
hide: !verbose,
negatable: false,
)
..addFlag(
'verbose',
abbr: 'v',
help: 'Print debug output during compilation',
negatable: false,
)
..addFlag(
'enable-asserts',
help: 'Enable assert statements.',
negatable: false,
)
..addOption(
'shared-memory',
help: 'Import a shared memory buffer.'
' The max number of pages must be passed.',
valueHelp: 'page count',
hide: !verbose,
)
..addMultiOption(
'extra-compiler-option',
abbr: 'E',
help: 'An extra option to pass to the dart2wasm compiler.',
hide: !verbose,
)
..addOption(
'optimization-level',
abbr: 'O',
help: 'Controls optimizations that can help reduce code-size and '
'improve performance of the generated code.',
allowed: ['0', '1', '2', '3', '4'],
defaultsTo: '1',
valueHelp: 'level',
allowedHelp: {
'0': optimizationLevel0Flags.join(' '),
'1': optimizationLevel1Flags.join(' '),
'2': optimizationLevel2Flags.join(' '),
'3': optimizationLevel3Flags.join(' '),
'4': optimizationLevel4Flags.join(' '),
},
hide: !verbose,
)
..addFlag(
'source-maps',
help: 'Generate a source map file.',
defaultsTo: true,
)
..addOption(
packagesOption.flag,
abbr: packagesOption.abbr,
valueHelp: packagesOption.valueHelp,
help: packagesOption.help,
hide: !verbose,
)
..addMultiOption(
defineOption.flag,
help: defineOption.help,
abbr: defineOption.abbr,
valueHelp: defineOption.valueHelp,
)
..addExperimentalFlags(verbose: verbose);
}
@override
String get invocation => '${super.invocation} <dart entry point>';
@override
FutureOr<int> run() async {
final args = argResults!;
final verbose = this.verbose || args.flag('verbose');
if (!Sdk.checkArtifactExists(sdk.wasmPlatformDill) ||
!Sdk.checkArtifactExists(sdk.dartAotRuntime) ||
!Sdk.checkArtifactExists(sdk.dart2wasmSnapshot) ||
!Sdk.checkArtifactExists(sdk.wasmOpt)) {
return 255;
}
// We expect a single rest argument; the dart entry point.
if (args.rest.length != 1) {
// This throws.
usageException('Missing Dart entry point.');
}
final String sourcePath = args.rest[0];
final extraCompilerOptions = args.multiOption('extra-compiler-option');
final isMultiRoot =
extraCompilerOptions.any((e) => e.contains('multi-root'));
// If we know the source file doesn't exist, we want to abort early with an
// obvious error message. We can't resolve the actual path here if the input
// is an URI, so we skip that check in that case.
final sourceIsPath =
!isMultiRoot || Uri.tryParse(sourcePath)?.hasScheme == false;
if (sourceIsPath && !checkFile(sourcePath)) {
return genericErrorExitCode;
}
// Determine output file name.
String? outputFile = args.option(outputFileOption.flag);
if (outputFile == null) {
final inputWithoutDart = sourcePath.endsWith('.dart')
? sourcePath.substring(0, sourcePath.length - 5)
: sourcePath;
outputFile = '$inputWithoutDart.wasm';
}
if (!outputFile.endsWith('.wasm')) {
log.stderr(
'Error: The output file "$outputFile" does not end with ".wasm"');
return 255;
}
final outputFileBasename =
outputFile.substring(0, outputFile.length - '.wasm'.length);
final packages = args.option(packagesOption.flag);
final defines = args.multiOption(defineOption.flag);
int? maxPages;
if (args.option('shared-memory') != null) {
maxPages = int.tryParse(args.option('shared-memory')!);
if (maxPages == null) {
usageException(
'Error: The --shared-memory flag must specify a number!');
}
}
final optimizationLevel = int.parse(args.option('optimization-level')!);
final runWasmOpt = optimizationLevel >= 1;
void handleOverride(List<String> flags, String name, bool? value) {
// If no override provided, default to what -O implies.
if (value == null) return;
flags.removeWhere((option) => option == '--no-$name');
flags.removeWhere((option) => option == '--$name');
// Explicitly use the flag value, irrespective of -O settings.
value ? flags.add('--$name') : flags.add('--no-$name');
}
final optimizationFlags = (switch (optimizationLevel) {
0 => optimizationLevel0Flags,
1 => optimizationLevel1Flags,
2 => optimizationLevel2Flags,
3 => optimizationLevel3Flags,
4 => optimizationLevel4Flags,
_ => throw 'unreachable',
})
.toList();
handleOverride(optimizationFlags, 'minify',
args.wasParsed('minify') ? args.flag('minify') : null);
final generateSourceMap = args.flag('source-maps');
final enabledExperiments = args.enabledExperiments;
final dart2wasmCommand = [
sdk.dartAotRuntime,
sdk.dart2wasmSnapshot,
'--platform=${sdk.wasmPlatformDill}',
if (verbose) '--verbose',
if (packages != null) '--packages=$packages',
if (args.flag('print-wasm')) '--print-wasm',
if (args.flag('print-kernel')) '--print-kernel',
if (args.flag('enable-asserts')) '--enable-asserts',
if (!generateSourceMap) '--no-source-maps',
for (final define in defines) '-D$define',
if (maxPages != null) ...[
'--import-shared-memory',
'--shared-memory-max-pages=$maxPages',
],
...enabledExperiments.map((e) => '--enable-experiment=$e'),
// First we pass flags based on the optimization level.
...optimizationFlags,
// Then we pass any extra compiler flags through.
...extraCompilerOptions,
sourcePath,
outputFile,
];
try {
final exitCode = await runProcess(dart2wasmCommand);
if (exitCode != 0) return exitCode;
} catch (e, st) {
log.stderr('Error: Wasm compilation failed');
log.stderr(e.toString());
if (verbose) {
log.stderr(st.toString());
}
return compileErrorExitCode;
}
final bool strip = args.flag('strip-wasm');
if (runWasmOpt) {
final unoptFile = '$outputFileBasename.unopt.wasm';
File(outputFile).renameSync(unoptFile);
final unoptSourceMapFile = '$outputFileBasename.unopt.wasm.map';
if (generateSourceMap) {
File('$outputFile.map').renameSync(unoptSourceMapFile);
}
final flags = [
...binaryenFlags,
if (!strip) '-g',
if (generateSourceMap) ...[
'-ism',
unoptSourceMapFile,
'-osm',
'$outputFile.map'
]
];
if (verbose) {
log.stdout('Optimizing output with: ${sdk.wasmOpt} $flags');
}
final processResult = Process.runSync(
sdk.wasmOpt,
[...flags, '-o', outputFile, unoptFile],
);
if (processResult.exitCode != 0) {
log.stderr('Error: Wasm compilation failed while optimizing output');
log.stderr(processResult.stderr);
return compileErrorExitCode;
}
}
final mjsFile = '$outputFileBasename.mjs';
log.stdout(
"Generated wasm module '$outputFile', and JS init file '$mjsFile'.");
return 0;
}
}
abstract class CompileSubcommandCommand extends DartdevCommand {
final outputFileOption = Option(
flag: 'output',
abbr: 'o',
help: '''
Write the output to <file name>.
This can be an absolute or relative path.
''',
);
final verbosityOption = Option(
flag: 'verbosity',
help: '''
Sets the verbosity level of the compilation.
''',
defaultsTo: Verbosity.defaultValue,
allowed: Verbosity.allowedValues,
allowedHelp: Verbosity.allowedValuesHelp,
);
final soundNullSafetyOption = Option(
flag: 'sound-null-safety',
help: 'DEPRECATED: Respect the nullability of types at runtime.',
flagDefaultsTo: true,
);