blob: 6a70b35a20f8382d1228122f8cf796dc74a5fa5e [file] [log] [blame]
// 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 'visitor.dart';
export 'visitor.dart';
import 'canonical_name.dart' show CanonicalName;
export 'canonical_name.dart' show CanonicalName;
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/printer.dart';
import 'src/text_util.dart';
/// Any type of node in the IR.
abstract class Node {
const Node();
R accept<R>(Visitor<R> v);
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.
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;
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;
R accept<R>(TreeVisitor<R> v);
void visitChildren(Visitor v);
void transformChildren(Transformer 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.
///
/// If [replacement] is `null`, this will [remove] the [child] node.
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.
///
/// If [replacement] is `null`, this will [remove] the node.
void replaceWith(TreeNode replacement) {
parent.replaceChild(this, replacement);
parent = null;
}
/// Removes this node from the [List] it is currently stored in, or assigns
/// `null` to the field on the parent currently pointing to the node.
///
/// Has no effect if the node is orphaned or if the parent pointer is stale.
void remove() {
parent?.replaceChild(this, null);
parent = null;
}
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;
}
CanonicalName get canonicalName => reference?.canonicalName;
/// 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;
}
}
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);
}
/// Indirection between a reference and its definition.
///
/// There is only one reference object per [NamedNode].
class Reference {
CanonicalName canonicalName;
NamedNode _node;
NamedNode get node {
if (_node == null) {
// Either this is an unbound reference or it belongs to a lazy-loaded
// (and not yet loaded) class. If it belongs to a lazy-loaded class,
// load the class.
CanonicalName canonicalNameParent = canonicalName?.parent;
while (canonicalNameParent != null) {
if (canonicalNameParent.name.startsWith("@")) {
break;
}
canonicalNameParent = canonicalNameParent.parent;
}
if (canonicalNameParent != null) {
NamedNode parentNamedNode =
canonicalNameParent?.parent?.reference?._node;
if (parentNamedNode is Class) {
Class parentClass = parentNamedNode;
if (parentClass.lazyBuilder != null) {
parentClass.ensureLoaded();
}
}
}
}
return _node;
}
void set node(NamedNode node) {
_node = node;
}
String toString() {
return "Reference to ${toStringInternal()}";
}
String toStringInternal() {
if (canonicalName != null) {
return '${canonicalName.toStringInternal()}';
}
if (node != null) {
return node.toStringInternal();
}
return 'Unbound reference';
}
Library get asLibrary {
if (node == null) {
throw '$this is not bound to an AST node. A library was expected';
}
return node as Library;
}
Class get asClass {
if (node == null) {
throw '$this is not bound to an AST node. A class was expected';
}
return node as Class;
}
Member get asMember {
if (node == null) {
throw '$this is not bound to an AST node. A member was expected';
}
return node as Member;
}
Field get asField {
if (node == null) {
throw '$this is not bound to an AST node. A field was expected';
}
return node as Field;
}
Constructor get asConstructor {
if (node == null) {
throw '$this is not bound to an AST node. A constructor was expected';
}
return node as Constructor;
}
Procedure get asProcedure {
if (node == null) {
throw '$this is not bound to an AST node. A procedure was expected';
}
return node as Procedure;
}
Typedef get asTypedef {
if (node == null) {
throw '$this is not bound to an AST node. A typedef was expected';
}
return node as Typedef;
}
}
// ------------------------------------------------------------------------
// LIBRARIES and CLASSES
// ------------------------------------------------------------------------
enum NonNullableByDefaultCompiledMode { Disabled, Weak, Strong, Agnostic }
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.
Uri fileUri;
Version _languageVersion;
Version get languageVersion => _languageVersion ?? defaultLanguageVersion;
void setLanguageVersion(Version languageVersion) {
if (languageVersion == null) {
throw new StateError("Trying to set language version 'null'");
}
_languageVersion = languageVersion;
}
static const int SyntheticFlag = 1 << 1;
static const int NonNullableByDefaultFlag = 1 << 2;
static const int NonNullableByDefaultModeBit1Weak = 1 << 3;
static const int NonNullableByDefaultModeBit2Strong = 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 weak = (flags & NonNullableByDefaultModeBit1Weak) != 0;
bool strong = (flags & NonNullableByDefaultModeBit2Strong) != 0;
if (weak && strong) return NonNullableByDefaultCompiledMode.Agnostic;
if (strong) return NonNullableByDefaultCompiledMode.Strong;
if (weak) return NonNullableByDefaultCompiledMode.Weak;
return NonNullableByDefaultCompiledMode.Disabled;
}
void set nonNullableByDefaultCompiledMode(
NonNullableByDefaultCompiledMode mode) {
switch (mode) {
case NonNullableByDefaultCompiledMode.Disabled:
flags = (flags & ~NonNullableByDefaultModeBit1Weak) &
~NonNullableByDefaultModeBit2Strong;
break;
case NonNullableByDefaultCompiledMode.Weak:
flags = (flags | NonNullableByDefaultModeBit1Weak) &
~NonNullableByDefaultModeBit2Strong;
break;
case NonNullableByDefaultCompiledMode.Strong:
flags = (flags & ~NonNullableByDefaultModeBit1Weak) |
NonNullableByDefaultModeBit2Strong;
break;
case NonNullableByDefaultCompiledMode.Agnostic:
flags = (flags | NonNullableByDefaultModeBit1Weak) |
NonNullableByDefaultModeBit2Strong;
break;
}
}
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;
final List<Expression> annotations;
final 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
final List<LibraryPart> parts;
final List<Typedef> typedefs;
final List<Class> classes;
final List<Extension> extensions;
final List<Procedure> procedures;
final 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<Procedure> procedures,
List<Field> fields,
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.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);
}
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);
void addMember(Member member) {
member.parent = this;
if (member is Procedure) {
procedures.add(member);
} else if (member is Field) {
fields.add(member);
} else {
throw new ArgumentError(member);
}
}
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 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_);
}
void computeCanonicalNames() {
assert(canonicalName != null);
for (int i = 0; i < typedefs.length; ++i) {
Typedef typedef_ = typedefs[i];
canonicalName.getChildFromTypedef(typedef_).bindTo(typedef_.reference);
}
for (int i = 0; i < fields.length; ++i) {
Field field = fields[i];
canonicalName.getChildFromMember(field).bindTo(field.reference);
}
for (int i = 0; i < procedures.length; ++i) {
Procedure member = procedures[i];
canonicalName.getChildFromMember(member).bindTo(member.reference);
}
for (int i = 0; i < classes.length; ++i) {
Class class_ = classes[i];
canonicalName.getChild(class_.name).bindTo(class_.reference);
class_.computeCanonicalNames();
}
for (int i = 0; i < extensions.length; ++i) {
Extension extension = extensions[i];
canonicalName.getChild(extension.name).bindTo(extension.reference);
}
}
/// 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();
}
}
void addDependency(LibraryDependency node) {
dependencies.add(node..parent = this);
}
void addPart(LibraryPart node) {
parts.add(node..parent = this);
}
R accept<R>(TreeVisitor<R> v) => v.visitLibrary(this);
visitChildren(Visitor v) {
visitList(annotations, v);
visitList(dependencies, v);
visitList(parts, v);
visitList(typedefs, v);
visitList(classes, v);
visitList(extensions, v);
visitList(procedures, v);
visitList(fields, v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
transformList(dependencies, v, this);
transformList(parts, v, this);
transformList(typedefs, v, this);
transformList(classes, v, this);
transformList(extensions, v, this);
transformList(procedures, v, this);
transformList(fields, v, this);
}
static int _libraryIdCounter = 0;
int _libraryId = ++_libraryIdCounter;
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));
}
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
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 {
int flags;
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;
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;
void addAnnotation(Expression annotation) {
annotations.add(annotation..parent = this);
}
R accept<R>(TreeVisitor<R> v) => v.visitLibraryDependency(this);
visitChildren(Visitor v) {
visitList(annotations, v);
visitList(combinators, v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
transformList(combinators, v, 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 {
final List<Expression> annotations;
final String partUri;
LibraryPart(this.annotations, this.partUri) {
setParents(annotations, this);
}
void addAnnotation(Expression annotation) {
annotations.add(annotation..parent = this);
}
R accept<R>(TreeVisitor<R> v) => v.visitLibraryPart(this);
visitChildren(Visitor v) {
visitList(annotations, v);
}
transformChildren(Transformer v) {
transformList(annotations, v, 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;
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
visitChildren(Visitor v) {}
@override
transformChildren(Transformer 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 {
/// The URI of the source file that contains the declaration of this typedef.
Uri fileUri;
List<Expression> annotations = const <Expression>[];
String name;
final List<TypeParameter> typeParameters;
DartType type;
// The following two fields describe parameters of the underlying type when
// that is a function type. They are needed to keep such attributes as names
// and annotations. When the underlying type is not a function type, they are
// empty.
final List<TypeParameter> typeParametersOfFunctionType;
final List<VariableDeclaration> positionalParameters;
final List<VariableDeclaration> namedParameters;
Typedef(this.name, this.type,
{Reference reference,
this.fileUri,
List<TypeParameter> typeParameters,
List<TypeParameter> typeParametersOfFunctionType,
List<VariableDeclaration> positionalParameters,
List<VariableDeclaration> namedParameters})
: this.typeParameters = typeParameters ?? <TypeParameter>[],
this.typeParametersOfFunctionType =
typeParametersOfFunctionType ?? <TypeParameter>[],
this.positionalParameters =
positionalParameters ?? <VariableDeclaration>[],
this.namedParameters = namedParameters ?? <VariableDeclaration>[],
super(reference) {
setParents(this.typeParameters, this);
}
Library get enclosingLibrary => parent;
R accept<R>(TreeVisitor<R> v) {
return v.visitTypedef(this);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
transformList(typeParameters, v, this);
if (type != null) {
type = v.visitDartType(type);
}
}
visitChildren(Visitor v) {
visitList(annotations, v);
visitList(typeParameters, v);
type?.accept(v);
}
void addAnnotation(Expression node) {
if (annotations.isEmpty) {
annotations = <Expression>[];
}
annotations.add(node);
node.parent = this;
}
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
@override
String toString() {
return "Typedef(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
printer.writeTypedefName(reference);
}
}
/// The degree to which the contents of a class have been loaded into memory.
///
/// Each level imply the requirements of the previous ones.
enum ClassLevel {
/// Temporary loading level for internal use by IR producers. Consumers of
/// kernel code should not expect to see classes at this level.
Temporary,
/// The class may be used as a type, and it may contain members that are
/// referenced from this build unit.
///
/// The type parameters and their bounds are present.
///
/// There is no guarantee that all members are present.
///
/// All supertypes of this class are at [Type] level or higher.
Type,
/// All instance members of the class are present.
///
/// All supertypes of this class are at [Hierarchy] level or higher.
///
/// This level exists so supertypes of a fully loaded class contain all the
/// members needed to detect override constraints.
Hierarchy,
/// All instance members of the class have their body loaded, and their
/// annotations are present.
///
/// All supertypes of this class are at [Hierarchy] level or higher.
///
/// If this class is a mixin application, then its mixin is loaded at [Mixin]
/// level or higher.
///
/// This level exists so the contents of a mixin can be cloned into a
/// mixin application.
Mixin,
/// All members of the class are fully loaded and are in the correct order.
///
/// Annotations are present on classes and members.
///
/// All supertypes of this class are at [Hierarchy] level or higher,
/// not necessarily at [Body] level.
Body,
}
/// 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 of a regular class or a mixin application.
///
/// Mixin applications may not contain fields or procedures, as they implicitly
/// use those from its mixed-in type. However, the IR does not enforce this
/// rule directly, as doing so can obstruct transformations. It is possible to
/// transform a mixin application to become a regular class, and vice versa.
class Class extends NamedNode implements Annotatable, FileUriNode {
/// Start offset of the class in the source file it comes from.
///
/// Note that this includes annotations if any.
///
/// Valid values are from 0 and up, or -1 ([TreeNode.noOffset]) if the file
/// start offset is not available (this is the default if none is specifically
/// set).
int startFileOffset = TreeNode.noOffset;
/// End offset in the source file it comes from. Valid values are from 0 and
/// up, or -1 ([TreeNode.noOffset]) if the file end offset is not available
/// (this is the default if none is specifically set).
int fileEndOffset = TreeNode.noOffset;
/// The degree to which the contents of the class have been loaded.
ClassLevel level = ClassLevel.Body;
/// List of metadata annotations on the class.
///
/// This defaults to an immutable empty list. Use [addAnnotation] to add
/// annotations if needed.
List<Expression> annotations = const <Expression>[];
/// Name of the class.
///
/// Must be non-null and must be unique within the library.
///
/// The name may contain characters that are not valid in a Dart identifier,
/// in particular, the symbol '&' is used in class names generated for mixin
/// applications.
String name;
// Must match serialized bit positions.
static const int LevelMask = 0x3; // Bits 0 and 1.
static const int FlagAbstract = 1 << 2;
static const int FlagEnum = 1 << 3;
static const int FlagAnonymousMixin = 1 << 4;
static const int FlagEliminatedMixin = 1 << 5;
static const int FlagMixinDeclaration = 1 << 6;
static const int FlagHasConstConstructor = 1 << 7;
int flags = 0;
bool get isAbstract => flags & FlagAbstract != 0;
void set isAbstract(bool value) {
flags = value ? (flags | FlagAbstract) : (flags & ~FlagAbstract);
}
/// Whether this class is an enum.
bool get isEnum => flags & FlagEnum != 0;
void set isEnum(bool value) {
flags = value ? (flags | FlagEnum) : (flags & ~FlagEnum);
}
/// Whether this class is a synthetic implementation created for each
/// mixed-in class. For example the following code:
/// class Z extends A with B, C, D {}
/// class A {}
/// class B {}
/// class C {}
/// class D {}
/// ...creates:
/// abstract class _Z&A&B extends A mixedIn B {}
/// abstract class _Z&A&B&C extends A&B mixedIn C {}
/// abstract class _Z&A&B&C&D extends A&B&C mixedIn D {}
/// class Z extends _Z&A&B&C&D {}
/// All X&Y classes are marked as synthetic.
bool get isAnonymousMixin => flags & FlagAnonymousMixin != 0;
void set isAnonymousMixin(bool value) {
flags =
value ? (flags | FlagAnonymousMixin) : (flags & ~FlagAnonymousMixin);
}
/// Whether this class was transformed from a mixin application.
/// In such case, its mixed-in type was pulled into the end of implemented
/// types list.
bool get isEliminatedMixin => flags & FlagEliminatedMixin != 0;
void set isEliminatedMixin(bool value) {
flags =
value ? (flags | FlagEliminatedMixin) : (flags & ~FlagEliminatedMixin);
}
/// True if this class was a mixin declaration in Dart.
///
/// Mixins are declared in Dart with the `mixin` keyword. They are compiled
/// to Kernel classes.
bool get isMixinDeclaration => flags & FlagMixinDeclaration != 0;
void set isMixinDeclaration(bool value) {
flags = value
? (flags | FlagMixinDeclaration)
: (flags & ~FlagMixinDeclaration);
}
/// True if this class declares one or more constant constructors.
bool get hasConstConstructor => flags & FlagHasConstConstructor != 0;
void set hasConstConstructor(bool value) {
flags = value
? (flags | FlagHasConstConstructor)
: (flags & ~FlagHasConstConstructor);
}
List<Supertype> superclassConstraints() {
var constraints = <Supertype>[];
// Not a mixin declaration.
if (!isMixinDeclaration) return constraints;
// Otherwise we have a left-linear binary tree (subtrees are supertype and
// mixedInType) of constraints, where all the interior nodes are anonymous
// mixin applications.
Supertype current = supertype;
while (current != null && current.classNode.isAnonymousMixin) {
Class currentClass = current.classNode;
assert(currentClass.implementedTypes.length == 2);
Substitution substitution = Substitution.fromSupertype(current);
constraints.add(
substitution.substituteSupertype(currentClass.implementedTypes[1]));
current =
substitution.substituteSupertype(currentClass.implementedTypes[0]);
}
return constraints..add(current);
}
/// The URI of the source file this class was loaded from.
Uri fileUri;
final List<TypeParameter> typeParameters;
/// The immediate super type, or `null` if this is the root class.
Supertype supertype;
/// The mixed-in type if this is a mixin application, otherwise `null`.
Supertype mixedInType;
/// The types from the `implements` clause.
final List<Supertype> implementedTypes;
/// Internal. Should *ONLY* be used from within kernel.
///
/// If non-null, the function that will have to be called to fill-out the
/// content of this class. Note that this should not be called directly
/// though.
void Function() lazyBuilder;
/// Makes sure the class is loaded, i.e. the fields, procedures etc have been
/// loaded from the dill. Generally, one should not need to call this as it is
/// done automatically when accessing the lists.
void ensureLoaded() {
if (lazyBuilder != null) {
var lazyBuilderLocal = lazyBuilder;
lazyBuilder = null;
lazyBuilderLocal();
}
}
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding fields when reading the dill file.
final List<Field> fieldsInternal;
DirtifyingList<Field> _fieldsView;
/// Fields declared in the class.
///
/// For mixin applications this should be empty.
List<Field> get fields {
ensureLoaded();
// If already dirty the caller just might as well add stuff directly too.
if (dirty) return fieldsInternal;
_fieldsView ??= new DirtifyingList(this, fieldsInternal);
return _fieldsView;
}
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding constructors when reading the dill file.
final List<Constructor> constructorsInternal;
DirtifyingList<Constructor> _constructorsView;
/// Constructors declared in the class.
List<Constructor> get constructors {
ensureLoaded();
// If already dirty the caller just might as well add stuff directly too.
if (dirty) return constructorsInternal;
_constructorsView ??= new DirtifyingList(this, constructorsInternal);
return _constructorsView;
}
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding procedures when reading the dill file.
final List<Procedure> proceduresInternal;
DirtifyingList<Procedure> _proceduresView;
/// Procedures declared in the class.
///
/// For mixin applications this should only contain forwarding stubs.
List<Procedure> get procedures {
ensureLoaded();
// If already dirty the caller just might as well add stuff directly too.
if (dirty) return proceduresInternal;
_proceduresView ??= new DirtifyingList(this, proceduresInternal);
return _proceduresView;
}
/// Internal. Should *ONLY* be used from within kernel.
///
/// Used for adding redirecting factory constructor when reading the dill
/// file.
final List<RedirectingFactoryConstructor>
redirectingFactoryConstructorsInternal;
DirtifyingList<RedirectingFactoryConstructor>
_redirectingFactoryConstructorsView;
/// Redirecting factory constructors declared in the class.
///
/// For mixin applications this should be empty.
List<RedirectingFactoryConstructor> get redirectingFactoryConstructors {
ensureLoaded();
// If already dirty the caller just might as well add stuff directly too.
if (dirty) return redirectingFactoryConstructorsInternal;
_redirectingFactoryConstructorsView ??=
new DirtifyingList(this, redirectingFactoryConstructorsInternal);
return _redirectingFactoryConstructorsView;
}
Class(
{this.name,
bool isAbstract: false,
bool isAnonymousMixin: false,
this.supertype,
this.mixedInType,
List<TypeParameter> typeParameters,
List<Supertype> implementedTypes,
List<Constructor> constructors,
List<Procedure> procedures,
List<Field> fields,
List<RedirectingFactoryConstructor> redirectingFactoryConstructors,
this.fileUri,
Reference reference})
: this.typeParameters = typeParameters ?? <TypeParameter>[],
this.implementedTypes = implementedTypes ?? <Supertype>[],
this.fieldsInternal = fields ?? <Field>[],
this.constructorsInternal = constructors ?? <Constructor>[],
this.proceduresInternal = procedures ?? <Procedure>[],
this.redirectingFactoryConstructorsInternal =
redirectingFactoryConstructors ?? <RedirectingFactoryConstructor>[],
super(reference) {
setParents(this.typeParameters, this);
setParents(this.constructorsInternal, this);
setParents(this.proceduresInternal, this);
setParents(this.fieldsInternal, this);
setParents(this.redirectingFactoryConstructorsInternal, this);
this.isAbstract = isAbstract;
this.isAnonymousMixin = isAnonymousMixin;
}
void computeCanonicalNames() {
assert(canonicalName != null);
if (!dirty) return;
for (int i = 0; i < fields.length; ++i) {
Field member = fields[i];
canonicalName.getChildFromMember(member).bindTo(member.reference);
}
for (int i = 0; i < procedures.length; ++i) {
Procedure member = procedures[i];
canonicalName.getChildFromMember(member).bindTo(member.reference);
}
for (int i = 0; i < constructors.length; ++i) {
Constructor member = constructors[i];
canonicalName.getChildFromMember(member).bindTo(member.reference);
}
for (int i = 0; i < redirectingFactoryConstructors.length; ++i) {
RedirectingFactoryConstructor member = redirectingFactoryConstructors[i];
canonicalName.getChildFromMember(member).bindTo(member.reference);
}
dirty = false;
}
/// 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 class points to said
/// named node.
void relink() {
this.reference.node = this;
for (int i = 0; i < fields.length; ++i) {
Field member = fields[i];
member._relinkNode();
}
for (int i = 0; i < procedures.length; ++i) {
Procedure member = procedures[i];
member._relinkNode();
}
for (int i = 0; i < constructors.length; ++i) {
Constructor member = constructors[i];
member._relinkNode();
}
for (int i = 0; i < redirectingFactoryConstructors.length; ++i) {
RedirectingFactoryConstructor member = redirectingFactoryConstructors[i];
member._relinkNode();
}
dirty = false;
}
/// The immediate super class, or `null` if this is the root class.
Class get superclass => supertype?.classNode;
/// The mixed-in class if this is a mixin application, otherwise `null`.
///
/// Note that this may itself be a mixin application. Use [mixin] to get the
/// class that has the fields and procedures.
Class get mixedInClass => mixedInType?.classNode;
/// The class that declares the field and procedures of this class.
Class get mixin => mixedInClass?.mixin ?? this;
bool get isMixinApplication => mixedInType != null;
String get demangledName {
if (isAnonymousMixin) return nameAsMixinApplication;
assert(!name.contains('&'));
return name;
}
String get nameAsMixinApplication {
assert(isAnonymousMixin);
return demangleMixinApplicationName(name);
}
String get nameAsMixinApplicationSubclass {
assert(isAnonymousMixin);
return demangleMixinApplicationSubclassName(name);
}
/// Members declared in this class.
///
/// 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,
constructors,
procedures,
redirectingFactoryConstructors
].expand((x) => x);
/// The immediately extended, mixed-in, and implemented types.
///
/// This getter is for convenience, not efficiency. Consider manually
/// iterating the super types to speed up code in production.
Iterable<Supertype> get supers => <Iterable<Supertype>>[
supertype == null ? const [] : [supertype],
mixedInType == null ? const [] : [mixedInType],
implementedTypes
].expand((x) => x);
/// The library containing this class.
Library get enclosingLibrary => parent;
/// Internal. Should *ONLY* be used from within kernel.
///
/// If true we have to compute canonical names for all children of this class.
/// if false we can skip it.
bool dirty = true;
/// Adds a member to this class.
///
/// Throws an error if attempting to add a field or procedure to a mixin
/// application.
void addMember(Member member) {
dirty = true;
member.parent = this;
if (member is Constructor) {
constructorsInternal.add(member);
} else if (member is Procedure) {
proceduresInternal.add(member);
} else if (member is Field) {
fieldsInternal.add(member);
} else if (member is RedirectingFactoryConstructor) {
redirectingFactoryConstructorsInternal.add(member);
} else {
throw new ArgumentError(member);
}
}
void addAnnotation(Expression node) {
if (annotations.isEmpty) {
annotations = <Expression>[];
}
annotations.add(node);
node.parent = this;
}
R accept<R>(TreeVisitor<R> v) => v.visitClass(this);
R acceptReference<R>(Visitor<R> v) => v.visitClassReference(this);
Supertype get asRawSupertype {
return new Supertype(this,
new List<DartType>.filled(typeParameters.length, const DynamicType()));
}
Supertype get asThisSupertype {
return new Supertype(
this, getAsTypeArguments(typeParameters, this.enclosingLibrary));
}
/// Returns the type of `this` for the class using [coreTypes] for caching.
InterfaceType getThisType(CoreTypes coreTypes, Nullability nullability) {
return coreTypes.thisInterfaceType(this, nullability);
}
@override
String toString() => 'Class(${toStringInternal()})';
@override
void toTextInternal(AstPrinter printer) {
printer.writeClassName(reference);
}
visitChildren(Visitor v) {
visitList(annotations, v);
visitList(typeParameters, v);
supertype?.accept(v);
mixedInType?.accept(v);
visitList(implementedTypes, v);
visitList(constructors, v);
visitList(procedures, v);
visitList(fields, v);
visitList(redirectingFactoryConstructors, v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
transformList(typeParameters, v, this);
if (supertype != null) {
supertype = v.visitSupertype(supertype);
}
if (mixedInType != null) {
mixedInType = v.visitSupertype(mixedInType);
}
transformSupertypeList(implementedTypes, v);
transformList(constructors, v, this);
transformList(procedures, v, this);
transformList(fields, v, this);
transformList(redirectingFactoryConstructors, v, this);
}
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
}
/// Declaration of an extension.
///
/// The members are converted into top-level procedures and only accessible
/// by reference in the [Extension] node.
class Extension extends NamedNode implements FileUriNode {
/// Name of the extension.
///
/// If unnamed, the extension will be given a synthesized name by the
/// front end.
String name;
/// The URI of the source file this class was loaded from.
Uri fileUri;
/// Type parameters declared on the extension.
final List<TypeParameter> typeParameters;
/// The type in the 'on clause' of the extension declaration.
///
/// For instance A in:
///
/// class A {}
/// extension B on A {}
///
DartType onType;
/// The members declared by the extension.
///
/// The members are converted into top-level members and only accessible
/// by reference through [ExtensionMemberDescriptor].
final List<ExtensionMemberDescriptor> members;
Extension(
{this.name,
List<TypeParameter> typeParameters,
this.onType,
List<ExtensionMemberDescriptor> members,
this.fileUri,
Reference reference})
: this.typeParameters = typeParameters ?? <TypeParameter>[],
this.members = members ?? <ExtensionMemberDescriptor>[],
super(reference) {
setParents(this.typeParameters, this);
}
Library get enclosingLibrary => parent;
@override
R accept<R>(TreeVisitor<R> v) => v.visitExtension(this);
@override
visitChildren(Visitor v) {
visitList(typeParameters, v);
onType?.accept(v);
}
@override
transformChildren(Transformer v) {
transformList(typeParameters, v, this);
if (onType != null) {
onType = v.visitDartType(onType);
}
}
@override
String toString() {
return "Extension(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
printer.writeExtensionName(reference);
}
}
enum ExtensionMemberKind {
Field,
Method,
Getter,
Setter,
Operator,
TearOff,
}
/// Information about an member declaration in an extension.
class ExtensionMemberDescriptor {
static const int FlagStatic = 1 << 0; // Must match serialized bit positions.
/// The name of the extension member.
///
/// The name of the generated top-level member is mangled to ensure
/// uniqueness. This name is used to lookup an extension method the
/// extension itself.
Name name;
/// [ExtensionMemberKind] kind of the original member.
///
/// An extension method is converted into a regular top-level method. For
/// instance:
///
/// class A {
/// var foo;
/// }
/// extension B on A {
/// get bar => this.foo;
/// }
///
/// will be converted into
///
/// class A {}
/// B|get#bar(A #this) => #this.foo;
///
/// where `B|get#bar` is the synthesized name of the top-level method and
/// `#this` is the synthesized parameter that holds represents `this`.
///
ExtensionMemberKind kind;
int flags = 0;
/// Reference to the top-level member created for the extension method.
Reference member;
ExtensionMemberDescriptor(
{this.name, this.kind, bool isStatic: false, this.member}) {
this.isStatic = isStatic;
}
/// Return `true` if the extension method was declared as `static`.
bool get isStatic => flags & FlagStatic != 0;
void set isStatic(bool value) {
flags = value ? (flags | FlagStatic) : (flags & ~FlagStatic);
}
}
// ------------------------------------------------------------------------
// MEMBERS
// ------------------------------------------------------------------------
abstract class Member extends NamedNode implements Annotatable, FileUriNode {
/// End offset in the source file it comes from.
///
/// Valid values are from 0 and up, or -1 ([TreeNode.noOffset]) if the file
/// end offset is not available (this is the default if none is specifically
/// set).
int fileEndOffset = TreeNode.noOffset;
/// List of metadata annotations on the member.
///
/// This defaults to an immutable empty list. Use [addAnnotation] to add
/// annotations if needed.
List<Expression> annotations = const <Expression>[];
Name name;
/// The URI of the source file this member was loaded from.
Uri fileUri;
/// Flags summarizing the kinds of AST nodes contained in this member, for
/// speeding up transformations that only affect certain types of nodes.
///
/// See [TransformerFlag] for the meaning of each bit.
///
/// These should not be used for any purpose other than skipping certain
/// members if it can be determined that no work is needed in there.
///
/// It is valid for these flags to be false positives in rare cases, so
/// transformers must tolerate the case where a flag is spuriously set.
///
/// This value is not serialized; it is populated by the frontend and the
/// deserializer.
//
// TODO(asgerf): It might be worthwhile to put this on classes as well.
int transformerFlags = 0;
Member(this.name, this.fileUri, Reference reference) : super(reference);
Class get enclosingClass => parent is Class ? parent : null;
Library get enclosingLibrary => parent is Class ? parent.parent : parent;
R accept<R>(MemberVisitor<R> v);
acceptReference(MemberReferenceVisitor v);
/// Returns true if this is an abstract procedure.
bool get isAbstract => false;
/// Returns true if the member has the 'const' modifier.
bool get isConst;
/// True if this is a field or non-setter procedure.
///
/// Note that operators and factories return `true`, even though there are
/// normally no calls to their getter.
bool get hasGetter;
/// True if this is a setter or a mutable field.
bool get hasSetter;
/// True if this is a non-static field or procedure.
bool get isInstanceMember;
/// True if the member has the `external` modifier, implying that the
/// implementation is provided by the backend, and is not necessarily written
/// in Dart.
///
/// Members can have this modifier independently of whether the enclosing
/// library is external.
bool get isExternal;
void set isExternal(bool value);
/// If `true` this member is compiled from a member declared in an extension
/// declaration.
///
/// For instance `field`, `method1` and `method2` in:
///
/// extension A on B {
/// static var field;
/// B method1() => this;
/// static B method2() => new B();
/// }
///
bool get isExtensionMember;
/// If `true` this member is defined in a library for which non-nullable by
/// default is enabled.
bool get isNonNullableByDefault;
void set isNonNullableByDefault(bool value);
/// The body of the procedure or constructor, or `null` if this is a field.
FunctionNode get function => null;
/// Returns a possibly synthesized name for this member, consistent with
/// the names used across all [toString] calls.
@override
String toString() => toStringInternal();
@override
void toTextInternal(AstPrinter printer) {
printer.writeMemberName(reference);
}
void addAnnotation(Expression node) {
if (annotations.isEmpty) {
annotations = <Expression>[];
}
annotations.add(node);
node.parent = this;
}
DartType get getterType;
DartType get setterType;
bool get containsSuperCalls {
return transformerFlags & TransformerFlag.superCalls != 0;
}
/// If this member is a member signature, [memberSignatureOrigin] is one of
/// the non-member signature members from which it was created.
Member get memberSignatureOrigin => null;
}
/// A field declaration.
///
/// The implied getter and setter for the field are not represented explicitly,
/// but can be made explicit if needed.
class Field extends Member {
DartType type; // Not null. Defaults to DynamicType.
int flags = 0;
Expression initializer; // May be null.
Field(Name name,
{this.type: const DynamicType(),
this.initializer,
bool isCovariant: false,
bool isFinal: false,
bool isConst: false,
bool isStatic: false,
bool hasImplicitGetter,
bool hasImplicitSetter,
bool isLate: false,
int transformerFlags: 0,
Uri fileUri,
Reference reference})
: super(name, fileUri, reference) {
assert(type != null);
initializer?.parent = this;
this.isCovariant = isCovariant;
this.isFinal = isFinal;
this.isConst = isConst;
this.isStatic = isStatic;
this.isLate = isLate;
this.hasImplicitGetter = hasImplicitGetter ?? !isStatic;
this.hasImplicitSetter = hasImplicitSetter ??
(!isStatic &&
!isConst &&
(!isFinal || (isLate && initializer == null)));
this.transformerFlags = transformerFlags;
}
static const int FlagFinal = 1 << 0; // Must match serialized bit positions.
static const int FlagConst = 1 << 1;
static const int FlagStatic = 1 << 2;
static const int FlagHasImplicitGetter = 1 << 3;
static const int FlagHasImplicitSetter = 1 << 4;
static const int FlagCovariant = 1 << 5;
static const int FlagGenericCovariantImpl = 1 << 6;
static const int FlagLate = 1 << 7;
static const int FlagExtensionMember = 1 << 8;
static const int FlagNonNullableByDefault = 1 << 9;
static const int FlagInternalImplementation = 1 << 10;
/// Whether the field is declared with the `covariant` keyword.
bool get isCovariant => flags & FlagCovariant != 0;
bool get isFinal => flags & FlagFinal != 0;
bool get isConst => flags & FlagConst != 0;
bool get isStatic => flags & FlagStatic != 0;
@override
bool get isExtensionMember => flags & FlagExtensionMember != 0;
/// If true, a getter should be generated for this field.
///
/// If false, there may or may not exist an explicit getter in the same class
/// with the same name as the field.
///
/// By default, all non-static fields have implicit getters.
bool get hasImplicitGetter => flags & FlagHasImplicitGetter != 0;
/// If true, a setter should be generated for this field.
///
/// If false, there may or may not exist an explicit setter in the same class
/// with the same name as the field.
///
/// Final fields never have implicit setters, but a field without an implicit
/// setter is not necessarily final, as it may be mutated by direct field
/// access.
///
/// By default, all non-static, non-final fields have implicit setters.
bool get hasImplicitSetter => flags & FlagHasImplicitSetter != 0;
/// Indicates whether the implicit setter associated with this field needs to
/// contain a runtime type check to deal with generic covariance.
///
/// When `true`, runtime checks may need to be performed; see
/// [DispatchCategory] for details.
bool get isGenericCovariantImpl => flags & FlagGenericCovariantImpl != 0;
/// Whether the field is declared with the `late` keyword.
bool get isLate => flags & FlagLate != 0;
// If `true` this field is not part of the interface but only part of the
// class members.
//
// This is `true` for instance for synthesized fields added for the late
// lowering.
bool get isInternalImplementation => flags & FlagInternalImplementation != 0;
void set isCovariant(bool value) {
flags = value ? (flags | FlagCovariant) : (flags & ~FlagCovariant);
}
void set isFinal(bool value) {
flags = value ? (flags | FlagFinal) : (flags & ~FlagFinal);
}
void set isConst(bool value) {
flags = value ? (flags | FlagConst) : (flags & ~FlagConst);
}
void set isStatic(bool value) {
flags = value ? (flags | FlagStatic) : (flags & ~FlagStatic);
}
void set isExtensionMember(bool value) {
flags =
value ? (flags | FlagExtensionMember) : (flags & ~FlagExtensionMember);
}
void set hasImplicitGetter(bool value) {
flags = value
? (flags | FlagHasImplicitGetter)
: (flags & ~FlagHasImplicitGetter);
}
void set hasImplicitSetter(bool value) {
flags = value
? (flags | FlagHasImplicitSetter)
: (flags & ~FlagHasImplicitSetter);
}
void set isGenericCovariantImpl(bool value) {
flags = value
? (flags | FlagGenericCovariantImpl)
: (flags & ~FlagGenericCovariantImpl);
}
void set isLate(bool value) {
flags = value ? (flags | FlagLate) : (flags & ~FlagLate);
}
void set isInternalImplementation(bool value) {
flags = value
? (flags | FlagInternalImplementation)
: (flags & ~FlagInternalImplementation);
}
/// True if the field is neither final nor const.
bool get isMutable => flags & (FlagFinal | FlagConst) == 0;
bool get isInstanceMember => !isStatic;
bool get hasGetter => true;
bool get hasSetter => isMutable || isLate && initializer == null;
bool get isExternal => false;
void set isExternal(bool value) {
if (value) throw 'Fields cannot be external';
}
@override
bool get isNonNullableByDefault => flags & FlagNonNullableByDefault != 0;
@override
void set isNonNullableByDefault(bool value) {
flags = value
? (flags | FlagNonNullableByDefault)
: (flags & ~FlagNonNullableByDefault);
}
R accept<R>(MemberVisitor<R> v) => v.visitField(this);
acceptReference(MemberReferenceVisitor v) => v.visitFieldReference(this);
visitChildren(Visitor v) {
visitList(annotations, v);
type?.accept(v);
name?.accept(v);
initializer?.accept(v);
}
transformChildren(Transformer v) {
type = v.visitDartType(type);
transformList(annotations, v, this);
if (initializer != null) {
initializer = initializer.accept<TreeNode>(v);
initializer?.parent = this;
}
}
DartType get getterType => type;
DartType get setterType => hasSetter ? type : const BottomType();
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
}
/// A generative constructor, possibly redirecting.
///
/// Note that factory constructors are treated as [Procedure]s.
///
/// Constructors do not take type parameters. Type arguments from a constructor
/// invocation should be matched with the type parameters declared in the class.
///
/// For unnamed constructors, the name is an empty string (in a [Name]).
class Constructor extends Member {
/// Start offset of the constructor in the source file it comes from.
///
/// Note that this includes annotations if any.
///
/// Valid values are from 0 and up, or -1 ([TreeNode.noOffset]) if the file
/// start offset is not available (this is the default if none is specifically
/// set).
int startFileOffset = TreeNode.noOffset;
int flags = 0;
FunctionNode function;
List<Initializer> initializers;
Constructor(this.function,
{Name name,
bool isConst: false,
bool isExternal: false,
bool isSynthetic: false,
List<Initializer> initializers,
int transformerFlags: 0,
Uri fileUri,
Reference reference})
: this.initializers = initializers ?? <Initializer>[],
super(name, fileUri, reference) {
function?.parent = this;
setParents(this.initializers, this);
this.isConst = isConst;
this.isExternal = isExternal;
this.isSynthetic = isSynthetic;
this.transformerFlags = transformerFlags;
}
static const int FlagConst = 1 << 0; // Must match serialized bit positions.
static const int FlagExternal = 1 << 1;
static const int FlagSynthetic = 1 << 2;
static const int FlagNonNullableByDefault = 1 << 3;
bool get isConst => flags & FlagConst != 0;
bool get isExternal => flags & FlagExternal != 0;
/// True if this is a synthetic constructor inserted in a class that
/// does not otherwise declare any constructors.
bool get isSynthetic => flags & FlagSynthetic != 0;
void set isConst(bool value) {
flags = value ? (flags | FlagConst) : (flags & ~FlagConst);
}
void set isExternal(bool value) {
flags = value ? (flags | FlagExternal) : (flags & ~FlagExternal);
}
void set isSynthetic(bool value) {
flags = value ? (flags | FlagSynthetic) : (flags & ~FlagSynthetic);
}
bool get isInstanceMember => false;
bool get hasGetter => false;
bool get hasSetter => false;
@override
bool get isExtensionMember => false;
@override
bool get isNonNullableByDefault => flags & FlagNonNullableByDefault != 0;
@override
void set isNonNullableByDefault(bool value) {
flags = value
? (flags | FlagNonNullableByDefault)
: (flags & ~FlagNonNullableByDefault);
}
R accept<R>(MemberVisitor<R> v) => v.visitConstructor(this);
acceptReference(MemberReferenceVisitor v) =>
v.visitConstructorReference(this);
visitChildren(Visitor v) {
visitList(annotations, v);
name?.accept(v);
visitList(initializers, v);
function?.accept(v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
transformList(initializers, v, this);
if (function != null) {
function = function.accept<TreeNode>(v);
function?.parent = this;
}
}
DartType get getterType => const BottomType();
DartType get setterType => const BottomType();
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
}
/// Residue of a redirecting factory constructor for the linking phase.
///
/// In the following example, `bar` is a redirecting factory constructor.
///
/// class A {
/// A.foo();
/// factory A.bar() = A.foo;
/// }
///
/// An invocation of `new A.bar()` has the same effect as an invocation of
/// `new A.foo()`. In Kernel, the invocations of `bar` are replaced with
/// invocations of `foo`, and after it is done, the redirecting constructor can
/// be removed from the class. However, it is needed during the linking phase,
/// because other modules can refer to that constructor.
///
/// [RedirectingFactoryConstructor]s contain the necessary information for
/// linking and are treated as non-runnable members of classes that merely serve
/// as containers for that information.
///
/// Redirecting factory constructors can be unnamed. In this case, the name is
/// an empty string (in a [Name]).
class RedirectingFactoryConstructor extends Member {
int flags = 0;
/// [RedirectingFactoryConstructor]s may redirect to constructors or factories
/// of instantiated generic types, that is, generic types with supplied type
/// arguments. The supplied type arguments are stored in this field.
final List<DartType> typeArguments;
/// Reference to the constructor or the factory that this
/// [RedirectingFactoryConstructor] redirects to.
Reference targetReference;
/// [typeParameters] are duplicates of the type parameters of the enclosing
/// class. Because [RedirectingFactoryConstructor]s aren't instance members,
/// references to the type parameters of the enclosing class in the
/// redirection target description are encoded with references to the elements
/// of [typeParameters].
List<TypeParameter> typeParameters;
/// Positional parameters of [RedirectingFactoryConstructor]s should be
/// compatible with that of the target constructor.
List<VariableDeclaration> positionalParameters;
int requiredParameterCount;
/// Named parameters of [RedirectingFactoryConstructor]s should be compatible
/// with that of the target constructor.
List<VariableDeclaration> namedParameters;
RedirectingFactoryConstructor(this.targetReference,
{Name name,
bool isConst: false,
bool isExternal: false,
int transformerFlags: 0,
List<DartType> typeArguments,
List<TypeParameter> typeParameters,
List<VariableDeclaration> positionalParameters,
List<VariableDeclaration> namedParameters,
int requiredParameterCount,
Uri fileUri,
Reference reference})
: this.typeArguments = typeArguments ?? <DartType>[],
this.typeParameters = typeParameters ?? <TypeParameter>[],
this.positionalParameters =
positionalParameters ?? <VariableDeclaration>[],
this.namedParameters = namedParameters ?? <VariableDeclaration>[],
this.requiredParameterCount =
requiredParameterCount ?? positionalParameters?.length ?? 0,
super(name, fileUri, reference) {
setParents(this.typeParameters, this);
setParents(this.positionalParameters, this);
setParents(this.namedParameters, this);
this.isConst = isConst;
this.isExternal = isExternal;
this.transformerFlags = transformerFlags;
}
static const int FlagConst = 1 << 0; // Must match serialized bit positions.
static const int FlagExternal = 1 << 1;
static const int FlagNonNullableByDefault = 1 << 2;
bool get isConst => flags & FlagConst != 0;
bool get isExternal => flags & FlagExternal != 0;
void set isConst(bool value) {
flags = value ? (flags | FlagConst) : (flags & ~FlagConst);
}
void set isExternal(bool value) {
flags = value ? (flags | FlagExternal) : (flags & ~FlagExternal);
}
bool get isInstanceMember => false;
bool get hasGetter => false;
bool get hasSetter => false;
@override
bool get isExtensionMember => false;
bool get isUnresolved => targetReference == null;
@override
bool get isNonNullableByDefault => flags & FlagNonNullableByDefault != 0;
@override
void set isNonNullableByDefault(bool value) {
flags = value
? (flags | FlagNonNullableByDefault)
: (flags & ~FlagNonNullableByDefault);
}
Member get target => targetReference?.asMember;
void set target(Member member) {
assert(member is Constructor ||
(member is Procedure && member.kind == ProcedureKind.Factory));
targetReference = getMemberReference(member);
}
R accept<R>(MemberVisitor<R> v) => v.visitRedirectingFactoryConstructor(this);
acceptReference(MemberReferenceVisitor v) =>
v.visitRedirectingFactoryConstructorReference(this);
visitChildren(Visitor v) {
visitList(annotations, v);
target?.acceptReference(v);
visitList(typeArguments, v);
name?.accept(v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
transformTypeList(typeArguments, v);
}
DartType get getterType => const BottomType();
DartType get setterType => const BottomType();
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
}
/// A method, getter, setter, index-getter, index-setter, operator overloader,
/// or factory.
///
/// Procedures can have the static, abstract, and/or external modifier, although
/// only the static and external modifiers may be used together.
///
/// For non-static procedures the name is required for dynamic dispatch.
/// For external procedures the name is required for identifying the external
/// implementation.
///
/// For methods, getters, and setters the name is just as it was declared.
/// For setters this does not include a trailing `=`.
/// For index-getters/setters, this is `[]` and `[]=`.
/// For operators, this is the token for the operator, e.g. `+` or `==`,
/// except for the unary minus operator, whose name is `unary-`.
class Procedure extends Member {
/// Start offset of the function in the source file it comes from.
///
/// Note that this includes annotations if any.
///
/// Valid values are from 0 and up, or -1 ([TreeNode.noOffset]) if the file
/// start offset is not available (this is the default if none is specifically
/// set).
int startFileOffset = TreeNode.noOffset;
ProcedureKind kind;
int flags = 0;
// function is null if and only if abstract, external.
FunctionNode function;
// The function node's body might be lazily loaded, meaning that this value
// might not be set correctly yet. Make sure the body is loaded before
// returning anything.
int get transformerFlags {
function?.body;
return super.transformerFlags;
}
// The function node's body might be lazily loaded, meaning that this value
// might get overwritten later (when the body is read). To avoid that read the
// body now and only set the value afterwards.
void set transformerFlags(int newValue) {
function?.body;
super.transformerFlags = newValue;
}
// This function will set the transformer flags without loading the body.
// Used when reading the binary. For other cases one should probably use
// `transformerFlags = value;`.
void setTransformerFlagsWithoutLazyLoading(int newValue) {
super.transformerFlags = newValue;
}
Reference forwardingStubSuperTargetReference;
Reference forwardingStubInterfaceTargetReference;
Reference memberSignatureOriginReference;
Procedure(Name name, ProcedureKind kind, FunctionNode function,
{bool isAbstract: false,
bool isStatic: false,
bool isExternal: false,
bool isConst: false,
bool isForwardingStub: false,
bool isForwardingSemiStub: false,
bool isMemberSignature: false,
bool isExtensionMember: false,
int transformerFlags: 0,
Uri fileUri,
Reference reference,
Member forwardingStubSuperTarget,
Member forwardingStubInterfaceTarget,
Member memberSignatureOrigin})
: this._byReferenceRenamed(name, kind, function,
isAbstract: isAbstract,
isStatic: isStatic,
isExternal: isExternal,
isConst: isConst,
isForwardingStub: isForwardingStub,
isMemberSignature: isMemberSignature,
isForwardingSemiStub: isForwardingSemiStub,
isExtensionMember: isExtensionMember,
transformerFlags: transformerFlags,
fileUri: fileUri,
reference: reference,
forwardingStubSuperTargetReference:
getMemberReference(forwardingStubSuperTarget),
forwardingStubInterfaceTargetReference:
getMemberReference(forwardingStubInterfaceTarget),
memberSignatureOriginReference:
getMemberReference(memberSignatureOrigin));
Procedure._byReferenceRenamed(Name name, this.kind, this.function,
{bool isAbstract: false,
bool isStatic: false,
bool isExternal: false,
bool isConst: false,
bool isForwardingStub: false,
bool isForwardingSemiStub: false,
bool isMemberSignature: false,
bool isExtensionMember: false,
int transformerFlags: 0,
Uri fileUri,
Reference reference,
this.forwardingStubSuperTargetReference,
this.forwardingStubInterfaceTargetReference,
this.memberSignatureOriginReference})
: super(name, fileUri, reference) {
function?.parent = this;
this.isAbstract = isAbstract;
this.isStatic = isStatic;
this.isExternal = isExternal;
this.isConst = isConst;
this.isForwardingStub = isForwardingStub;
this.isForwardingSemiStub = isForwardingSemiStub;
this.isMemberSignature = isMemberSignature;
this.isExtensionMember = isExtensionMember;
this.transformerFlags = transformerFlags;
assert(!(isMemberSignature && memberSignatureOriginReference == null),
"No member signature origin for member signature $this.");
assert(
!(memberSignatureOrigin is Procedure &&
(memberSignatureOrigin as Procedure).isMemberSignature),
"Member signature origin cannot be a member signature "
"$memberSignatureOrigin for $this.");
}
static const int FlagStatic = 1 << 0; // Must match serialized bit positions.
static const int FlagAbstract = 1 << 1;
static const int FlagExternal = 1 << 2;
static const int FlagConst = 1 << 3; // Only for external const factories.
static const int FlagForwardingStub = 1 << 4;
static const int FlagForwardingSemiStub = 1 << 5;
// TODO(29841): Remove this flag after the issue is resolved.
static const int FlagRedirectingFactoryConstructor = 1 << 6;
static const int FlagNoSuchMethodForwarder = 1 << 7;
static const int FlagExtensionMember = 1 << 8;
static const int FlagMemberSignature = 1 << 9;
static const int FlagNonNullableByDefault = 1 << 10;
bool get isStatic => flags & FlagStatic != 0;
bool get isAbstract => flags & FlagAbstract != 0;
bool get isExternal => flags & FlagExternal != 0;
/// True if this has the `const` modifier. This is only possible for external
/// constant factories, such as `String.fromEnvironment`.
bool get isConst => flags & FlagConst != 0;
/// If set, this flag indicates that this function's implementation exists
/// solely for the purpose of type checking arguments and forwarding to
/// [forwardingStubSuperTarget].
///
/// Note that just because this bit is set doesn't mean that the function was
/// not declared in the source; it's possible that this is a forwarding
/// semi-stub (see isForwardingSemiStub). To determine whether this function
/// was present in the source, consult [isSyntheticForwarder].
bool get isForwardingStub => flags & FlagForwardingStub != 0;
/// If set, this flag indicates that although this function is a forwarding
/// stub, it was present in the original source as an abstract method.
bool get isForwardingSemiStub => flags & FlagForwardingSemiStub != 0;
/// If set, this method is a class member added to show the type of an
/// inherited member.
///
/// This is used when the type of the inherited member cannot be computed
/// directly from the member(s) in the supertypes. For instance in case of
/// an nnbd opt-out class inheriting from an nnbd opt-in class; here all nnbd-
/// aware types are replaced with legacy types in the inherited signature.
bool get isMemberSignature => flags & FlagMemberSignature != 0;
// Indicates if this [Procedure] represents a redirecting factory constructor
// and doesn't have a runnable body.
bool get isRedirectingFactoryConstructor {
return flags & FlagRedirectingFactoryConstructor != 0;
}
/// If set, this flag indicates that this function was not present in the
/// source, and it exists solely for the purpose of type checking arguments
/// and forwarding to [forwardingStubSuperTarget].
bool get isSyntheticForwarder => isForwardingStub && !isForwardingSemiStub;
bool get isNoSuchMethodForwarder => flags & FlagNoSuchMethodForwarder != 0;
@override
bool get isExtensionMember => flags & FlagExtensionMember != 0;
void set isStatic(bool value) {
flags = value ? (flags | FlagStatic) : (flags & ~FlagStatic);
}
void set isAbstract(bool value) {
flags = value ? (flags | FlagAbstract) : (flags & ~FlagAbstract);
}
void set isExternal(bool value) {
flags = value ? (flags | FlagExternal) : (flags & ~FlagExternal);
}
void set isConst(bool value) {
flags = value ? (flags | FlagConst) : (flags & ~FlagConst);
}
void set isForwardingStub(bool value) {
flags =
value ? (flags | FlagForwardingStub) : (flags & ~FlagForwardingStub);
}
void set isForwardingSemiStub(bool value) {
flags = value
? (flags | FlagForwardingSemiStub)
: (flags & ~FlagForwardingSemiStub);
}
void set isMemberSignature(bool value) {
flags =
value ? (flags | FlagMemberSignature) : (flags & ~FlagMemberSignature);
}
void set isRedirectingFactoryConstructor(bool value) {
flags = value
? (flags | FlagRedirectingFactoryConstructor)
: (flags & ~FlagRedirectingFactoryConstructor);
}
void set isNoSuchMethodForwarder(bool value) {
flags = value
? (flags | FlagNoSuchMethodForwarder)
: (flags & ~FlagNoSuchMethodForwarder);
}
void set isExtensionMember(bool value) {
flags =
value ? (flags | FlagExtensionMember) : (flags & ~FlagExtensionMember);
}
bool get isInstanceMember => !isStatic;
bool get isGetter => kind == ProcedureKind.Getter;
bool get isSetter => kind == ProcedureKind.Setter;
bool get isAccessor => isGetter || isSetter;
bool get hasGetter => kind != ProcedureKind.Setter;
bool get hasSetter => kind == ProcedureKind.Setter;
bool get isFactory => kind == ProcedureKind.Factory;
@override
bool get isNonNullableByDefault => flags & FlagNonNullableByDefault != 0;
@override
void set isNonNullableByDefault(bool value) {
flags = value
? (flags | FlagNonNullableByDefault)
: (flags & ~FlagNonNullableByDefault);
}
Member get forwardingStubSuperTarget =>
forwardingStubSuperTargetReference?.asMember;
void set forwardingStubSuperTarget(Member target) {
forwardingStubSuperTargetReference = getMemberReference(target);
}
Member get forwardingStubInterfaceTarget =>
forwardingStubInterfaceTargetReference?.asMember;
void set forwardingStubInterfaceTarget(Member target) {
forwardingStubInterfaceTargetReference = getMemberReference(target);
}
@override
Member get memberSignatureOrigin => memberSignatureOriginReference?.asMember;
void set memberSignatureOrigin(Member target) {
memberSignatureOriginReference = getMemberReference(target);
}
R accept<R>(MemberVisitor<R> v) => v.visitProcedure(this);
acceptReference(MemberReferenceVisitor v) => v.visitProcedureReference(this);
visitChildren(Visitor v) {
visitList(annotations, v);
name?.accept(v);
function?.accept(v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
if (function != null) {
function = function.accept<TreeNode>(v);
function?.parent = this;
}
}
DartType get getterType {
return isGetter
? function.returnType
: function.computeFunctionType(enclosingLibrary.nonNullable);
}
DartType get setterType {
return isSetter
? function.positionalParameters[0].type
: const BottomType();
}
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
}
enum ProcedureKind {
Method,
Getter,
Setter,
Operator,
Factory,
}
// ------------------------------------------------------------------------
// CONSTRUCTOR INITIALIZERS
// ------------------------------------------------------------------------
/// Part of an initializer list in a constructor.
abstract class Initializer extends TreeNode {
/// True if this is a synthetic constructor initializer.
@informative
bool isSynthetic = false;
R accept<R>(InitializerVisitor<R> v);
}
/// An initializer with a compile-time error.
///
/// Should throw an exception at runtime.
//
// DESIGN TODO: The frontend should use this in a lot more cases to catch
// invalid cases.
class InvalidInitializer extends Initializer {
R accept<R>(InitializerVisitor<R> v) => v.visitInvalidInitializer(this);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
@override
String toString() {
return "InvalidInitializer(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
/// A field assignment `field = value` occurring in the initializer list of
/// a constructor.
///
/// This node has nothing to do with declaration-site field initializers; those
/// are [Expression]s stored in [Field.initializer].
//
// TODO: The frontend should check that all final fields are initialized
// exactly once, and that no fields are assigned twice in the initializer list.
class FieldInitializer extends Initializer {
/// Reference to the field being initialized. Not null.
Reference fieldReference;
Expression value;
FieldInitializer(Field field, Expression value)
: this.byReference(field?.reference, value);
FieldInitializer.byReference(this.fieldReference, this.value) {
value?.parent = this;
}
Field get field => fieldReference?.node;
void set field(Field field) {
fieldReference = field?.reference;
}
R accept<R>(InitializerVisitor<R> v) => v.visitFieldInitializer(this);
visitChildren(Visitor v) {
field?.acceptReference(v);
value?.accept(v);
}
transformChildren(Transformer v) {
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
@override
String toString() {
return "FieldInitializer(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
/// A super call `super(x,y)` occurring in the initializer list of a
/// constructor.
///
/// There are no type arguments on this call.
//
// TODO: The frontend should check that there is no more than one super call.
//
// DESIGN TODO: Consider if the frontend should insert type arguments derived
// from the extends clause.
class SuperInitializer extends Initializer {
/// Reference to the constructor being invoked in the super class. Not null.
Reference targetReference;
Arguments arguments;
SuperInitializer(Constructor target, Arguments arguments)
: this.byReference(getMemberReference(target), arguments);
SuperInitializer.byReference(this.targetReference, this.arguments) {
arguments?.parent = this;
}
Constructor get target => targetReference?.asConstructor;
void set target(Constructor target) {
targetReference = getMemberReference(target);
}
R accept<R>(InitializerVisitor<R> v) => v.visitSuperInitializer(this);
visitChildren(Visitor v) {
target?.acceptReference(v);
arguments?.accept(v);
}
transformChildren(Transformer v) {
if (arguments != null) {
arguments = arguments.accept<TreeNode>(v);
arguments?.parent = this;
}
}
@override
String toString() {
return "SuperInitializer(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
/// A redirecting call `this(x,y)` occurring in the initializer list of
/// a constructor.
//
// TODO: The frontend should check that this is the only initializer and if the
// constructor has a body or if there is a cycle in the initializer calls.
class RedirectingInitializer extends Initializer {
/// Reference to the constructor being invoked in the same class. Not null.
Reference targetReference;
Arguments arguments;
RedirectingInitializer(Constructor target, Arguments arguments)
: this.byReference(getMemberReference(target), arguments);
RedirectingInitializer.byReference(this.targetReference, this.arguments) {
arguments?.parent = this;
}
Constructor get target => targetReference?.asConstructor;
void set target(Constructor target) {
targetReference = getMemberReference(target);
}
R accept<R>(InitializerVisitor<R> v) => v.visitRedirectingInitializer(this);
visitChildren(Visitor v) {
target?.acceptReference(v);
arguments?.accept(v);
}
transformChildren(Transformer v) {
if (arguments != null) {
arguments = arguments.accept<TreeNode>(v);
arguments?.parent = this;
}
}
@override
String toString() {
return "RedirectingInitializer(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
/// Binding of a temporary variable in the initializer list of a constructor.
///
/// The variable is in scope for the remainder of the initializer list, but is
/// not in scope in the constructor body.
class LocalInitializer extends Initializer {
VariableDeclaration variable;
LocalInitializer(this.variable) {
variable?.parent = this;
}
R accept<R>(InitializerVisitor<R> v) => v.visitLocalInitializer(this);
visitChildren(Visitor v) {
variable?.accept(v);
}
transformChildren(Transformer v) {
if (variable != null) {
variable = variable.accept<TreeNode>(v);
variable?.parent = this;
}
}
@override
String toString() {
return "LocalInitializer(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
class AssertInitializer extends Initializer {
AssertStatement statement;
AssertInitializer(this.statement) {
statement.parent = this;
}
R accept<R>(InitializerVisitor<R> v) => v.visitAssertInitializer(this);
visitChildren(Visitor v) {
statement.accept(v);
}
transformChildren(Transformer v) {
statement = statement.accept<TreeNode>(v);
statement.parent = this;
}
@override
String toString() {
return "AssertInitializer(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
// ------------------------------------------------------------------------
// FUNCTIONS
// ------------------------------------------------------------------------
/// A function declares parameters and has a body.
///
/// This may occur in a procedure, constructor, function expression, or local
/// function declaration.
class FunctionNode extends TreeNode {
/// End offset in the source file it comes from. Valid values are from 0 and
/// up, or -1 ([TreeNode.noOffset]) if the file end offset is not available
/// (this is the default if none is specifically set).
int fileEndOffset = TreeNode.noOffset;
/// Kernel async marker for the function.
///
/// See also [dartAsyncMarker].
AsyncMarker asyncMarker;
/// Dart async marker for the function.
///
/// See also [asyncMarker].
///
/// A Kernel function can represent a Dart function with a different async
/// marker.
///
/// For example, when async/await is translated away,
/// a Dart async function might be represented by a Kernel sync function.
AsyncMarker dartAsyncMarker;
List<TypeParameter> typeParameters;
int requiredParameterCount;
List<VariableDeclaration> positionalParameters;
List<VariableDeclaration> namedParameters;
DartType returnType; // Not null.
Statement _body;
void Function() lazyBuilder;
void _buildLazy() {
if (lazyBuilder != null) {
var lazyBuilderLocal = lazyBuilder;
lazyBuilder = null;
lazyBuilderLocal();
}
}
Statement get body {
_buildLazy();
return _body;
}
void set body(Statement body) {
_buildLazy();
_body = body;
}
FunctionNode(this._body,
{List<TypeParameter> typeParameters,
List<VariableDeclaration> positionalParameters,
List<VariableDeclaration> namedParameters,
int requiredParameterCount,
this.returnType: const DynamicType(),
this.asyncMarker: AsyncMarker.Sync,
this.dartAsyncMarker})
: this.positionalParameters =
positionalParameters ?? <VariableDeclaration>[],
this.requiredParameterCount =
requiredParameterCount ?? positionalParameters?.length ?? 0,
this.namedParameters = namedParameters ?? <VariableDeclaration>[],
this.typeParameters = typeParameters ?? <TypeParameter>[] {
assert(returnType != null);
setParents(this.typeParameters, this);
setParents(this.positionalParameters, this);
setParents(this.namedParameters, this);
_body?.parent = this;
dartAsyncMarker ??= asyncMarker;
}
static DartType _getTypeOfVariable(VariableDeclaration node) => node.type;
static NamedType _getNamedTypeOfVariable(VariableDeclaration node) {
return new NamedType(node.name, node.type, isRequired: node.isRequired);
}
/// Returns the function type of the node reusing its type parameters.
///
/// This getter works similarly to [functionType], but reuses type parameters
/// of the function node (or the class enclosing it -- see the comment on
/// [functionType] about constructors of generic classes) in the result. It
/// is useful in some contexts, especially when reasoning about the function
/// type of the enclosing generic function and in combination with
/// [FunctionType.withoutTypeParameters].
FunctionType computeThisFunctionType(Nullability nullability) {
TreeNode parent = this.parent;
List<NamedType> named =
namedParameters.map(_getNamedTypeOfVariable).toList(growable: false);
named.sort();
// We need create a copy of the list of type parameters, otherwise
// transformations like erasure don't work.
var typeParametersCopy = new List<TypeParameter>.from(parent is Constructor
? parent.enclosingClass.typeParameters
: typeParameters);
return new FunctionType(
positionalParameters.map(_getTypeOfVariable).toList(growable: false),
returnType,
nullability,
namedParameters: named,
typeParameters: typeParametersCopy,
requiredParameterCount: requiredParameterCount);
}
/// Returns the function type of the function node.
///
/// If the function node describes a generic function, the resulting function
/// type will be generic. If the function node describes a constructor of a
/// generic class, the resulting function type will be generic with its type
/// parameters constructed after those of the class. In both cases, if the
/// resulting function type is generic, a fresh set of type parameters is used
/// in it.
FunctionType computeFunctionType(Nullability nullability) {
return typeParameters.isEmpty
? computeThisFunctionType(nullability)
: getFreshTypeParameters(typeParameters)
.applyToFunctionType(computeThisFunctionType(nullability));
}
/// Return function type of node returning [typedefType] reuse type parameters
///
/// When this getter is invoked, the parent must be a [Constructor].
/// This getter works similarly to [computeThisFunctionType], but uses
/// [typedef] to compute the return type of the returned function type. It
/// is useful in some contexts, especially during inference of aliased
/// constructor invocations.
FunctionType computeAliasedConstructorFunctionType(
Typedef typedef, Library library) {
TreeNode parent = this.parent;
assert(parent is Constructor, "Only run this method on constructors");
Constructor parentConstructor = parent;
// We need create a copy of the list of type parameters, otherwise
// transformations like erasure don't work.
List<TypeParameter> classTypeParametersCopy =
List.from(parentConstructor.enclosingClass.typeParameters);
List<TypeParameter> typedefTypeParametersCopy =
List.from(typedef.typeParameters);
List<DartType> asTypeArguments =
getAsTypeArguments(typedefTypeParametersCopy, library);
TypedefType typedefType =
TypedefType(typedef, library.nonNullable, asTypeArguments);
DartType unaliasedTypedef = typedefType.unalias;
assert(unaliasedTypedef is InterfaceType,
"[typedef] is assumed to resolve to an interface type");
InterfaceType targetType = unaliasedTypedef;
Substitution substitution = Substitution.fromPairs(
classTypeParametersCopy, targetType.typeArguments);
List<DartType> positional = positionalParameters
.map((VariableDeclaration decl) =>
substitution.substituteType(decl.type))
.toList(growable: false);
List<NamedType> named = namedParameters
.map((VariableDeclaration decl) => NamedType(
decl.name, substitution.substituteType(decl.type),
isRequired: decl.isRequired))
.toList(growable: false);
named.sort();
return FunctionType(positional, typedefType.unalias, library.nonNullable,
namedParameters: named,
typeParameters: typedefTypeParametersCopy,
requiredParameterCount: requiredParameterCount);
}
/// Return function type of node returning [typedefType] reuse type parameters
///
/// When this getter is invoked, the parent must be a [Procedure] which is a
/// redirecting factory constructor. This getter works similarly to
/// [computeThisFunctionType], but uses [typedef] to compute the return type
/// of the returned function type. It is useful in some contexts, especially
/// during inference of aliased factory invocations.
FunctionType computeAliasedFactoryFunctionType(
Typedef typedef, Library library) {
assert(
parent is Procedure &&
(parent as Procedure).kind == ProcedureKind.Factory,
"Only run this method on a factory");
// We need create a copy of the list of type parameters, otherwise
// transformations like erasure don't work.
List<TypeParameter> classTypeParametersCopy = List.from(typeParameters);
List<TypeParameter> typedefTypeParametersCopy =
List.from(typedef.typeParameters);
List<DartType> asTypeArguments =
getAsTypeArguments(typedefTypeParametersCopy, library);
TypedefType typedefType =
TypedefType(typedef, library.nonNullable, asTypeArguments);
DartType unaliasedTypedef = typedefType.unalias;
assert(unaliasedTypedef is InterfaceType,
"[typedef] is assumed to resolve to an interface type");
InterfaceType targetType = unaliasedTypedef;
Substitution substitution = Substitution.fromPairs(
classTypeParametersCopy, targetType.typeArguments);
List<DartType> positional = positionalParameters
.map((VariableDeclaration decl) =>
substitution.substituteType(decl.type))
.toList(growable: false);
List<NamedType> named = namedParameters
.map((VariableDeclaration decl) => NamedType(
decl.name, substitution.substituteType(decl.type),
isRequired: decl.isRequired))
.toList(growable: false);
named.sort();
return FunctionType(positional, typedefType.unalias, library.nonNullable,
namedParameters: named,
typeParameters: typedefTypeParametersCopy,
requiredParameterCount: requiredParameterCount);
}
R accept<R>(TreeVisitor<R> v) => v.visitFunctionNode(this);
visitChildren(Visitor v) {
visitList(typeParameters, v);
visitList(positionalParameters, v);
visitList(namedParameters, v);
returnType?.accept(v);
body?.accept(v);
}
transformChildren(Transformer v) {
transformList(typeParameters, v, this);
transformList(positionalParameters, v, this);
transformList(namedParameters, v, this);
returnType = v.visitDartType(returnType);
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
@override
String toString() {
return "FunctionNode(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
// TODO(johnniwinther): Implement this.
}
}
enum AsyncMarker {
// Do not change the order of these, the frontends depend on it.
Sync,
SyncStar,
Async,
AsyncStar,
// `SyncYielding` is a marker that tells Dart VM that this function is an
// artificial closure introduced by an async transformer which desugared all
// async syntax into a combination of native yields and helper method calls.
//
// Native yields (formatted as `[yield]`) are semantically close to
// `yield x` statement: they denote a yield/resume point within a function
// but are completely decoupled from the notion of iterators. When
// execution of the closure reaches `[yield] x` it stops and return the
// value of `x` to the caller. If closure is called again it continues
// to the next statement after this yield as if it was suspended and resumed.
//
// Consider this example:
//
// g() {
// var :await_jump_var = 0;
// var :await_ctx_var;
//
// f(x) yielding {
// [yield] '${x}:0';
// [yield] '${x}:1';
// [yield] '${x}:2';
// }
//
// return f;
// }
//
// print(f('a')); /* prints 'a:0', :await_jump_var = 1 */
// print(f('b')); /* prints 'b:1', :await_jump_var = 2 */
// print(f('c')); /* prints 'c:2', :await_jump_var = 3 */
//
// Note: currently Dart VM implicitly relies on async transformer to
// inject certain artificial variables into g (like `:await_jump_var`).
// As such SyncYielding and native yield are not intended to be used on their
// own, but are rather an implementation artifact of the async transformer
// itself.
SyncYielding,
}
// ------------------------------------------------------------------------
// EXPRESSIONS
// ------------------------------------------------------------------------
abstract class Expression extends TreeNode {
/// Returns the static type of the expression.
DartType getStaticType(StaticTypeContext context);
/// Returns the static type of the expression as an instantiation of
/// [superclass].
///
/// Shouldn't be used on code compiled in legacy mode, as this method assumes
/// the IR is strongly typed.
///
/// This method furthermore assumes that the type of the expression actually
/// is a subtype of (some instantiation of) the given [superclass].
/// If this is not the case, either an exception is thrown or the raw type of
/// [superclass] is returned.
InterfaceType getStaticTypeAsInstanceOf(
Class superclass, StaticTypeContext context) {
// This method assumes the program is correctly typed, so if the superclass
// is not generic, we can just return its raw type without computing the
// type of this expression. It also ensures that all types are considered
// subtypes of Object (not just interface types), and function types are
// considered subtypes of Function.
if (superclass.typeParameters.isEmpty) {
return context.typeEnvironment.coreTypes
.rawType(superclass, context.nonNullable);
}
var type = getStaticType(context);
while (type is TypeParameterType) {
TypeParameterType typeParameterType = type;
type =
typeParameterType.promotedBound ?? typeParameterType.parameter.bound;
}
if (type == context.typeEnvironment.nullType) {
return context.typeEnvironment.coreTypes
.bottomInterfaceType(superclass, context.nullable);
} else if (type is NeverType) {
return context.typeEnvironment.coreTypes
.bottomInterfaceType(superclass, type.nullability);
}
if (type is InterfaceType) {
List<DartType> upcastTypeArguments = context.typeEnvironment
.getTypeArgumentsAsInstanceOf(type, superclass);
if (upcastTypeArguments != null) {
return new InterfaceType(
superclass, type.nullability, upcastTypeArguments);
}
} else if (type is BottomType) {
return context.typeEnvironment.coreTypes
.bottomInterfaceType(superclass, context.nonNullable);
}
context.typeEnvironment
.typeError(this, '$type is not a subtype of $superclass');
return context.typeEnvironment.coreTypes
.rawType(superclass, context.nonNullable);
}
R accept<R>(ExpressionVisitor<R> v);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg);
int get precedence => astToText.Precedence.of(this);
String toText(AstTextStrategy strategy) {
AstPrinter printer = new AstPrinter(strategy);
printer.writeExpression(this);
return printer.getText();
}
void toTextInternal(AstPrinter printer);
}
/// An expression containing compile-time errors.
///
/// Should throw a runtime error when evaluated.
///
/// The [fileOffset] of an [InvalidExpression] indicates the location in the
/// tree where the expression occurs, rather than the location of the error.
class InvalidExpression extends Expression {
String message;
InvalidExpression(this.message);
DartType getStaticType(StaticTypeContext context) => const BottomType();
R accept<R>(ExpressionVisitor<R> v) => v.visitInvalidExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitInvalidExpression(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
@override
String toString() {
return "InvalidExpression(${toStringInternal()})";
}
@override
void toTextInternal(AstPrinter printer) {
printer.write('<invalid:');
printer.write(message);
printer.write('>');
}
}
/// Read a local variable, a local function, or a function parameter.
class VariableGet extends Expression {
VariableDeclaration variable;
DartType promotedType; // Null if not promoted.
VariableGet(this.variable,