-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsource_loader.dart
3213 lines (2909 loc) · 121 KB
/
source_loader.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) 2016, 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:collection' show Queue;
import 'dart:convert' show utf8;
import 'dart:typed_data' show Uint8List;
import 'package:_fe_analyzer_shared/src/parser/class_member_parser.dart'
show ClassMemberParser;
import 'package:_fe_analyzer_shared/src/parser/forwarding_listener.dart'
show ForwardingListener;
import 'package:_fe_analyzer_shared/src/parser/parser.dart'
show Parser, lengthForToken;
import 'package:_fe_analyzer_shared/src/scanner/scanner.dart'
show
ErrorToken,
LanguageVersionToken,
Scanner,
ScannerConfiguration,
ScannerResult,
Token,
scan;
import 'package:kernel/ast.dart';
import 'package:kernel/class_hierarchy.dart' show ClassHierarchy;
import 'package:kernel/core_types.dart' show CoreTypes;
import 'package:kernel/reference_from_index.dart'
show IndexedLibrary, ReferenceFromIndex;
import 'package:kernel/target/targets.dart';
import 'package:kernel/type_environment.dart';
import 'package:kernel/util/graph.dart';
import 'package:package_config/package_config.dart' as package_config;
import '../api_prototype/experimental_flags.dart';
import '../api_prototype/file_system.dart';
import '../base/common.dart';
import '../base/export.dart' show Export;
import '../base/import_chains.dart';
import '../base/instrumentation.dart' show Instrumentation;
import '../base/loader.dart' show Loader, untranslatableUriScheme;
import '../base/local_scope.dart';
import '../base/problems.dart' show internalProblem;
import '../base/scope.dart';
import '../base/ticker.dart' show Ticker;
import '../base/uri_offset.dart';
import '../base/uris.dart';
import '../builder/builder.dart';
import '../builder/declaration_builders.dart';
import '../builder/library_builder.dart';
import '../builder/member_builder.dart';
import '../builder/name_iterator.dart';
import '../builder/omitted_type_builder.dart';
import '../builder/type_builder.dart';
import '../codes/cfe_codes.dart';
import '../codes/denylisted_classes.dart'
show denylistedCoreClasses, denylistedTypedDataClasses;
import '../dill/dill_library_builder.dart';
import '../kernel/benchmarker.dart' show BenchmarkSubdivides;
import '../kernel/body_builder.dart' show BodyBuilder;
import '../kernel/body_builder_context.dart';
import '../kernel/exhaustiveness.dart';
import '../kernel/hierarchy/class_member.dart';
import '../kernel/hierarchy/delayed.dart';
import '../kernel/hierarchy/hierarchy_builder.dart';
import '../kernel/hierarchy/hierarchy_node.dart';
import '../kernel/hierarchy/members_builder.dart';
import '../kernel/kernel_helper.dart'
show DelayedDefaultValueCloner, TypeDependency;
import '../kernel/kernel_target.dart' show KernelTarget;
import '../kernel/type_builder_computer.dart' show TypeBuilderComputer;
import '../type_inference/type_inference_engine.dart';
import '../type_inference/type_inferrer.dart';
import 'diet_listener.dart' show DietListener;
import 'diet_parser.dart' show DietParser, useImplicitCreationExpressionInCfe;
import 'offset_map.dart';
import 'outline_builder.dart' show OutlineBuilder;
import 'source_class_builder.dart' show SourceClassBuilder;
import 'source_enum_builder.dart';
import 'source_extension_type_declaration_builder.dart';
import 'source_factory_builder.dart';
import 'source_library_builder.dart'
show
ImplicitLanguageVersion,
InvalidLanguageVersion,
LanguageVersion,
LibraryAccess,
SourceCompilationUnitImpl,
SourceLibraryBuilder;
import 'stack_listener_impl.dart' show offsetForToken;
class SourceLoader extends Loader {
/// The [FileSystem] which should be used to access files.
final FileSystem fileSystem;
/// Whether comments should be scanned and parsed.
final bool includeComments;
final Map<Uri, Uint8List> sourceBytes = <Uri, Uint8List>{};
ClassHierarchyBuilder? _hierarchyBuilder;
ClassMembersBuilder? _membersBuilder;
ReferenceFromIndex? referenceFromIndex;
/// Used when building directly to kernel.
ClassHierarchy? _hierarchy;
CoreTypes? _coreTypes;
TypeEnvironment? _typeEnvironment;
/// For builders created with a reference, this maps from that reference to
/// that builder. This is used for looking up source builders when finalizing
/// exports in dill builders.
Map<Reference, Builder> buildersCreatedWithReferences = {};
/// Used when checking whether a return type of an async function is valid.
///
/// The said return type is valid if it's a subtype of [futureOfBottom].
DartType? _futureOfBottom;
DartType get futureOfBottom => _futureOfBottom!;
/// Used when checking whether a return type of a sync* function is valid.
///
/// The said return type is valid if it's a subtype of [iterableOfBottom].
DartType? _iterableOfBottom;
DartType get iterableOfBottom => _iterableOfBottom!;
/// Used when checking whether a return type of an async* function is valid.
///
/// The said return type is valid if it's a subtype of [streamOfBottom].
DartType? _streamOfBottom;
DartType get streamOfBottom => _streamOfBottom!;
TypeInferenceEngineImpl? _typeInferenceEngine;
Instrumentation? instrumentation;
final SourceLoaderDataForTesting? dataForTesting;
final Map<Uri, CompilationUnit> _compilationUnits = {};
Map<Uri, LibraryBuilder> _loadedLibraryBuilders = <Uri, LibraryBuilder>{};
List<SourceLibraryBuilder>? _sourceLibraryBuilders;
final Queue<SourceCompilationUnit> _unparsedLibraries =
new Queue<SourceCompilationUnit>();
final List<Library> libraries = <Library>[];
final KernelTarget target;
/// List of all handled compile-time errors seen so far by libraries loaded
/// by this loader.
///
/// A handled error is an error that has been added to the generated AST
/// already, for example, as a throw expression.
final List<LocatedMessage> handledErrors = <LocatedMessage>[];
/// List of all unhandled compile-time errors seen so far by libraries loaded
/// by this loader.
///
/// An unhandled error is an error that hasn't been handled, see
/// [handledErrors].
final List<LocatedMessage> unhandledErrors = <LocatedMessage>[];
/// List of all problems seen so far by libraries loaded by this loader that
/// does not belong directly to a library.
final List<FormattedMessage> allComponentProblems = <FormattedMessage>[];
/// The text of the messages that have been reported.
///
/// This is used filter messages so that we don't report the same error twice.
final Set<String> seenMessages = new Set<String>();
/// Set to `true` if one of the reported errors had severity `Severity.error`.
///
/// This is used for [hasSeenError].
bool _hasSeenError = false;
// Coverage-ignore(suite): Not run.
/// Clears the [seenMessages] and [hasSeenError] state.
void resetSeenMessages() {
seenMessages.clear();
_hasSeenError = false;
}
/// Returns `true` if a compile time error has been reported.
bool get hasSeenError => _hasSeenError;
LibraryBuilder? _coreLibrary;
CompilationUnit? _coreLibraryCompilationUnit;
CompilationUnit? _typedDataLibraryCompilationUnit;
LibraryBuilder? get typedDataLibrary =>
_typedDataLibraryCompilationUnit?.libraryBuilder;
final Set<Uri> roots = {};
// TODO(johnniwinther): Replace with a `singleRoot`.
// See also https://dart-review.googlesource.com/c/sdk/+/273381.
LibraryBuilder? get rootLibrary {
for (Uri uri in roots) {
LibraryBuilder? builder = lookupLoadedLibraryBuilder(uri);
if (builder != null) return builder;
}
return null;
}
CompilationUnit? get rootCompilationUnit {
for (Uri uri in roots) {
CompilationUnit? builder = _compilationUnits[uri];
if (builder != null) return builder;
}
return null;
}
int byteCount = 0;
UriOffset? currentUriForCrashReporting;
final List<String> _expectedOutlineFutureProblems = [];
final List<String> _expectedBodyBuildingFutureProblems = [];
SourceLoader(this.fileSystem, this.includeComments, this.target)
: dataForTesting = retainDataForTesting
?
// Coverage-ignore(suite): Not run.
new SourceLoaderDataForTesting()
: null;
void installAllProblemsIntoComponent(Component component,
{required CompilationPhaseForProblemReporting currentPhase}) {
List<String> expectedFutureProblemsForCurrentPhase = switch (currentPhase) {
CompilationPhaseForProblemReporting.outline =>
_expectedOutlineFutureProblems,
CompilationPhaseForProblemReporting.bodyBuilding =>
_expectedBodyBuildingFutureProblems
};
assert(
expectedFutureProblemsForCurrentPhase.isEmpty || hasSeenError,
"Expected problems to be reported, but there were none.\n"
"Current compilation phase: ${currentPhase}\n"
"Expected at these locations:\n"
" * ${expectedFutureProblemsForCurrentPhase.join("\n * ")}");
if (allComponentProblems.isNotEmpty) {
component.problemsAsJson ??= <String>[];
}
for (int i = 0; i < allComponentProblems.length; i++) {
FormattedMessage formattedMessage = allComponentProblems[i];
component.problemsAsJson!.add(formattedMessage.toJsonString());
}
allComponentProblems.clear();
}
/// Assert that a compile-time error was reported during [expectedPhase] of
/// compilation.
///
/// The parameters [location] and [originalStackTrace] are supposed to help to
/// locate the place where the expectation was declared.
///
/// To avoid spending resources on stack trace computations, it is recommended
/// to wrap the calls to [assertProblemReportedElsewhere] into `assert`s.
bool assertProblemReportedElsewhere(String location,
{required CompilationPhaseForProblemReporting expectedPhase}) {
if (hasSeenError) return true;
List<String> expectedFutureProblemsForCurrentPhase =
switch (expectedPhase) {
CompilationPhaseForProblemReporting.outline =>
_expectedOutlineFutureProblems,
CompilationPhaseForProblemReporting.bodyBuilding =>
_expectedBodyBuildingFutureProblems
};
expectedFutureProblemsForCurrentPhase
.add("${location}\n${StackTrace.current}\n");
return true;
}
bool containsLoadedLibraryBuilder(Uri importUri) =>
lookupLoadedLibraryBuilder(importUri) != null;
LibraryBuilder? lookupLoadedLibraryBuilder(Uri importUri) {
return _loadedLibraryBuilders[importUri];
}
CompilationUnit? lookupCompilationUnit(Uri importUri) =>
_compilationUnits[importUri];
// Coverage-ignore(suite): Not run.
CompilationUnit? lookupCompilationUnitByFileUri(Uri fileUri) {
// TODO(johnniwinther): Store compilation units in a map by file URI?
for (CompilationUnit compilationUnit in _compilationUnits.values) {
if (compilationUnit.fileUri == fileUri) {
return compilationUnit;
}
}
return null;
}
Iterable<CompilationUnit> get compilationUnits => _compilationUnits.values;
Iterable<LibraryBuilder> get loadedLibraryBuilders {
return _loadedLibraryBuilders.values;
}
/// The [SourceLibraryBuilder]s for the libraries built from source by this
/// source loader.
///
/// This is available after [resolveParts] have been called and doesn't
/// include parts or augmentations. Orphaned parts _are_ included.
List<SourceLibraryBuilder> get sourceLibraryBuilders {
assert(
_sourceLibraryBuilders != null,
"Source library builder hasn't been computed yet. "
"The source libraries are in SourceLoader.resolveParts.");
return _sourceLibraryBuilders!;
}
void clearSourceLibraryBuilders() {
assert(
_sourceLibraryBuilders != null,
"Source library builder hasn't been computed yet. "
"The source libraries are in SourceLoader.resolveParts.");
_sourceLibraryBuilders!.clear();
}
// Coverage-ignore(suite): Not run.
Iterable<Uri> get loadedLibraryImportUris => _loadedLibraryBuilders.keys;
void registerLoadedDillLibraryBuilder(DillLibraryBuilder libraryBuilder) {
assert(!libraryBuilder.isPart, "Unexpected part $libraryBuilder.");
Uri uri = libraryBuilder.importUri;
_markDartLibraries(uri, libraryBuilder.mainCompilationUnit);
_compilationUnits[uri] = libraryBuilder.mainCompilationUnit;
_loadedLibraryBuilders[uri] = libraryBuilder;
}
LibraryBuilder? deregisterLoadedLibraryBuilder(Uri importUri) {
LibraryBuilder? libraryBuilder = _loadedLibraryBuilders.remove(importUri);
if (libraryBuilder != null) {
_compilationUnits.remove(importUri);
}
return libraryBuilder;
}
// Coverage-ignore(suite): Not run.
void clearLibraryBuilders() {
_compilationUnits.clear();
_loadedLibraryBuilders.clear();
}
/// Run [f] with [uri] and [fileOffset] as the current uri/offset used for
/// reporting crashes.
T withUriForCrashReporting<T>(Uri uri, int fileOffset, T Function() f) {
UriOffset? oldUriForCrashReporting = currentUriForCrashReporting;
currentUriForCrashReporting = new UriOffset(uri, fileOffset);
T result = f();
currentUriForCrashReporting = oldUriForCrashReporting;
return result;
}
@override
LibraryBuilder get coreLibrary =>
_coreLibrary ??= _coreLibraryCompilationUnit!.libraryBuilder;
@override
CompilationUnit get coreLibraryCompilationUnit =>
_coreLibraryCompilationUnit!;
Ticker get ticker => target.ticker;
/// Creates a [SourceLibraryBuilder] corresponding to [importUri], if one
/// doesn't exist already.
///
/// [fileUri] must not be null and is a URI that can be passed to FileSystem
/// to locate the corresponding file.
///
/// [origin] is non-null if the created library is an augmentation of
/// [origin].
///
/// [packageUri] is the base uri for the package which the library belongs to.
/// For instance 'package:foo'.
///
/// This is used to associate libraries in for instance the 'bin' and 'test'
/// folders of a package source with the package uri of the 'lib' folder.
///
/// If the [packageUri] is `null` the package association of this library is
/// based on its [importUri].
///
/// For libraries with a 'package:' [importUri], the package path must match
/// the path in the [importUri]. For libraries with a 'dart:' [importUri] the
/// [packageUri] must be `null`.
///
/// [packageLanguageVersion] is the language version defined by the package
/// which the library belongs to, or the current sdk version if the library
/// doesn't belong to a package.
SourceCompilationUnit createSourceCompilationUnit(
{required Uri importUri,
required Uri fileUri,
Uri? packageUri,
required Uri originImportUri,
required LanguageVersion packageLanguageVersion,
SourceCompilationUnit? origin,
IndexedLibrary? referencesFromIndex,
bool? referenceIsPartOwner,
bool isAugmentation = false,
bool isPatch = false,
required bool mayImplementRestrictedTypes}) {
return new SourceCompilationUnitImpl(
importUri: importUri,
fileUri: fileUri,
packageUri: packageUri,
originImportUri: originImportUri,
packageLanguageVersion: packageLanguageVersion,
loader: this,
augmentationRoot: origin,
nameOrigin: null,
indexedLibrary: referencesFromIndex,
referenceIsPartOwner: referenceIsPartOwner,
isUnsupported: origin?.isUnsupported ??
importUri.isScheme('dart') &&
!target.uriTranslator.isLibrarySupported(importUri.path),
isAugmenting: origin != null,
forAugmentationLibrary: isAugmentation,
forPatchLibrary: isPatch,
mayImplementRestrictedTypes: mayImplementRestrictedTypes);
}
/// Return `"true"` if the [dottedName] is a 'dart.library.*' qualifier for a
/// supported dart:* library, and `null` otherwise.
///
/// This is used to determine conditional imports and `bool.fromEnvironment`
/// constant values for "dart.library.[libraryName]" values.
///
/// The `null` value will not be equal to the tested string value of
/// a configurable URI, which is always non-`null`. This prevents
/// the configurable URI from matching an absent entry,
/// even for an `if (dart.library.nonLibrary == "")` test.
String? getLibrarySupportValue(String dottedName) {
if (!DartLibrarySupport.isDartLibraryQualifier(dottedName)) {
return "";
}
String libraryName = DartLibrarySupport.getDartLibraryName(dottedName);
Uri uri = new Uri(scheme: "dart", path: libraryName);
// TODO(johnniwinther): This should really be libraries only.
CompilationUnit? compilationUnit = lookupCompilationUnit(uri);
// TODO(johnniwinther): Why is the dill target sometimes not loaded at this
// point? And does it matter?
compilationUnit ??= target.dillTarget.loader
.lookupLibraryBuilder(uri)
// Coverage-ignore(suite): Not run.
?.mainCompilationUnit;
return DartLibrarySupport.isDartLibrarySupported(libraryName,
libraryExists: compilationUnit != null,
isSynthetic: compilationUnit?.isSynthetic ?? true,
isUnsupported: compilationUnit?.isUnsupported ?? true,
dartLibrarySupport: target.backendTarget.dartLibrarySupport)
? "true"
: null;
}
SourceCompilationUnit _createSourceCompilationUnit(
{required Uri uri,
required Uri? fileUri,
required Uri? originImportUri,
required SourceCompilationUnit? origin,
required IndexedLibrary? referencesFromIndex,
required bool? referenceIsPartOwner,
required bool isAugmentation,
required bool isPatch,
required bool addAsRoot}) {
if (fileUri != null &&
(fileUri.isScheme("dart") ||
fileUri.isScheme("package") ||
fileUri.isScheme("dart-ext"))) {
fileUri = null;
}
package_config.Package? packageForLanguageVersion;
if (fileUri == null) {
switch (uri.scheme) {
case "package":
case "dart":
fileUri = target.translateUri(uri) ??
new Uri(
scheme: untranslatableUriScheme,
path: Uri.encodeComponent("$uri"));
if (uri.isScheme("package")) {
packageForLanguageVersion = target.uriTranslator.getPackage(uri);
} else {
packageForLanguageVersion =
target.uriTranslator.packages.packageOf(fileUri);
}
break;
default:
fileUri = uri;
packageForLanguageVersion =
target.uriTranslator.packages.packageOf(fileUri);
break;
}
} else {
packageForLanguageVersion =
target.uriTranslator.packages.packageOf(fileUri);
}
LanguageVersion? packageLanguageVersion;
Uri? packageUri;
Message? packageLanguageVersionProblem;
if (packageForLanguageVersion != null) {
Uri importUri = origin?.importUri ?? uri;
if (!importUri.isScheme('dart') && !importUri.isScheme('package')) {
packageUri =
new Uri(scheme: 'package', path: packageForLanguageVersion.name);
}
if (packageForLanguageVersion.languageVersion != null) {
if (packageForLanguageVersion.languageVersion
is package_config.InvalidLanguageVersion) {
// Coverage-ignore-block(suite): Not run.
packageLanguageVersionProblem =
messageLanguageVersionInvalidInDotPackages;
packageLanguageVersion = new InvalidLanguageVersion(
fileUri, 0, noLength, target.currentSdkVersion, false);
} else {
Version version = new Version(
packageForLanguageVersion.languageVersion!.major,
packageForLanguageVersion.languageVersion!.minor);
if (version > target.currentSdkVersion) {
packageLanguageVersionProblem =
templateLanguageVersionTooHighPackage.withArguments(
version.major,
version.minor,
packageForLanguageVersion.name,
target.currentSdkVersion.major,
target.currentSdkVersion.minor);
packageLanguageVersion = new InvalidLanguageVersion(
fileUri, 0, noLength, target.currentSdkVersion, false);
} else if (version < target.leastSupportedVersion) {
packageLanguageVersionProblem =
templateLanguageVersionTooLowPackage.withArguments(
version.major,
version.minor,
packageForLanguageVersion.name,
target.leastSupportedVersion.major,
target.leastSupportedVersion.minor);
packageLanguageVersion = new InvalidLanguageVersion(
fileUri, 0, noLength, target.leastSupportedVersion, false);
} else {
packageLanguageVersion = new ImplicitLanguageVersion(version);
}
}
}
}
packageLanguageVersion ??=
new ImplicitLanguageVersion(target.currentSdkVersion);
originImportUri ??= uri;
SourceCompilationUnit compilationUnit = createSourceCompilationUnit(
importUri: uri,
fileUri: fileUri,
packageUri: packageUri,
originImportUri: originImportUri,
packageLanguageVersion: packageLanguageVersion,
origin: origin,
referencesFromIndex: referencesFromIndex,
referenceIsPartOwner: referenceIsPartOwner,
isAugmentation: isAugmentation,
isPatch: isPatch,
mayImplementRestrictedTypes:
target.backendTarget.mayDefineRestrictedType(originImportUri));
if (packageLanguageVersionProblem != null) {
compilationUnit.addPostponedProblem(
packageLanguageVersionProblem, 0, noLength, compilationUnit.fileUri);
}
if (addAsRoot) {
roots.add(uri);
}
_checkForDartCore(uri, compilationUnit);
if (uri.isScheme("dart") && originImportUri.isScheme("dart")) {
// We only read the patch files if the [compilationUnit] is loaded as a
// dart: library (through [uri]) and is considered a dart: library
// (through [originImportUri]).
//
// This is to avoid reading patches and when reading dart: parts, and to
// avoid reading patches of non-dart: libraries that claim to be a part of
// a dart: library.
target.readPatchFiles(compilationUnit, originImportUri);
}
_unparsedLibraries.addLast(compilationUnit);
return compilationUnit;
}
DillLibraryBuilder? _lookupDillLibraryBuilder(Uri uri) {
DillLibraryBuilder? libraryBuilder =
target.dillTarget.loader.lookupLibraryBuilder(uri);
if (libraryBuilder != null) {
_checkForDartCore(uri, libraryBuilder.mainCompilationUnit);
}
return libraryBuilder;
}
void _markDartLibraries(Uri uri, CompilationUnit compilationUnit) {
if (uri.isScheme("dart")) {
if (uri.path == "core") {
_coreLibraryCompilationUnit = compilationUnit;
} else if (uri.path == "typed_data") {
_typedDataLibraryCompilationUnit = compilationUnit;
}
}
}
void _checkForDartCore(Uri uri, CompilationUnit compilationUnit) {
_markDartLibraries(uri, compilationUnit);
// TODO(johnniwinther): If we save the created library in [_builders]
// here, i.e. before calling `target.loadExtraRequiredLibraries` below,
// the order of the libraries change, making `dart:core` come before the
// required arguments. Currently [DillLoader.appendLibrary] one works
// when this is not the case.
if (_coreLibraryCompilationUnit == compilationUnit) {
target.loadExtraRequiredLibraries(this);
}
}
/// Look up a library builder by the [uri], or if such doesn't exist, create
/// one. The canonical URI of the library is [uri], and its actual location is
/// [fileUri].
///
/// Canonical URIs have schemes like "dart", or "package", and the actual
/// location is often a file URI.
///
/// The [accessor] is the library that's trying to import, export, or include
/// as part [uri], and [charOffset] is the location of the corresponding
/// directive. If [accessor] isn't allowed to access [uri], it's a
/// compile-time error.
CompilationUnit read(Uri uri, int charOffset,
{Uri? fileUri,
required CompilationUnit accessor,
Uri? originImportUri,
SourceCompilationUnit? origin,
IndexedLibrary? referencesFromIndex,
bool? referenceIsPartOwner,
bool isAugmentation = false,
bool isPatch = false}) {
CompilationUnit libraryBuilder = _read(uri,
fileUri: fileUri,
originImportUri: originImportUri,
origin: origin,
referencesFromIndex: referencesFromIndex,
referenceIsPartOwner: referenceIsPartOwner,
isAugmentation: isAugmentation,
isPatch: isPatch,
addAsRoot: false);
libraryBuilder.recordAccess(
accessor, charOffset, noLength, accessor.fileUri);
if (!_hasLibraryAccess(imported: uri, importer: accessor.importUri) &&
!accessor.isAugmenting) {
accessor.addProblem(messagePlatformPrivateLibraryAccess, charOffset,
noLength, accessor.fileUri);
}
return libraryBuilder;
}
/// Reads the library [uri] as an entry point. This is used for reading the
/// entry point library of a script or the explicitly mention libraries of
/// a modular or incremental compilation.
///
/// This differs from [read] in that there is no accessor library, meaning
/// that access to platform private libraries cannot be granted.
CompilationUnit readAsEntryPoint(
Uri uri, {
Uri? fileUri,
IndexedLibrary? referencesFromIndex,
}) {
CompilationUnit libraryBuilder = _read(uri,
fileUri: fileUri,
referencesFromIndex: referencesFromIndex,
addAsRoot: true,
isAugmentation: false,
isPatch: false);
// TODO(johnniwinther): Avoid using the first library, if present, as the
// accessor of [libraryBuilder]. Currently the incremental compiler doesn't
// handle errors reported without an accessor, since the messages are not
// associated with a library. This currently has the side effect that
// the first library is the accessor of itself.
CompilationUnit? firstLibrary = rootCompilationUnit;
if (firstLibrary != null) {
libraryBuilder.recordAccess(
firstLibrary, -1, noLength, firstLibrary.fileUri);
}
if (!_hasLibraryAccess(imported: uri, importer: firstLibrary?.importUri)) {
// Coverage-ignore-block(suite): Not run.
if (firstLibrary != null) {
firstLibrary.addProblem(messagePlatformPrivateLibraryAccess, -1,
noLength, firstLibrary.importUri);
} else {
addProblem(messagePlatformPrivateLibraryAccess, -1, noLength, null);
}
}
return libraryBuilder;
}
bool _hasLibraryAccess({required Uri imported, required Uri? importer}) {
if (imported.isScheme("dart") && imported.path.startsWith("_")) {
if (importer == null) {
return false;
} else {
return target.backendTarget
.allowPlatformPrivateLibraryAccess(importer, imported);
}
}
return true;
}
CompilationUnit _read(Uri uri,
{required Uri? fileUri,
Uri? originImportUri,
SourceCompilationUnit? origin,
required IndexedLibrary? referencesFromIndex,
bool? referenceIsPartOwner,
required bool isAugmentation,
required bool isPatch,
required bool addAsRoot}) {
CompilationUnit? compilationUnit = _compilationUnits[uri];
if (compilationUnit == null) {
if (target.dillTarget.isLoaded) {
compilationUnit = _lookupDillLibraryBuilder(uri)?.mainCompilationUnit;
}
if (compilationUnit == null) {
compilationUnit = _createSourceCompilationUnit(
uri: uri,
fileUri: fileUri,
originImportUri: originImportUri,
origin: origin,
referencesFromIndex: referencesFromIndex,
referenceIsPartOwner: referenceIsPartOwner,
isAugmentation: isAugmentation,
isPatch: isPatch,
addAsRoot: addAsRoot);
}
_compilationUnits[uri] = compilationUnit;
}
return compilationUnit;
}
void _ensureCoreLibrary() {
if (_coreLibraryCompilationUnit == null) {
readAsEntryPoint(Uri.parse("dart:core"));
// TODO(askesc): When all backends support set literals, we no longer
// need to index dart:collection, as it is only needed for desugaring of
// const sets. We can remove it from this list at that time.
readAsEntryPoint(Uri.parse("dart:collection"));
assert(_coreLibraryCompilationUnit != null);
}
}
Future<Null> buildBodies(List<SourceLibraryBuilder> libraryBuilders) async {
assert(_coreLibraryCompilationUnit != null);
for (SourceLibraryBuilder library in libraryBuilders) {
currentUriForCrashReporting =
new UriOffset(library.importUri, TreeNode.noOffset);
await buildBody(library);
}
// Workaround: This will return right away but avoid a "semi leak"
// where the latest library is saved in a context somewhere.
await buildBody(null);
currentUriForCrashReporting = null;
logSummary(templateSourceBodySummary);
}
void logSummary(Template<SummaryTemplate> template) {
ticker.log(
// Coverage-ignore(suite): Not run.
(Duration elapsed, Duration sinceStart) {
int libraryCount = 0;
for (CompilationUnit library in compilationUnits) {
if (library.loader == this) {
libraryCount++;
}
}
double ms = elapsed.inMicroseconds / Duration.microsecondsPerMillisecond;
Message message = template.withArguments(
libraryCount, byteCount, ms, byteCount / ms, ms / libraryCount);
print("$sinceStart: ${message.problemMessage}");
});
}
/// Register [message] as a problem with a severity determined by the
/// intrinsic severity of the message.
@override
FormattedMessage? addProblem(
Message message, int charOffset, int length, Uri? fileUri,
{bool wasHandled = false,
List<LocatedMessage>? context,
Severity? severity,
bool problemOnLibrary = false,
List<Uri>? involvedFiles}) {
return addMessage(message, charOffset, length, fileUri, severity,
wasHandled: wasHandled,
context: context,
problemOnLibrary: problemOnLibrary,
involvedFiles: involvedFiles);
}
/// All messages reported by the compiler (errors, warnings, etc.) are routed
/// through this method.
///
/// Returns a FormattedMessage if the message is new, that is, not previously
/// reported. This is important as some parser errors may be reported up to
/// three times by `OutlineBuilder`, `DietListener`, and `BodyBuilder`.
/// If the message is not new, [null] is reported.
///
/// If [severity] is `Severity.error`, the message is added to
/// [handledErrors] if [wasHandled] is true or to [unhandledErrors] if
/// [wasHandled] is false.
FormattedMessage? addMessage(Message message, int charOffset, int length,
Uri? fileUri, Severity? severity,
{bool wasHandled = false,
List<LocatedMessage>? context,
bool problemOnLibrary = false,
List<Uri>? involvedFiles}) {
assert(
fileUri != missingUri, "Message unexpectedly reported on missing uri.");
severity ??= message.code.severity;
if (severity == Severity.ignored) return null;
String trace = """
message: ${message.problemMessage}
charOffset: $charOffset
fileUri: $fileUri
severity: $severity
""";
if (!seenMessages.add(trace)) return null;
if (message.code.severity == Severity.error) {
_hasSeenError = true;
}
if (message.code.severity == Severity.context) {
internalProblem(
templateInternalProblemContextSeverity
.withArguments(message.code.name),
charOffset,
fileUri);
}
target.context.report(
fileUri != null
? message.withLocation(fileUri, charOffset, length)
:
// Coverage-ignore(suite): Not run.
message.withoutLocation(),
severity,
context: context,
involvedFiles: involvedFiles);
if (severity == Severity.error) {
(wasHandled ? handledErrors : unhandledErrors).add(fileUri != null
? message.withLocation(fileUri, charOffset, length)
:
// Coverage-ignore(suite): Not run.
message.withoutLocation());
}
FormattedMessage formattedMessage = target.createFormattedMessage(
message, charOffset, length, fileUri, context, severity,
involvedFiles: involvedFiles);
if (!problemOnLibrary) {
allComponentProblems.add(formattedMessage);
}
return formattedMessage;
}
MemberBuilder getDuplicatedFieldInitializerError() {
return target.getDuplicatedFieldInitializerError(this);
}
MemberBuilder getNativeAnnotation() => target.getNativeAnnotation(this);
void addNativeAnnotation(Annotatable annotatable, String nativeMethodName) {
MemberBuilder constructor = getNativeAnnotation();
Arguments arguments =
new Arguments(<Expression>[new StringLiteral(nativeMethodName)]);
Expression annotation;
if (constructor.isConstructor) {
annotation = new ConstructorInvocation(
constructor.invokeTarget as Constructor, arguments)
..isConst = true;
} else {
// Coverage-ignore-block(suite): Not run.
annotation =
new StaticInvocation(constructor.invokeTarget as Procedure, arguments)
..isConst = true;
}
annotatable.addAnnotation(annotation);
}
BodyBuilder createBodyBuilderForOutlineExpression(
SourceLibraryBuilder libraryBuilder,
BodyBuilderContext bodyBuilderContext,
LookupScope scope,
Uri fileUri,
{LocalScope? formalParameterScope}) {
return new BodyBuilder.forOutlineExpression(
libraryBuilder, bodyBuilderContext, scope, fileUri,
formalParameterScope: formalParameterScope);
}
CoreTypes get coreTypes {
assert(_coreTypes != null, "CoreTypes has not been computed.");
return _coreTypes!;
}
ClassHierarchy get hierarchy => _hierarchy!;
void set hierarchy(ClassHierarchy? value) {
if (_hierarchy != value) {
_hierarchy = value;
_typeEnvironment = null;
}
}
TypeEnvironment get typeEnvironment {
return _typeEnvironment ??= new TypeEnvironment(coreTypes, hierarchy);
}
final InferableTypes inferableTypes = new InferableTypes();
TypeInferenceEngineImpl get typeInferenceEngine => _typeInferenceEngine!;
ClassHierarchyBuilder get hierarchyBuilder => _hierarchyBuilder!;
ClassMembersBuilder get membersBuilder => _membersBuilder!;
Template<SummaryTemplate> get outlineSummaryTemplate =>
templateSourceOutlineSummary;
/// The [SourceCompilationUnit]s for the `dart:` libraries that are not
/// available.
///
/// We special-case the errors for accessing these libraries and report
/// it at the end of [buildOutlines] to ensure that all import paths are
/// part of the error message.
Set<SourceCompilationUnit> _unavailableDartLibraries = {};
Future<Token> tokenize(SourceCompilationUnit compilationUnit,
{bool suppressLexicalErrors = false,
bool allowLazyStrings = true}) async {
target.benchmarker
// Coverage-ignore(suite): Not run.
?.beginSubdivide(BenchmarkSubdivides.tokenize);
Uri fileUri = compilationUnit.fileUri;
// Lookup the file URI in the cache.
Uint8List? bytes = sourceBytes[fileUri];
if (bytes == null) {
// Error recovery.
if (fileUri.isScheme(untranslatableUriScheme)) {
Uri importUri = compilationUnit.importUri;
if (importUri.isScheme('dart')) {
// We report this error later in [buildOutlines].
_unavailableDartLibraries.add(compilationUnit);
} else {
compilationUnit.addProblemAtAccessors(
templateUntranslatableUri.withArguments(importUri));
}
bytes = synthesizeSourceForMissingFile(importUri, null);
} else if (!fileUri.hasScheme) {
// Coverage-ignore-block(suite): Not run.
target.benchmarker?.endSubdivide();
return internalProblem(
templateInternalProblemUriMissingScheme.withArguments(fileUri),
-1,
compilationUnit.importUri);
} else if (fileUri.isScheme(MALFORMED_URI_SCHEME)) {
compilationUnit.addProblemAtAccessors(messageExpectedUri);
bytes = synthesizeSourceForMissingFile(compilationUnit.importUri, null);
}
if (bytes != null) {
sourceBytes[fileUri] = bytes;
}
}
if (bytes == null) {
// If it isn't found in the cache, read the file read from the file
// system.
Uint8List rawBytes;
try {
rawBytes = await fileSystem.entityForUri(fileUri).readAsBytes();
} on FileSystemException catch (e) {
Message message = templateCantReadFile.withArguments(
fileUri, target.context.options.osErrorMessage(e.message));
compilationUnit.addProblemAtAccessors(message);
rawBytes =
synthesizeSourceForMissingFile(compilationUnit.importUri, message);
}
bytes = rawBytes;
sourceBytes[fileUri] = bytes;