-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathdart2js.dart
1452 lines (1296 loc) · 48.1 KB
/
dart2js.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) 2013, 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.
library;
import 'dart:async' show Future, StreamSubscription;
import 'dart:convert' show utf8, LineSplitter;
import 'dart:io' show exit, File, FileMode, Platform, stdin, stderr;
import 'dart:isolate' show Isolate;
// ignore: implementation_imports
import 'package:front_end/src/api_unstable/dart2js.dart' as fe;
import 'package:shell_arg_splitter/shell_arg_splitter.dart';
import '../compiler_api.dart' as api;
import 'commandline_options.dart';
import 'common/ram_usage.dart';
import 'compiler.dart' as default_compiler show Compiler;
import 'io/mapped_file.dart';
import 'options.dart'
show CompilerOptions, CompilerStage, DumpInfoFormat, FeatureOptions;
import 'source_file_provider.dart';
import 'util/util.dart' show stackTraceFilePrefix;
const String _defaultSpecificationUri = '../../../../sdk/lib/libraries.json';
const String outputLanguageDart = 'Dart';
/// A string to identify the revision or build.
///
/// This ID is displayed if the compiler crashes and in verbose mode, and is
/// an aid in reproducing bug reports.
///
/// The actual string is rewritten by a wrapper script when included in the sdk.
String? buildID;
/// The data passed to the [HandleOption] callback is either a single
/// string argument, or the arguments iterator for multiple arguments
/// handlers.
typedef HandleOption = void Function(String data);
typedef HandleMultiOption = void Function(Iterator<String> data);
abstract class OptionHandler<T extends Object> {
String get pattern;
void handle(T argument);
}
class _OneOption implements OptionHandler<String> {
@override
final String pattern;
final HandleOption _handle;
@override
void handle(String argument) {
_handle(argument);
}
_OneOption(this.pattern, this._handle);
}
class _ManyOptions implements OptionHandler<Iterator<String>> {
@override
final String pattern;
final HandleMultiOption _handle;
@override
void handle(Iterator<String> argument) {
_handle(argument);
}
_ManyOptions(this.pattern, this._handle);
}
/// Extract the parameter of an option.
///
/// For example, in ['--out=fisk.js'] and ['-ohest.js'], the parameters
/// are ['fisk.js'] and ['hest.js'], respectively.
String? extractOptionalParameter(String argument) {
// m[0] is the entire match (which will be equal to argument). m[1]
// is something like "-o" or "--out=", and m[2] is the parameter.
final m = RegExp('^(-[a-zA-Z]|--.+=)(.*)').firstMatch(argument);
return m?[2];
}
/// Extract the parameter of an option.
///
/// For example, in ['--out=fisk.js'] and ['-ohest.js'], the parameters
/// are ['fisk.js'] and ['hest.js'], respectively.
String extractParameter(String argument) {
// m[0] is the entire match (which will be equal to argument). m[1]
// is something like "-o" or "--out=", and m[2] is the parameter.
final m = RegExp('^(-[a-zA-Z]|--.+=)(.*)').firstMatch(argument);
if (m == null) {
_helpAndFail('Unknown option "$argument".');
}
return m[2]!;
}
String extractPath(String argument, {bool isDirectory = true}) {
String path = fe.nativeToUriPath(extractParameter(argument));
return !path.endsWith("/") && isDirectory ? "$path/" : path;
}
void parseCommandLine(List<OptionHandler> handlers, List<String> argv) {
// TODO(ahe): Use ../../args/args.dart for parsing options instead.
var patterns = <String>[];
for (OptionHandler handler in handlers) {
patterns.add(handler.pattern);
}
var pattern = RegExp('^(${patterns.join(")\$|^(")})\$');
Iterator<String> arguments = argv.iterator;
OUTER:
while (arguments.moveNext()) {
String argument = arguments.current;
final match = pattern.firstMatch(argument)!;
assert(match.groupCount == handlers.length);
for (int i = 0; i < handlers.length; i++) {
if (match[i + 1] != null) {
OptionHandler handler = handlers[i];
if (handler is _ManyOptions) {
handler.handle(arguments);
} else {
handler.handle(argument);
}
continue OUTER;
}
}
throw 'Internal error: "$argument" did not match';
}
}
FormattingDiagnosticHandler? diagnosticHandler;
Future<api.CompilationResult> compile(
List<String> argv, {
fe.InitializedCompilerState? kernelInitializedCompilerState,
}) {
Stopwatch wallclock = Stopwatch()..start();
stackTraceFilePrefix = '${Uri.base}';
Uri? entryUri;
Uri? inputDillUri;
Uri librariesSpecificationUri = Uri.base.resolve('lib/libraries.json');
Uri? out;
Uri? sourceMapOut;
List<String>? bazelPaths;
List<Uri>? multiRoots;
String? multiRootScheme = 'org-dartlang-app';
Uri? packageConfig;
List<String> options = <String>[];
bool wantHelp = false;
bool wantVersion = false;
bool trustTypeAnnotations = false;
bool checkedMode = false;
bool strongMode = true;
List<String> hints = <String>[];
bool? verbose;
bool? throwOnError;
int? throwOnErrorCount;
bool? showWarnings;
bool? showHints;
bool? enableColors;
int? optimizationLevel;
Uri? platformBinaries;
Map<String, String> environment = <String, String>{};
FeatureOptions features = FeatureOptions();
String? invoker;
void passThrough(String argument) => options.add(argument);
void ignoreOption(String argument) {}
if (buildID != null) {
passThrough("--build-id=$buildID");
}
Uri extractResolvedFileUri(String argument) {
return Uri.base.resolve(extractPath(argument, isDirectory: false));
}
void setEntryUri(String argument) {
entryUri = extractResolvedFileUri(argument);
options.add('${Flags.entryUri}=$entryUri');
}
void setInputDillUri(String argument) {
inputDillUri = extractResolvedFileUri(argument);
options.add('${Flags.inputDill}=$inputDillUri');
}
void setLibrarySpecificationUri(String argument) {
librariesSpecificationUri = extractResolvedFileUri(argument);
}
void setPackageConfig(String argument) {
packageConfig = extractResolvedFileUri(argument);
}
void Function(String) setDataUri(String flag) {
return (String argument) {
final uri = fe.nativeToUri(extractPath(argument, isDirectory: false));
options.add('$flag=$uri');
};
}
void setOutput(Iterator<String> arguments) {
String option = arguments.current;
String path;
if (option == '-o' || option == '--out' || option == '--output') {
if (!arguments.moveNext()) {
_helpAndFail("Missing file after '$option' option.");
}
path = arguments.current;
} else {
path = extractParameter(option);
}
out = Uri.base.resolve(fe.nativeToUriPath(path));
options.add('--out=$out');
}
void setOptimizationLevel(String argument) {
final value = int.tryParse(extractParameter(argument));
if (value == null || value < 0 || value > 4) {
_helpAndFail(
"Unsupported optimization level '$argument', "
"supported levels are: 0, 1, 2, 3, 4",
);
}
if (optimizationLevel != null) {
print(
"Optimization level '$argument' ignored "
"due to preceding '-O$optimizationLevel'",
);
return;
}
optimizationLevel = value;
}
void setOutputType(String argument) {
if (argument == '--output-type=dart' ||
argument == '--output-type=dart-multi') {
_helpAndFail(
"--output-type=dart is no longer supported. It was deprecated "
"since Dart 1.11 and removed in Dart 1.19.",
);
}
}
Never setStrip(String argument) {
_helpAndFail(
"Option '--force-strip' is not in use now that"
"--output-type=dart is no longer supported.",
);
}
void setBazelPaths(String argument) {
String paths = extractParameter(argument);
bazelPaths = <String>[...paths.split(',')];
}
void setMultiRoots(String argument) {
String paths = extractParameter(argument);
(multiRoots ??= <Uri>[]).addAll(paths.split(',').map(fe.nativeToUri));
}
void setMultiRootScheme(String argument) {
multiRootScheme = extractParameter(argument);
}
String getDepsOutput(Iterable<Uri> sourceFiles) {
var filenames = sourceFiles.map((uri) => '$uri').toList();
filenames.sort();
return filenames.join("\n");
}
void setAllowNativeExtensions(String argument) {
_helpAndFail("Option '${Flags.allowNativeExtensions}' is not supported.");
}
void setVerbose(_) {
verbose = true;
passThrough('--verbose');
}
void setTrustTypeAnnotations(String argument) {
trustTypeAnnotations = true;
}
void setCheckedMode(String argument) {
checkedMode = true;
passThrough(argument);
}
void addInEnvironment(Iterator<String> arguments) {
final isDefine = arguments.current.startsWith('--define');
String argument;
if (arguments.current == '--define') {
arguments.moveNext();
argument = arguments.current;
} else {
argument = arguments.current.substring(isDefine ? '--define='.length : 2);
}
// Allow for ' ' or '=' after --define
int eqIndex = argument.indexOf('=');
if (eqIndex <= 0) {
_helpAndFail('Invalid value for --define: $argument');
}
String name = argument.substring(0, eqIndex);
String value = argument.substring(eqIndex + 1);
environment[name] = value;
}
void setCategories(String argument) {
List<String> categories = extractParameter(argument).split(',');
bool isServerMode = categories.length == 1 && categories.single == "Server";
if (isServerMode) {
hints.add(
"The --categories flag is deprecated and will be deleted in a "
"future release, please use '${Flags.serverMode}' instead of "
"'--categories=Server'.",
);
passThrough(Flags.serverMode);
} else {
hints.add(
"The --categories flag is deprecated, see the usage for details.",
);
}
}
void setPlatformBinaries(String argument) {
platformBinaries = Uri.base.resolve(
extractPath(argument, isDirectory: true),
);
}
List<Uri> setUriList(String flag, String argument) {
String list = extractParameter(argument);
List<Uri> uris = list.split(',').map(fe.nativeToUri).toList();
String uriList = uris.map((uri) => '$uri').join(',');
options.add('$flag=$uriList');
return uris;
}
void setDillDependencies(String argument) {
setUriList(Flags.dillDependencies, argument);
}
void setDumpInfo(String argument) {
final hasEnumFormatMatch = DumpInfoFormat.values.any(
(e) => '${Flags.dumpInfo}=${e.name}' == argument,
);
if (argument == Flags.dumpInfo || hasEnumFormatMatch) {
passThrough(argument);
return;
}
_helpAndFail(
"Unsupported dump-info format '$argument', "
"supported formats: "
"${DumpInfoFormat.values.map((e) => e.name).join(', ')}",
);
}
void setInvoker(String argument) {
invoker = extractParameter(argument);
}
void handleThrowOnError(String argument) {
throwOnError = true;
final parameter = extractOptionalParameter(argument);
if (parameter != null) {
var count = int.parse(parameter);
throwOnErrorCount = count;
}
}
void handleShortOptions(String argument) {
var shortOptions = argument.substring(1).split("");
for (var shortOption in shortOptions) {
switch (shortOption) {
case 'v':
setVerbose(null);
break;
case 'h':
case '?':
wantHelp = true;
break;
case 'c':
setCheckedMode(Flags.enableCheckedMode);
break;
case 'm':
passThrough(Flags.minify);
break;
default:
throw 'Internal error: "$shortOption" did not match';
}
}
}
List<String> arguments = <String>[];
List<OptionHandler> handlers = <OptionHandler>[
_OneOption('${Flags.entryUri}=.+', setEntryUri),
_OneOption('${Flags.inputDill}=.+', setInputDillUri),
_OneOption('-[chvm?]+', handleShortOptions),
_OneOption('--throw-on-error(?:=[0-9]+)?', handleThrowOnError),
_OneOption(Flags.suppressWarnings, (String argument) {
showWarnings = false;
passThrough(argument);
}),
_OneOption(Flags.fatalWarnings, passThrough),
_OneOption(Flags.suppressHints, (String argument) {
showHints = false;
passThrough(argument);
}),
// TODO(sigmund): remove entirely after Dart 1.20
_OneOption(
'--output-type=dart|--output-type=dart-multi|--output-type=js',
setOutputType,
),
_OneOption('--use-kernel', ignoreOption),
_OneOption(Flags.platformBinaries, setPlatformBinaries),
_OneOption(Flags.noFrequencyBasedMinification, passThrough),
_OneOption(Flags.verbose, setVerbose),
_OneOption(Flags.progress, passThrough),
_OneOption(Flags.reportMetrics, passThrough),
_OneOption(Flags.reportAllMetrics, passThrough),
_OneOption(Flags.version, (_) => wantVersion = true),
_OneOption('--library-root=.+', ignoreOption),
_OneOption('--libraries-spec=.+', setLibrarySpecificationUri),
_OneOption('${Flags.dillDependencies}=.+', setDillDependencies),
_OneOption('${Flags.sources}=.+', ignoreOption),
_OneOption(
'${Flags.globalInferenceUri}=.+',
setDataUri(Flags.globalInferenceUri),
),
_OneOption('${Flags.closedWorldUri}=.+', setDataUri(Flags.closedWorldUri)),
_OneOption('${Flags.codegenUri}=.+', setDataUri(Flags.codegenUri)),
_OneOption('${Flags.codegenShard}=.+', passThrough),
_OneOption('${Flags.codegenShards}=.+', passThrough),
_OneOption(Flags.cfeOnly, passThrough),
_OneOption(Flags.memoryMappedFiles, passThrough),
_OneOption('${Flags.stage}=.+', passThrough),
_OneOption(Flags.debugGlobalInference, passThrough),
_ManyOptions('--output(?:=.+)?|--out(?:=.+)?|-o.*', setOutput),
_OneOption('-O.*', setOptimizationLevel),
_OneOption(Flags.allowMockCompilation, ignoreOption),
_OneOption(Flags.fastStartup, ignoreOption),
_OneOption(Flags.genericMethodSyntax, ignoreOption),
_OneOption(Flags.initializingFormalAccess, ignoreOption),
_OneOption(Flags.minify, passThrough),
_OneOption(Flags.noMinify, passThrough),
_OneOption(Flags.omitLateNames, passThrough),
_OneOption(Flags.noOmitLateNames, passThrough),
_OneOption(Flags.preserveUris, ignoreOption),
_OneOption('--force-strip=.*', setStrip),
_OneOption(Flags.disableDiagnosticColors, (_) {
enableColors = false;
}),
_OneOption(Flags.enableDiagnosticColors, (_) {
enableColors = true;
}),
_OneOption(
'--enable[_-]checked[_-]mode|--checked',
(_) => setCheckedMode(Flags.enableCheckedMode),
),
_OneOption(Flags.enableAsserts, passThrough),
_OneOption(Flags.enableNullAssertions, passThrough),
_OneOption(Flags.nativeNullAssertions, passThrough),
_OneOption(Flags.noNativeNullAssertions, passThrough),
_OneOption(Flags.interopNullAssertions, passThrough),
_OneOption(Flags.noInteropNullAssertions, passThrough),
_OneOption(Flags.trustTypeAnnotations, setTrustTypeAnnotations),
_OneOption(Flags.trustPrimitives, passThrough),
_OneOption(Flags.trustJSInteropTypeAnnotations, ignoreOption),
_OneOption(r'--help|/\?|/h', (_) => wantHelp = true),
_OneOption('--packages=.+', setPackageConfig),
_OneOption(Flags.noSourceMaps, passThrough),
_OneOption(Option.resolutionInput, ignoreOption),
_OneOption(Option.bazelPaths, setBazelPaths),
_OneOption(Option.multiRoots, setMultiRoots),
_OneOption(Option.multiRootScheme, setMultiRootScheme),
_OneOption(Flags.resolveOnly, ignoreOption),
_OneOption(Flags.disableNativeLiveTypeAnalysis, passThrough),
_OneOption('--categories=.*', setCategories),
_OneOption(Flags.serverMode, passThrough),
_OneOption(Flags.disableInlining, passThrough),
_OneOption(Flags.disableProgramSplit, passThrough),
_OneOption(Flags.stopAfterProgramSplit, passThrough),
_OneOption(Flags.disableTypeInference, passThrough),
_OneOption(Flags.useTrivialAbstractValueDomain, passThrough),
_OneOption(Flags.experimentalWrapped, passThrough),
_OneOption(Flags.experimentalPowersets, passThrough),
_OneOption(Flags.disableRtiOptimization, passThrough),
_OneOption(Flags.terse, passThrough),
_OneOption('--deferred-map=.+', passThrough),
_OneOption(
'${Flags.deferredLoadIdMapUri}=.+',
setDataUri(Flags.deferredLoadIdMapUri),
),
_OneOption('${Flags.writeProgramSplit}=.+', passThrough),
_OneOption('${Flags.readProgramSplit}=.+', passThrough),
_OneOption('${Flags.dumpInfo}|${Flags.dumpInfo}=.+', setDumpInfo),
_OneOption(
'${Flags.dumpInfoDataUri}=.+',
setDataUri(Flags.dumpInfoDataUri),
),
_OneOption('--disallow-unsafe-eval', ignoreOption),
_OneOption(Option.showPackageWarnings, passThrough),
_OneOption(Option.enableLanguageExperiments, passThrough),
_OneOption('--enable-experimental-mirrors', ignoreOption),
_OneOption(Flags.enableAssertMessage, passThrough),
_OneOption('--strong', ignoreOption),
_OneOption(Flags.previewDart2, ignoreOption),
_OneOption(Flags.omitImplicitChecks, passThrough),
_OneOption(Flags.omitAsCasts, passThrough),
_OneOption(Flags.laxRuntimeTypeToString, passThrough),
_OneOption(Flags.enableProtoShaking, passThrough),
_OneOption(Flags.enableProtoMixinShaking, passThrough),
_OneOption(Flags.benchmarkingProduction, passThrough),
_OneOption(Flags.benchmarkingExperiment, passThrough),
_OneOption(Flags.soundNullSafety, passThrough),
_OneOption(Flags.dumpUnusedLibraries, passThrough),
_OneOption(Flags.writeResources, passThrough),
// TODO(floitsch): remove conditional directives flag.
// We don't provide the info-message yet, since we haven't publicly
// launched the feature yet.
_OneOption(Flags.conditionalDirectives, ignoreOption),
_OneOption('--enable-async', ignoreOption),
_OneOption('--enable-null-aware-operators', ignoreOption),
_OneOption('--enable-enum', ignoreOption),
_OneOption(Flags.allowNativeExtensions, setAllowNativeExtensions),
_OneOption(Flags.generateCodeWithCompileTimeErrors, ignoreOption),
_OneOption(Flags.useMultiSourceInfo, passThrough),
_OneOption(Flags.useNewSourceInfo, passThrough),
_OneOption(Flags.useSimpleLoadIds, passThrough),
_OneOption(Flags.testMode, passThrough),
_OneOption('${Flags.dumpSsa}=.+', passThrough),
_OneOption('${Flags.cfeInvocationModes}=.+', passThrough),
_OneOption('${Flags.invoker}=.+', setInvoker),
_OneOption('${Flags.verbosity}=.+', passThrough),
_OneOption(Flags.disableDiagnosticByteCache, passThrough),
// Experimental features.
// We don't provide documentation for these yet.
// TODO(29574): provide documentation when this feature is supported.
// TODO(29574): provide a warning/hint/error, when profile-based data is
// used without `--fast-startup`.
_OneOption(Flags.experimentalTrackAllocations, passThrough),
_OneOption(Flags.experimentLocalNames, ignoreOption),
_OneOption(Flags.experimentStartupFunctions, passThrough),
_OneOption(Flags.experimentToBoolean, passThrough),
_OneOption(Flags.experimentUnreachableMethodsThrow, passThrough),
_OneOption(Flags.experimentCallInstrumentation, passThrough),
_OneOption('${Flags.mergeFragmentsThreshold}=.+', passThrough),
// Wire up feature flags.
_OneOption(Flags.canary, passThrough),
_OneOption(Flags.noShipping, passThrough),
// Shipped features.
for (var feature in features.shipped)
_OneOption('--${feature.flag}', passThrough),
for (var feature in features.shipped)
_OneOption('--no-${feature.flag}', passThrough),
// Shipping features.
for (var feature in features.shipping)
_OneOption('--${feature.flag}', passThrough),
for (var feature in features.shipping)
_OneOption('--no-${feature.flag}', passThrough),
// Canary features.
for (var feature in features.canary)
_OneOption('--${feature.flag}', passThrough),
for (var feature in features.canary)
_OneOption('--no-${feature.flag}', passThrough),
// The following three options must come last.
_ManyOptions('-D.+=.*|--define=.+=.*|--define', addInEnvironment),
_OneOption('-.*', (String argument) {
_helpAndFail("Unknown option '$argument'.");
}),
_OneOption('.*', (String argument) {
arguments.add(fe.nativeToUriPath(argument));
}),
];
parseCommandLine(handlers, argv);
final diagnostic = diagnosticHandler = FormattingDiagnosticHandler();
if (verbose != null) {
diagnostic.verbose = verbose!;
}
if (throwOnError != null) {
diagnostic.throwOnError = throwOnError!;
}
if (throwOnErrorCount != null) {
diagnostic.throwOnErrorCount = throwOnErrorCount!;
}
if (showWarnings != null) {
diagnostic.showWarnings = showWarnings!;
}
if (showHints != null) {
diagnostic.showHints = showHints!;
}
if (enableColors != null) {
diagnostic.enableColors = enableColors!;
}
if (checkedMode && strongMode) {
checkedMode = false;
hints.add(
"Option '${Flags.enableCheckedMode}' is not needed in Dart 2.0. "
"To enable assertions use '${Flags.enableAsserts}' instead.",
);
}
if (trustTypeAnnotations && strongMode) {
hints.add(
"Option '${Flags.trustTypeAnnotations}' is not available "
"in Dart 2.0. Try using '${Flags.omitImplicitChecks}' instead.",
);
}
if (options.contains(Flags.soundNullSafety)) {
warning(
"Option '${Flags.soundNullSafety}' is deprecated. As of Dart 3, Dart "
"only supports sound null safety. This flag will be removed in a future "
"version of Dart.",
);
}
for (String hint in hints) {
diagnostic.info(hint, api.Diagnostic.hint);
}
if (wantHelp || wantVersion) {
helpAndExit(wantHelp, wantVersion, diagnostic.verbose);
}
if (invoker == null) {
final message =
"The 'dart2js' entrypoint script is deprecated, "
"please use 'dart compile js' instead.";
// Aside from asking for `-h`, dart2js fails when it is invoked from its
// snapshot directly and not using the supported workflows. However, we
// allow invoking dart2js from Dart sources to support the dart2js team
// local workflows and testing.
if (!Platform.script.path.endsWith(".dart")) {
_fail(message);
} else {
warning(message);
}
} else if (verbose != null) {
print("Compiler invoked from: '$invoker'");
}
if (arguments.isEmpty && entryUri == null && inputDillUri == null) {
_helpAndFail('No Dart file specified.');
}
if (arguments.length > 1) {
var extra = arguments.sublist(1);
_helpAndFail('Extra arguments: ${extra.join(" ")}');
}
if (trustTypeAnnotations && checkedMode) {
_helpAndFail(
"Option '${Flags.trustTypeAnnotations}' may not be used in "
"checked mode.",
);
}
if (arguments.isNotEmpty) {
String sourceOrDill = arguments[0];
Uri file = Uri.base.resolve(fe.nativeToUriPath(sourceOrDill));
if (sourceOrDill.endsWith('.dart')) {
options.add('${Flags.entryUri}=$file');
entryUri = file;
} else {
assert(sourceOrDill.endsWith('.dill'));
options.add('${Flags.inputDill}=$file');
inputDillUri = file;
}
}
// Make [scriptName] a relative path.
String scriptName = fe.relativizeUri(
Uri.base,
inputDillUri ?? entryUri!,
Platform.isWindows,
);
CompilerOptions compilerOptions =
CompilerOptions.parse(
options,
featureOptions: features,
librariesSpecificationUri: librariesSpecificationUri,
platformBinaries: platformBinaries,
useDefaultOutputUri: true,
onError: (String message) => _fail(message),
onWarning: (String message) => print(message),
)
..packageConfig = packageConfig
..environment = environment
..kernelInitializedCompilerState = kernelInitializedCompilerState
..optimizationLevel = optimizationLevel;
final errorMessage = compilerOptions.validateStage();
if (errorMessage != null) {
_fail(errorMessage);
}
out = compilerOptions.setResolvedOutputUri();
if (compilerOptions.stage.emitsJs) {
sourceMapOut = Uri.parse('$out.map');
compilerOptions.sourceMapUri ??= sourceMapOut;
}
// TODO(johnniwinther): Measure time for reading files.
SourceFileByteReader byteReader =
compilerOptions.memoryMappedFiles
? const MemoryMapSourceFileByteReader()
: const MemoryCopySourceFileByteReader();
SourceFileProvider inputProvider;
if (bazelPaths != null) {
if (multiRoots != null) {
_helpAndFail(
'The options --bazel-root and --multi-root cannot be supplied '
'together, please choose one or the other.',
);
}
inputProvider = BazelInputProvider(
bazelPaths!,
byteReader,
disableByteCache: compilerOptions.disableDiagnosticByteCache,
);
} else if (multiRoots != null) {
inputProvider = MultiRootInputProvider(
multiRootScheme!,
multiRoots!,
byteReader,
disableByteCache: compilerOptions.disableDiagnosticByteCache,
);
} else {
inputProvider = CompilerSourceFileProvider(
byteReader: byteReader,
disableByteCache: compilerOptions.disableDiagnosticByteCache,
);
}
diagnostic.registerFileProvider(inputProvider);
RandomAccessFileOutputProvider outputProvider =
RandomAccessFileOutputProvider(
out,
sourceMapOut,
onInfo: diagnostic.info,
onFailure: _fail,
);
Future<api.CompilationResult> compilationDone(
api.CompilationResult result,
) async {
if (!result.isSuccess) {
_fail('Compilation failed.');
}
if (out != null) {
writeString(
Uri.parse('$out.deps'),
getDepsOutput(inputProvider.getSourceUris()),
);
}
String input = scriptName;
int inputSize;
String processName;
String inputName;
int outputSize;
int? primaryOutputSize;
String outputName;
String? summary;
switch (compilerOptions.stage) {
case CompilerStage.all:
case CompilerStage.cfe:
case CompilerStage.dumpInfoAll:
final sourceCharCount = _formatCharacterCount(
inputProvider.sourceBytesFromDill,
);
inputName = 'input bytes ($sourceCharCount characters source)';
inputSize = inputProvider.bytesRead;
summary = 'Dart file $input ';
break;
case CompilerStage.closedWorld:
case CompilerStage.deferredLoadIds:
inputName = 'input bytes';
inputSize = inputProvider.bytesRead;
summary = 'Dart file $input ';
break;
case CompilerStage.globalInference:
inputName = 'bytes data';
inputSize = inputProvider.bytesRead;
String dataInput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(CompilerStage.closedWorld),
Platform.isWindows,
);
summary = 'Data files $input and $dataInput ';
break;
case CompilerStage.codegenSharded:
case CompilerStage.codegenAndJsEmitter:
case CompilerStage.dumpInfo:
inputName = 'bytes data';
inputSize = inputProvider.bytesRead;
String worldInput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(CompilerStage.closedWorld),
Platform.isWindows,
);
String dataInput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(CompilerStage.globalInference),
Platform.isWindows,
);
summary = 'Data files $input, $worldInput, and $dataInput ';
break;
case CompilerStage.jsEmitter:
inputName = 'bytes data';
inputSize = inputProvider.bytesRead;
String worldInput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(CompilerStage.closedWorld),
Platform.isWindows,
);
String dataInput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(CompilerStage.globalInference),
Platform.isWindows,
);
String codeInput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(CompilerStage.codegenSharded),
Platform.isWindows,
);
summary =
'Data files $input, $worldInput, $dataInput and '
'$codeInput[0-${compilerOptions.codegenShards! - 1}] ';
break;
}
switch (compilerOptions.stage) {
case CompilerStage.all:
case CompilerStage.dumpInfoAll:
case CompilerStage.jsEmitter:
case CompilerStage.codegenAndJsEmitter:
case CompilerStage.dumpInfo:
processName = 'Compiled';
outputName = 'characters JavaScript';
outputSize = outputProvider.totalCharactersWrittenJavaScript;
primaryOutputSize = outputProvider.totalCharactersWrittenPrimary;
String output = fe.relativizeUri(
Uri.base,
out ?? Uri.parse('out.js'),
Platform.isWindows,
);
summary += 'compiled to JavaScript: $output';
break;
case CompilerStage.cfe:
processName = 'Compiled';
outputName = 'kernel bytes';
outputSize = outputProvider.totalDataWritten;
String output = fe.relativizeUri(Uri.base, out!, Platform.isWindows);
summary += 'compiled to dill: $output.';
break;
case CompilerStage.closedWorld:
processName = 'Serialized';
outputName = 'bytes data';
outputSize = outputProvider.totalDataWritten;
final producesDill = compilerOptions.producesModifiedDill;
String dataOutput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(compilerOptions.stage),
Platform.isWindows,
);
String summaryLine = dataOutput;
if (producesDill) {
summaryLine += ' and ';
summaryLine += fe.relativizeUri(Uri.base, out!, Platform.isWindows);
}
summary += 'serialized to data: $summaryLine.';
break;
case CompilerStage.deferredLoadIds:
processName = 'Serialized';
outputName = 'character map';
outputSize = outputProvider.totalCharactersWritten;
String dataOutput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(compilerOptions.stage),
Platform.isWindows,
);
summary += 'mapped to: $dataOutput.';
break;
case CompilerStage.globalInference:
processName = 'Serialized';
outputName = 'bytes data';
outputSize = outputProvider.totalDataWritten;
String dataOutput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(compilerOptions.stage),
Platform.isWindows,
);
summary += 'serialized to data: $dataOutput.';
break;
case CompilerStage.codegenSharded:
processName = 'Serialized';
outputName = 'bytes data';
outputSize = outputProvider.totalDataWritten;
String codeOutput = fe.relativizeUri(
Uri.base,
compilerOptions.dataUriForStage(compilerOptions.stage),
Platform.isWindows,
);
summary +=
'serialized to codegen data: '
'$codeOutput${compilerOptions.codegenShard}.';
break;
}
print(
'$processName '
'${_formatCharacterCount(inputSize)} $inputName to '
'${_formatCharacterCount(outputSize)} $outputName in '
'${_formatDurationAsSeconds(wallclock.elapsed)} seconds using '
'${await currentHeapCapacityInMb()} of memory',
);
if (primaryOutputSize != null && out != null) {
diagnostic.info(
'${_formatCharacterCount(primaryOutputSize)} $outputName '
'in ${fe.relativizeUri(Uri.base, out!, Platform.isWindows)}',
);
}
if (compilerOptions.stage.emitsJs) {
if (diagnostic.verbose) {
print(summary);
if (diagnostic.verbose) {
var files = outputProvider.allOutputFiles;
int jsCount = files.where((f) => f.endsWith('.js')).length;
print('Emitted file $jsCount JavaScript files.');
}
}
} else {
print(summary);
}
return result;
}
return compileFunc(
compilerOptions,
inputProvider,
diagnostic,
outputProvider,
).then(compilationDone);
}
/// Returns the non-negative integer formatted with a thousands separator.
String _formatCharacterCount(int value, [String separator = ',']) {
String text = '$value';
// 'Insert' separators right-to-left. Inefficient, but used just a few times.
for (int position = text.length - 3; position > 0; position -= 3) {
text = text.substring(0, position) + separator + text.substring(position);
}
return text;
}
/// Formats [duration] in seconds in fixed-point format, preferring to keep the
/// result at to below [width] characters.
String _formatDurationAsSeconds(Duration duration, [int width = 4]) {
num seconds = duration.inMilliseconds / 1000.0;
late String text;
for (int digits = 3; digits >= 0; digits--) {
text = seconds.toStringAsFixed(digits);
if (text.length <= width) return text;
}
return text;
}
void writeString(Uri uri, String text) {
if (!enableWriteString) return;
if (!uri.isScheme('file')) {
_fail('Unhandled scheme ${uri.scheme}.');
}
var file = (File(uri.toFilePath())
..createSync(recursive: true)).openSync(mode: FileMode.write);
file.writeStringSync(text);
file.closeSync();
}
Never _fail(String message) {