forked from dart-lang/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathast.dart
15794 lines (13227 loc) · 460 KB
/
ast.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.
/// -----------------------------------------------------------------------
/// WHEN CHANGING THIS FILE:
/// -----------------------------------------------------------------------
///
/// If you are adding/removing/modifying fields/classes of the AST, you must
/// also update the following files:
///
/// - binary/ast_to_binary.dart
/// - binary/ast_from_binary.dart
/// - text/ast_to_text.dart
/// - clone.dart
/// - binary.md
/// - type_checker.dart (if relevant)
///
/// -----------------------------------------------------------------------
/// ERROR HANDLING
/// -----------------------------------------------------------------------
///
/// As a rule of thumb, errors that can be detected statically are handled by
/// the frontend, typically by translating the erroneous code into a 'throw' or
/// a call to 'noSuchMethod'.
///
/// For example, there are no arity mismatches in static invocations, and
/// there are no direct invocations of a constructor on a abstract class.
///
/// -----------------------------------------------------------------------
/// STATIC vs TOP-LEVEL
/// -----------------------------------------------------------------------
///
/// The term `static` includes both static class members and top-level members.
///
/// "Static class member" is the preferred term for non-top level statics.
///
/// Static class members are not lifted to the library level because mirrors
/// and stack traces can observe that they are class members.
///
/// -----------------------------------------------------------------------
/// PROCEDURES
/// -----------------------------------------------------------------------
///
/// "Procedure" is an umbrella term for method, getter, setter, index-getter,
/// index-setter, operator overloader, and factory constructor.
///
/// Generative constructors, field initializers, local functions are NOT
/// procedures.
///
/// -----------------------------------------------------------------------
/// TRANSFORMATIONS
/// -----------------------------------------------------------------------
///
/// AST transformations can be performed using [TreeNode.replaceWith] or the
/// [Transformer] visitor class.
///
/// Use [Transformer] for bulk transformations that are likely to transform lots
/// of nodes, and [TreeNode.replaceWith] for sparse transformations that mutate
/// relatively few nodes. Or use whichever is more convenient.
///
/// The AST can also be mutated by direct field manipulation, but the user then
/// has to update parent pointers manually.
///
library kernel.ast;
import 'dart:collection' show ListBase;
import 'dart:convert' show utf8;
import 'src/extension_type_erasure.dart';
import 'visitor.dart';
export 'visitor.dart';
import 'canonical_name.dart' show CanonicalName, Reference;
export 'canonical_name.dart' show CanonicalName, Reference;
import 'default_language_version.dart' show defaultLanguageVersion;
export 'default_language_version.dart' show defaultLanguageVersion;
import 'transformations/flags.dart';
import 'text/ast_to_text.dart' as astToText;
import 'core_types.dart';
import 'type_algebra.dart';
import 'type_environment.dart';
import 'src/assumptions.dart';
import 'src/non_null.dart';
import 'src/printer.dart';
import 'src/text_util.dart';
part 'src/ast/patterns.dart';
/// Any type of node in the IR.
abstract class Node {
const Node();
R accept<R>(Visitor<R> v);
R accept1<R, A>(Visitor1<R, A> v, A arg);
void visitChildren(Visitor v);
/// Returns the textual representation of this node for use in debugging.
///
/// [toString] should only be used for debugging, but should not leak.
///
/// The data is generally bare-bones, but can easily be updated for your
/// specific debugging needs.
@override
String toString();
/// Returns the textual representation of this node for use in debugging.
///
/// [toStringInternal] should only be used for debugging, but should not leak.
///
/// The data is generally bare-bones, but can easily be updated for your
/// specific debugging needs.
///
/// This method is called internally by toString methods to create conciser
/// textual representations.
String toStringInternal() => toText(defaultAstTextStrategy);
/// Returns the textual representation of this node for use in debugging.
///
/// Note that this adds some nodes to a static map to ensure consistent
/// naming, but that it thus also leaks memory. [leakingDebugToString] should
/// thus only be used for debugging and short-running test tools.
///
/// Synthetic names are cached globally to retain consistency across different
/// [leakingDebugToString] calls (hence the memory leak).
String leakingDebugToString() => astToText.debugNodeToString(this);
String toText(AstTextStrategy strategy) {
AstPrinter printer = new AstPrinter(strategy);
toTextInternal(printer);
return printer.getText();
}
void toTextInternal(AstPrinter printer);
}
/// A mutable AST node with a parent pointer.
///
/// This is anything other than [Name] and [DartType] nodes.
abstract class TreeNode extends Node {
static int _hashCounter = 0;
@override
final int hashCode = _hashCounter = (_hashCounter + 1) & 0x3fffffff;
static const int noOffset = -1;
TreeNode? parent;
/// Offset in the source file it comes from.
///
/// Valid values are from 0 and up, or -1 ([noOffset]) if the file offset is
/// not available (this is the default if none is specifically set).
int fileOffset = noOffset;
/// Returns List<int> if this node has more offsets than [fileOffset].
List<int>? get fileOffsetsIfMultiple => null;
@override
R accept<R>(TreeVisitor<R> v);
@override
R accept1<R, A>(TreeVisitor1<R, A> v, A arg);
@override
void visitChildren(Visitor v);
void transformChildren(Transformer v);
void transformOrRemoveChildren(RemovingTransformer v);
/// Replaces [child] with [replacement].
///
/// The caller is responsible for ensuring that the AST remains a tree. In
/// particular, [replacement] should be an orphan or be part of an orphaned
/// subtree.
///
/// Has no effect if [child] is not actually a child of this node.
///
/// [replacement] must be non-null.
void replaceChild(TreeNode child, TreeNode replacement) {
transformChildren(new _ChildReplacer(child, replacement));
}
/// Inserts another node in place of this one.
///
/// The caller is responsible for ensuring that the AST remains a tree. In
/// particular, [replacement] should be an orphan or be part of an orphaned
/// subtree.
///
/// [replacement] must be non-null.
void replaceWith(TreeNode replacement) {
parent!.replaceChild(this, replacement);
parent = null;
}
// TODO(johnniwinther): Make this non-nullable.
Component? get enclosingComponent => parent?.enclosingComponent;
/// Returns the best known source location of the given AST node, or `null` if
/// the node is orphaned.
///
/// This getter is intended for diagnostics and debugging, and should be
/// avoided in production code.
Location? get location {
if (fileOffset == noOffset) return parent?.location;
return _getLocationInEnclosingFile(fileOffset);
}
Location? _getLocationInEnclosingFile(int offset) {
return parent?._getLocationInEnclosingFile(offset);
}
}
/// An AST node that can be referenced by other nodes.
///
/// There is a single [reference] belonging to this node, providing a level of
/// indirection that is needed during serialization.
abstract class NamedNode extends TreeNode {
final Reference reference;
NamedNode(Reference? reference)
: this.reference = reference ?? new Reference() {
this.reference.node = this;
}
/// This is an advanced feature.
///
/// See [Component.relink] for a comprehensive description.
///
/// Makes sure the reference in this named node points to itself.
void _relinkNode() {
this.reference.node = this;
}
/// Computes the canonical names for this node using the [parent] as the
/// canonical name of the parent node.
void bindCanonicalNames(CanonicalName parent);
}
abstract class FileUriNode extends TreeNode {
/// The URI of the source file this node was loaded from.
Uri get fileUri;
}
abstract class Annotatable extends TreeNode {
List<Expression> get annotations;
void addAnnotation(Expression node);
}
// ------------------------------------------------------------------------
// LIBRARIES and CLASSES
// ------------------------------------------------------------------------
enum NonNullableByDefaultCompiledMode { Weak, Strong, Agnostic, Invalid }
class Library extends NamedNode
implements Annotatable, Comparable<Library>, FileUriNode {
/// An import path to this library.
///
/// The [Uri] should have the `dart`, `package`, `app`, or `file` scheme.
///
/// If the URI has the `app` scheme, it is relative to the application root.
Uri importUri;
/// The URI of the source file this library was loaded from.
@override
Uri fileUri;
Version? _languageVersion;
Version get languageVersion => _languageVersion ?? defaultLanguageVersion;
void setLanguageVersion(Version languageVersion) {
_languageVersion = languageVersion;
}
static const int SyntheticFlag = 1 << 0;
static const int NonNullableByDefaultFlag = 1 << 1;
static const int NonNullableByDefaultModeBit1 = 1 << 2;
static const int NonNullableByDefaultModeBit2 = 1 << 3;
static const int IsUnsupportedFlag = 1 << 4;
int flags = 0;
/// If true, the library is synthetic, for instance library that doesn't
/// represents an actual file and is created as the result of error recovery.
bool get isSynthetic => flags & SyntheticFlag != 0;
void set isSynthetic(bool value) {
flags = value ? (flags | SyntheticFlag) : (flags & ~SyntheticFlag);
}
bool get isNonNullableByDefault => (flags & NonNullableByDefaultFlag) != 0;
void set isNonNullableByDefault(bool value) {
flags = value
? (flags | NonNullableByDefaultFlag)
: (flags & ~NonNullableByDefaultFlag);
}
NonNullableByDefaultCompiledMode get nonNullableByDefaultCompiledMode {
bool bit1 = (flags & NonNullableByDefaultModeBit1) != 0;
bool bit2 = (flags & NonNullableByDefaultModeBit2) != 0;
if (!bit1 && !bit2) return NonNullableByDefaultCompiledMode.Weak;
if (bit1 && !bit2) return NonNullableByDefaultCompiledMode.Strong;
if (bit1 && bit2) return NonNullableByDefaultCompiledMode.Agnostic;
if (!bit1 && bit2) return NonNullableByDefaultCompiledMode.Invalid;
throw new StateError("Unused bit-pattern for compilation mode");
}
void set nonNullableByDefaultCompiledMode(
NonNullableByDefaultCompiledMode mode) {
switch (mode) {
case NonNullableByDefaultCompiledMode.Weak:
flags = (flags & ~NonNullableByDefaultModeBit1) &
~NonNullableByDefaultModeBit2;
break;
case NonNullableByDefaultCompiledMode.Strong:
flags = (flags | NonNullableByDefaultModeBit1) &
~NonNullableByDefaultModeBit2;
break;
case NonNullableByDefaultCompiledMode.Agnostic:
flags = (flags | NonNullableByDefaultModeBit1) |
NonNullableByDefaultModeBit2;
break;
case NonNullableByDefaultCompiledMode.Invalid:
flags = (flags & ~NonNullableByDefaultModeBit1) |
NonNullableByDefaultModeBit2;
break;
}
}
/// If true, the library is not supported through the 'dart.library.*' value
/// used in conditional imports and `bool.fromEnvironment` constants.
bool get isUnsupported => flags & IsUnsupportedFlag != 0;
void set isUnsupported(bool value) {
flags = value ? (flags | IsUnsupportedFlag) : (flags & ~IsUnsupportedFlag);
}
String? name;
/// Problems in this [Library] encoded as json objects.
///
/// Note that this field can be null, and by convention should be null if the
/// list is empty.
List<String>? problemsAsJson;
@override
List<Expression> annotations;
List<LibraryDependency> dependencies;
/// References to nodes exported by `export` declarations that:
/// - aren't ambiguous, or
/// - aren't hidden by local declarations.
final List<Reference> additionalExports = <Reference>[];
@informative
List<LibraryPart> parts;
List<Typedef> _typedefs;
List<Class> _classes;
List<Extension> _extensions;
List<ExtensionTypeDeclaration> _extensionTypeDeclarations;
List<Procedure> _procedures;
List<Field> _fields;
Library(this.importUri,
{this.name,
List<Expression>? annotations,
List<LibraryDependency>? dependencies,
List<LibraryPart>? parts,
List<Typedef>? typedefs,
List<Class>? classes,
List<Extension>? extensions,
List<ExtensionTypeDeclaration>? extensionTypeDeclarations,
List<Procedure>? procedures,
List<Field>? fields,
required this.fileUri,
Reference? reference})
: this.annotations = annotations ?? <Expression>[],
this.dependencies = dependencies ?? <LibraryDependency>[],
this.parts = parts ?? <LibraryPart>[],
this._typedefs = typedefs ?? <Typedef>[],
this._classes = classes ?? <Class>[],
this._extensions = extensions ?? <Extension>[],
this._extensionTypeDeclarations =
extensionTypeDeclarations ?? <ExtensionTypeDeclaration>[],
this._procedures = procedures ?? <Procedure>[],
this._fields = fields ?? <Field>[],
super(reference) {
setParents(this.dependencies, this);
setParents(this.parts, this);
setParents(this._typedefs, this);
setParents(this._classes, this);
setParents(this._extensions, this);
setParents(this._procedures, this);
setParents(this._fields, this);
}
List<Typedef> get typedefs => _typedefs;
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding typedefs when reading the dill file.
void set typedefsInternal(List<Typedef> typedefs) {
_typedefs = typedefs;
}
List<Class> get classes => _classes;
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding classes when reading the dill file.
void set classesInternal(List<Class> classes) {
_classes = classes;
}
List<Extension> get extensions => _extensions;
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding extensions when reading the dill file.
void set extensionsInternal(List<Extension> extensions) {
_extensions = extensions;
}
List<ExtensionTypeDeclaration> get extensionTypeDeclarations =>
_extensionTypeDeclarations;
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding extension type declarations when reading the dill file.
void set extensionTypeDeclarationsInternal(
List<ExtensionTypeDeclaration> extensionTypeDeclarations) {
_extensionTypeDeclarations = extensionTypeDeclarations;
}
List<Procedure> get procedures => _procedures;
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding procedures when reading the dill file.
void set proceduresInternal(List<Procedure> procedures) {
_procedures = procedures;
}
List<Field> get fields => _fields;
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding fields when reading the dill file.
void set fieldsInternal(List<Field> fields) {
_fields = fields;
}
Nullability get nullable {
return isNonNullableByDefault ? Nullability.nullable : Nullability.legacy;
}
Nullability get nonNullable {
return isNonNullableByDefault
? Nullability.nonNullable
: Nullability.legacy;
}
Nullability nullableIfTrue(bool isNullable) {
if (isNonNullableByDefault) {
return isNullable ? Nullability.nullable : Nullability.nonNullable;
}
return Nullability.legacy;
}
/// Returns the top-level fields and procedures defined in this library.
///
/// This getter is for convenience, not efficiency. Consider manually
/// iterating the members to speed up code in production.
Iterable<Member> get members =>
<Iterable<Member>>[fields, procedures].expand((x) => x);
@override
void addAnnotation(Expression node) {
node.parent = this;
annotations.add(node);
}
void addClass(Class class_) {
class_.parent = this;
classes.add(class_);
}
void addExtension(Extension extension) {
extension.parent = this;
extensions.add(extension);
}
void addExtensionTypeDeclaration(
ExtensionTypeDeclaration extensionTypeDeclaration) {
extensionTypeDeclaration.parent = this;
extensionTypeDeclarations.add(extensionTypeDeclaration);
}
void addField(Field field) {
field.parent = this;
fields.add(field);
}
void addProcedure(Procedure procedure) {
procedure.parent = this;
procedures.add(procedure);
}
void addTypedef(Typedef typedef_) {
typedef_.parent = this;
typedefs.add(typedef_);
}
@override
CanonicalName bindCanonicalNames(CanonicalName parent) {
return parent.getChildFromUri(importUri)..bindTo(reference);
}
/// Computes the canonical name for this library and all its members.
void ensureCanonicalNames(CanonicalName parent) {
CanonicalName canonicalName = bindCanonicalNames(parent);
for (int i = 0; i < typedefs.length; ++i) {
typedefs[i].bindCanonicalNames(canonicalName);
}
for (int i = 0; i < fields.length; ++i) {
fields[i].bindCanonicalNames(canonicalName);
}
for (int i = 0; i < procedures.length; ++i) {
procedures[i].bindCanonicalNames(canonicalName);
}
for (int i = 0; i < classes.length; ++i) {
classes[i].ensureCanonicalNames(canonicalName);
}
for (int i = 0; i < extensions.length; ++i) {
extensions[i].bindCanonicalNames(canonicalName);
}
for (int i = 0; i < extensionTypeDeclarations.length; ++i) {
extensionTypeDeclarations[i].ensureCanonicalNames(canonicalName);
}
}
/// This is an advanced feature. Use of this method should be coordinated
/// with the kernel team.
///
/// See [Component.relink] for a comprehensive description.
///
/// Makes sure all references in named nodes in this library points to said
/// named node.
void relink() {
_relinkNode();
for (int i = 0; i < typedefs.length; ++i) {
Typedef typedef_ = typedefs[i];
typedef_._relinkNode();
}
for (int i = 0; i < fields.length; ++i) {
Field field = fields[i];
field._relinkNode();
}
for (int i = 0; i < procedures.length; ++i) {
Procedure member = procedures[i];
member._relinkNode();
}
for (int i = 0; i < classes.length; ++i) {
Class class_ = classes[i];
class_.relink();
}
for (int i = 0; i < extensions.length; ++i) {
Extension extension = extensions[i];
extension._relinkNode();
}
for (int i = 0; i < extensionTypeDeclarations.length; ++i) {
ExtensionTypeDeclaration extensionTypeDeclaration =
extensionTypeDeclarations[i];
extensionTypeDeclaration._relinkNode();
}
}
void addDependency(LibraryDependency node) {
dependencies.add(node..parent = this);
}
void addPart(LibraryPart node) {
parts.add(node..parent = this);
}
@override
R accept<R>(TreeVisitor<R> v) => v.visitLibrary(this);
@override
R accept1<R, A>(TreeVisitor1<R, A> v, A arg) => v.visitLibrary(this, arg);
@override
void visitChildren(Visitor v) {
visitList(annotations, v);
visitList(dependencies, v);
visitList(parts, v);
visitList(typedefs, v);
visitList(classes, v);
visitList(extensions, v);
visitList(extensionTypeDeclarations, v);
visitList(procedures, v);
visitList(fields, v);
}
@override
void transformChildren(Transformer v) {
v.transformList(annotations, this);
v.transformList(dependencies, this);
v.transformList(parts, this);
v.transformList(typedefs, this);
v.transformList(classes, this);
v.transformList(extensions, this);
v.transformList(extensionTypeDeclarations, this);
v.transformList(procedures, this);
v.transformList(fields, this);
}
@override
void transformOrRemoveChildren(RemovingTransformer v) {
v.transformExpressionList(annotations, this);
v.transformLibraryDependencyList(dependencies, this);
v.transformLibraryPartList(parts, this);
v.transformTypedefList(typedefs, this);
v.transformClassList(classes, this);
v.transformExtensionList(extensions, this);
v.transformExtensionTypeDeclarationList(extensionTypeDeclarations, this);
v.transformProcedureList(procedures, this);
v.transformFieldList(fields, this);
}
static int _libraryIdCounter = 0;
int _libraryId = ++_libraryIdCounter;
int get libraryIdForTesting => _libraryId;
@override
int compareTo(Library other) => _libraryId - other._libraryId;
/// Returns a possibly synthesized name for this library, consistent with
/// the names across all [toString] calls.
@override
String toString() => libraryNameToString(this);
@override
void toTextInternal(AstPrinter printer) {
printer.write(libraryNameToString(this));
}
@override
Location? _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
@override
String leakingDebugToString() => astToText.debugLibraryToString(this);
}
/// An import or export declaration in a library.
///
/// It can represent any of the following forms,
///
/// import <url>;
/// import <url> as <name>;
/// import <url> deferred as <name>;
/// export <url>;
///
/// optionally with metadata and [Combinators].
class LibraryDependency extends TreeNode implements Annotatable {
int flags;
@override
final List<Expression> annotations;
Reference importedLibraryReference;
/// The name of the import prefix, if any, or `null` if this is not an import
/// with a prefix.
///
/// Must be non-null for deferred imports, and must be null for exports.
String? name;
final List<Combinator> combinators;
LibraryDependency(int flags, List<Expression> annotations,
Library importedLibrary, String name, List<Combinator> combinators)
: this.byReference(
flags, annotations, importedLibrary.reference, name, combinators);
LibraryDependency.deferredImport(Library importedLibrary, String name,
{List<Combinator>? combinators, List<Expression>? annotations})
: this.byReference(DeferredFlag, annotations ?? <Expression>[],
importedLibrary.reference, name, combinators ?? <Combinator>[]);
LibraryDependency.import(Library importedLibrary,
{String? name,
List<Combinator>? combinators,
List<Expression>? annotations})
: this.byReference(0, annotations ?? <Expression>[],
importedLibrary.reference, name, combinators ?? <Combinator>[]);
LibraryDependency.export(Library importedLibrary,
{List<Combinator>? combinators, List<Expression>? annotations})
: this.byReference(ExportFlag, annotations ?? <Expression>[],
importedLibrary.reference, null, combinators ?? <Combinator>[]);
LibraryDependency.byReference(this.flags, this.annotations,
this.importedLibraryReference, this.name, this.combinators) {
setParents(annotations, this);
setParents(combinators, this);
}
Library get enclosingLibrary => parent as Library;
Library get targetLibrary => importedLibraryReference.asLibrary;
static const int ExportFlag = 1 << 0;
static const int DeferredFlag = 1 << 1;
bool get isExport => flags & ExportFlag != 0;
bool get isImport => !isExport;
bool get isDeferred => flags & DeferredFlag != 0;
@override
void addAnnotation(Expression annotation) {
annotations.add(annotation..parent = this);
}
@override
R accept<R>(TreeVisitor<R> v) => v.visitLibraryDependency(this);
@override
R accept1<R, A>(TreeVisitor1<R, A> v, A arg) =>
v.visitLibraryDependency(this, arg);
@override
void visitChildren(Visitor v) {
visitList(annotations, v);
visitList(combinators, v);
}
@override
void transformChildren(Transformer v) {
v.transformList(annotations, this);
v.transformList(combinators, this);
}
@override
void transformOrRemoveChildren(RemovingTransformer v) {
v.transformExpressionList(annotations, this);
v.transformCombinatorList(combinators, this);
}
@override
String toString() {
return "LibraryDependency(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
/// A part declaration in a library.
///
/// part <url>;
///
/// optionally with metadata.
class LibraryPart extends TreeNode implements Annotatable {
@override
final List<Expression> annotations;
final String partUri;
LibraryPart(this.annotations, this.partUri) {
setParents(annotations, this);
}
@override
void addAnnotation(Expression annotation) {
annotations.add(annotation..parent = this);
}
@override
R accept<R>(TreeVisitor<R> v) => v.visitLibraryPart(this);
@override
R accept1<R, A>(TreeVisitor1<R, A> v, A arg) => v.visitLibraryPart(this, arg);
@override
void visitChildren(Visitor v) {
visitList(annotations, v);
}
@override
void transformChildren(Transformer v) {
v.transformList(annotations, this);
}
@override
void transformOrRemoveChildren(RemovingTransformer v) {
v.transformExpressionList(annotations, this);
}
@override
String toString() {
return "LibraryPart(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
/// A `show` or `hide` clause for an import or export.
class Combinator extends TreeNode {
bool isShow;
final List<String> names;
LibraryDependency get dependency => parent as LibraryDependency;
Combinator(this.isShow, this.names);
Combinator.show(this.names) : isShow = true;
Combinator.hide(this.names) : isShow = false;
bool get isHide => !isShow;
@override
R accept<R>(TreeVisitor<R> v) => v.visitCombinator(this);
@override
R accept1<R, A>(TreeVisitor1<R, A> v, A arg) => v.visitCombinator(this, arg);
@override
void visitChildren(Visitor v) {}
@override
void transformChildren(Transformer v) {}
@override
void transformOrRemoveChildren(RemovingTransformer v) {}
@override
String toString() {
return "Combinator(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
/// Declaration of a type alias.
class Typedef extends NamedNode
implements FileUriNode, Annotatable, GenericDeclaration {
/// The URI of the source file that contains the declaration of this typedef.
@override
Uri fileUri;
@override
List<Expression> annotations = const <Expression>[];
String name;
@override
final List<TypeParameter> typeParameters;
// TODO(johnniwinther): Make this non-nullable.
DartType? type;
Typedef(this.name, this.type,
{Reference? reference,
required this.fileUri,
List<TypeParameter>? typeParameters,
List<TypeParameter>? typeParametersOfFunctionType,
List<VariableDeclaration>? positionalParameters,
List<VariableDeclaration>? namedParameters})
: this.typeParameters = typeParameters ?? <TypeParameter>[],
super(reference) {
setParents(this.typeParameters, this);
}
@override
void bindCanonicalNames(CanonicalName parent) {
parent.getChildFromTypedef(this).bindTo(reference);
}
Library get enclosingLibrary => parent as Library;
@override
R accept<R>(TreeVisitor<R> v) => v.visitTypedef(this);
@override
R accept1<R, A>(TreeVisitor1<R, A> v, A arg) => v.visitTypedef(this, arg);
@override
void visitChildren(Visitor v) {
visitList(annotations, v);
visitList(typeParameters, v);
type?.accept(v);
}
@override
void transformChildren(Transformer v) {
v.transformList(annotations, this);
v.transformList(typeParameters, this);
if (type != null) {
type = v.visitDartType(type!);
}
}
@override
void transformOrRemoveChildren(RemovingTransformer v) {
v.transformExpressionList(annotations, this);
v.transformTypeParameterList(typeParameters, this);
if (type != null) {
DartType newType = v.visitDartType(type!, dummyDartType);
if (identical(newType, dummyDartType)) {
type = null;
} else {
type = newType;
}
}
}
@override
void addAnnotation(Expression node) {
if (annotations.isEmpty) {
annotations = <Expression>[];
}
annotations.add(node);
node.parent = this;
}
@override
Location? _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
@override
String toString() {
return "Typedef(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
printer.writeTypedefName(reference);
}
}
/// List-wrapper that marks the parent-class as dirty if the list is modified.
///
/// The idea being, that for non-dirty classes (classes just loaded from dill)
/// the canonical names has already been calculated, and recalculating them is
/// not needed. If, however, we change anything, recalculation of the canonical
/// names can be needed.
class DirtifyingList<E> extends ListBase<E> {
final Class dirtifyClass;
final List<E> wrapped;
DirtifyingList(this.dirtifyClass, this.wrapped);
@override
int get length {
return wrapped.length;
}
@override
void set length(int length) {
dirtifyClass.dirty = true;
wrapped.length = length;
}
@override
E operator [](int index) {
return wrapped[index];
}
@override
void operator []=(int index, E value) {
dirtifyClass.dirty = true;
wrapped[index] = value;
}
}
/// Declaration that can introduce [TypeParameter]s.
sealed class GenericDeclaration implements TreeNode {
/// The type parameters introduced by this declaration.
List<TypeParameter> get typeParameters;
}
/// Functions that can introduce [TypeParameter]s.
sealed class GenericFunction implements GenericDeclaration {
/// The [FunctionNode] that holds the introduced [typeParameters].
FunctionNode get function;
}
/// Common interface for [Class] and [ExtensionTypeDeclaration].
sealed class TypeDeclaration
implements Annotatable, FileUriNode, GenericDeclaration {
/// The name of the declaration.