repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/visitors.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:meta/meta.dart';
import 'base.dart';
import 'specs/class.dart';
import 'specs/constructor.dart';
import 'specs/directive.dart';
import 'specs/enum.dart';
import 'specs/expression.dart';
import 'specs/extension.dart';
import 'specs/field.dart';
import 'specs/library.dart';
import 'specs/method.dart';
import 'specs/reference.dart';
import 'specs/type_function.dart';
import 'specs/type_reference.dart';
@optionalTypeArgs
abstract class SpecVisitor<T> {
const SpecVisitor._();
T visitAnnotation(Expression spec, [T context]);
T visitClass(Class spec, [T context]);
T visitExtension(Extension spec, [T context]);
T visitEnum(Enum spec, [T context]);
T visitConstructor(Constructor spec, String clazz, [T context]);
T visitDirective(Directive spec, [T context]);
T visitField(Field spec, [T context]);
T visitLibrary(Library spec, [T context]);
T visitFunctionType(FunctionType spec, [T context]);
T visitMethod(Method spec, [T context]);
T visitReference(Reference spec, [T context]);
T visitSpec(Spec spec, [T context]);
T visitType(TypeReference spec, [T context]);
T visitTypeParameters(Iterable<Reference> specs, [T context]);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/extension.dart | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'package:meta/meta.dart';
import '../../code_builder.dart';
import '../base.dart';
import '../mixins/annotations.dart';
import '../mixins/dartdoc.dart';
import '../mixins/generics.dart';
import '../visitors.dart';
import 'expression.dart';
import 'field.dart';
import 'method.dart';
import 'reference.dart';
part 'extension.g.dart';
@immutable
abstract class Extension extends Object
with HasAnnotations, HasDartDocs, HasGenerics
implements Built<Extension, ExtensionBuilder>, Spec {
factory Extension([void Function(ExtensionBuilder b) updates]) = _$Extension;
Extension._();
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
@nullable
Reference get on;
@override
BuiltList<Reference> get types;
BuiltList<Method> get methods;
BuiltList<Field> get fields;
/// Name of the extension - optional.
@nullable
String get name;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitExtension(this, context);
}
abstract class ExtensionBuilder extends Object
with HasAnnotationsBuilder, HasDartDocsBuilder, HasGenericsBuilder
implements Builder<Extension, ExtensionBuilder> {
factory ExtensionBuilder() = _$ExtensionBuilder;
ExtensionBuilder._();
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
Reference on;
@override
ListBuilder<Reference> types = ListBuilder<Reference>();
ListBuilder<Method> methods = ListBuilder<Method>();
ListBuilder<Field> fields = ListBuilder<Field>();
/// Name of the extension - optional.
String name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/code.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:meta/meta.dart';
import '../allocator.dart';
import '../base.dart';
import '../emitter.dart';
import '../visitors.dart';
import 'expression.dart';
import 'reference.dart';
part 'code.g.dart';
/// Returns a scoped symbol to [Reference], with an import prefix if needed.
///
/// This is short-hand for [Allocator.allocate] in most implementations.
typedef Allocate = String Function(Reference);
/// Represents arbitrary Dart code (either expressions or statements).
///
/// See the various constructors for details.
abstract class Code implements Spec {
/// Create a simple code body based on a static string.
const factory Code(String code) = StaticCode._;
/// Create a code based that may use a provided [Allocator] for scoping:
///
/// ```dart
/// // Emits `_i123.FooType()`, where `_i123` is the import prefix.
///
/// Code.scope((a) {
/// return '${a.allocate(fooType)}()'
/// });
/// ```
const factory Code.scope(
String Function(Allocate) scope,
) = ScopedCode._;
@override
R accept<R>(covariant CodeVisitor<R> visitor, [R context]);
}
/// Represents blocks of statements of Dart code.
abstract class Block implements Built<Block, BlockBuilder>, Code, Spec {
factory Block([void Function(BlockBuilder) updates]) = _$Block;
factory Block.of(Iterable<Code> statements) =>
Block((b) => b..statements.addAll(statements));
Block._();
@override
R accept<R>(covariant CodeVisitor<R> visitor, [R context]) =>
visitor.visitBlock(this, context);
BuiltList<Code> get statements;
}
abstract class BlockBuilder implements Builder<Block, BlockBuilder> {
factory BlockBuilder() = _$BlockBuilder;
BlockBuilder._();
/// Adds an [expression] to [statements].
///
/// **NOTE**: Not all expressions are _useful_ statements.
void addExpression(Expression expression) {
statements.add(expression.statement);
}
ListBuilder<Code> statements = ListBuilder<Code>();
}
/// Knowledge of different types of blocks of code in Dart.
///
/// **INTERNAL ONLY**.
abstract class CodeVisitor<T> implements SpecVisitor<T> {
T visitBlock(Block code, [T context]);
T visitStaticCode(StaticCode code, [T context]);
T visitScopedCode(ScopedCode code, [T context]);
}
/// Knowledge of how to write valid Dart code from [CodeVisitor].
abstract class CodeEmitter implements CodeVisitor<StringSink> {
@protected
Allocator get allocator;
@override
StringSink visitBlock(Block block, [StringSink output]) {
output ??= StringBuffer();
return visitAll<Code>(block.statements, output, (statement) {
statement.accept(this, output);
}, '\n');
}
@override
StringSink visitStaticCode(StaticCode code, [StringSink output]) {
output ??= StringBuffer();
return output..write(code.code);
}
@override
StringSink visitScopedCode(ScopedCode code, [StringSink output]) {
output ??= StringBuffer();
return output..write(code.code(allocator.allocate));
}
}
/// Represents a code block that requires lazy visiting.
class LazyCode implements Code {
final Spec Function(SpecVisitor) generate;
const LazyCode._(this.generate);
@override
R accept<R>(CodeVisitor<R> visitor, [R context]) =>
generate(visitor).accept(visitor, context);
}
/// Returns a generic [Code] that is lazily generated when visited.
Code lazyCode(Code Function() generate) => _LazyCode(generate);
class _LazyCode implements Code {
final Code Function() generate;
const _LazyCode(this.generate);
@override
R accept<R>(CodeVisitor<R> visitor, [R context]) =>
generate().accept(visitor, context);
}
/// Represents a simple, literal code block to be inserted as-is.
class StaticCode implements Code {
final String code;
const StaticCode._(this.code);
@override
R accept<R>(CodeVisitor<R> visitor, [R context]) =>
visitor.visitStaticCode(this, context);
@override
String toString() => code;
}
/// Represents a code block that may require scoping.
class ScopedCode implements Code {
final String Function(Allocate) code;
const ScopedCode._(this.code);
@override
R accept<R>(CodeVisitor<R> visitor, [R context]) =>
visitor.visitScopedCode(this, context);
@override
String toString() => code((ref) => ref.symbol);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/type_function.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'type_function.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$FunctionType extends FunctionType {
@override
final Reference returnType;
@override
final BuiltList<Reference> types;
@override
final BuiltList<Reference> requiredParameters;
@override
final BuiltList<Reference> optionalParameters;
@override
final BuiltMap<String, Reference> namedParameters;
@override
final bool isNullable;
factory _$FunctionType([void Function(FunctionTypeBuilder) updates]) =>
(new FunctionTypeBuilder()..update(updates)).build() as _$FunctionType;
_$FunctionType._(
{this.returnType,
this.types,
this.requiredParameters,
this.optionalParameters,
this.namedParameters,
this.isNullable})
: super._() {
if (types == null) {
throw new BuiltValueNullFieldError('FunctionType', 'types');
}
if (requiredParameters == null) {
throw new BuiltValueNullFieldError('FunctionType', 'requiredParameters');
}
if (optionalParameters == null) {
throw new BuiltValueNullFieldError('FunctionType', 'optionalParameters');
}
if (namedParameters == null) {
throw new BuiltValueNullFieldError('FunctionType', 'namedParameters');
}
}
@override
FunctionType rebuild(void Function(FunctionTypeBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$FunctionTypeBuilder toBuilder() =>
new _$FunctionTypeBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is FunctionType &&
returnType == other.returnType &&
types == other.types &&
requiredParameters == other.requiredParameters &&
optionalParameters == other.optionalParameters &&
namedParameters == other.namedParameters &&
isNullable == other.isNullable;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc($jc($jc(0, returnType.hashCode), types.hashCode),
requiredParameters.hashCode),
optionalParameters.hashCode),
namedParameters.hashCode),
isNullable.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('FunctionType')
..add('returnType', returnType)
..add('types', types)
..add('requiredParameters', requiredParameters)
..add('optionalParameters', optionalParameters)
..add('namedParameters', namedParameters)
..add('isNullable', isNullable))
.toString();
}
}
class _$FunctionTypeBuilder extends FunctionTypeBuilder {
_$FunctionType _$v;
@override
Reference get returnType {
_$this;
return super.returnType;
}
@override
set returnType(Reference returnType) {
_$this;
super.returnType = returnType;
}
@override
ListBuilder<Reference> get types {
_$this;
return super.types ??= new ListBuilder<Reference>();
}
@override
set types(ListBuilder<Reference> types) {
_$this;
super.types = types;
}
@override
ListBuilder<Reference> get requiredParameters {
_$this;
return super.requiredParameters ??= new ListBuilder<Reference>();
}
@override
set requiredParameters(ListBuilder<Reference> requiredParameters) {
_$this;
super.requiredParameters = requiredParameters;
}
@override
ListBuilder<Reference> get optionalParameters {
_$this;
return super.optionalParameters ??= new ListBuilder<Reference>();
}
@override
set optionalParameters(ListBuilder<Reference> optionalParameters) {
_$this;
super.optionalParameters = optionalParameters;
}
@override
MapBuilder<String, Reference> get namedParameters {
_$this;
return super.namedParameters ??= new MapBuilder<String, Reference>();
}
@override
set namedParameters(MapBuilder<String, Reference> namedParameters) {
_$this;
super.namedParameters = namedParameters;
}
@override
bool get isNullable {
_$this;
return super.isNullable;
}
@override
set isNullable(bool isNullable) {
_$this;
super.isNullable = isNullable;
}
_$FunctionTypeBuilder() : super._();
FunctionTypeBuilder get _$this {
if (_$v != null) {
super.returnType = _$v.returnType;
super.types = _$v.types?.toBuilder();
super.requiredParameters = _$v.requiredParameters?.toBuilder();
super.optionalParameters = _$v.optionalParameters?.toBuilder();
super.namedParameters = _$v.namedParameters?.toBuilder();
super.isNullable = _$v.isNullable;
_$v = null;
}
return this;
}
@override
void replace(FunctionType other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$FunctionType;
}
@override
void update(void Function(FunctionTypeBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$FunctionType build() {
_$FunctionType _$result;
try {
_$result = _$v ??
new _$FunctionType._(
returnType: returnType,
types: types.build(),
requiredParameters: requiredParameters.build(),
optionalParameters: optionalParameters.build(),
namedParameters: namedParameters.build(),
isNullable: isNullable);
} catch (_) {
String _$failedField;
try {
_$failedField = 'types';
types.build();
_$failedField = 'requiredParameters';
requiredParameters.build();
_$failedField = 'optionalParameters';
optionalParameters.build();
_$failedField = 'namedParameters';
namedParameters.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'FunctionType', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/library.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'library.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Library extends Library {
@override
final BuiltList<Directive> directives;
@override
final BuiltList<Spec> body;
factory _$Library([void Function(LibraryBuilder) updates]) =>
(new LibraryBuilder()..update(updates)).build() as _$Library;
_$Library._({this.directives, this.body}) : super._() {
if (directives == null) {
throw new BuiltValueNullFieldError('Library', 'directives');
}
if (body == null) {
throw new BuiltValueNullFieldError('Library', 'body');
}
}
@override
Library rebuild(void Function(LibraryBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$LibraryBuilder toBuilder() => new _$LibraryBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Library &&
directives == other.directives &&
body == other.body;
}
@override
int get hashCode {
return $jf($jc($jc(0, directives.hashCode), body.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Library')
..add('directives', directives)
..add('body', body))
.toString();
}
}
class _$LibraryBuilder extends LibraryBuilder {
_$Library _$v;
@override
ListBuilder<Directive> get directives {
_$this;
return super.directives ??= new ListBuilder<Directive>();
}
@override
set directives(ListBuilder<Directive> directives) {
_$this;
super.directives = directives;
}
@override
ListBuilder<Spec> get body {
_$this;
return super.body ??= new ListBuilder<Spec>();
}
@override
set body(ListBuilder<Spec> body) {
_$this;
super.body = body;
}
_$LibraryBuilder() : super._();
LibraryBuilder get _$this {
if (_$v != null) {
super.directives = _$v.directives?.toBuilder();
super.body = _$v.body?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(Library other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Library;
}
@override
void update(void Function(LibraryBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Library build() {
_$Library _$result;
try {
_$result = _$v ??
new _$Library._(directives: directives.build(), body: body.build());
} catch (_) {
String _$failedField;
try {
_$failedField = 'directives';
directives.build();
_$failedField = 'body';
body.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Library', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/directive.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_value/built_value.dart';
import 'package:collection/collection.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../visitors.dart';
part 'directive.g.dart';
@immutable
abstract class Directive
implements Built<Directive, DirectiveBuilder>, Spec, Comparable<Directive> {
factory Directive([void Function(DirectiveBuilder) updates]) = _$Directive;
factory Directive.import(
String url, {
String as,
List<String> show = const [],
List<String> hide = const [],
}) =>
Directive((builder) => builder
..as = as
..type = DirectiveType.import
..url = url
..show.addAll(show)
..hide.addAll(hide));
factory Directive.importDeferredAs(
String url,
String as, {
List<String> show = const [],
List<String> hide = const [],
}) =>
Directive((builder) => builder
..as = as
..type = DirectiveType.import
..url = url
..deferred = true
..show.addAll(show)
..hide.addAll(hide));
factory Directive.export(
String url, {
List<String> show = const [],
List<String> hide = const [],
}) =>
Directive((builder) => builder
..type = DirectiveType.export
..url = url
..show.addAll(show)
..hide.addAll(hide));
factory Directive.part(String url) => Directive((builder) => builder
..type = DirectiveType.part
..url = url);
Directive._();
@nullable
String get as;
String get url;
DirectiveType get type;
List<String> get show;
List<String> get hide;
bool get deferred;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitDirective(this, context);
@override
int compareTo(Directive other) => _compareDirectives(this, other);
}
abstract class DirectiveBuilder
implements Builder<Directive, DirectiveBuilder> {
factory DirectiveBuilder() = _$DirectiveBuilder;
DirectiveBuilder._();
bool deferred = false;
String as;
String url;
List<String> show = <String>[];
List<String> hide = <String>[];
DirectiveType type;
}
enum DirectiveType {
import,
export,
part,
}
/// Sort import URIs represented by [a] and [b] to honor the
/// "Effective Dart" ordering rules which are enforced by the
/// `directives_ordering` lint.
///
/// 1. `import`s before `export`s
/// 2. `dart:`
/// 3. `package:`
/// 4. relative
/// 5. `part`s
int _compareDirectives(Directive a, Directive b) {
// NOTE: using the fact that `import` is before `export` in the
// `DirectiveType` enum – which allows us to compare using `indexOf`.
var value = DirectiveType.values
.indexOf(a.type)
.compareTo(DirectiveType.values.indexOf(b.type));
if (value == 0) {
final uriA = Uri.parse(a.url);
final uriB = Uri.parse(b.url);
if (uriA.hasScheme) {
if (uriB.hasScheme) {
// If both import URIs have schemes, compare them based on scheme
// `dart` will sort before `package` which is what we want
// schemes are case-insensitive, so compare accordingly
value = compareAsciiLowerCase(uriA.scheme, uriB.scheme);
} else {
value = -1;
}
} else if (uriB.hasScheme) {
value = 1;
}
// If both schemes are the same, compare based on path
if (value == 0) {
value = compareAsciiLowerCase(uriA.path, uriB.path);
}
assert((value == 0) == (a.url == b.url));
}
return value;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/type_reference.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../mixins/generics.dart';
import '../visitors.dart';
import 'code.dart';
import 'expression.dart';
import 'reference.dart';
part 'type_reference.g.dart';
@immutable
abstract class TypeReference extends Expression
with HasGenerics
implements Built<TypeReference, TypeReferenceBuilder>, Reference, Spec {
factory TypeReference([
void Function(TypeReferenceBuilder) updates,
]) = _$TypeReference;
TypeReference._();
@override
String get symbol;
@override
@nullable
String get url;
/// Optional bound generic.
@nullable
Reference get bound;
@override
BuiltList<Reference> get types;
/// Optional nullability.
///
/// An emitter may ignore this if the output is not targeting a Dart language
/// version that supports null safety.
@nullable
bool get isNullable;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitType(this, context);
@override
Expression get expression => CodeExpression(Code.scope((a) => a(this)));
@override
TypeReference get type => this;
@override
Expression newInstance(
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.newOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
);
@override
Expression newInstanceNamed(
String name,
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.newOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
name,
);
@override
Expression constInstance(
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.constOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
);
@override
Expression constInstanceNamed(
String name,
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.constOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
name,
);
}
abstract class TypeReferenceBuilder extends Object
with HasGenericsBuilder
implements Builder<TypeReference, TypeReferenceBuilder> {
factory TypeReferenceBuilder() = _$TypeReferenceBuilder;
TypeReferenceBuilder._();
String symbol;
String url;
/// Optional bound generic.
Reference bound;
@override
ListBuilder<Reference> types = ListBuilder<Reference>();
/// Optional nullability.
///
/// An emitter may ignore this if the output is not targeting a Dart language
/// version that supports null safety.
bool isNullable;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/constructor.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'constructor.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Constructor extends Constructor {
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
@override
final BuiltList<Parameter> optionalParameters;
@override
final BuiltList<Parameter> requiredParameters;
@override
final BuiltList<Code> initializers;
@override
final Code body;
@override
final bool external;
@override
final bool constant;
@override
final bool factory;
@override
final bool lambda;
@override
final String name;
@override
final Reference redirect;
factory _$Constructor([void Function(ConstructorBuilder) updates]) =>
(new ConstructorBuilder()..update(updates)).build() as _$Constructor;
_$Constructor._(
{this.annotations,
this.docs,
this.optionalParameters,
this.requiredParameters,
this.initializers,
this.body,
this.external,
this.constant,
this.factory,
this.lambda,
this.name,
this.redirect})
: super._() {
if (annotations == null) {
throw new BuiltValueNullFieldError('Constructor', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('Constructor', 'docs');
}
if (optionalParameters == null) {
throw new BuiltValueNullFieldError('Constructor', 'optionalParameters');
}
if (requiredParameters == null) {
throw new BuiltValueNullFieldError('Constructor', 'requiredParameters');
}
if (initializers == null) {
throw new BuiltValueNullFieldError('Constructor', 'initializers');
}
if (external == null) {
throw new BuiltValueNullFieldError('Constructor', 'external');
}
if (constant == null) {
throw new BuiltValueNullFieldError('Constructor', 'constant');
}
if (factory == null) {
throw new BuiltValueNullFieldError('Constructor', 'factory');
}
}
@override
Constructor rebuild(void Function(ConstructorBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$ConstructorBuilder toBuilder() => new _$ConstructorBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Constructor &&
annotations == other.annotations &&
docs == other.docs &&
optionalParameters == other.optionalParameters &&
requiredParameters == other.requiredParameters &&
initializers == other.initializers &&
body == other.body &&
external == other.external &&
constant == other.constant &&
factory == other.factory &&
lambda == other.lambda &&
name == other.name &&
redirect == other.redirect;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc($jc(0, annotations.hashCode),
docs.hashCode),
optionalParameters.hashCode),
requiredParameters.hashCode),
initializers.hashCode),
body.hashCode),
external.hashCode),
constant.hashCode),
factory.hashCode),
lambda.hashCode),
name.hashCode),
redirect.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Constructor')
..add('annotations', annotations)
..add('docs', docs)
..add('optionalParameters', optionalParameters)
..add('requiredParameters', requiredParameters)
..add('initializers', initializers)
..add('body', body)
..add('external', external)
..add('constant', constant)
..add('factory', factory)
..add('lambda', lambda)
..add('name', name)
..add('redirect', redirect))
.toString();
}
}
class _$ConstructorBuilder extends ConstructorBuilder {
_$Constructor _$v;
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
@override
ListBuilder<Parameter> get optionalParameters {
_$this;
return super.optionalParameters ??= new ListBuilder<Parameter>();
}
@override
set optionalParameters(ListBuilder<Parameter> optionalParameters) {
_$this;
super.optionalParameters = optionalParameters;
}
@override
ListBuilder<Parameter> get requiredParameters {
_$this;
return super.requiredParameters ??= new ListBuilder<Parameter>();
}
@override
set requiredParameters(ListBuilder<Parameter> requiredParameters) {
_$this;
super.requiredParameters = requiredParameters;
}
@override
ListBuilder<Code> get initializers {
_$this;
return super.initializers ??= new ListBuilder<Code>();
}
@override
set initializers(ListBuilder<Code> initializers) {
_$this;
super.initializers = initializers;
}
@override
Code get body {
_$this;
return super.body;
}
@override
set body(Code body) {
_$this;
super.body = body;
}
@override
bool get external {
_$this;
return super.external;
}
@override
set external(bool external) {
_$this;
super.external = external;
}
@override
bool get constant {
_$this;
return super.constant;
}
@override
set constant(bool constant) {
_$this;
super.constant = constant;
}
@override
bool get factory {
_$this;
return super.factory;
}
@override
set factory(bool factory) {
_$this;
super.factory = factory;
}
@override
bool get lambda {
_$this;
return super.lambda;
}
@override
set lambda(bool lambda) {
_$this;
super.lambda = lambda;
}
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
@override
Reference get redirect {
_$this;
return super.redirect;
}
@override
set redirect(Reference redirect) {
_$this;
super.redirect = redirect;
}
_$ConstructorBuilder() : super._();
ConstructorBuilder get _$this {
if (_$v != null) {
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
super.optionalParameters = _$v.optionalParameters?.toBuilder();
super.requiredParameters = _$v.requiredParameters?.toBuilder();
super.initializers = _$v.initializers?.toBuilder();
super.body = _$v.body;
super.external = _$v.external;
super.constant = _$v.constant;
super.factory = _$v.factory;
super.lambda = _$v.lambda;
super.name = _$v.name;
super.redirect = _$v.redirect;
_$v = null;
}
return this;
}
@override
void replace(Constructor other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Constructor;
}
@override
void update(void Function(ConstructorBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Constructor build() {
_$Constructor _$result;
try {
_$result = _$v ??
new _$Constructor._(
annotations: annotations.build(),
docs: docs.build(),
optionalParameters: optionalParameters.build(),
requiredParameters: requiredParameters.build(),
initializers: initializers.build(),
body: body,
external: external,
constant: constant,
factory: factory,
lambda: lambda,
name: name,
redirect: redirect);
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
_$failedField = 'optionalParameters';
optionalParameters.build();
_$failedField = 'requiredParameters';
requiredParameters.build();
_$failedField = 'initializers';
initializers.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Constructor', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/library.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../visitors.dart';
import 'directive.dart';
part 'library.g.dart';
@immutable
abstract class Library implements Built<Library, LibraryBuilder>, Spec {
factory Library([void Function(LibraryBuilder) updates]) = _$Library;
Library._();
BuiltList<Directive> get directives;
BuiltList<Spec> get body;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitLibrary(this, context);
}
abstract class LibraryBuilder implements Builder<Library, LibraryBuilder> {
factory LibraryBuilder() = _$LibraryBuilder;
LibraryBuilder._();
ListBuilder<Spec> body = ListBuilder<Spec>();
ListBuilder<Directive> directives = ListBuilder<Directive>();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/method.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../mixins/annotations.dart';
import '../mixins/dartdoc.dart';
import '../mixins/generics.dart';
import '../visitors.dart';
import 'code.dart';
import 'expression.dart';
import 'reference.dart';
part 'method.g.dart';
const _$void = Reference('void');
@immutable
abstract class Method extends Object
with HasAnnotations, HasGenerics, HasDartDocs
implements Built<Method, MethodBuilder>, Spec {
factory Method([void Function(MethodBuilder) updates]) = _$Method;
factory Method.returnsVoid([void Function(MethodBuilder) updates]) =>
Method((b) {
if (updates != null) {
updates(b);
}
b.returns = _$void;
});
Method._();
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
@override
BuiltList<Reference> get types;
/// Optional parameters.
BuiltList<Parameter> get optionalParameters;
/// Required parameters.
BuiltList<Parameter> get requiredParameters;
/// Body of the method.
@nullable
Code get body;
/// Whether the method should be prefixed with `external`.
bool get external;
/// Whether this method is a simple lambda expression.
///
/// May be `null` to be inferred based on the value of [body].
@nullable
bool get lambda;
/// Whether this method should be prefixed with `static`.
///
/// This is only valid within classes.
bool get static;
/// Name of the method or function.
///
/// May be `null` when being used as a [closure].
@nullable
String get name;
/// Whether this is a getter or setter.
@nullable
MethodType get type;
/// Whether this method is `async`, `async*`, or `sync*`.
@nullable
MethodModifier get modifier;
@nullable
Reference get returns;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitMethod(this, context);
/// This method as a closure.
Expression get closure => toClosure(this);
}
abstract class MethodBuilder extends Object
with HasAnnotationsBuilder, HasGenericsBuilder, HasDartDocsBuilder
implements Builder<Method, MethodBuilder> {
factory MethodBuilder() = _$MethodBuilder;
MethodBuilder._();
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
@override
ListBuilder<Reference> types = ListBuilder<Reference>();
/// Optional parameters.
ListBuilder<Parameter> optionalParameters = ListBuilder<Parameter>();
/// Required parameters.
ListBuilder<Parameter> requiredParameters = ListBuilder<Parameter>();
/// Body of the method.
Code body;
/// Whether the method should be prefixed with `external`.
bool external = false;
/// Whether this method is a simple lambda expression.
///
/// If not specified this is inferred from the [body].
bool lambda;
/// Whether this method should be prefixed with `static`.
///
/// This is only valid within classes.
bool static = false;
/// Name of the method or function.
String name;
/// Whether this is a getter or setter.
MethodType type;
/// Whether this method is `async`, `async*`, or `sync*`.
MethodModifier modifier;
Reference returns;
}
enum MethodType {
getter,
setter,
}
enum MethodModifier {
async,
asyncStar,
syncStar,
}
abstract class Parameter extends Object
with HasAnnotations, HasGenerics, HasDartDocs
implements Built<Parameter, ParameterBuilder> {
factory Parameter([void Function(ParameterBuilder) updates]) = _$Parameter;
Parameter._();
/// If not `null`, a default assignment if the parameter is optional.
@nullable
Code get defaultTo;
/// Name of the parameter.
String get name;
/// Whether this parameter should be named, if optional.
bool get named;
/// Whether this parameter should be field formal (i.e. `this.`).
///
/// This is only valid on constructors;
bool get toThis;
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
@override
BuiltList<Reference> get types;
/// Type of the parameter;
@nullable
Reference get type;
/// Whether this parameter should be annotated with the `required` keyword.
///
/// This is only valid on named parameters.
///
/// This is only valid when the output is targeting a Dart language version
/// that supports null safety.
bool get required;
/// Whether this parameter should be annotated with the `covariant` keyword.
///
/// This is only valid on instance methods.
bool get covariant;
}
abstract class ParameterBuilder extends Object
with HasAnnotationsBuilder, HasGenericsBuilder, HasDartDocsBuilder
implements Builder<Parameter, ParameterBuilder> {
factory ParameterBuilder() = _$ParameterBuilder;
ParameterBuilder._();
/// If not `null`, a default assignment if the parameter is optional.
Code defaultTo;
/// Name of the parameter.
String name;
/// Whether this parameter should be named, if optional.
bool named = false;
/// Whether this parameter should be field formal (i.e. `this.`).
///
/// This is only valid on constructors;
bool toThis = false;
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
@override
ListBuilder<Reference> types = ListBuilder<Reference>();
/// Type of the parameter;
Reference type;
/// Whether this parameter should be annotated with the `required` keyword.
///
/// This is only valid on named parameters.
///
/// This is only valid when the output is targeting a Dart language version
/// that supports null safety.
bool required = false;
/// Whether this parameter should be annotated with the `covariant` keyword.
///
/// This is only valid on instance methods.
bool covariant = false;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/reference.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library code_builder.src.specs.reference;
import 'package:built_value/built_value.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../visitors.dart';
import 'code.dart';
import 'expression.dart';
import 'type_reference.dart';
/// Short-hand for `Reference(symbol, url)`.
Reference refer(String symbol, [String url]) => Reference(symbol, url);
/// A reference to [symbol], such as a class, or top-level method or field.
///
/// References can be collected and collated in order to automatically generate
/// `import` statements for all used symbols.
@immutable
class Reference extends Expression implements Spec {
/// Relative, `package:` or `dart:` URL of the library.
///
/// May be omitted (`null`) in order to express "same library".
final String url;
/// Name of the class, method, or field.
final String symbol;
/// Create a reference to [symbol] in [url].
const Reference(this.symbol, [this.url]);
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitReference(this, context);
@override
int get hashCode => '$url#$symbol'.hashCode;
@override
bool operator ==(Object other) =>
other is Reference && other.url == url && other.symbol == symbol;
/// Returns a new instance of this expression.
Expression newInstance(
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.newOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
);
/// Returns a new instance of this expression with a named constructor.
Expression newInstanceNamed(
String name,
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.newOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
name,
);
/// Returns a const instance of this expression.
Expression constInstance(
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.constOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
);
/// Returns a const instance of this expression with a named constructor.
Expression constInstanceNamed(
String name,
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression.constOf(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
name,
);
@override
Expression get expression => CodeExpression(Code.scope((a) => a(this)));
@override
String toString() => (newBuiltValueToStringHelper('Reference')
..add('url', url)
..add('symbol', symbol))
.toString();
/// Returns as a [TypeReference], which allows adding generic type parameters.
Reference get type => TypeReference((b) => b
..url = url
..symbol = symbol);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/type_reference.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'type_reference.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$TypeReference extends TypeReference {
@override
final String symbol;
@override
final String url;
@override
final Reference bound;
@override
final BuiltList<Reference> types;
@override
final bool isNullable;
factory _$TypeReference([void Function(TypeReferenceBuilder) updates]) =>
(new TypeReferenceBuilder()..update(updates)).build() as _$TypeReference;
_$TypeReference._(
{this.symbol, this.url, this.bound, this.types, this.isNullable})
: super._() {
if (symbol == null) {
throw new BuiltValueNullFieldError('TypeReference', 'symbol');
}
if (types == null) {
throw new BuiltValueNullFieldError('TypeReference', 'types');
}
}
@override
TypeReference rebuild(void Function(TypeReferenceBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$TypeReferenceBuilder toBuilder() =>
new _$TypeReferenceBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is TypeReference &&
symbol == other.symbol &&
url == other.url &&
bound == other.bound &&
types == other.types &&
isNullable == other.isNullable;
}
@override
int get hashCode {
return $jf($jc(
$jc($jc($jc($jc(0, symbol.hashCode), url.hashCode), bound.hashCode),
types.hashCode),
isNullable.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('TypeReference')
..add('symbol', symbol)
..add('url', url)
..add('bound', bound)
..add('types', types)
..add('isNullable', isNullable))
.toString();
}
}
class _$TypeReferenceBuilder extends TypeReferenceBuilder {
_$TypeReference _$v;
@override
String get symbol {
_$this;
return super.symbol;
}
@override
set symbol(String symbol) {
_$this;
super.symbol = symbol;
}
@override
String get url {
_$this;
return super.url;
}
@override
set url(String url) {
_$this;
super.url = url;
}
@override
Reference get bound {
_$this;
return super.bound;
}
@override
set bound(Reference bound) {
_$this;
super.bound = bound;
}
@override
ListBuilder<Reference> get types {
_$this;
return super.types ??= new ListBuilder<Reference>();
}
@override
set types(ListBuilder<Reference> types) {
_$this;
super.types = types;
}
@override
bool get isNullable {
_$this;
return super.isNullable;
}
@override
set isNullable(bool isNullable) {
_$this;
super.isNullable = isNullable;
}
_$TypeReferenceBuilder() : super._();
TypeReferenceBuilder get _$this {
if (_$v != null) {
super.symbol = _$v.symbol;
super.url = _$v.url;
super.bound = _$v.bound;
super.types = _$v.types?.toBuilder();
super.isNullable = _$v.isNullable;
_$v = null;
}
return this;
}
@override
void replace(TypeReference other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$TypeReference;
}
@override
void update(void Function(TypeReferenceBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$TypeReference build() {
_$TypeReference _$result;
try {
_$result = _$v ??
new _$TypeReference._(
symbol: symbol,
url: url,
bound: bound,
types: types.build(),
isNullable: isNullable);
} catch (_) {
String _$failedField;
try {
_$failedField = 'types';
types.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'TypeReference', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/field.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'field.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Field extends Field {
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
@override
final Code assignment;
@override
final bool static;
@override
final String name;
@override
final Reference type;
@override
final FieldModifier modifier;
factory _$Field([void Function(FieldBuilder) updates]) =>
(new FieldBuilder()..update(updates)).build() as _$Field;
_$Field._(
{this.annotations,
this.docs,
this.assignment,
this.static,
this.name,
this.type,
this.modifier})
: super._() {
if (annotations == null) {
throw new BuiltValueNullFieldError('Field', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('Field', 'docs');
}
if (static == null) {
throw new BuiltValueNullFieldError('Field', 'static');
}
if (name == null) {
throw new BuiltValueNullFieldError('Field', 'name');
}
if (modifier == null) {
throw new BuiltValueNullFieldError('Field', 'modifier');
}
}
@override
Field rebuild(void Function(FieldBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$FieldBuilder toBuilder() => new _$FieldBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Field &&
annotations == other.annotations &&
docs == other.docs &&
assignment == other.assignment &&
static == other.static &&
name == other.name &&
type == other.type &&
modifier == other.modifier;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc($jc($jc(0, annotations.hashCode), docs.hashCode),
assignment.hashCode),
static.hashCode),
name.hashCode),
type.hashCode),
modifier.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Field')
..add('annotations', annotations)
..add('docs', docs)
..add('assignment', assignment)
..add('static', static)
..add('name', name)
..add('type', type)
..add('modifier', modifier))
.toString();
}
}
class _$FieldBuilder extends FieldBuilder {
_$Field _$v;
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
@override
Code get assignment {
_$this;
return super.assignment;
}
@override
set assignment(Code assignment) {
_$this;
super.assignment = assignment;
}
@override
bool get static {
_$this;
return super.static;
}
@override
set static(bool static) {
_$this;
super.static = static;
}
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
@override
Reference get type {
_$this;
return super.type;
}
@override
set type(Reference type) {
_$this;
super.type = type;
}
@override
FieldModifier get modifier {
_$this;
return super.modifier;
}
@override
set modifier(FieldModifier modifier) {
_$this;
super.modifier = modifier;
}
_$FieldBuilder() : super._();
FieldBuilder get _$this {
if (_$v != null) {
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
super.assignment = _$v.assignment;
super.static = _$v.static;
super.name = _$v.name;
super.type = _$v.type;
super.modifier = _$v.modifier;
_$v = null;
}
return this;
}
@override
void replace(Field other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Field;
}
@override
void update(void Function(FieldBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Field build() {
_$Field _$result;
try {
_$result = _$v ??
new _$Field._(
annotations: annotations.build(),
docs: docs.build(),
assignment: assignment,
static: static,
name: name,
type: type,
modifier: modifier);
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Field', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/expression.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library code_builder.src.specs.expression;
import 'package:meta/meta.dart';
import '../base.dart';
import '../emitter.dart';
import '../visitors.dart';
import 'code.dart';
import 'method.dart';
import 'reference.dart';
import 'type_function.dart';
part 'expression/binary.dart';
part 'expression/closure.dart';
part 'expression/code.dart';
part 'expression/invoke.dart';
part 'expression/literal.dart';
/// Represents a [code] block that wraps an [Expression].
/// Represents a Dart expression.
///
/// See various concrete implementations for details.
abstract class Expression implements Spec {
const Expression();
/// An empty expression.
static const _empty = CodeExpression(Code(''));
@override
R accept<R>(covariant ExpressionVisitor<R> visitor, [R context]);
/// The expression as a valid [Code] block.
///
/// Also see [statement].
Code get code => ToCodeExpression(this);
/// The expression as a valid [Code] block with a trailing `;`.
Code get statement => ToCodeExpression(this, true);
/// Returns the result of `this` `&&` [other].
Expression and(Expression other) =>
BinaryExpression._(expression, other, '&&');
/// Returns the result of `this` `||` [other].
Expression or(Expression other) =>
BinaryExpression._(expression, other, '||');
/// Returns the result of `!this`.
Expression negate() =>
BinaryExpression._(_empty, expression, '!', addSpace: false);
/// Returns the result of `this` `as` [other].
Expression asA(Expression other) => CodeExpression(Block.of([
const Code('('),
BinaryExpression._(
expression,
other,
'as',
).code,
const Code(')')
]));
/// Returns accessing the index operator (`[]`) on `this`.
Expression index(Expression index) => BinaryExpression._(
expression,
CodeExpression(Block.of([
const Code('['),
index.code,
const Code(']'),
])),
'',
);
/// Returns the result of `this` `is` [other].
Expression isA(Expression other) => BinaryExpression._(
expression,
other,
'is',
);
/// Returns the result of `this` `is!` [other].
Expression isNotA(Expression other) => BinaryExpression._(
expression,
other,
'is!',
);
/// Returns the result of `this` `==` [other].
Expression equalTo(Expression other) => BinaryExpression._(
expression,
other,
'==',
);
/// Returns the result of `this` `!=` [other].
Expression notEqualTo(Expression other) => BinaryExpression._(
expression,
other,
'!=',
);
/// Returns the result of `this` `>` [other].
Expression greaterThan(Expression other) => BinaryExpression._(
expression,
other,
'>',
);
/// Returns the result of `this` `<` [other].
Expression lessThan(Expression other) => BinaryExpression._(
expression,
other,
'<',
);
/// Returns the result of `this` `>=` [other].
Expression greaterOrEqualTo(Expression other) => BinaryExpression._(
expression,
other,
'>=',
);
/// Returns the result of `this` `<=` [other].
Expression lessOrEqualTo(Expression other) => BinaryExpression._(
expression,
other,
'<=',
);
/// Returns the result of `this` `+` [other].
Expression operatorAdd(Expression other) => BinaryExpression._(
expression,
other,
'+',
);
/// Returns the result of `this` `-` [other].
Expression operatorSubstract(Expression other) => BinaryExpression._(
expression,
other,
'-',
);
/// Returns the result of `this` `/` [other].
Expression operatorDivide(Expression other) => BinaryExpression._(
expression,
other,
'/',
);
/// Returns the result of `this` `*` [other].
Expression operatorMultiply(Expression other) => BinaryExpression._(
expression,
other,
'*',
);
/// Returns the result of `this` `%` [other].
Expression operatorEuclideanModulo(Expression other) => BinaryExpression._(
expression,
other,
'%',
);
Expression conditional(Expression whenTrue, Expression whenFalse) =>
BinaryExpression._(
expression,
BinaryExpression._(whenTrue, whenFalse, ':'),
'?',
);
/// This expression preceded by `await`.
Expression get awaited => BinaryExpression._(
_empty,
this,
'await',
);
/// Return `{other} = {this}`.
Expression assign(Expression other) => BinaryExpression._(
this,
other,
'=',
);
/// Return `{other} ?? {this}`.
Expression ifNullThen(Expression other) => BinaryExpression._(
this,
other,
'??',
);
/// Return `{other} ??= {this}`.
Expression assignNullAware(Expression other) => BinaryExpression._(
this,
other,
'??=',
);
/// Return `var {name} = {this}`.
Expression assignVar(String name, [Reference type]) => BinaryExpression._(
type == null
? LiteralExpression._('var $name')
: BinaryExpression._(
type.expression,
LiteralExpression._(name),
'',
),
this,
'=',
);
/// Return `final {name} = {this}`.
Expression assignFinal(String name, [Reference type]) => BinaryExpression._(
type == null
? const LiteralExpression._('final')
: BinaryExpression._(
const LiteralExpression._('final'),
type.expression,
'',
),
this,
'$name =',
);
/// Return `const {name} = {this}`.
Expression assignConst(String name, [Reference type]) => BinaryExpression._(
type == null
? const LiteralExpression._('const')
: BinaryExpression._(
const LiteralExpression._('const'),
type.expression,
'',
),
this,
'$name =',
isConst: true,
);
/// Call this expression as a method.
Expression call(
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
InvokeExpression._(
this,
positionalArguments.toList(),
namedArguments,
typeArguments,
);
/// Returns an expression accessing `.<name>` on this expression.
Expression property(String name) => BinaryExpression._(
this,
LiteralExpression._(name),
'.',
addSpace: false,
);
/// Returns an expression accessing `..<name>` on this expression.
Expression cascade(String name) => BinaryExpression._(
this,
LiteralExpression._(name),
'..',
addSpace: false,
);
/// Returns an expression accessing `?.<name>` on this expression.
Expression nullSafeProperty(String name) => BinaryExpression._(
this,
LiteralExpression._(name),
'?.',
addSpace: false,
);
/// This expression preceded by `return`.
Expression get returned => BinaryExpression._(
const LiteralExpression._('return'),
this,
'',
);
/// This expression preceded by `throw`.
Expression get thrown => BinaryExpression._(
const LiteralExpression._('throw'),
this,
'',
);
/// May be overridden to support other types implementing [Expression].
@visibleForOverriding
Expression get expression => this;
}
/// Creates `typedef {name} =`.
Code createTypeDef(String name, FunctionType type) => BinaryExpression._(
LiteralExpression._('typedef $name'), type.expression, '=')
.statement;
class ToCodeExpression implements Code {
final Expression code;
/// Whether this code should be considered a _statement_.
final bool isStatement;
@visibleForTesting
const ToCodeExpression(this.code, [this.isStatement = false]);
@override
R accept<R>(CodeVisitor<R> visitor, [R context]) =>
(visitor as ExpressionVisitor<R>).visitToCodeExpression(this, context);
@override
String toString() => code.toString();
}
/// Knowledge of different types of expressions in Dart.
///
/// **INTERNAL ONLY**.
abstract class ExpressionVisitor<T> implements SpecVisitor<T> {
T visitToCodeExpression(ToCodeExpression code, [T context]);
T visitBinaryExpression(BinaryExpression expression, [T context]);
T visitClosureExpression(ClosureExpression expression, [T context]);
T visitCodeExpression(CodeExpression expression, [T context]);
T visitInvokeExpression(InvokeExpression expression, [T context]);
T visitLiteralExpression(LiteralExpression expression, [T context]);
T visitLiteralListExpression(LiteralListExpression expression, [T context]);
T visitLiteralSetExpression(LiteralSetExpression expression, [T context]);
T visitLiteralMapExpression(LiteralMapExpression expression, [T context]);
}
/// Knowledge of how to write valid Dart code from [ExpressionVisitor].
///
/// **INTERNAL ONLY**.
abstract class ExpressionEmitter implements ExpressionVisitor<StringSink> {
@override
StringSink visitToCodeExpression(ToCodeExpression expression,
[StringSink output]) {
output ??= StringBuffer();
expression.code.accept(this, output);
if (expression.isStatement) {
output.write(';');
}
return output;
}
@override
StringSink visitBinaryExpression(BinaryExpression expression,
[StringSink output]) {
output ??= StringBuffer();
expression.left.accept(this, output);
if (expression.addSpace) {
output.write(' ');
}
output.write(expression.operator);
if (expression.addSpace) {
output.write(' ');
}
startConstCode(expression.isConst, () {
expression.right.accept(this, output);
});
return output;
}
@override
StringSink visitClosureExpression(ClosureExpression expression,
[StringSink output]) {
output ??= StringBuffer();
return expression.method.accept(this, output);
}
@override
StringSink visitCodeExpression(CodeExpression expression,
[StringSink output]) {
output ??= StringBuffer();
final visitor = this as CodeVisitor<StringSink>;
return expression.code.accept(visitor, output);
}
@override
StringSink visitInvokeExpression(InvokeExpression expression,
[StringSink output]) {
output ??= StringBuffer();
return _writeConstExpression(
output, expression.type == InvokeExpressionType.constInstance, () {
expression.target.accept(this, output);
if (expression.name != null) {
output..write('.')..write(expression.name);
}
if (expression.typeArguments.isNotEmpty) {
output.write('<');
visitAll<Reference>(expression.typeArguments, output, (type) {
type.accept(this, output);
});
output.write('>');
}
output.write('(');
visitAll<Spec>(expression.positionalArguments, output, (spec) {
spec.accept(this, output);
});
if (expression.positionalArguments.isNotEmpty &&
expression.namedArguments.isNotEmpty) {
output.write(', ');
}
visitAll<String>(expression.namedArguments.keys, output, (name) {
output..write(name)..write(': ');
expression.namedArguments[name].accept(this, output);
});
return output..write(')');
});
}
@override
StringSink visitLiteralExpression(LiteralExpression expression,
[StringSink output]) {
output ??= StringBuffer();
return output..write(expression.literal);
}
void _acceptLiteral(Object literalOrSpec, StringSink output) {
if (literalOrSpec is Spec) {
literalOrSpec.accept(this, output);
return;
}
literal(literalOrSpec).accept(this, output);
}
bool _withInConstExpression = false;
@override
StringSink visitLiteralListExpression(
LiteralListExpression expression, [
StringSink output,
]) {
output ??= StringBuffer();
return _writeConstExpression(output, expression.isConst, () {
if (expression.type != null) {
output.write('<');
expression.type.accept(this, output);
output.write('>');
}
output.write('[');
visitAll<Object>(expression.values, output, (value) {
_acceptLiteral(value, output);
});
return output..write(']');
});
}
@override
StringSink visitLiteralSetExpression(
LiteralSetExpression expression, [
StringSink output,
]) {
output ??= StringBuffer();
return _writeConstExpression(output, expression.isConst, () {
if (expression.type != null) {
output.write('<');
expression.type.accept(this, output);
output.write('>');
}
output.write('{');
visitAll<Object>(expression.values, output, (value) {
_acceptLiteral(value, output);
});
return output..write('}');
});
}
@override
StringSink visitLiteralMapExpression(
LiteralMapExpression expression, [
StringSink output,
]) {
output ??= StringBuffer();
return _writeConstExpression(output, expression.isConst, () {
if (expression.keyType != null) {
output.write('<');
expression.keyType.accept(this, output);
output.write(', ');
if (expression.valueType == null) {
const Reference('dynamic', 'dart:core').accept(this, output);
} else {
expression.valueType.accept(this, output);
}
output.write('>');
}
output.write('{');
visitAll<Object>(expression.values.keys, output, (key) {
final value = expression.values[key];
_acceptLiteral(key, output);
output.write(': ');
_acceptLiteral(value, output);
});
return output..write('}');
});
}
/// Executes [visit] within a context which may alter the output if [isConst]
/// is `true`.
///
/// This allows constant expressions to omit the `const` keyword if they
/// are already within a constant expression.
void startConstCode(
bool isConst,
Null Function() visit,
) {
final previousConstContext = _withInConstExpression;
if (isConst) {
_withInConstExpression = true;
}
visit();
_withInConstExpression = previousConstContext;
}
/// Similar to [startConstCode], but handles writing `"const "` if [isConst]
/// is `true` and the invocation is not nested under other invocations where
/// [isConst] is true.
StringSink _writeConstExpression(
StringSink sink,
bool isConst,
StringSink Function() visitExpression,
) {
final previousConstContext = _withInConstExpression;
if (isConst) {
if (!_withInConstExpression) {
sink.write('const ');
}
_withInConstExpression = true;
}
final returnedSink = visitExpression();
assert(identical(returnedSink, sink));
_withInConstExpression = previousConstContext;
return sink;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/method.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'method.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Method extends Method {
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
@override
final BuiltList<Reference> types;
@override
final BuiltList<Parameter> optionalParameters;
@override
final BuiltList<Parameter> requiredParameters;
@override
final Code body;
@override
final bool external;
@override
final bool lambda;
@override
final bool static;
@override
final String name;
@override
final MethodType type;
@override
final MethodModifier modifier;
@override
final Reference returns;
factory _$Method([void Function(MethodBuilder) updates]) =>
(new MethodBuilder()..update(updates)).build() as _$Method;
_$Method._(
{this.annotations,
this.docs,
this.types,
this.optionalParameters,
this.requiredParameters,
this.body,
this.external,
this.lambda,
this.static,
this.name,
this.type,
this.modifier,
this.returns})
: super._() {
if (annotations == null) {
throw new BuiltValueNullFieldError('Method', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('Method', 'docs');
}
if (types == null) {
throw new BuiltValueNullFieldError('Method', 'types');
}
if (optionalParameters == null) {
throw new BuiltValueNullFieldError('Method', 'optionalParameters');
}
if (requiredParameters == null) {
throw new BuiltValueNullFieldError('Method', 'requiredParameters');
}
if (external == null) {
throw new BuiltValueNullFieldError('Method', 'external');
}
if (static == null) {
throw new BuiltValueNullFieldError('Method', 'static');
}
}
@override
Method rebuild(void Function(MethodBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$MethodBuilder toBuilder() => new _$MethodBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Method &&
annotations == other.annotations &&
docs == other.docs &&
types == other.types &&
optionalParameters == other.optionalParameters &&
requiredParameters == other.requiredParameters &&
body == other.body &&
external == other.external &&
lambda == other.lambda &&
static == other.static &&
name == other.name &&
type == other.type &&
modifier == other.modifier &&
returns == other.returns;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(0,
annotations.hashCode),
docs.hashCode),
types.hashCode),
optionalParameters.hashCode),
requiredParameters.hashCode),
body.hashCode),
external.hashCode),
lambda.hashCode),
static.hashCode),
name.hashCode),
type.hashCode),
modifier.hashCode),
returns.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Method')
..add('annotations', annotations)
..add('docs', docs)
..add('types', types)
..add('optionalParameters', optionalParameters)
..add('requiredParameters', requiredParameters)
..add('body', body)
..add('external', external)
..add('lambda', lambda)
..add('static', static)
..add('name', name)
..add('type', type)
..add('modifier', modifier)
..add('returns', returns))
.toString();
}
}
class _$MethodBuilder extends MethodBuilder {
_$Method _$v;
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
@override
ListBuilder<Reference> get types {
_$this;
return super.types ??= new ListBuilder<Reference>();
}
@override
set types(ListBuilder<Reference> types) {
_$this;
super.types = types;
}
@override
ListBuilder<Parameter> get optionalParameters {
_$this;
return super.optionalParameters ??= new ListBuilder<Parameter>();
}
@override
set optionalParameters(ListBuilder<Parameter> optionalParameters) {
_$this;
super.optionalParameters = optionalParameters;
}
@override
ListBuilder<Parameter> get requiredParameters {
_$this;
return super.requiredParameters ??= new ListBuilder<Parameter>();
}
@override
set requiredParameters(ListBuilder<Parameter> requiredParameters) {
_$this;
super.requiredParameters = requiredParameters;
}
@override
Code get body {
_$this;
return super.body;
}
@override
set body(Code body) {
_$this;
super.body = body;
}
@override
bool get external {
_$this;
return super.external;
}
@override
set external(bool external) {
_$this;
super.external = external;
}
@override
bool get lambda {
_$this;
return super.lambda;
}
@override
set lambda(bool lambda) {
_$this;
super.lambda = lambda;
}
@override
bool get static {
_$this;
return super.static;
}
@override
set static(bool static) {
_$this;
super.static = static;
}
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
@override
MethodType get type {
_$this;
return super.type;
}
@override
set type(MethodType type) {
_$this;
super.type = type;
}
@override
MethodModifier get modifier {
_$this;
return super.modifier;
}
@override
set modifier(MethodModifier modifier) {
_$this;
super.modifier = modifier;
}
@override
Reference get returns {
_$this;
return super.returns;
}
@override
set returns(Reference returns) {
_$this;
super.returns = returns;
}
_$MethodBuilder() : super._();
MethodBuilder get _$this {
if (_$v != null) {
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
super.types = _$v.types?.toBuilder();
super.optionalParameters = _$v.optionalParameters?.toBuilder();
super.requiredParameters = _$v.requiredParameters?.toBuilder();
super.body = _$v.body;
super.external = _$v.external;
super.lambda = _$v.lambda;
super.static = _$v.static;
super.name = _$v.name;
super.type = _$v.type;
super.modifier = _$v.modifier;
super.returns = _$v.returns;
_$v = null;
}
return this;
}
@override
void replace(Method other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Method;
}
@override
void update(void Function(MethodBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Method build() {
_$Method _$result;
try {
_$result = _$v ??
new _$Method._(
annotations: annotations.build(),
docs: docs.build(),
types: types.build(),
optionalParameters: optionalParameters.build(),
requiredParameters: requiredParameters.build(),
body: body,
external: external,
lambda: lambda,
static: static,
name: name,
type: type,
modifier: modifier,
returns: returns);
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
_$failedField = 'types';
types.build();
_$failedField = 'optionalParameters';
optionalParameters.build();
_$failedField = 'requiredParameters';
requiredParameters.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Method', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
class _$Parameter extends Parameter {
@override
final Code defaultTo;
@override
final String name;
@override
final bool named;
@override
final bool toThis;
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
@override
final BuiltList<Reference> types;
@override
final Reference type;
@override
final bool required;
@override
final bool covariant;
factory _$Parameter([void Function(ParameterBuilder) updates]) =>
(new ParameterBuilder()..update(updates)).build() as _$Parameter;
_$Parameter._(
{this.defaultTo,
this.name,
this.named,
this.toThis,
this.annotations,
this.docs,
this.types,
this.type,
this.required,
this.covariant})
: super._() {
if (name == null) {
throw new BuiltValueNullFieldError('Parameter', 'name');
}
if (named == null) {
throw new BuiltValueNullFieldError('Parameter', 'named');
}
if (toThis == null) {
throw new BuiltValueNullFieldError('Parameter', 'toThis');
}
if (annotations == null) {
throw new BuiltValueNullFieldError('Parameter', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('Parameter', 'docs');
}
if (types == null) {
throw new BuiltValueNullFieldError('Parameter', 'types');
}
if (required == null) {
throw new BuiltValueNullFieldError('Parameter', 'required');
}
if (covariant == null) {
throw new BuiltValueNullFieldError('Parameter', 'covariant');
}
}
@override
Parameter rebuild(void Function(ParameterBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$ParameterBuilder toBuilder() => new _$ParameterBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Parameter &&
defaultTo == other.defaultTo &&
name == other.name &&
named == other.named &&
toThis == other.toThis &&
annotations == other.annotations &&
docs == other.docs &&
types == other.types &&
type == other.type &&
required == other.required &&
covariant == other.covariant;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc($jc(0, defaultTo.hashCode),
name.hashCode),
named.hashCode),
toThis.hashCode),
annotations.hashCode),
docs.hashCode),
types.hashCode),
type.hashCode),
required.hashCode),
covariant.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Parameter')
..add('defaultTo', defaultTo)
..add('name', name)
..add('named', named)
..add('toThis', toThis)
..add('annotations', annotations)
..add('docs', docs)
..add('types', types)
..add('type', type)
..add('required', required)
..add('covariant', covariant))
.toString();
}
}
class _$ParameterBuilder extends ParameterBuilder {
_$Parameter _$v;
@override
Code get defaultTo {
_$this;
return super.defaultTo;
}
@override
set defaultTo(Code defaultTo) {
_$this;
super.defaultTo = defaultTo;
}
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
@override
bool get named {
_$this;
return super.named;
}
@override
set named(bool named) {
_$this;
super.named = named;
}
@override
bool get toThis {
_$this;
return super.toThis;
}
@override
set toThis(bool toThis) {
_$this;
super.toThis = toThis;
}
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
@override
ListBuilder<Reference> get types {
_$this;
return super.types ??= new ListBuilder<Reference>();
}
@override
set types(ListBuilder<Reference> types) {
_$this;
super.types = types;
}
@override
Reference get type {
_$this;
return super.type;
}
@override
set type(Reference type) {
_$this;
super.type = type;
}
@override
bool get required {
_$this;
return super.required;
}
@override
set required(bool required) {
_$this;
super.required = required;
}
@override
bool get covariant {
_$this;
return super.covariant;
}
@override
set covariant(bool covariant) {
_$this;
super.covariant = covariant;
}
_$ParameterBuilder() : super._();
ParameterBuilder get _$this {
if (_$v != null) {
super.defaultTo = _$v.defaultTo;
super.name = _$v.name;
super.named = _$v.named;
super.toThis = _$v.toThis;
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
super.types = _$v.types?.toBuilder();
super.type = _$v.type;
super.required = _$v.required;
super.covariant = _$v.covariant;
_$v = null;
}
return this;
}
@override
void replace(Parameter other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Parameter;
}
@override
void update(void Function(ParameterBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Parameter build() {
_$Parameter _$result;
try {
_$result = _$v ??
new _$Parameter._(
defaultTo: defaultTo,
name: name,
named: named,
toThis: toThis,
annotations: annotations.build(),
docs: docs.build(),
types: types.build(),
type: type,
required: required,
covariant: covariant);
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
_$failedField = 'types';
types.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Parameter', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/code.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'code.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Block extends Block {
@override
final BuiltList<Code> statements;
factory _$Block([void Function(BlockBuilder) updates]) =>
(new BlockBuilder()..update(updates)).build() as _$Block;
_$Block._({this.statements}) : super._() {
if (statements == null) {
throw new BuiltValueNullFieldError('Block', 'statements');
}
}
@override
Block rebuild(void Function(BlockBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$BlockBuilder toBuilder() => new _$BlockBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Block && statements == other.statements;
}
@override
int get hashCode {
return $jf($jc(0, statements.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Block')..add('statements', statements))
.toString();
}
}
class _$BlockBuilder extends BlockBuilder {
_$Block _$v;
@override
ListBuilder<Code> get statements {
_$this;
return super.statements ??= new ListBuilder<Code>();
}
@override
set statements(ListBuilder<Code> statements) {
_$this;
super.statements = statements;
}
_$BlockBuilder() : super._();
BlockBuilder get _$this {
if (_$v != null) {
super.statements = _$v.statements?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(Block other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Block;
}
@override
void update(void Function(BlockBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Block build() {
_$Block _$result;
try {
_$result = _$v ?? new _$Block._(statements: statements.build());
} catch (_) {
String _$failedField;
try {
_$failedField = 'statements';
statements.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Block', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/enum.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'enum.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Enum extends Enum {
@override
final String name;
@override
final BuiltList<EnumValue> values;
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
factory _$Enum([void Function(EnumBuilder) updates]) =>
(new EnumBuilder()..update(updates)).build() as _$Enum;
_$Enum._({this.name, this.values, this.annotations, this.docs}) : super._() {
if (name == null) {
throw new BuiltValueNullFieldError('Enum', 'name');
}
if (values == null) {
throw new BuiltValueNullFieldError('Enum', 'values');
}
if (annotations == null) {
throw new BuiltValueNullFieldError('Enum', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('Enum', 'docs');
}
}
@override
Enum rebuild(void Function(EnumBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$EnumBuilder toBuilder() => new _$EnumBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Enum &&
name == other.name &&
values == other.values &&
annotations == other.annotations &&
docs == other.docs;
}
@override
int get hashCode {
return $jf($jc(
$jc($jc($jc(0, name.hashCode), values.hashCode), annotations.hashCode),
docs.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Enum')
..add('name', name)
..add('values', values)
..add('annotations', annotations)
..add('docs', docs))
.toString();
}
}
class _$EnumBuilder extends EnumBuilder {
_$Enum _$v;
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
@override
ListBuilder<EnumValue> get values {
_$this;
return super.values ??= new ListBuilder<EnumValue>();
}
@override
set values(ListBuilder<EnumValue> values) {
_$this;
super.values = values;
}
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
_$EnumBuilder() : super._();
EnumBuilder get _$this {
if (_$v != null) {
super.name = _$v.name;
super.values = _$v.values?.toBuilder();
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(Enum other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Enum;
}
@override
void update(void Function(EnumBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Enum build() {
_$Enum _$result;
try {
_$result = _$v ??
new _$Enum._(
name: name,
values: values.build(),
annotations: annotations.build(),
docs: docs.build());
} catch (_) {
String _$failedField;
try {
_$failedField = 'values';
values.build();
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Enum', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
class _$EnumValue extends EnumValue {
@override
final String name;
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
factory _$EnumValue([void Function(EnumValueBuilder) updates]) =>
(new EnumValueBuilder()..update(updates)).build() as _$EnumValue;
_$EnumValue._({this.name, this.annotations, this.docs}) : super._() {
if (name == null) {
throw new BuiltValueNullFieldError('EnumValue', 'name');
}
if (annotations == null) {
throw new BuiltValueNullFieldError('EnumValue', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('EnumValue', 'docs');
}
}
@override
EnumValue rebuild(void Function(EnumValueBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$EnumValueBuilder toBuilder() => new _$EnumValueBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is EnumValue &&
name == other.name &&
annotations == other.annotations &&
docs == other.docs;
}
@override
int get hashCode {
return $jf(
$jc($jc($jc(0, name.hashCode), annotations.hashCode), docs.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('EnumValue')
..add('name', name)
..add('annotations', annotations)
..add('docs', docs))
.toString();
}
}
class _$EnumValueBuilder extends EnumValueBuilder {
_$EnumValue _$v;
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
_$EnumValueBuilder() : super._();
EnumValueBuilder get _$this {
if (_$v != null) {
super.name = _$v.name;
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(EnumValue other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$EnumValue;
}
@override
void update(void Function(EnumValueBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$EnumValue build() {
_$EnumValue _$result;
try {
_$result = _$v ??
new _$EnumValue._(
name: name, annotations: annotations.build(), docs: docs.build());
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'EnumValue', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/class.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'class.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Class extends Class {
@override
final bool abstract;
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
@override
final Reference extend;
@override
final BuiltList<Reference> implements;
@override
final BuiltList<Reference> mixins;
@override
final BuiltList<Reference> types;
@override
final BuiltList<Constructor> constructors;
@override
final BuiltList<Method> methods;
@override
final BuiltList<Field> fields;
@override
final String name;
factory _$Class([void Function(ClassBuilder) updates]) =>
(new ClassBuilder()..update(updates)).build() as _$Class;
_$Class._(
{this.abstract,
this.annotations,
this.docs,
this.extend,
this.implements,
this.mixins,
this.types,
this.constructors,
this.methods,
this.fields,
this.name})
: super._() {
if (abstract == null) {
throw new BuiltValueNullFieldError('Class', 'abstract');
}
if (annotations == null) {
throw new BuiltValueNullFieldError('Class', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('Class', 'docs');
}
if (implements == null) {
throw new BuiltValueNullFieldError('Class', 'implements');
}
if (mixins == null) {
throw new BuiltValueNullFieldError('Class', 'mixins');
}
if (types == null) {
throw new BuiltValueNullFieldError('Class', 'types');
}
if (constructors == null) {
throw new BuiltValueNullFieldError('Class', 'constructors');
}
if (methods == null) {
throw new BuiltValueNullFieldError('Class', 'methods');
}
if (fields == null) {
throw new BuiltValueNullFieldError('Class', 'fields');
}
if (name == null) {
throw new BuiltValueNullFieldError('Class', 'name');
}
}
@override
Class rebuild(void Function(ClassBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$ClassBuilder toBuilder() => new _$ClassBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Class &&
abstract == other.abstract &&
annotations == other.annotations &&
docs == other.docs &&
extend == other.extend &&
implements == other.implements &&
mixins == other.mixins &&
types == other.types &&
constructors == other.constructors &&
methods == other.methods &&
fields == other.fields &&
name == other.name;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc(
$jc($jc(0, abstract.hashCode),
annotations.hashCode),
docs.hashCode),
extend.hashCode),
implements.hashCode),
mixins.hashCode),
types.hashCode),
constructors.hashCode),
methods.hashCode),
fields.hashCode),
name.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Class')
..add('abstract', abstract)
..add('annotations', annotations)
..add('docs', docs)
..add('extend', extend)
..add('implements', implements)
..add('mixins', mixins)
..add('types', types)
..add('constructors', constructors)
..add('methods', methods)
..add('fields', fields)
..add('name', name))
.toString();
}
}
class _$ClassBuilder extends ClassBuilder {
_$Class _$v;
@override
bool get abstract {
_$this;
return super.abstract;
}
@override
set abstract(bool abstract) {
_$this;
super.abstract = abstract;
}
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
@override
Reference get extend {
_$this;
return super.extend;
}
@override
set extend(Reference extend) {
_$this;
super.extend = extend;
}
@override
ListBuilder<Reference> get implements {
_$this;
return super.implements ??= new ListBuilder<Reference>();
}
@override
set implements(ListBuilder<Reference> implements) {
_$this;
super.implements = implements;
}
@override
ListBuilder<Reference> get mixins {
_$this;
return super.mixins ??= new ListBuilder<Reference>();
}
@override
set mixins(ListBuilder<Reference> mixins) {
_$this;
super.mixins = mixins;
}
@override
ListBuilder<Reference> get types {
_$this;
return super.types ??= new ListBuilder<Reference>();
}
@override
set types(ListBuilder<Reference> types) {
_$this;
super.types = types;
}
@override
ListBuilder<Constructor> get constructors {
_$this;
return super.constructors ??= new ListBuilder<Constructor>();
}
@override
set constructors(ListBuilder<Constructor> constructors) {
_$this;
super.constructors = constructors;
}
@override
ListBuilder<Method> get methods {
_$this;
return super.methods ??= new ListBuilder<Method>();
}
@override
set methods(ListBuilder<Method> methods) {
_$this;
super.methods = methods;
}
@override
ListBuilder<Field> get fields {
_$this;
return super.fields ??= new ListBuilder<Field>();
}
@override
set fields(ListBuilder<Field> fields) {
_$this;
super.fields = fields;
}
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
_$ClassBuilder() : super._();
ClassBuilder get _$this {
if (_$v != null) {
super.abstract = _$v.abstract;
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
super.extend = _$v.extend;
super.implements = _$v.implements?.toBuilder();
super.mixins = _$v.mixins?.toBuilder();
super.types = _$v.types?.toBuilder();
super.constructors = _$v.constructors?.toBuilder();
super.methods = _$v.methods?.toBuilder();
super.fields = _$v.fields?.toBuilder();
super.name = _$v.name;
_$v = null;
}
return this;
}
@override
void replace(Class other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Class;
}
@override
void update(void Function(ClassBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Class build() {
_$Class _$result;
try {
_$result = _$v ??
new _$Class._(
abstract: abstract,
annotations: annotations.build(),
docs: docs.build(),
extend: extend,
implements: implements.build(),
mixins: mixins.build(),
types: types.build(),
constructors: constructors.build(),
methods: methods.build(),
fields: fields.build(),
name: name);
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
_$failedField = 'implements';
implements.build();
_$failedField = 'mixins';
mixins.build();
_$failedField = 'types';
types.build();
_$failedField = 'constructors';
constructors.build();
_$failedField = 'methods';
methods.build();
_$failedField = 'fields';
fields.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Class', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/extension.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'extension.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Extension extends Extension {
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
@override
final Reference on;
@override
final BuiltList<Reference> types;
@override
final BuiltList<Method> methods;
@override
final BuiltList<Field> fields;
@override
final String name;
factory _$Extension([void Function(ExtensionBuilder) updates]) =>
(new ExtensionBuilder()..update(updates)).build() as _$Extension;
_$Extension._(
{this.annotations,
this.docs,
this.on,
this.types,
this.methods,
this.fields,
this.name})
: super._() {
if (annotations == null) {
throw new BuiltValueNullFieldError('Extension', 'annotations');
}
if (docs == null) {
throw new BuiltValueNullFieldError('Extension', 'docs');
}
if (types == null) {
throw new BuiltValueNullFieldError('Extension', 'types');
}
if (methods == null) {
throw new BuiltValueNullFieldError('Extension', 'methods');
}
if (fields == null) {
throw new BuiltValueNullFieldError('Extension', 'fields');
}
}
@override
Extension rebuild(void Function(ExtensionBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$ExtensionBuilder toBuilder() => new _$ExtensionBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Extension &&
annotations == other.annotations &&
docs == other.docs &&
on == other.on &&
types == other.types &&
methods == other.methods &&
fields == other.fields &&
name == other.name;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc($jc($jc(0, annotations.hashCode), docs.hashCode),
on.hashCode),
types.hashCode),
methods.hashCode),
fields.hashCode),
name.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Extension')
..add('annotations', annotations)
..add('docs', docs)
..add('on', on)
..add('types', types)
..add('methods', methods)
..add('fields', fields)
..add('name', name))
.toString();
}
}
class _$ExtensionBuilder extends ExtensionBuilder {
_$Extension _$v;
@override
ListBuilder<Expression> get annotations {
_$this;
return super.annotations ??= new ListBuilder<Expression>();
}
@override
set annotations(ListBuilder<Expression> annotations) {
_$this;
super.annotations = annotations;
}
@override
ListBuilder<String> get docs {
_$this;
return super.docs ??= new ListBuilder<String>();
}
@override
set docs(ListBuilder<String> docs) {
_$this;
super.docs = docs;
}
@override
Reference get on {
_$this;
return super.on;
}
@override
set on(Reference on) {
_$this;
super.on = on;
}
@override
ListBuilder<Reference> get types {
_$this;
return super.types ??= new ListBuilder<Reference>();
}
@override
set types(ListBuilder<Reference> types) {
_$this;
super.types = types;
}
@override
ListBuilder<Method> get methods {
_$this;
return super.methods ??= new ListBuilder<Method>();
}
@override
set methods(ListBuilder<Method> methods) {
_$this;
super.methods = methods;
}
@override
ListBuilder<Field> get fields {
_$this;
return super.fields ??= new ListBuilder<Field>();
}
@override
set fields(ListBuilder<Field> fields) {
_$this;
super.fields = fields;
}
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
_$ExtensionBuilder() : super._();
ExtensionBuilder get _$this {
if (_$v != null) {
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
super.on = _$v.on;
super.types = _$v.types?.toBuilder();
super.methods = _$v.methods?.toBuilder();
super.fields = _$v.fields?.toBuilder();
super.name = _$v.name;
_$v = null;
}
return this;
}
@override
void replace(Extension other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Extension;
}
@override
void update(void Function(ExtensionBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Extension build() {
_$Extension _$result;
try {
_$result = _$v ??
new _$Extension._(
annotations: annotations.build(),
docs: docs.build(),
on: on,
types: types.build(),
methods: methods.build(),
fields: fields.build(),
name: name);
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
_$failedField = 'types';
types.build();
_$failedField = 'methods';
methods.build();
_$failedField = 'fields';
fields.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Extension', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/field.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../mixins/annotations.dart';
import '../mixins/dartdoc.dart';
import '../visitors.dart';
import 'code.dart';
import 'expression.dart';
import 'reference.dart';
part 'field.g.dart';
@immutable
abstract class Field extends Object
with HasAnnotations, HasDartDocs
implements Built<Field, FieldBuilder>, Spec {
factory Field([void Function(FieldBuilder) updates]) = _$Field;
Field._();
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
/// Field assignment, if any.
@nullable
Code get assignment;
/// Whether this field should be prefixed with `static`.
///
/// This is only valid within classes.
bool get static;
/// Name of the field.
String get name;
@nullable
Reference get type;
FieldModifier get modifier;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitField(this, context);
}
enum FieldModifier {
var$,
final$,
constant,
}
abstract class FieldBuilder extends Object
with HasAnnotationsBuilder, HasDartDocsBuilder
implements Builder<Field, FieldBuilder> {
factory FieldBuilder() = _$FieldBuilder;
FieldBuilder._();
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
/// Field assignment, if any.
Code assignment;
/// Whether this field should be prefixed with `static`.
///
/// This is only valid within classes.
bool static = false;
/// Name of the field.
String name;
Reference type;
FieldModifier modifier = FieldModifier.var$;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/directive.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'directive.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
class _$Directive extends Directive {
@override
final String as;
@override
final String url;
@override
final DirectiveType type;
@override
final List<String> show;
@override
final List<String> hide;
@override
final bool deferred;
factory _$Directive([void Function(DirectiveBuilder) updates]) =>
(new DirectiveBuilder()..update(updates)).build() as _$Directive;
_$Directive._(
{this.as, this.url, this.type, this.show, this.hide, this.deferred})
: super._() {
if (url == null) {
throw new BuiltValueNullFieldError('Directive', 'url');
}
if (type == null) {
throw new BuiltValueNullFieldError('Directive', 'type');
}
if (show == null) {
throw new BuiltValueNullFieldError('Directive', 'show');
}
if (hide == null) {
throw new BuiltValueNullFieldError('Directive', 'hide');
}
if (deferred == null) {
throw new BuiltValueNullFieldError('Directive', 'deferred');
}
}
@override
Directive rebuild(void Function(DirectiveBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
_$DirectiveBuilder toBuilder() => new _$DirectiveBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Directive &&
as == other.as &&
url == other.url &&
type == other.type &&
show == other.show &&
hide == other.hide &&
deferred == other.deferred;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc($jc($jc($jc(0, as.hashCode), url.hashCode), type.hashCode),
show.hashCode),
hide.hashCode),
deferred.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Directive')
..add('as', as)
..add('url', url)
..add('type', type)
..add('show', show)
..add('hide', hide)
..add('deferred', deferred))
.toString();
}
}
class _$DirectiveBuilder extends DirectiveBuilder {
_$Directive _$v;
@override
String get as {
_$this;
return super.as;
}
@override
set as(String as) {
_$this;
super.as = as;
}
@override
String get url {
_$this;
return super.url;
}
@override
set url(String url) {
_$this;
super.url = url;
}
@override
DirectiveType get type {
_$this;
return super.type;
}
@override
set type(DirectiveType type) {
_$this;
super.type = type;
}
@override
List<String> get show {
_$this;
return super.show;
}
@override
set show(List<String> show) {
_$this;
super.show = show;
}
@override
List<String> get hide {
_$this;
return super.hide;
}
@override
set hide(List<String> hide) {
_$this;
super.hide = hide;
}
@override
bool get deferred {
_$this;
return super.deferred;
}
@override
set deferred(bool deferred) {
_$this;
super.deferred = deferred;
}
_$DirectiveBuilder() : super._();
DirectiveBuilder get _$this {
if (_$v != null) {
super.as = _$v.as;
super.url = _$v.url;
super.type = _$v.type;
super.show = _$v.show;
super.hide = _$v.hide;
super.deferred = _$v.deferred;
_$v = null;
}
return this;
}
@override
void replace(Directive other) {
if (other == null) {
throw new ArgumentError.notNull('other');
}
_$v = other as _$Directive;
}
@override
void update(void Function(DirectiveBuilder) updates) {
if (updates != null) updates(this);
}
@override
_$Directive build() {
final _$result = _$v ??
new _$Directive._(
as: as,
url: url,
type: type,
show: show,
hide: hide,
deferred: deferred);
replace(_$result);
return _$result;
}
}
// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/type_function.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../mixins/generics.dart';
import '../visitors.dart';
import 'code.dart';
import 'expression.dart';
import 'reference.dart';
part 'type_function.g.dart';
@immutable
abstract class FunctionType extends Expression
with HasGenerics
implements Built<FunctionType, FunctionTypeBuilder>, Reference, Spec {
factory FunctionType([
void Function(FunctionTypeBuilder) updates,
]) = _$FunctionType;
FunctionType._();
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitFunctionType(this, context);
/// Return type.
@nullable
Reference get returnType;
@override
BuiltList<Reference> get types;
/// Required positional arguments to this function type.
BuiltList<Reference> get requiredParameters;
/// Optional positional arguments to this function type.
BuiltList<Reference> get optionalParameters;
/// Named optional arguments to this function type.
BuiltMap<String, Reference> get namedParameters;
@override
String get url => null;
@override
String get symbol => null;
@override
Reference get type => this;
/// Optional nullability.
///
/// An emitter may ignore this if the output is not targeting a Dart language
/// version that supports null safety.
@nullable
bool get isNullable;
@override
Expression newInstance(
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
throw UnsupportedError('Cannot instantiate a function type.');
@override
Expression newInstanceNamed(
String name,
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
throw UnsupportedError('Cannot instantiate a function type.');
@override
Expression constInstance(
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
throw UnsupportedError('Cannot "const" a function type.');
@override
Expression constInstanceNamed(
String name,
Iterable<Expression> positionalArguments, [
Map<String, Expression> namedArguments = const {},
List<Reference> typeArguments = const [],
]) =>
throw UnsupportedError('Cannot "const" a function type.');
/// A typedef assignment to this type.
Code toTypeDef(String name) => createTypeDef(name, this);
}
abstract class FunctionTypeBuilder extends Object
with HasGenericsBuilder
implements Builder<FunctionType, FunctionTypeBuilder> {
factory FunctionTypeBuilder() = _$FunctionTypeBuilder;
FunctionTypeBuilder._();
Reference returnType;
@override
ListBuilder<Reference> types = ListBuilder<Reference>();
ListBuilder<Reference> requiredParameters = ListBuilder<Reference>();
ListBuilder<Reference> optionalParameters = ListBuilder<Reference>();
MapBuilder<String, Reference> namedParameters =
MapBuilder<String, Reference>();
bool isNullable;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/constructor.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'package:meta/meta.dart';
import '../mixins/annotations.dart';
import '../mixins/dartdoc.dart';
import 'code.dart';
import 'expression.dart';
import 'method.dart';
import 'reference.dart';
part 'constructor.g.dart';
@immutable
abstract class Constructor extends Object
with HasAnnotations, HasDartDocs
implements Built<Constructor, ConstructorBuilder> {
factory Constructor([void Function(ConstructorBuilder) updates]) =
_$Constructor;
Constructor._();
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
/// Optional parameters.
BuiltList<Parameter> get optionalParameters;
/// Required parameters.
BuiltList<Parameter> get requiredParameters;
/// Constructor initializer statements.
BuiltList<Code> get initializers;
/// Body of the method.
@nullable
Code get body;
/// Whether the constructor should be prefixed with `external`.
bool get external;
/// Whether the constructor should be prefixed with `const`.
bool get constant;
/// Whether this constructor should be prefixed with `factory`.
bool get factory;
/// Whether this constructor is a simple lambda expression.
@nullable
bool get lambda;
/// Name of the constructor - optional.
@nullable
String get name;
/// If non-null, redirect to this constructor.
@nullable
Reference get redirect;
}
abstract class ConstructorBuilder extends Object
with HasAnnotationsBuilder, HasDartDocsBuilder
implements Builder<Constructor, ConstructorBuilder> {
factory ConstructorBuilder() = _$ConstructorBuilder;
ConstructorBuilder._();
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
/// Optional parameters.
ListBuilder<Parameter> optionalParameters = ListBuilder<Parameter>();
/// Required parameters.
ListBuilder<Parameter> requiredParameters = ListBuilder<Parameter>();
/// Constructor initializer statements.
ListBuilder<Code> initializers = ListBuilder<Code>();
/// Body of the constructor.
Code body;
/// Whether the constructor should be prefixed with `const`.
bool constant = false;
/// Whether the constructor should be prefixed with `external`.
bool external = false;
/// Whether this constructor should be prefixed with `factory`.
bool factory = false;
/// Whether this constructor is a simple lambda expression.
bool lambda;
/// Name of the constructor - optional.
String name;
/// If non-null, redirect to this constructor.
@nullable
Reference redirect;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/class.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_value/built_value.dart';
import 'package:built_collection/built_collection.dart';
import 'package:meta/meta.dart';
import '../base.dart';
import '../mixins/annotations.dart';
import '../mixins/dartdoc.dart';
import '../mixins/generics.dart';
import '../visitors.dart';
import 'constructor.dart';
import 'expression.dart';
import 'field.dart';
import 'method.dart';
import 'reference.dart';
part 'class.g.dart';
@immutable
abstract class Class extends Object
with HasAnnotations, HasDartDocs, HasGenerics
implements Built<Class, ClassBuilder>, Spec {
factory Class([void Function(ClassBuilder) updates]) = _$Class;
Class._();
/// Whether the class is `abstract`.
bool get abstract;
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
@nullable
Reference get extend;
BuiltList<Reference> get implements;
BuiltList<Reference> get mixins;
@override
BuiltList<Reference> get types;
BuiltList<Constructor> get constructors;
BuiltList<Method> get methods;
BuiltList<Field> get fields;
/// Name of the class.
String get name;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitClass(this, context);
}
abstract class ClassBuilder extends Object
with HasAnnotationsBuilder, HasDartDocsBuilder, HasGenericsBuilder
implements Builder<Class, ClassBuilder> {
factory ClassBuilder() = _$ClassBuilder;
ClassBuilder._();
/// Whether the class is `abstract`.
bool abstract = false;
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
Reference extend;
ListBuilder<Reference> implements = ListBuilder<Reference>();
ListBuilder<Reference> mixins = ListBuilder<Reference>();
@override
ListBuilder<Reference> types = ListBuilder<Reference>();
ListBuilder<Constructor> constructors = ListBuilder<Constructor>();
ListBuilder<Method> methods = ListBuilder<Method>();
ListBuilder<Field> fields = ListBuilder<Field>();
/// Name of the class.
String name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/enum.dart | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:meta/meta.dart';
import '../../code_builder.dart';
import '../mixins/annotations.dart';
import '../mixins/dartdoc.dart';
import '../visitors.dart';
part 'enum.g.dart';
@immutable
abstract class Enum extends Object
with HasAnnotations, HasDartDocs
implements Built<Enum, EnumBuilder>, Spec {
factory Enum([void Function(EnumBuilder) updates]) = _$Enum;
Enum._();
String get name;
BuiltList<EnumValue> get values;
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
@override
R accept<R>(
SpecVisitor<R> visitor, [
R context,
]) =>
visitor.visitEnum(this, context);
}
abstract class EnumBuilder extends Object
with HasAnnotationsBuilder, HasDartDocsBuilder
implements Builder<Enum, EnumBuilder> {
factory EnumBuilder() = _$EnumBuilder;
EnumBuilder._();
String name;
ListBuilder<EnumValue> values = ListBuilder<EnumValue>();
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
}
@immutable
abstract class EnumValue extends Object
with HasAnnotations, HasDartDocs
implements Built<EnumValue, EnumValueBuilder> {
factory EnumValue([void Function(EnumValueBuilder) updates]) = _$EnumValue;
EnumValue._();
String get name;
@override
BuiltList<Expression> get annotations;
@override
BuiltList<String> get docs;
}
abstract class EnumValueBuilder extends Object
with HasAnnotationsBuilder, HasDartDocsBuilder
implements Builder<EnumValue, EnumValueBuilder> {
factory EnumValueBuilder() = _$EnumValueBuilder;
EnumValueBuilder._();
String name;
@override
ListBuilder<Expression> annotations = ListBuilder<Expression>();
@override
ListBuilder<String> docs = ListBuilder<String>();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/expression/code.dart | // Copyright (c) 2017, 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.
part of code_builder.src.specs.expression;
/// Represents a [Code] block as an [Expression].
class CodeExpression extends Expression {
@override
final Code code;
/// **INTERNAL ONLY**: Used to wrap [Code] as an [Expression].
const CodeExpression(this.code);
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitCodeExpression(this, context);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/expression/closure.dart | // Copyright (c) 2017, 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.
part of code_builder.src.specs.expression;
Expression toClosure(Method method) {
final withoutTypes = method.rebuild((b) {
b.returns = null;
b.types.clear();
});
return ClosureExpression._(withoutTypes);
}
class ClosureExpression extends Expression {
final Method method;
const ClosureExpression._(this.method);
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitClosureExpression(this, context);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/expression/binary.dart | // Copyright (c) 2017, 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.
part of code_builder.src.specs.expression;
/// Represents two expressions ([left] and [right]) and an [operator].
class BinaryExpression extends Expression {
final Expression left;
final Expression right;
final String operator;
final bool addSpace;
final bool isConst;
const BinaryExpression._(
this.left,
this.right,
this.operator, {
this.addSpace = true,
this.isConst = false,
});
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitBinaryExpression(this, context);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/expression/invoke.dart | // Copyright (c) 2017, 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.
part of code_builder.src.specs.expression;
/// Represents invoking [target] as a method with arguments.
class InvokeExpression extends Expression {
/// Target of the method invocation.
final Expression target;
/// Optional; type of invocation.
final InvokeExpressionType type;
final List<Expression> positionalArguments;
final Map<String, Expression> namedArguments;
final List<Reference> typeArguments;
final String name;
const InvokeExpression._(
this.target,
this.positionalArguments, [
this.namedArguments = const {},
this.typeArguments,
this.name,
]) : type = null;
const InvokeExpression.newOf(
this.target,
this.positionalArguments, [
this.namedArguments = const {},
this.typeArguments,
this.name,
]) : type = InvokeExpressionType.newInstance;
const InvokeExpression.constOf(
this.target,
this.positionalArguments, [
this.namedArguments = const {},
this.typeArguments,
this.name,
]) : type = InvokeExpressionType.constInstance;
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitInvokeExpression(this, context);
@override
String toString() =>
'${type ?? ''} $target($positionalArguments, $namedArguments)';
}
enum InvokeExpressionType {
newInstance,
constInstance,
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/specs/expression/literal.dart | // Copyright (c) 2017, 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.
part of code_builder.src.specs.expression;
/// Converts a runtime Dart [literal] value into an [Expression].
///
/// Unsupported inputs invoke the [onError] callback.
Expression literal(Object literal, {Expression Function(Object) onError}) {
if (literal is bool) {
return literalBool(literal);
}
if (literal is num) {
return literalNum(literal);
}
if (literal is String) {
return literalString(literal);
}
if (literal is List) {
return literalList(literal);
}
if (literal is Set) {
return literalSet(literal);
}
if (literal is Map) {
return literalMap(literal);
}
if (literal == null) {
return literalNull;
}
if (onError != null) {
return onError(literal);
}
throw UnsupportedError('Not a supported literal type: $literal.');
}
/// Represents the literal value `true`.
const Expression literalTrue = LiteralExpression._('true');
/// Represents the literal value `false`.
const Expression literalFalse = LiteralExpression._('false');
/// Create a literal expression from a boolean [value].
Expression literalBool(bool value) => value ? literalTrue : literalFalse;
/// Represents the literal value `null`.
const Expression literalNull = LiteralExpression._('null');
/// Create a literal expression from a number [value].
Expression literalNum(num value) => LiteralExpression._('$value');
/// Create a literal expression from a string [value].
///
/// **NOTE**: The string is always formatted `'<value>'`.
///
/// If [raw] is `true`, creates a raw String formatted `r'<value>'` and the
/// value may not contain a single quote.
/// Escapes single quotes and newlines in the value.
Expression literalString(String value, {bool raw = false}) {
if (raw && value.contains('\'')) {
throw ArgumentError('Cannot include a single quote in a raw string');
}
final escaped = value.replaceAll('\'', '\\\'').replaceAll('\n', '\\n');
return LiteralExpression._("${raw ? 'r' : ''}'$escaped'");
}
/// Creates a literal list expression from [values].
LiteralListExpression literalList(Iterable<Object> values, [Reference type]) =>
LiteralListExpression._(false, values.toList(), type);
/// Creates a literal `const` list expression from [values].
LiteralListExpression literalConstList(List<Object> values, [Reference type]) =>
LiteralListExpression._(true, values, type);
/// Creates a literal set expression from [values].
LiteralSetExpression literalSet(Iterable<Object> values, [Reference type]) =>
LiteralSetExpression._(false, values.toSet(), type);
/// Creates a literal `const` set expression from [values].
LiteralSetExpression literalConstSet(Set<Object> values, [Reference type]) =>
LiteralSetExpression._(true, values, type);
/// Create a literal map expression from [values].
LiteralMapExpression literalMap(
Map<Object, Object> values, [
Reference keyType,
Reference valueType,
]) =>
LiteralMapExpression._(false, values, keyType, valueType);
/// Create a literal `const` map expression from [values].
LiteralMapExpression literalConstMap(
Map<Object, Object> values, [
Reference keyType,
Reference valueType,
]) =>
LiteralMapExpression._(true, values, keyType, valueType);
/// Represents a literal value in Dart source code.
///
/// For example, `LiteralExpression('null')` should emit `null`.
///
/// Some common literals and helpers are available as methods/fields:
/// * [literal]
/// * [literalBool] and [literalTrue], [literalFalse]
/// * [literalNull]
/// * [literalList] and [literalConstList]
/// * [literalSet] and [literalConstSet]
class LiteralExpression extends Expression {
final String literal;
const LiteralExpression._(this.literal);
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitLiteralExpression(this, context);
@override
String toString() => literal;
}
class LiteralListExpression extends Expression {
final bool isConst;
final List<Object> values;
final Reference type;
const LiteralListExpression._(this.isConst, this.values, this.type);
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitLiteralListExpression(this, context);
@override
String toString() => '[${values.map(literal).join(', ')}]';
}
class LiteralSetExpression extends Expression {
final bool isConst;
final Set<Object> values;
final Reference type;
const LiteralSetExpression._(this.isConst, this.values, this.type);
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitLiteralSetExpression(this, context);
@override
String toString() => '{${values.map(literal).join(', ')}}';
}
class LiteralMapExpression extends Expression {
final bool isConst;
final Map<Object, Object> values;
final Reference keyType;
final Reference valueType;
const LiteralMapExpression._(
this.isConst,
this.values,
this.keyType,
this.valueType,
);
@override
R accept<R>(ExpressionVisitor<R> visitor, [R context]) =>
visitor.visitLiteralMapExpression(this, context);
@override
String toString() => '{$values}';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/mixins/generics.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_collection/built_collection.dart';
import '../specs/reference.dart';
abstract class HasGenerics {
/// Generic type parameters.
BuiltList<Reference> get types;
}
abstract class HasGenericsBuilder {
/// Generic type parameters.
ListBuilder<Reference> types;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/mixins/annotations.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_collection/built_collection.dart';
import '../specs/expression.dart';
/// A type of AST node that can have metadata [annotations].
abstract class HasAnnotations {
/// Annotations as metadata on the node.
BuiltList<Expression> get annotations;
}
/// Compliment to the [HasAnnotations] mixin for metadata [annotations].
abstract class HasAnnotationsBuilder {
/// Annotations as metadata on the node.
ListBuilder<Expression> annotations;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/mixins/dartdoc.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:built_collection/built_collection.dart';
abstract class HasDartDocs {
/// Dart docs.
BuiltList<String> get docs;
}
abstract class HasDartDocsBuilder {
/// Dart docs.
ListBuilder<String> docs;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/shelf_io.dart | // Copyright (c) 2014, 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.
/// A Shelf adapter for handling [HttpRequest] objects from `dart:io`.
///
/// One can provide an instance of [HttpServer] as the `requests` parameter in
/// [serveRequests].
///
/// This adapter supports request hijacking; see [Request.hijack]. It also
/// supports the `"shelf.io.buffer_output"` `Response.context` property. If this
/// property is `true` (the default), streamed responses will be buffered to
/// improve performance; if it's `false`, all chunks will be pushed over the
/// wire as they're received. See
/// [`HttpResponse.bufferOutput`](https://api.dart.dev/stable/dart-io/HttpResponse/bufferOutput.html)
/// for more information.
///
/// `Request`s passed to a `Handler` will contain the
/// `"shelf.io.connection_info"` `Request.context` property, which holds the
/// `HttpConnectionInfo` object from the underlying `HttpRequest`.
import 'dart:async';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:http_parser/http_parser.dart';
import 'package:stack_trace/stack_trace.dart';
import 'package:stream_channel/stream_channel.dart';
import 'shelf.dart';
import 'src/util.dart';
export 'src/io_server.dart';
/// Starts an [HttpServer] that listens on the specified [address] and
/// [port] and sends requests to [handler].
///
/// If a [securityContext] is provided an HTTPS server will be started.
////
/// See the documentation for [HttpServer.bind] and [HttpServer.bindSecure]
/// for more details on [address], [port], [backlog], and [shared].
Future<HttpServer> serve(Handler handler, address, int port,
{SecurityContext securityContext, int backlog, bool shared = false}) async {
backlog ??= 0;
var server = await (securityContext == null
? HttpServer.bind(address, port, backlog: backlog, shared: shared)
: HttpServer.bindSecure(address, port, securityContext,
backlog: backlog, shared: shared));
serveRequests(server, handler);
return server;
}
/// Serve a [Stream] of [HttpRequest]s.
///
/// [HttpServer] implements [Stream<HttpRequest>] so it can be passed directly
/// to [serveRequests].
///
/// Errors thrown by [handler] while serving a request will be printed to the
/// console and cause a 500 response with no body. Errors thrown asynchronously
/// by [handler] will be printed to the console or, if there's an active error
/// zone, passed to that zone.
void serveRequests(Stream<HttpRequest> requests, Handler handler) {
catchTopLevelErrors(() {
requests.listen((request) => handleRequest(request, handler));
}, (error, stackTrace) {
_logTopLevelError('Asynchronous error\n$error', stackTrace);
});
}
/// Uses [handler] to handle [request].
///
/// Returns a [Future] which completes when the request has been handled.
Future handleRequest(HttpRequest request, Handler handler) async {
Request shelfRequest;
try {
shelfRequest = _fromHttpRequest(request);
} on ArgumentError catch (error, stackTrace) {
if (error.name == 'method' || error.name == 'requestedUri') {
// TODO: use a reduced log level when using package:logging
_logTopLevelError('Error parsing request.\n$error', stackTrace);
final response = Response(400,
body: 'Bad Request',
headers: {HttpHeaders.contentTypeHeader: 'text/plain'});
await _writeResponse(response, request.response);
} else {
_logTopLevelError('Error parsing request.\n$error', stackTrace);
final response = Response.internalServerError();
await _writeResponse(response, request.response);
}
return;
} catch (error, stackTrace) {
_logTopLevelError('Error parsing request.\n$error', stackTrace);
final response = Response.internalServerError();
await _writeResponse(response, request.response);
return;
}
// TODO(nweiz): abstract out hijack handling to make it easier to implement an
// adapter.
Response response;
try {
response = await handler(shelfRequest);
} on HijackException catch (error, stackTrace) {
// A HijackException should bypass the response-writing logic entirely.
if (!shelfRequest.canHijack) return;
// If the request wasn't hijacked, we shouldn't be seeing this exception.
response = _logError(shelfRequest,
"Caught HijackException, but the request wasn't hijacked.", stackTrace);
} catch (error, stackTrace) {
response =
_logError(shelfRequest, 'Error thrown by handler.\n$error', stackTrace);
}
if (response == null) {
await _writeResponse(_logError(shelfRequest, 'null response from handler.'),
request.response);
return;
} else if (shelfRequest.canHijack) {
await _writeResponse(response, request.response);
return;
}
var message = StringBuffer()
..writeln('Got a response for hijacked request '
'${shelfRequest.method} ${shelfRequest.requestedUri}:')
..writeln(response.statusCode);
response.headers.forEach((key, value) => message.writeln('$key: $value'));
throw Exception(message.toString().trim());
}
/// Creates a new [Request] from the provided [HttpRequest].
Request _fromHttpRequest(HttpRequest request) {
var headers = <String, List<String>>{};
request.headers.forEach((k, v) {
headers[k] = v;
});
// Remove the Transfer-Encoding header per the adapter requirements.
headers.remove(HttpHeaders.transferEncodingHeader);
void onHijack(void Function(StreamChannel<List<int>>) callback) {
request.response
.detachSocket(writeHeaders: false)
.then((socket) => callback(StreamChannel(socket, socket)));
}
return Request(request.method, request.requestedUri,
protocolVersion: request.protocolVersion,
headers: headers,
body: request,
onHijack: onHijack,
context: {'shelf.io.connection_info': request.connectionInfo});
}
Future _writeResponse(Response response, HttpResponse httpResponse) {
if (response.context.containsKey('shelf.io.buffer_output')) {
httpResponse.bufferOutput =
response.context['shelf.io.buffer_output'] as bool;
}
httpResponse.statusCode = response.statusCode;
// An adapter must not add or modify the `Transfer-Encoding` parameter, but
// the Dart SDK sets it by default. Set this before we fill in
// [response.headers] so that the user or Shelf can explicitly override it if
// necessary.
httpResponse.headers.chunkedTransferEncoding = false;
response.headersAll.forEach((header, value) {
if (value == null) return;
httpResponse.headers.set(header, value);
});
var coding = response.headers['transfer-encoding'];
if (coding != null && !equalsIgnoreAsciiCase(coding, 'identity')) {
// If the response is already in a chunked encoding, de-chunk it because
// otherwise `dart:io` will try to add another layer of chunking.
//
// TODO(nweiz): Do this more cleanly when sdk#27886 is fixed.
response =
response.change(body: chunkedCoding.decoder.bind(response.read()));
httpResponse.headers.set(HttpHeaders.transferEncodingHeader, 'chunked');
} else if (response.statusCode >= 200 &&
response.statusCode != 204 &&
response.statusCode != 304 &&
response.contentLength == null &&
response.mimeType != 'multipart/byteranges') {
// If the response isn't chunked yet and there's no other way to tell its
// length, enable `dart:io`'s chunked encoding.
httpResponse.headers.set(HttpHeaders.transferEncodingHeader, 'chunked');
}
if (!response.headers.containsKey(HttpHeaders.serverHeader)) {
httpResponse.headers.set(HttpHeaders.serverHeader, 'dart:io with Shelf');
}
if (!response.headers.containsKey(HttpHeaders.dateHeader)) {
httpResponse.headers.date = DateTime.now().toUtc();
}
return httpResponse
.addStream(response.read())
.then((_) => httpResponse.close());
}
// TODO(kevmoo) A developer mode is needed to include error info in response
// TODO(kevmoo) Make error output plugable. stderr, logging, etc
Response _logError(Request request, String message, [StackTrace stackTrace]) {
// Add information about the request itself.
var buffer = StringBuffer();
buffer.write('${request.method} ${request.requestedUri.path}');
if (request.requestedUri.query.isNotEmpty) {
buffer.write('?${request.requestedUri.query}');
}
buffer.writeln();
buffer.write(message);
_logTopLevelError(buffer.toString(), stackTrace);
return Response.internalServerError();
}
void _logTopLevelError(String message, [StackTrace stackTrace]) {
var chain = Chain.current();
if (stackTrace != null) {
chain = Chain.forTrace(stackTrace);
}
chain = chain
.foldFrames((frame) => frame.isCore || frame.package == 'shelf')
.terse;
stderr.writeln('ERROR - ${DateTime.now()}');
stderr.writeln(message);
stderr.writeln(chain);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/shelf.dart | // Copyright (c) 2014, 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.
export 'src/cascade.dart';
export 'src/handler.dart';
export 'src/hijack_exception.dart';
export 'src/middleware.dart';
export 'src/middleware/add_chunked_encoding.dart';
export 'src/middleware/logger.dart';
export 'src/pipeline.dart';
export 'src/request.dart';
export 'src/response.dart';
export 'src/server.dart';
export 'src/server_handler.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/hijack_exception.dart | // Copyright (c) 2014, 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.
/// An exception used to indicate that a request has been hijacked.
///
/// This shouldn't be captured by any code other than the Shelf adapter that
/// created the hijackable request. Middleware that captures exceptions should
/// make sure to pass on HijackExceptions.
///
/// See also [Request.hijack].
class HijackException implements Exception {
const HijackException();
@override
String toString() =>
"A shelf request's underlying data stream was hijacked.\n"
'This exception is used for control flow and should only be handled by a '
'Shelf adapter.';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/cascade.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'handler.dart';
import 'response.dart';
/// A typedef for [Cascade._shouldCascade].
typedef _ShouldCascade = bool Function(Response response);
/// A helper that calls several handlers in sequence and returns the first
/// acceptable response.
///
/// By default, a response is considered acceptable if it has a status other
/// than 404 or 405; other statuses indicate that the handler understood the
/// request.
///
/// If all handlers return unacceptable responses, the final response will be
/// returned.
///
/// var handler = new Cascade()
/// .add(webSocketHandler)
/// .add(staticFileHandler)
/// .add(application)
/// .handler;
class Cascade {
/// The function used to determine whether the cascade should continue on to
/// the next handler.
final _ShouldCascade _shouldCascade;
final Cascade _parent;
final Handler _handler;
/// Creates a new, empty cascade.
///
/// If [statusCodes] is passed, responses with those status codes are
/// considered unacceptable. If [shouldCascade] is passed, responses for which
/// it returns `true` are considered unacceptable. [statusCodes] and
/// [shouldCascade] may not both be passed.
Cascade({Iterable<int> statusCodes, bool Function(Response) shouldCascade})
: _shouldCascade = _computeShouldCascade(statusCodes, shouldCascade),
_parent = null,
_handler = null {
if (statusCodes != null && shouldCascade != null) {
throw ArgumentError('statusCodes and shouldCascade may not both be '
'passed.');
}
}
Cascade._(this._parent, this._handler, this._shouldCascade);
/// Returns a new cascade with [handler] added to the end.
///
/// [handler] will only be called if all previous handlers in the cascade
/// return unacceptable responses.
Cascade add(Handler handler) => Cascade._(this, handler, _shouldCascade);
/// Exposes this cascade as a single handler.
///
/// This handler will call each inner handler in the cascade until one returns
/// an acceptable response, and return that. If no inner handlers return an
/// acceptable response, this will return the final response.
Handler get handler {
if (_handler == null) {
throw StateError("Can't get a handler for a cascade with no inner "
'handlers.');
}
return (request) {
if (_parent._handler == null) return _handler(request);
return Future.sync(() => _parent.handler(request)).then((response) {
if (_shouldCascade(response)) return _handler(request);
return response;
});
};
}
}
/// Computes the [Cascade._shouldCascade] function based on the user's
/// parameters.
_ShouldCascade _computeShouldCascade(
Iterable<int> statusCodes, bool Function(Response) shouldCascade) {
if (shouldCascade != null) return shouldCascade;
statusCodes ??= [404, 405];
statusCodes = statusCodes.toSet();
return (response) => statusCodes.contains(response.statusCode);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/middleware.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'handler.dart';
import 'hijack_exception.dart';
import 'request.dart';
import 'response.dart';
/// A function which creates a new [Handler] by wrapping a [Handler].
///
/// You can extend the functions of a [Handler] by wrapping it in
/// [Middleware] that can intercept and process a request before it it sent
/// to a handler, a response after it is sent by a handler, or both.
///
/// Because [Middleware] consumes a [Handler] and returns a new
/// [Handler], multiple [Middleware] instances can be composed
/// together to offer rich functionality.
///
/// Common uses for middleware include caching, logging, and authentication.
///
/// Middleware that captures exceptions should be sure to pass
/// [HijackException]s on without modification.
///
/// A simple [Middleware] can be created using [createMiddleware].
typedef Middleware = Handler Function(Handler innerHandler);
/// Creates a [Middleware] using the provided functions.
///
/// If provided, [requestHandler] receives a [Request]. It can respond to
/// the request by returning a [Response] or [Future<Response>].
/// [requestHandler] can also return `null` for some or all requests in which
/// case the request is sent to the inner [Handler].
///
/// If provided, [responseHandler] is called with the [Response] generated
/// by the inner [Handler]. Responses generated by [requestHandler] are not
/// sent to [responseHandler].
///
/// [responseHandler] should return either a [Response] or
/// [Future<Response>]. It may return the response parameter it receives or
/// create a new response object.
///
/// If provided, [errorHandler] receives errors thrown by the inner handler. It
/// does not receive errors thrown by [requestHandler] or [responseHandler], nor
/// does it receive [HijackException]s. It can either return a new response or
/// throw an error.
Middleware createMiddleware(
{FutureOr<Response> Function(Request) requestHandler,
FutureOr<Response> Function(Response) responseHandler,
FutureOr<Response> Function(dynamic error, StackTrace) errorHandler}) {
requestHandler ??= (request) => null;
responseHandler ??= (response) => response;
void Function(Object, StackTrace) onError;
if (errorHandler != null) {
onError = (error, stackTrace) {
if (error is HijackException) throw error;
return errorHandler(error, stackTrace);
};
}
return (Handler innerHandler) {
return (request) {
return Future.sync(() => requestHandler(request)).then((response) {
if (response != null) return response;
return Future.sync(() => innerHandler(request))
.then((response) => responseHandler(response), onError: onError);
});
};
};
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/util.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:collection/collection.dart';
import 'shelf_unmodifiable_map.dart';
/// Run [callback] and capture any errors that would otherwise be top-leveled.
///
/// If [this] is called in a non-root error zone, it will just run [callback]
/// and return the result. Otherwise, it will capture any errors using
/// [runZoned] and pass them to [onError].
void catchTopLevelErrors(void Function() callback,
void Function(dynamic error, StackTrace) onError) {
if (Zone.current.inSameErrorZone(Zone.root)) {
return runZoned(callback, onError: onError);
} else {
return callback();
}
}
/// Returns a [Map] with the values from [original] and the values from
/// [updates].
///
/// For keys that are the same between [original] and [updates], the value in
/// [updates] is used.
///
/// If [updates] is `null` or empty, [original] is returned unchanged.
Map<K, V> updateMap<K, V>(Map<K, V> original, Map<K, V> updates) {
if (updates == null || updates.isEmpty) return original;
return Map.from(original)..addAll(updates);
}
/// Adds a header with [name] and [value] to [headers], which may be null.
///
/// Returns a new map without modifying [headers].
Map<String, dynamic> addHeader(
Map<String, dynamic> headers, String name, String value) {
headers = headers == null ? {} : Map.from(headers);
headers[name] = value;
return headers;
}
/// Returns the header with the given [name] in [headers].
///
/// This works even if [headers] is `null`, or if it's not yet a
/// case-insensitive map.
String findHeader(Map<String, List<String>> headers, String name) {
if (headers == null) return null;
if (headers is ShelfUnmodifiableMap) {
return joinHeaderValues(headers[name]);
}
for (var key in headers.keys) {
if (equalsIgnoreAsciiCase(key, name)) {
return joinHeaderValues(headers[key]);
}
}
return null;
}
Map<String, List<String>> expandToHeadersAll(
Map<String, /* String | List<String> */ dynamic> headers) {
if (headers is Map<String, List<String>>) return headers;
if (headers == null || headers.isEmpty) return null;
return Map<String, List<String>>.fromEntries(headers.entries.map((e) {
return MapEntry<String, List<String>>(e.key, expandHeaderValue(e.value));
}));
}
List<String> expandHeaderValue(dynamic v) {
if (v is String) {
return [v];
} else if (v is List<String>) {
return v;
} else if (v == null) {
return null;
} else {
throw ArgumentError('Expected String or List<String>, got: `$v`.');
}
}
/// Multiple header values are joined with commas.
/// See http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21#page-22
String joinHeaderValues(List<String> values) {
if (values == null || values.isEmpty) return null;
if (values.length == 1) return values.single;
return values.join(',');
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/server.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'handler.dart';
/// An [adapter][] with a concrete URL.
///
/// [adapter]: https://github.com/dart-lang/shelf#adapters
///
/// The most basic definition of "adapter" includes any function that passes
/// incoming requests to a [Handler] and passes its responses to some external
/// client. However, in practice, most adapters are also *servers*—that is,
/// they're serving requests that are made to a certain well-known URL.
///
/// This interface represents those servers in a general way. It's useful for
/// writing code that needs to know its own URL without tightly coupling that
/// code to a single server implementation.
///
/// There are two built-in implementations of this interface. You can create a
/// server backed by `dart:io` using [IOServer], or you can create a server
/// that's backed by a normal [Handler] using [ServerHandler].
///
/// Implementations of this interface are responsible for ensuring that the
/// members work as documented.
abstract class Server {
/// The URL of the server.
///
/// Requests to this URL or any URL beneath it are handled by the handler
/// passed to [mount]. If [mount] hasn't yet been called, the requests wait
/// until it is. If [close] has been called, the handler will not be invoked;
/// otherwise, the behavior is implementation-dependent.
Uri get url;
/// Mounts [handler] as the base handler for this server.
///
/// All requests to [url] or and URLs beneath it will be sent to [handler]
/// until [close] is called.
///
/// Throws a [StateError] if there's already a handler mounted.
void mount(Handler handler);
/// Closes the server and returns a Future that completes when all resources
/// are released.
///
/// Once this is called, no more requests will be passed to this server's
/// handler. Otherwise, the cleanup behavior is implementation-dependent.
Future close();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/server_handler.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:async/async.dart';
import 'handler.dart';
import 'request.dart';
import 'response.dart';
import 'server.dart';
/// A connected pair of a [Server] and a [Handler].
///
/// Requests to the handler are sent to the server's mounted handler once it's
/// available. This is used to expose a virtual [Server] that's actually one
/// part of a larger URL-space.
class ServerHandler {
/// The server.
///
/// Once this has a handler mounted, it's passed all requests to [handler]
/// until this server is closed.
Server get server => _server;
final _HandlerServer _server;
/// The handler.
///
/// This passes requests to [server]'s handler. If that handler isn't mounted
/// yet, the requests are handled once it is.
Handler get handler => _onRequest;
/// Creates a new connected pair of a [Server] with the given [url] and a
/// [Handler].
///
/// The caller is responsible for ensuring that requests to [url] or any URL
/// beneath it are handled by [handler].
///
/// If [onClose] is passed, it's called when [server] is closed. It may return
/// a [Future] or `null`; its return value is returned by [Server.close].
ServerHandler(Uri url, {void Function() onClose})
: _server = _HandlerServer(url, onClose);
/// Pipes requests to [server]'s handler.
FutureOr<Response> _onRequest(Request request) {
if (_server._closeMemo.hasRun) {
throw StateError('Request received after the server was closed.');
}
if (_server._handler != null) return _server._handler(request);
// Avoid async/await so that the common case of a handler already being
// mounted doesn't involve any extra asynchronous delays.
return _server._onMounted.then((_) => _server._handler(request));
}
}
/// The [Server] returned by [ServerHandler].
class _HandlerServer implements Server {
@override
final Uri url;
/// The callback to call when [close] is called, or `null`.
final ZoneCallback _onClose;
/// The mounted handler.
///
/// This is `null` until [mount] is called.
Handler _handler;
/// A future that fires once [mount] has been called.
Future get _onMounted => _onMountedCompleter.future;
final _onMountedCompleter = Completer();
_HandlerServer(this.url, this._onClose);
@override
void mount(Handler handler) {
if (_handler != null) {
throw StateError("Can't mount two handlers for the same server.");
}
_handler = handler;
_onMountedCompleter.complete();
}
@override
Future close() => _closeMemo.runOnce(() {
return _onClose == null ? null : _onClose();
});
final _closeMemo = AsyncMemoizer();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/request.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'package:http_parser/http_parser.dart';
import 'package:stream_channel/stream_channel.dart';
import 'hijack_exception.dart';
import 'message.dart';
import 'util.dart';
/// An HTTP request to be processed by a Shelf application.
class Request extends Message {
/// The URL path from the current handler to the requested resource, relative
/// to [handlerPath], plus any query parameters.
///
/// This should be used by handlers for determining which resource to serve,
/// in preference to [requestedUri]. This allows handlers to do the right
/// thing when they're mounted anywhere in the application. Routers should be
/// sure to update this when dispatching to a nested handler, using the
/// `path` parameter to [change].
///
/// [url]'s path is always relative. It may be empty, if [requestedUri] ends
/// at this handler. [url] will always have the same query parameters as
/// [requestedUri].
///
/// [handlerPath] and [url]'s path combine to create [requestedUri]'s path.
final Uri url;
/// The HTTP request method, such as "GET" or "POST".
final String method;
/// The URL path to the current handler.
///
/// This allows a handler to know its location within the URL-space of an
/// application. Routers should be sure to update this when dispatching to a
/// nested handler, using the `path` parameter to [change].
///
/// [handlerPath] is always a root-relative URL path; that is, it always
/// starts with `/`. It will also end with `/` whenever [url]'s path is
/// non-empty, or if [requestedUri]'s path ends with `/`.
///
/// [handlerPath] and [url]'s path combine to create [requestedUri]'s path.
final String handlerPath;
/// The HTTP protocol version used in the request, either "1.0" or "1.1".
final String protocolVersion;
/// The original [Uri] for the request.
final Uri requestedUri;
/// The callback wrapper for hijacking this request.
///
/// This will be `null` if this request can't be hijacked.
final _OnHijack _onHijack;
/// Whether this request can be hijacked.
///
/// This will be `false` either if the adapter doesn't support hijacking, or
/// if the request has already been hijacked.
bool get canHijack => _onHijack != null && !_onHijack.called;
/// If this is non-`null` and the requested resource hasn't been modified
/// since this date and time, the server should return a 304 Not Modified
/// response.
///
/// This is parsed from the If-Modified-Since header in [headers]. If
/// [headers] doesn't have an If-Modified-Since header, this will be `null`.
///
/// Throws [FormatException], if incoming HTTP request has an invalid
/// If-Modified-Since header.
DateTime get ifModifiedSince {
if (_ifModifiedSinceCache != null) return _ifModifiedSinceCache;
if (!headers.containsKey('if-modified-since')) return null;
_ifModifiedSinceCache = parseHttpDate(headers['if-modified-since']);
return _ifModifiedSinceCache;
}
DateTime _ifModifiedSinceCache;
/// Creates a new [Request].
///
/// [handlerPath] must be root-relative. [url]'s path must be fully relative,
/// and it must have the same query parameters as [requestedUri].
/// [handlerPath] and [url]'s path must combine to be the path component of
/// [requestedUri]. If they're not passed, [handlerPath] will default to `/`
/// and [url] to `requestedUri.path` without the initial `/`. If only one is
/// passed, the other will be inferred.
///
/// [body] is the request body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body. If it's a [String],
/// [encoding] is used to encode it to a [Stream<List<int>>]. The default
/// encoding is UTF-8.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
///
/// The default value for [protocolVersion] is '1.1'.
///
/// ## `onHijack`
///
/// [onHijack] allows handlers to take control of the underlying socket for
/// the request. It should be passed by adapters that can provide access to
/// the bidirectional socket underlying the HTTP connection stream.
///
/// The [onHijack] callback will only be called once per request. It will be
/// passed another callback which takes a byte StreamChannel. [onHijack] must
/// pass the channel for the connection stream to this callback, although it
/// may do so asynchronously.
///
/// If a request is hijacked, the adapter should expect to receive a
/// [HijackException] from the handler. This is a special exception used to
/// indicate that hijacking has occurred. The adapter should avoid either
/// sending a response or notifying the user of an error if a
/// [HijackException] is caught.
///
/// An adapter can check whether a request was hijacked using [canHijack],
/// which will be `false` for a hijacked request. The adapter may throw an
/// error if a [HijackException] is received for a non-hijacked request, or if
/// no [HijackException] is received for a hijacked request.
///
/// See also [hijack].
// TODO(kevmoo) finish documenting the rest of the arguments.
Request(String method, Uri requestedUri,
{String protocolVersion,
Map<String, /* String | List<String> */ Object> headers,
String handlerPath,
Uri url,
body,
Encoding encoding,
Map<String, Object> context,
void Function(void Function(StreamChannel<List<int>>)) onHijack})
: this._(method, requestedUri,
protocolVersion: protocolVersion,
headers: headers,
url: url,
handlerPath: handlerPath,
body: body,
encoding: encoding,
context: context,
onHijack: onHijack == null ? null : _OnHijack(onHijack));
/// This constructor has the same signature as [new Request] except that
/// accepts [onHijack] as [_OnHijack].
///
/// Any [Request] created by calling [change] will pass [_onHijack] from the
/// source [Request] to ensure that [hijack] can only be called once, even
/// from a changed [Request].
Request._(this.method, this.requestedUri,
{String protocolVersion,
Map<String, /* String | List<String> */ Object> headers,
String handlerPath,
Uri url,
body,
Encoding encoding,
Map<String, Object> context,
_OnHijack onHijack})
: protocolVersion = protocolVersion ?? '1.1',
url = _computeUrl(requestedUri, handlerPath, url),
handlerPath = _computeHandlerPath(requestedUri, handlerPath, url),
_onHijack = onHijack,
super(body, encoding: encoding, headers: headers, context: context) {
if (method.isEmpty) {
throw ArgumentError.value(method, 'method', 'cannot be empty.');
}
try {
// Trigger URI parsing methods that may throw format exception (in Request
// constructor or in handlers / routing).
requestedUri.pathSegments;
requestedUri.queryParametersAll;
} on FormatException catch (e) {
throw ArgumentError.value(
requestedUri, 'requestedUri', 'URI parsing failed: $e');
}
if (!requestedUri.isAbsolute) {
throw ArgumentError.value(
requestedUri, 'requestedUri', 'must be an absolute URL.');
}
if (requestedUri.fragment.isNotEmpty) {
throw ArgumentError.value(
requestedUri, 'requestedUri', 'may not have a fragment.');
}
// Notice that because relative paths must encode colon (':') as %3A we
// cannot actually combine this.handlerPath and this.url.path, but we can
// compare the pathSegments. In practice exposing this.url.path as a Uri
// and not a String is probably the underlying flaw here.
final handlerPart = Uri(path: this.handlerPath).pathSegments.join('/');
final rest = this.url.pathSegments.join('/');
final join = this.url.path.startsWith('/') ? '/' : '';
final pathSegments = '$handlerPart$join$rest';
if (pathSegments != requestedUri.pathSegments.join('/')) {
throw ArgumentError.value(
requestedUri,
'requestedUri',
'handlerPath "${this.handlerPath}" and url "${this.url}" must '
'combine to equal requestedUri path "${requestedUri.path}".');
}
}
/// Creates a new [Request] by copying existing values and applying specified
/// changes.
///
/// New key-value pairs in [context] and [headers] will be added to the copied
/// [Request]. If [context] or [headers] includes a key that already exists,
/// the key-value pair will replace the corresponding entry in the copied
/// [Request]. All other context and header values from the [Request] will be
/// included in the copied [Request] unchanged.
///
/// [body] is the request body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// [path] is used to update both [handlerPath] and [url]. It's designed for
/// routing middleware, and represents the path from the current handler to
/// the next handler. It must be a prefix of [url]; [handlerPath] becomes
/// `handlerPath + "/" + path`, and [url] becomes relative to that. For
/// example:
///
/// print(request.handlerPath); // => /static/
/// print(request.url); // => dir/file.html
///
/// request = request.change(path: "dir");
/// print(request.handlerPath); // => /static/dir/
/// print(request.url); // => file.html
@override
Request change(
{Map<String, /* String | List<String> */ Object> headers,
Map<String, Object> context,
String path,
body}) {
final headersAll = updateMap(this.headersAll, expandToHeadersAll(headers));
context = updateMap(this.context, context);
body ??= extractBody(this);
var handlerPath = this.handlerPath;
if (path != null) handlerPath += path;
return Request._(method, requestedUri,
protocolVersion: protocolVersion,
headers: headersAll,
handlerPath: handlerPath,
body: body,
context: context,
onHijack: _onHijack);
}
/// Takes control of the underlying request socket.
///
/// Synchronously, this throws a [HijackException] that indicates to the
/// adapter that it shouldn't emit a response itself. Asynchronously,
/// [callback] is called with a [StreamChannel<List<int>>] that provides
/// access to the underlying request socket.
///
/// This may only be called when using a Shelf adapter that supports
/// hijacking, such as the `dart:io` adapter. In addition, a given request may
/// only be hijacked once. [canHijack] can be used to detect whether this
/// request can be hijacked.
void hijack(void Function(StreamChannel<List<int>>) callback) {
if (_onHijack == null) {
throw StateError("This request can't be hijacked.");
}
_onHijack.run(callback);
throw const HijackException();
}
}
/// A callback for [Request.hijack] and tracking of whether it has been called.
class _OnHijack {
final void Function(void Function(StreamChannel<List<int>>)) _callback;
bool called = false;
_OnHijack(this._callback);
/// Calls [this].
///
/// Throws a [StateError] if [this] has already been called.
void run(void Function(StreamChannel<List<int>>) callback) {
if (called) throw StateError('This request has already been hijacked.');
called = true;
Future.microtask(() => _callback(callback));
}
}
/// Computes `url` from the provided [Request] constructor arguments.
///
/// If [url] is `null`, the value is inferred from [requestedUri] and
/// [handlerPath] if available. Otherwise [url] is returned.
Uri _computeUrl(Uri requestedUri, String handlerPath, Uri url) {
if (handlerPath != null &&
handlerPath != requestedUri.path &&
!handlerPath.endsWith('/')) {
handlerPath += '/';
}
if (url != null) {
if (url.scheme.isNotEmpty || url.hasAuthority || url.fragment.isNotEmpty) {
throw ArgumentError('url "$url" may contain only a path and query '
'parameters.');
}
if (!requestedUri.path.endsWith(url.path)) {
throw ArgumentError('url "$url" must be a suffix of requestedUri '
'"$requestedUri".');
}
if (requestedUri.query != url.query) {
throw ArgumentError('url "$url" must have the same query parameters '
'as requestedUri "$requestedUri".');
}
if (url.path.startsWith('/')) {
throw ArgumentError('url "$url" must be relative.');
}
var startOfUrl = requestedUri.path.length - url.path.length;
if (url.path.isNotEmpty &&
requestedUri.path.substring(startOfUrl - 1, startOfUrl) != '/') {
throw ArgumentError('url "$url" must be on a path boundary in '
'requestedUri "$requestedUri".');
}
return url;
} else if (handlerPath != null) {
return Uri(
path: requestedUri.path.substring(handlerPath.length),
query: requestedUri.query);
} else {
// Skip the initial "/".
var path = requestedUri.path.substring(1);
return Uri(path: path, query: requestedUri.query);
}
}
/// Computes `handlerPath` from the provided [Request] constructor arguments.
///
/// If [handlerPath] is `null`, the value is inferred from [requestedUri] and
/// [url] if available. Otherwise [handlerPath] is returned.
String _computeHandlerPath(Uri requestedUri, String handlerPath, Uri url) {
if (handlerPath != null &&
handlerPath != requestedUri.path &&
!handlerPath.endsWith('/')) {
handlerPath += '/';
}
if (handlerPath != null) {
if (!requestedUri.path.startsWith(handlerPath)) {
throw ArgumentError('handlerPath "$handlerPath" must be a prefix of '
'requestedUri path "${requestedUri.path}"');
}
if (!handlerPath.startsWith('/')) {
throw ArgumentError('handlerPath "$handlerPath" must be root-relative.');
}
return handlerPath;
} else if (url != null) {
if (url.path.isEmpty) return requestedUri.path;
var index = requestedUri.path.indexOf(url.path);
return requestedUri.path.substring(0, index);
} else {
return '/';
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/response.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'package:http_parser/http_parser.dart';
import 'message.dart';
import 'util.dart';
/// The response returned by a [Handler].
class Response extends Message {
/// The HTTP status code of the response.
final int statusCode;
/// The date and time after which the response's data should be considered
/// stale.
///
/// This is parsed from the Expires header in [headers]. If [headers] doesn't
/// have an Expires header, this will be `null`.
DateTime get expires {
if (_expiresCache != null) return _expiresCache;
if (!headers.containsKey('expires')) return null;
_expiresCache = parseHttpDate(headers['expires']);
return _expiresCache;
}
DateTime _expiresCache;
/// The date and time the source of the response's data was last modified.
///
/// This is parsed from the Last-Modified header in [headers]. If [headers]
/// doesn't have a Last-Modified header, this will be `null`.
DateTime get lastModified {
if (_lastModifiedCache != null) return _lastModifiedCache;
if (!headers.containsKey('last-modified')) return null;
_lastModifiedCache = parseHttpDate(headers['last-modified']);
return _lastModifiedCache;
}
DateTime _lastModifiedCache;
/// Constructs a 200 OK response.
///
/// This indicates that the request has succeeded.
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response.ok(body,
{Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: this(200,
body: body, headers: headers, encoding: encoding, context: context);
/// Constructs a 301 Moved Permanently response.
///
/// This indicates that the requested resource has moved permanently to a new
/// URI. [location] is that URI; it can be either a [String] or a [Uri]. It's
/// automatically set as the Location header in [headers].
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response.movedPermanently(location,
{body,
Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: this._redirect(301, location, body, headers, encoding,
context: context);
/// Constructs a 302 Found response.
///
/// This indicates that the requested resource has moved temporarily to a new
/// URI. [location] is that URI; it can be either a [String] or a [Uri]. It's
/// automatically set as the Location header in [headers].
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response.found(location,
{body,
Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: this._redirect(302, location, body, headers, encoding,
context: context);
/// Constructs a 303 See Other response.
///
/// This indicates that the response to the request should be retrieved using
/// a GET request to a new URI. [location] is that URI; it can be either a
/// [String] or a [Uri]. It's automatically set as the Location header in
/// [headers].
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response.seeOther(location,
{body,
Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: this._redirect(303, location, body, headers, encoding,
context: context);
/// Constructs a helper constructor for redirect responses.
Response._redirect(
int statusCode,
location,
body,
Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
{Map<String, Object> context})
: this(statusCode,
body: body,
encoding: encoding,
headers:
addHeader(headers, 'location', _locationToString(location)),
context: context);
/// Constructs a 304 Not Modified response.
///
/// This is used to respond to a conditional GET request that provided
/// information used to determine whether the requested resource has changed
/// since the last request. It indicates that the resource has not changed and
/// the old value should be used.
Response.notModified(
{Map<String, /* String | List<String> */ Object> headers,
Map<String, Object> context})
: this(304,
headers: addHeader(headers, 'date', formatHttpDate(DateTime.now())),
context: context);
/// Constructs a 403 Forbidden response.
///
/// This indicates that the server is refusing to fulfill the request.
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response.forbidden(body,
{Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: this(403,
headers: body == null ? _adjustErrorHeaders(headers) : headers,
body: body ?? 'Forbidden',
context: context,
encoding: encoding);
/// Constructs a 404 Not Found response.
///
/// This indicates that the server didn't find any resource matching the
/// requested URI.
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response.notFound(body,
{Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: this(404,
headers: body == null ? _adjustErrorHeaders(headers) : headers,
body: body ?? 'Not Found',
context: context,
encoding: encoding);
/// Constructs a 500 Internal Server Error response.
///
/// This indicates that the server had an internal error that prevented it
/// from fulfilling the request.
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response.internalServerError(
{body,
Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: this(500,
headers: body == null ? _adjustErrorHeaders(headers) : headers,
body: body ?? 'Internal Server Error',
context: context,
encoding: encoding);
/// Constructs an HTTP response with the given [statusCode].
///
/// [statusCode] must be greater than or equal to 100.
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
///
/// If the body is a [String], [encoding] is used to encode it to a
/// [Stream<List<int>>]. It defaults to UTF-8. If it's a [String], a
/// [List<int>], or `null`, the Content-Length header is set automatically
/// unless a Transfer-Encoding header is set. Otherwise, it's a
/// [Stream<List<int>>] and no Transfer-Encoding header is set, the adapter
/// will set the Transfer-Encoding header to "chunked" and apply the chunked
/// encoding to the body.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Response(this.statusCode,
{body,
Map<String, /* String | List<String> */ Object> headers,
Encoding encoding,
Map<String, Object> context})
: super(body, encoding: encoding, headers: headers, context: context) {
if (statusCode < 100) {
throw ArgumentError('Invalid status code: $statusCode.');
}
}
/// Creates a new [Response] by copying existing values and applying specified
/// changes.
///
/// New key-value pairs in [context] and [headers] will be added to the copied
/// [Response].
///
/// If [context] or [headers] includes a key that already exists, the
/// key-value pair will replace the corresponding entry in the copied
/// [Response].
///
/// All other context and header values from the [Response] will be included
/// in the copied [Response] unchanged.
///
/// [body] is the request body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `<int>[]` (empty list) to indicate no body.
@override
Response change(
{Map<String, /* String | List<String> */ Object> headers,
Map<String, Object> context,
body}) {
final headersAll = updateMap(this.headersAll, expandToHeadersAll(headers));
context = updateMap(this.context, context);
body ??= extractBody(this);
return Response(statusCode,
body: body, headers: headersAll, context: context);
}
}
/// Adds content-type information to [headers].
///
/// Returns a new map without modifying [headers]. This is used to add
/// content-type information when creating a 500 response with a default body.
Map<String, dynamic> _adjustErrorHeaders(
Map<String, /* String | List<String> */ Object> headers) {
if (headers == null || headers['content-type'] == null) {
return addHeader(headers, 'content-type', 'text/plain');
}
final contentTypeValue = expandHeaderValue(headers['content-type']).join(',');
var contentType =
MediaType.parse(contentTypeValue).change(mimeType: 'text/plain');
return addHeader(headers, 'content-type', contentType.toString());
}
/// Converts [location], which may be a [String] or a [Uri], to a [String].
///
/// Throws an [ArgumentError] if [location] isn't a [String] or a [Uri].
String _locationToString(location) {
if (location is String) return location;
if (location is Uri) return location.toString();
throw ArgumentError('Response location must be a String or Uri, was '
'"$location".');
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/message.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:http_parser/http_parser.dart';
import 'body.dart';
import 'headers.dart';
import 'shelf_unmodifiable_map.dart';
import 'util.dart';
Body extractBody(Message message) => message._body;
/// The default set of headers for a message created with no body and no
/// explicit headers.
final _defaultHeaders = Headers.from({
'content-length': ['0'],
});
/// Represents logic shared between [Request] and [Response].
abstract class Message {
final Headers _headers;
/// The HTTP headers with case-insensitive keys.
///
/// If a header occurs more than once in the query string, they are mapped to
/// by concatenating them with a comma.
///
/// The returned map is unmodifiable.
Map<String, String> get headers => _headers.singleValues;
/// The HTTP headers with multiple values with case-insensitive keys.
///
/// If a header occurs only once, its value is a singleton list.
/// If a header occurs with no value, the empty string is used as the value
/// for that occurrence.
///
/// The returned map and the lists it contains are unmodifiable.
Map<String, List<String>> get headersAll => _headers;
/// Extra context that can be used by for middleware and handlers.
///
/// For requests, this is used to pass data to inner middleware and handlers;
/// for responses, it's used to pass data to outer middleware and handlers.
///
/// Context properties that are used by a particular package should begin with
/// that package's name followed by a period. For example, if [logRequests]
/// wanted to take a prefix, its property name would be `"shelf.prefix"`,
/// since it's in the `shelf` package.
///
/// The value is immutable.
final Map<String, Object> context;
/// The streaming body of the message.
///
/// This can be read via [read] or [readAsString].
final Body _body;
/// If `true`, the stream returned by [read] won't emit any bytes.
///
/// This may have false negatives, but it won't have false positives.
bool get isEmpty => _body.contentLength == 0;
/// Creates a new [Message].
///
/// [body] is the response body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body. If it's a [String],
/// [encoding] is used to encode it to a [Stream<List<int>>]. It defaults to
/// UTF-8.
///
/// If [headers] is `null`, it is treated as empty.
///
/// If [encoding] is passed, the "encoding" field of the Content-Type header
/// in [headers] will be set appropriately. If there is no existing
/// Content-Type header, it will be set to "application/octet-stream".
Message(body,
{Encoding encoding,
Map<String, /* String | List<String> */ Object> headers,
Map<String, Object> context})
: this._withBody(Body(body, encoding), headers, context);
Message._withBody(
Body body, Map<String, dynamic> headers, Map<String, Object> context)
: this._withHeadersAll(
body,
Headers.from(_adjustHeaders(expandToHeadersAll(headers), body)),
context);
Message._withHeadersAll(
Body body, Headers headers, Map<String, Object> context)
: _body = body,
_headers = headers,
context = ShelfUnmodifiableMap<Object>(context, ignoreKeyCase: false);
/// The contents of the content-length field in [headers].
///
/// If not set, `null`.
int get contentLength {
if (_contentLengthCache != null) return _contentLengthCache;
if (!headers.containsKey('content-length')) return null;
_contentLengthCache = int.parse(headers['content-length']);
return _contentLengthCache;
}
int _contentLengthCache;
/// The MIME type of the message.
///
/// This is parsed from the Content-Type header in [headers]. It contains only
/// the MIME type, without any Content-Type parameters.
///
/// If [headers] doesn't have a Content-Type header, this will be `null`.
String get mimeType {
var contentType = _contentType;
if (contentType == null) return null;
return contentType.mimeType;
}
/// The encoding of the message body.
///
/// This is parsed from the "charset" parameter of the Content-Type header in
/// [headers].
///
/// If [headers] doesn't have a Content-Type header or it specifies an
/// encoding that `dart:convert` doesn't support, this will be `null`.
Encoding get encoding {
var contentType = _contentType;
if (contentType == null) return null;
if (!contentType.parameters.containsKey('charset')) return null;
return Encoding.getByName(contentType.parameters['charset']);
}
/// The parsed version of the Content-Type header in [headers].
///
/// This is cached for efficient access.
MediaType get _contentType {
if (_contentTypeCache != null) return _contentTypeCache;
if (!headers.containsKey('content-type')) return null;
_contentTypeCache = MediaType.parse(headers['content-type']);
return _contentTypeCache;
}
MediaType _contentTypeCache;
/// Returns a [Stream] representing the body.
///
/// Can only be called once.
Stream<List<int>> read() => _body.read();
/// Returns a [Future] containing the body as a String.
///
/// If [encoding] is passed, that's used to decode the body.
/// Otherwise the encoding is taken from the Content-Type header. If that
/// doesn't exist or doesn't have a "charset" parameter, UTF-8 is used.
///
/// This calls [read] internally, which can only be called once.
Future<String> readAsString([Encoding encoding]) {
encoding ??= this.encoding ?? utf8;
return encoding.decodeStream(read());
}
/// Creates a new [Message] by copying existing values and applying specified
/// changes.
Message change(
{Map<String, String> headers, Map<String, Object> context, body});
}
/// Adds information about [encoding] to [headers].
///
/// Returns a new map without modifying [headers].
Map<String, List<String>> _adjustHeaders(
Map<String, List<String>> headers, Body body) {
var sameEncoding = _sameEncoding(headers, body);
if (sameEncoding) {
if (body.contentLength == null ||
findHeader(headers, 'content-length') == '${body.contentLength}') {
return headers ?? Headers.empty();
} else if (body.contentLength == 0 &&
(headers == null || headers.isEmpty)) {
return _defaultHeaders;
}
}
var newHeaders = headers == null
? CaseInsensitiveMap<List<String>>()
: CaseInsensitiveMap<List<String>>.from(headers);
if (!sameEncoding) {
if (newHeaders['content-type'] == null) {
newHeaders['content-type'] = [
'application/octet-stream; charset=${body.encoding.name}'
];
} else {
final contentType =
MediaType.parse(joinHeaderValues(newHeaders['content-type']))
.change(parameters: {'charset': body.encoding.name});
newHeaders['content-type'] = [contentType.toString()];
}
}
if (body.contentLength != null) {
final coding = joinHeaderValues(newHeaders['transfer-encoding']);
if (coding == null || equalsIgnoreAsciiCase(coding, 'identity')) {
newHeaders['content-length'] = [body.contentLength.toString()];
}
}
return newHeaders;
}
/// Returns whether [headers] declares the same encoding as [body].
bool _sameEncoding(Map<String, List<String>> headers, Body body) {
if (body.encoding == null) return true;
var contentType = findHeader(headers, 'content-type');
if (contentType == null) return false;
var charset = MediaType.parse(contentType).parameters['charset'];
return Encoding.getByName(charset) == body.encoding;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/headers.dart | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:http_parser/http_parser.dart';
import 'package:shelf/src/util.dart';
final _emptyHeaders = Headers._empty();
/// Unmodifiable, key-insensitive header map.
class Headers extends UnmodifiableMapView<String, List<String>> {
Map<String, String> _singleValues;
factory Headers.from(Map<String, List<String>> values) {
if (values == null || values.isEmpty) {
return _emptyHeaders;
} else if (values is Headers) {
return values;
} else {
return Headers._(values);
}
}
Headers._(Map<String, List<String>> values)
: super(CaseInsensitiveMap.from(Map.fromEntries(values.entries
.where((e) => e.value?.isNotEmpty ?? false)
.map((e) => MapEntry(e.key, List.unmodifiable(e.value))))));
Headers._empty() : super(const {});
factory Headers.empty() => _emptyHeaders;
Map<String, String> get singleValues => _singleValues ??= UnmodifiableMapView(
CaseInsensitiveMap.from(
map((key, value) => MapEntry(key, joinHeaderValues(value)))),
);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/body.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
/// The body of a request or response.
///
/// This tracks whether the body has been read. It's separate from [Message]
/// because the message may be changed with [Message.change], but each instance
/// should share a notion of whether the body was read.
class Body {
/// The contents of the message body.
///
/// This will be `null` after [read] is called.
Stream<List<int>> _stream;
/// The encoding used to encode the stream returned by [read], or `null` if no
/// encoding was used.
final Encoding encoding;
/// The length of the stream returned by [read], or `null` if that can't be
/// determined efficiently.
final int contentLength;
Body._(this._stream, this.encoding, this.contentLength);
/// Converts [body] to a byte stream and wraps it in a [Body].
///
/// [body] may be either a [Body], a [String], a [List<int>], a
/// [Stream<List<int>>], or `null`. If it's a [String], [encoding] will be
/// used to convert it to a [Stream<List<int>>].
factory Body(body, [Encoding encoding]) {
if (body is Body) return body;
Stream<List<int>> stream;
int contentLength;
if (body == null) {
contentLength = 0;
stream = Stream.fromIterable([]);
} else if (body is String) {
if (encoding == null) {
var encoded = utf8.encode(body);
// If the text is plain ASCII, don't modify the encoding. This means
// that an encoding of "text/plain" will stay put.
if (!_isPlainAscii(encoded, body.length)) encoding = utf8;
contentLength = encoded.length;
stream = Stream.fromIterable([encoded]);
} else {
var encoded = encoding.encode(body);
contentLength = encoded.length;
stream = Stream.fromIterable([encoded]);
}
} else if (body is List) {
contentLength = body.length;
stream = Stream.fromIterable([body.cast()]);
} else if (body is Stream) {
stream = body.cast();
} else {
throw ArgumentError('Response body "$body" must be a String or a '
'Stream.');
}
return Body._(stream, encoding, contentLength);
}
/// Returns whether [bytes] is plain ASCII.
///
/// [codeUnits] is the number of code units in the original string.
static bool _isPlainAscii(List<int> bytes, int codeUnits) {
// Most non-ASCII code units will produce multiple bytes and make the text
// longer.
if (bytes.length != codeUnits) return false;
// Non-ASCII code units between U+0080 and U+009F produce 8-bit characters
// with the high bit set.
return bytes.every((byte) => byte & 0x80 == 0);
}
/// Returns a [Stream] representing the body.
///
/// Can only be called once.
Stream<List<int>> read() {
if (_stream == null) {
throw StateError("The 'read' method can only be called once on a "
'shelf.Request/shelf.Response object.');
}
var stream = _stream;
_stream = null;
return stream;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/shelf_unmodifiable_map.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:collection/collection.dart';
import 'package:http_parser/http_parser.dart';
/// A simple wrapper over [UnmodifiableMapView] which avoids re-wrapping itself.
class ShelfUnmodifiableMap<V> extends UnmodifiableMapView<String, V> {
/// `true` if the key values are already lowercase.
final bool _ignoreKeyCase;
/// If [source] is a [ShelfUnmodifiableMap] with matching [ignoreKeyCase],
/// then [source] is returned.
///
/// If [source] is `null` it is treated like an empty map.
///
/// If [ignoreKeyCase] is `true`, the keys will have case-insensitive access.
///
/// [source] is copied to a new [Map] to ensure changes to the parameter value
/// after constructions are not reflected.
factory ShelfUnmodifiableMap(Map<String, V> source,
{bool ignoreKeyCase = false}) {
if (source is ShelfUnmodifiableMap<V> &&
// !ignoreKeyCase: no transformation of the input is required
// source._ignoreKeyCase: the input cannot be transformed any more
(!ignoreKeyCase || source._ignoreKeyCase)) {
return source;
}
if (source == null || source.isEmpty) {
return const _EmptyShelfUnmodifiableMap();
}
if (ignoreKeyCase) {
source = CaseInsensitiveMap<V>.from(source);
} else {
source = Map<String, V>.from(source);
}
return ShelfUnmodifiableMap<V>._(source, ignoreKeyCase);
}
/// Returns an empty [ShelfUnmodifiableMap].
const factory ShelfUnmodifiableMap.empty() = _EmptyShelfUnmodifiableMap<V>;
ShelfUnmodifiableMap._(Map<String, V> source, this._ignoreKeyCase)
: super(source);
}
/// A const implementation of an empty [ShelfUnmodifiableMap].
class _EmptyShelfUnmodifiableMap<V> extends MapView<String, V>
implements ShelfUnmodifiableMap<V> {
@override
bool get _ignoreKeyCase => true;
const _EmptyShelfUnmodifiableMap() : super(const <String, Null>{});
// Override modifier methods that care about the type of key they use so that
// when V is Null, they throw UnsupportedErrors instead of type errors.
@override
void operator []=(String key, Object value) => super[key] = null;
@override
void addAll(Map<String, Object> other) => super.addAll({});
@override
V putIfAbsent(String key, Object Function() ifAbsent) =>
super.putIfAbsent(key, () => null);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/handler.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'request.dart';
import 'response.dart';
/// A function which handles a [Request].
///
/// For example a static file handler may read the requested URI from the
/// filesystem and return it as the body of the [Response].
///
/// A [Handler] which wraps one or more other handlers to perform pre or post
/// processing is known as a "middleware".
///
/// A [Handler] may receive a request directly from an HTTP server or it
/// may have been touched by other middleware. Similarly the response may be
/// directly returned by an HTTP server or have further processing done by other
/// middleware.
typedef Handler = FutureOr<Response> Function(Request request);
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/pipeline.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'handler.dart';
import 'middleware.dart';
/// A helper that makes it easy to compose a set of [Middleware] and a
/// [Handler].
///
/// var handler = const Pipeline()
/// .addMiddleware(loggingMiddleware)
/// .addMiddleware(cachingMiddleware)
/// .addHandler(application);
class Pipeline {
final Pipeline _parent;
final Middleware _middleware;
const Pipeline()
: _middleware = null,
_parent = null;
Pipeline._(this._middleware, this._parent);
/// Returns a new [Pipeline] with [middleware] added to the existing set of
/// [Middleware].
///
/// [middleware] will be the last [Middleware] to process a request and
/// the first to process a response.
Pipeline addMiddleware(Middleware middleware) => Pipeline._(middleware, this);
/// Returns a new [Handler] with [handler] as the final processor of a
/// [Request] if all of the middleware in the pipeline have passed the request
/// through.
Handler addHandler(Handler handler) {
if (_middleware == null) return handler;
return _parent.addHandler(_middleware(handler));
}
/// Exposes this pipeline of [Middleware] as a single middleware instance.
Middleware get middleware => addHandler;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/io_server.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import '../shelf_io.dart';
import 'handler.dart';
import 'server.dart';
/// A [Server] backed by a `dart:io` [HttpServer].
class IOServer implements Server {
/// The underlying [HttpServer].
final HttpServer server;
/// Whether [mount] has been called.
bool _mounted = false;
@override
Uri get url {
if (server.address.isLoopback) {
return Uri(scheme: 'http', host: 'localhost', port: server.port);
}
// IPv6 addresses in URLs need to be enclosed in square brackets to avoid
// URL ambiguity with the ":" in the address.
if (server.address.type == InternetAddressType.IPv6) {
return Uri(
scheme: 'http',
host: '[${server.address.address}]',
port: server.port);
}
return Uri(scheme: 'http', host: server.address.address, port: server.port);
}
/// Calls [HttpServer.bind] and wraps the result in an [IOServer].
static Future<IOServer> bind(address, int port, {int backlog}) async {
backlog ??= 0;
var server = await HttpServer.bind(address, port, backlog: backlog);
return IOServer(server);
}
IOServer(this.server);
@override
void mount(Handler handler) {
if (_mounted) {
throw StateError("Can't mount two handlers for the same server.");
}
_mounted = true;
serveRequests(server, handler);
}
@override
Future close() => server.close();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/middleware/logger.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:stack_trace/stack_trace.dart';
import '../hijack_exception.dart';
import '../middleware.dart';
/// Middleware which prints the time of the request, the elapsed time for the
/// inner handlers, the response's status code and the request URI.
///
/// If [logger] is passed, it's called for each request. The `msg` parameter is
/// a formatted string that includes the request time, duration, request method,
/// and requested path. When an exception is thrown, it also includes the
/// exception's string and stack trace; otherwise, it includes the status code.
/// The `isError` parameter indicates whether the message is caused by an error.
///
/// If [logger] is not passed, the message is just passed to [print].
Middleware logRequests({void Function(String message, bool isError) logger}) =>
(innerHandler) {
logger ??= _defaultLogger;
return (request) {
var startTime = DateTime.now();
var watch = Stopwatch()..start();
return Future.sync(() => innerHandler(request)).then((response) {
var msg = _message(startTime, response.statusCode,
request.requestedUri, request.method, watch.elapsed);
logger(msg, false);
return response;
}, onError: (error, StackTrace stackTrace) {
if (error is HijackException) throw error;
var msg = _errorMessage(startTime, request.requestedUri,
request.method, watch.elapsed, error, stackTrace);
logger(msg, true);
throw error;
});
};
};
String _formatQuery(String query) {
return query == '' ? '' : '?$query';
}
String _message(DateTime requestTime, int statusCode, Uri requestedUri,
String method, Duration elapsedTime) {
return '${requestTime.toIso8601String()} '
'${elapsedTime.toString().padLeft(15)} '
'${method.padRight(7)} [$statusCode] ' // 7 - longest standard HTTP method
'${requestedUri.path}${_formatQuery(requestedUri.query)}';
}
String _errorMessage(DateTime requestTime, Uri requestedUri, String method,
Duration elapsedTime, Object error, StackTrace stack) {
var chain = Chain.current();
if (stack != null) {
chain = Chain.forTrace(stack)
.foldFrames((frame) => frame.isCore || frame.package == 'shelf')
.terse;
}
var msg = '$requestTime\t$elapsedTime\t$method\t${requestedUri.path}'
'${_formatQuery(requestedUri.query)}\n$error';
if (chain == null) return msg;
return '$msg\n$chain';
}
void _defaultLogger(String msg, bool isError) {
if (isError) {
print('[ERROR] $msg');
} else {
print(msg);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf/src/middleware/add_chunked_encoding.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:collection/collection.dart';
import 'package:http_parser/http_parser.dart';
import '../middleware.dart';
/// Middleware that adds [chunked transfer coding][] to responses if none of the
/// following conditions are true:
///
/// [chunked transfer coding]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
///
/// * A Content-Length header is provided.
/// * The Content-Type header indicates the MIME type `multipart/byteranges`.
/// * The Transfer-Encoding header already includes the `chunked` coding.
///
/// This is intended for use by [Shelf adapters][] rather than end-users.
///
/// [Shelf adapters]: https://github.com/dart-lang/shelf#adapters
final addChunkedEncoding = createMiddleware(responseHandler: (response) {
if (response.contentLength != null) return response;
if (response.statusCode < 200) return response;
if (response.statusCode == 204) return response;
if (response.statusCode == 304) return response;
if (response.mimeType == 'multipart/byteranges') return response;
// We only check the last coding here because HTTP requires that the chunked
// encoding be listed last.
var coding = response.headers['transfer-encoding'];
if (coding != null && !equalsIgnoreAsciiCase(coding, 'identity')) {
return response;
}
return response.change(
headers: {'transfer-encoding': 'chunked'},
body: chunkedCoding.encoder.bind(response.read()));
});
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/typed_data/typed_buffers.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Growable typed-data lists.
///
/// These lists works just as a typed-data list, except that they are growable.
/// They use an underlying buffer, and when that buffer becomes too small, it
/// is replaced by a new buffer.
///
/// That means that using the `buffer` getter is not guaranteed
/// to return the same result each time it is used, and that the buffer may
/// be larger than what the list is using.
library typed_data.typed_buffers;
export 'src/typed_buffer.dart' hide TypedDataBuffer;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/typed_data/typed_data.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Utilities and functionality related to the "dart:typed_data" library.
library typed_data;
export "src/typed_queue.dart";
export "typed_buffers.dart";
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/typed_data | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/typed_data/src/typed_queue.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import "dart:collection";
import "dart:typed_data";
import "package:collection/collection.dart";
import 'typed_buffer.dart';
/// The shared superclass of all the typed queue subclasses.
abstract class _TypedQueue<E, L extends List<E>> with ListMixin<E> {
/// The underlying data buffer.
///
/// This is always both a List<E> and a TypedData, which we don't have a type
/// for that. For example, for a `Uint8Queue`, this is a `Uint8List`.
L _table;
int _head;
int _tail;
/// Create an empty queue.
_TypedQueue(this._table)
: _head = 0,
_tail = 0;
// Iterable interface.
int get length => (_tail - _head) & (_table.length - 1);
List<E> toList({bool growable = true}) {
var list = growable ? _createBuffer(length) : _createList(length);
_writeToList(list);
return list;
}
QueueList<T> cast<T>() {
if (this is QueueList<T>) return this as QueueList<T>;
throw UnsupportedError("$this cannot be cast to the desired type.");
}
@deprecated
QueueList<T> retype<T>() => cast<T>();
// Queue interface.
void addLast(E value) {
_table[_tail] = value;
_tail = (_tail + 1) & (_table.length - 1);
if (_head == _tail) _growAtCapacity();
}
void addFirst(E value) {
_head = (_head - 1) & (_table.length - 1);
_table[_head] = value;
if (_head == _tail) _growAtCapacity();
}
E removeFirst() {
if (_head == _tail) throw StateError("No element");
var result = _table[_head];
_head = (_head + 1) & (_table.length - 1);
return result;
}
E removeLast() {
if (_head == _tail) throw StateError("No element");
_tail = (_tail - 1) & (_table.length - 1);
return _table[_tail];
}
// List interface.
void add(E value) => addLast(value);
set length(int value) {
RangeError.checkNotNegative(value, "length");
var delta = value - length;
if (delta >= 0) {
var needsToGrow = _table.length <= value;
if (needsToGrow) _growTo(value);
_tail = (_tail + delta) & (_table.length - 1);
// If we didn't copy into a new table, make sure that we overwrite the
// existing data so that users don't accidentally depend on it still
// existing.
if (!needsToGrow) fillRange(value - delta, value, _defaultValue);
} else {
removeRange(value, length);
}
}
E operator [](int index) {
RangeError.checkValidIndex(index, this, null, length);
return _table[(_head + index) & (_table.length - 1)];
}
void operator []=(int index, E value) {
RangeError.checkValidIndex(index, this);
_table[(_head + index) & (_table.length - 1)] = value;
}
void removeRange(int start, int end) {
var length = this.length;
RangeError.checkValidRange(start, end, length);
// Special-case removing an initial or final range because we can do it very
// efficiently by adjusting `_head` or `_tail`.
if (start == 0) {
_head = (_head + end) & (_table.length - 1);
return;
}
var elementsAfter = length - end;
if (elementsAfter == 0) {
_tail = (_head + start) & (_table.length - 1);
return;
}
// Choose whether to copy from the beginning of the end of the queue based
// on which will require fewer copied elements.
var removedElements = end - start;
if (start < elementsAfter) {
setRange(removedElements, end, this);
_head = (_head + removedElements) & (_table.length - 1);
} else {
setRange(start, length - removedElements, this, end);
_tail = (_tail - removedElements) & (_table.length - 1);
}
}
void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) {
RangeError.checkValidRange(start, end, length);
if (start == end) return;
var targetStart = (_head + start) & (_table.length - 1);
var targetEnd = (_head + end) & (_table.length - 1);
var targetIsContiguous = targetStart < targetEnd;
if (identical(iterable, this)) {
// If we're copying this queue to itself, we can copy [_table] in directly
// which requires some annoying case analysis but in return bottoms out on
// an extremely efficient `memmove` call. However, we may need to do three
// copies to avoid overwriting data we'll need to use later.
var sourceStart = (_head + skipCount) & (_table.length - 1);
var sourceEnd = (sourceStart + (end - start)) & (_table.length - 1);
if (sourceStart == targetStart) return;
var sourceIsContiguous = sourceStart < sourceEnd;
if (targetIsContiguous && sourceIsContiguous) {
// If both the source and destination ranges are contiguous, we can
// do a single [setRange]. Hooray!
_table.setRange(targetStart, targetEnd, _table, sourceStart);
} else if (!targetIsContiguous && !sourceIsContiguous) {
// If neither range is contiguous, we need to do three copies.
if (sourceStart > targetStart) {
// [=====| targetEnd targetStart |======]
// [========| sourceEnd sourceStart |===]
// Copy front to back.
var startGap = sourceStart - targetStart;
var firstEnd = _table.length - startGap;
_table.setRange(targetStart, firstEnd, _table, sourceStart);
_table.setRange(firstEnd, _table.length, _table);
_table.setRange(0, targetEnd, _table, startGap);
} else if (sourceEnd < targetEnd) {
// [=====| targetEnd targetStart |======]
// [==| sourceEnd sourceStart |=========]
// Copy back to front.
var firstStart = targetEnd - sourceEnd;
_table.setRange(firstStart, targetEnd, _table);
_table.setRange(0, firstStart, _table, _table.length - firstStart);
_table.setRange(targetStart, _table.length, _table, sourceStart);
}
} else if (sourceStart < targetEnd) {
// Copying twice is safe here as long as we copy front to back.
if (sourceIsContiguous) {
// [=====| targetEnd targetStart |======]
// [ |===========| sourceEnd ]
// sourceStart
_table.setRange(targetStart, _table.length, _table, sourceStart);
_table.setRange(0, targetEnd, _table,
sourceStart + (_table.length - targetStart));
} else {
// targetEnd
// [ targetStart |===========| ]
// [=====| sourceEnd sourceStart |======]
var firstEnd = _table.length - sourceStart;
_table.setRange(targetStart, firstEnd, _table, sourceStart);
_table.setRange(firstEnd, targetEnd, _table);
}
} else {
// Copying twice is safe here as long as we copy back to front. This
// also covers the case where there's no overlap between the source and
// target ranges, in which case the direction doesn't matter.
if (sourceIsContiguous) {
// [=====| targetEnd targetStart |======]
// [ sourceStart |===========| ]
// sourceEnd
_table.setRange(0, targetEnd, _table,
sourceStart + (_table.length - targetStart));
_table.setRange(targetStart, _table.length, _table, sourceStart);
} else {
// targetStart
// [ |===========| targetEnd ]
// [=====| sourceEnd sourceStart |======]
var firstStart = targetEnd - sourceEnd;
_table.setRange(firstStart, targetEnd, _table);
_table.setRange(targetStart, firstStart, _table, sourceStart);
}
}
} else if (targetIsContiguous) {
// If the range is contiguous within the table, we can set it with a single
// underlying [setRange] call.
_table.setRange(targetStart, targetEnd, iterable, skipCount);
} else if (iterable is List<E>) {
// If the range isn't contiguous and [iterable] is actually a [List] (but
// not this queue), set it with two underlying [setRange] calls.
_table.setRange(targetStart, _table.length, iterable, skipCount);
_table.setRange(
0, targetEnd, iterable, skipCount + (_table.length - targetStart));
} else {
// If [iterable] isn't a [List], we don't want to make two different
// [setRange] calls because it could materialize a lazy iterable twice.
// Instead we just fall back to the default iteration-based
// implementation.
super.setRange(start, end, iterable, skipCount);
}
}
void fillRange(int start, int end, [E value]) {
var startInTable = (_head + start) & (_table.length - 1);
var endInTable = (_head + end) & (_table.length - 1);
if (startInTable <= endInTable) {
_table.fillRange(startInTable, endInTable, value);
} else {
_table.fillRange(startInTable, _table.length, value);
_table.fillRange(0, endInTable, value);
}
}
L sublist(int start, [int end]) {
var length = this.length;
end = RangeError.checkValidRange(start, end, length);
var list = _createList(end - start);
_writeToList(list, start, end);
return list;
}
// Internal helper functions.
/// Writes the contents of `this` between [start] (which defaults to 0) and
/// [end] (which defaults to [length]) to the beginning of [target].
///
/// This is functionally identical to `target.setRange(0, end - start, this,
/// start)`, but it's more efficient when [target] is typed data.
///
/// Returns the number of elements written to [target].
int _writeToList(List<E> target, [int start, int end]) {
start ??= 0;
end ??= length;
assert(target.length >= end - start);
assert(start <= end);
var elementsToWrite = end - start;
var startInTable = (_head + start) & (_table.length - 1);
var endInTable = (_head + end) & (_table.length - 1);
if (startInTable <= endInTable) {
target.setRange(0, elementsToWrite, _table, startInTable);
} else {
var firstPartSize = _table.length - startInTable;
target.setRange(0, firstPartSize, _table, startInTable);
target.setRange(firstPartSize, firstPartSize + endInTable, _table, 0);
}
return elementsToWrite;
}
/// Assumes the table is currently full to capacity, and grows it to the next
/// power of two.
void _growAtCapacity() {
assert(_head == _tail);
var newTable = _createList(_table.length * 2);
// We can't use [_writeToList] here because when `_head == _tail` it thinks
// the queue is empty rather than full.
var partitionPoint = _table.length - _head;
newTable.setRange(0, partitionPoint, _table, _head);
if (partitionPoint != _table.length) {
newTable.setRange(partitionPoint, _table.length, _table);
}
_head = 0;
_tail = _table.length;
_table = newTable;
}
/// Grows the tableso it's at least large enough size to include that many
/// elements.
void _growTo(int newElementCount) {
assert(newElementCount >= length);
// Add some extra room to ensure that there's room for more elements after
// expansion.
newElementCount += newElementCount >> 1;
var newTable = _createList(_nextPowerOf2(newElementCount));
_tail = _writeToList(newTable);
_table = newTable;
_head = 0;
}
// Specialization for the specific type.
// Create a new typed list.
L _createList(int size);
// Create a new typed buffer of the given type.
List<E> _createBuffer(int size);
/// The default value used to fill the queue when changing length.
E get _defaultValue;
}
abstract class _IntQueue<L extends List<int>> extends _TypedQueue<int, L> {
_IntQueue(L queue) : super(queue);
int get _defaultValue => 0;
}
abstract class _FloatQueue<L extends List<double>>
extends _TypedQueue<double, L> {
_FloatQueue(L queue) : super(queue);
double get _defaultValue => 0.0;
}
/// A [QueueList] that efficiently stores 8-bit unsigned integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low eight bits, interpreted
/// as an unsigned 8-bit integer with values in the range 0 to 255.
class Uint8Queue extends _IntQueue<Uint8List> implements QueueList<int> {
/// Creates an empty [Uint8Queue] with the given initial internal capacity (in
/// elements).
Uint8Queue([int initialCapacity])
: super(Uint8List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Uint8Queue] with the same length and contents as [elements].
factory Uint8Queue.fromList(List<int> elements) =>
Uint8Queue(elements.length)..addAll(elements);
Uint8List _createList(int size) => Uint8List(size);
Uint8Buffer _createBuffer(int size) => Uint8Buffer(size);
}
/// A [QueueList] that efficiently stores 8-bit signed integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low eight bits, interpreted
/// as a signed 8-bit two's complement integer with values in the range -128 to
/// +127.
class Int8Queue extends _IntQueue<Int8List> implements QueueList<int> {
/// Creates an empty [Int8Queue] with the given initial internal capacity (in
/// elements).
Int8Queue([int initialCapacity])
: super(Int8List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Int8Queue] with the same length and contents as [elements].
factory Int8Queue.fromList(List<int> elements) =>
Int8Queue(elements.length)..addAll(elements);
Int8List _createList(int size) => Int8List(size);
Int8Buffer _createBuffer(int size) => Int8Buffer(size);
}
/// A [QueueList] that efficiently stores 8-bit unsigned integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are clamped to an unsigned eight bit value. That is,
/// all values below zero are stored as zero and all values above 255 are stored
/// as 255.
class Uint8ClampedQueue extends _IntQueue<Uint8ClampedList>
implements QueueList<int> {
/// Creates an empty [Uint8ClampedQueue] with the given initial internal
/// capacity (in elements).
Uint8ClampedQueue([int initialCapacity])
: super(Uint8ClampedList(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Uint8ClampedQueue] with the same length and contents as
/// [elements].
factory Uint8ClampedQueue.fromList(List<int> elements) =>
Uint8ClampedQueue(elements.length)..addAll(elements);
Uint8ClampedList _createList(int size) => Uint8ClampedList(size);
Uint8ClampedBuffer _createBuffer(int size) => Uint8ClampedBuffer(size);
}
/// A [QueueList] that efficiently stores 16-bit unsigned integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low 16 bits, interpreted as
/// an unsigned 16-bit integer with values in the range 0 to 65535.
class Uint16Queue extends _IntQueue<Uint16List> implements QueueList<int> {
/// Creates an empty [Uint16Queue] with the given initial internal capacity
/// (in elements).
Uint16Queue([int initialCapacity])
: super(Uint16List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Uint16Queue] with the same length and contents as [elements].
factory Uint16Queue.fromList(List<int> elements) =>
Uint16Queue(elements.length)..addAll(elements);
Uint16List _createList(int size) => Uint16List(size);
Uint16Buffer _createBuffer(int size) => Uint16Buffer(size);
}
/// A [QueueList] that efficiently stores 16-bit signed integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low 16 bits, interpreted as a
/// signed 16-bit two's complement integer with values in the range -32768 to
/// +32767.
class Int16Queue extends _IntQueue<Int16List> implements QueueList<int> {
/// Creates an empty [Int16Queue] with the given initial internal capacity (in
/// elements).
Int16Queue([int initialCapacity])
: super(Int16List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Int16Queue] with the same length and contents as [elements].
factory Int16Queue.fromList(List<int> elements) =>
Int16Queue(elements.length)..addAll(elements);
Int16List _createList(int size) => Int16List(size);
Int16Buffer _createBuffer(int size) => Int16Buffer(size);
}
/// A [QueueList] that efficiently stores 32-bit unsigned integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low 32 bits, interpreted as
/// an unsigned 32-bit integer with values in the range 0 to 4294967295.
class Uint32Queue extends _IntQueue<Uint32List> implements QueueList<int> {
/// Creates an empty [Uint32Queue] with the given initial internal capacity
/// (in elements).
Uint32Queue([int initialCapacity])
: super(Uint32List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Uint32Queue] with the same length and contents as [elements].
factory Uint32Queue.fromList(List<int> elements) =>
Uint32Queue(elements.length)..addAll(elements);
Uint32List _createList(int size) => Uint32List(size);
Uint32Buffer _createBuffer(int size) => Uint32Buffer(size);
}
/// A [QueueList] that efficiently stores 32-bit signed integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low 32 bits, interpreted as a
/// signed 32-bit two's complement integer with values in the range -2147483648
/// to 2147483647.
class Int32Queue extends _IntQueue<Int32List> implements QueueList<int> {
/// Creates an empty [Int32Queue] with the given initial internal capacity (in
/// elements).
Int32Queue([int initialCapacity])
: super(Int32List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Int32Queue] with the same length and contents as [elements].
factory Int32Queue.fromList(List<int> elements) =>
Int32Queue(elements.length)..addAll(elements);
Int32List _createList(int size) => Int32List(size);
Int32Buffer _createBuffer(int size) => Int32Buffer(size);
}
/// A [QueueList] that efficiently stores 64-bit unsigned integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low 64 bits, interpreted as
/// an unsigned 64-bit integer with values in the range 0 to
/// 18446744073709551615.
class Uint64Queue extends _IntQueue<Uint64List> implements QueueList<int> {
/// Creates an empty [Uint64Queue] with the given initial internal capacity
/// (in elements).
Uint64Queue([int initialCapacity])
: super(Uint64List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Uint64Queue] with the same length and contents as [elements].
factory Uint64Queue.fromList(List<int> elements) =>
Uint64Queue(elements.length)..addAll(elements);
Uint64List _createList(int size) => Uint64List(size);
Uint64Buffer _createBuffer(int size) => Uint64Buffer(size);
}
/// A [QueueList] that efficiently stores 64-bit signed integers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Integers stored in this are truncated to their low 64 bits, interpreted as a
/// signed 64-bit two's complement integer with values in the range
/// -9223372036854775808 to +9223372036854775807.
class Int64Queue extends _IntQueue<Int64List> implements QueueList<int> {
/// Creates an empty [Int64Queue] with the given initial internal capacity (in
/// elements).
Int64Queue([int initialCapacity])
: super(Int64List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Int64Queue] with the same length and contents as [elements].
factory Int64Queue.fromList(List<int> elements) =>
Int64Queue(elements.length)..addAll(elements);
Int64List _createList(int size) => Int64List(size);
Int64Buffer _createBuffer(int size) => Int64Buffer(size);
}
/// A [QueueList] that efficiently stores IEEE 754 single-precision binary
/// floating-point numbers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
///
/// Doubles stored in this are converted to the nearest single-precision value.
/// Values read are converted to a double value with the same value.
class Float32Queue extends _FloatQueue<Float32List>
implements QueueList<double> {
/// Creates an empty [Float32Queue] with the given initial internal capacity
/// (in elements).
Float32Queue([int initialCapacity])
: super(Float32List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Float32Queue] with the same length and contents as [elements].
factory Float32Queue.fromList(List<double> elements) =>
Float32Queue(elements.length)..addAll(elements);
Float32List _createList(int size) => Float32List(size);
Float32Buffer _createBuffer(int size) => Float32Buffer(size);
}
/// A [QueueList] that efficiently stores IEEE 754 double-precision binary
/// floating-point numbers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
class Float64Queue extends _FloatQueue<Float64List>
implements QueueList<double> {
/// Creates an empty [Float64Queue] with the given initial internal capacity
/// (in elements).
Float64Queue([int initialCapacity])
: super(Float64List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Float64Queue] with the same length and contents as [elements].
factory Float64Queue.fromList(List<double> elements) =>
Float64Queue(elements.length)..addAll(elements);
Float64List _createList(int size) => Float64List(size);
Float64Buffer _createBuffer(int size) => Float64Buffer(size);
}
/// A [QueueList] that efficiently stores [Int32x4] numbers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
class Int32x4Queue extends _TypedQueue<Int32x4, Int32x4List>
implements QueueList<Int32x4> {
static final Int32x4 _zero = Int32x4(0, 0, 0, 0);
/// Creates an empty [Int32x4Queue] with the given initial internal capacity
/// (in elements).
Int32x4Queue([int initialCapacity])
: super(Int32x4List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Int32x4Queue] with the same length and contents as [elements].
factory Int32x4Queue.fromList(List<Int32x4> elements) =>
Int32x4Queue(elements.length)..addAll(elements);
Int32x4List _createList(int size) => Int32x4List(size);
Int32x4Buffer _createBuffer(int size) => Int32x4Buffer(size);
Int32x4 get _defaultValue => _zero;
}
/// A [QueueList] that efficiently stores [Float32x4] numbers.
///
/// For long queues, this implementation can be considerably more space- and
/// time-efficient than a default [QueueList] implementation.
class Float32x4Queue extends _TypedQueue<Float32x4, Float32x4List>
implements QueueList<Float32x4> {
/// Creates an empty [Float32x4Queue] with the given initial internal capacity (in
/// elements).
Float32x4Queue([int initialCapacity])
: super(Float32x4List(_chooseRealInitialCapacity(initialCapacity)));
/// Creates a [Float32x4Queue] with the same length and contents as [elements].
factory Float32x4Queue.fromList(List<Float32x4> elements) =>
Float32x4Queue(elements.length)..addAll(elements);
Float32x4List _createList(int size) => Float32x4List(size);
Float32x4Buffer _createBuffer(int size) => Float32x4Buffer(size);
Float32x4 get _defaultValue => Float32x4.zero();
}
/// The initial capacity of queues if the user doesn't specify one.
const _defaultInitialCapacity = 16;
/// Choose the next-highest power of two given a user-specified
/// [initialCapacity] for a queue.
int _chooseRealInitialCapacity(int initialCapacity) {
if (initialCapacity == null || initialCapacity < _defaultInitialCapacity) {
return _defaultInitialCapacity;
} else if (!_isPowerOf2(initialCapacity)) {
return _nextPowerOf2(initialCapacity);
} else {
return initialCapacity;
}
}
/// Whether [number] is a power of two.
///
/// Only works for positive numbers.
bool _isPowerOf2(int number) => (number & (number - 1)) == 0;
/// Rounds [number] up to the nearest power of 2.
///
/// If [number] is a power of 2 already, it is returned.
///
/// Only works for positive numbers.
int _nextPowerOf2(int number) {
assert(number > 0);
number = (number << 1) - 1;
for (;;) {
var nextNumber = number & (number - 1);
if (nextNumber == 0) return number;
number = nextNumber;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/typed_data | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/typed_data/src/typed_buffer.dart | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection' show ListBase;
import 'dart:typed_data';
abstract class TypedDataBuffer<E> extends ListBase<E> {
static const int _initialLength = 8;
/// The underlying data buffer.
///
/// This is always both a List<E> and a TypedData, which we don't have a type
/// for here. For example, for a `Uint8Buffer`, this is a `Uint8List`.
List<E> _buffer;
/// Returns a view of [_buffer] as a [TypedData].
TypedData get _typedBuffer => _buffer as TypedData;
/// The length of the list being built.
int _length;
TypedDataBuffer(List<E> buffer)
: _buffer = buffer,
_length = buffer.length;
@override
int get length => _length;
@override
E operator [](int index) {
if (index >= length) throw RangeError.index(index, this);
return _buffer[index];
}
@override
void operator []=(int index, E value) {
if (index >= length) throw RangeError.index(index, this);
_buffer[index] = value;
}
@override
set length(int newLength) {
if (newLength < _length) {
var defaultValue = _defaultValue;
for (var i = newLength; i < _length; i++) {
_buffer[i] = defaultValue;
}
} else if (newLength > _buffer.length) {
List<E> newBuffer;
if (_buffer.isEmpty) {
newBuffer = _createBuffer(newLength);
} else {
newBuffer = _createBiggerBuffer(newLength);
}
newBuffer.setRange(0, _length, _buffer);
_buffer = newBuffer;
}
_length = newLength;
}
void _add(E value) {
if (_length == _buffer.length) _grow(_length);
_buffer[_length++] = value;
}
// We override the default implementation of `add` because it grows the list
// by setting the length in increments of one. We want to grow by doubling
// capacity in most cases.
@override
void add(E value) {
_add(value);
}
/// Appends all objects of [values] to the end of this buffer.
///
/// This adds values from [start] (inclusive) to [end] (exclusive) in
/// [values]. If [end] is omitted, it defaults to adding all elements of
/// [values] after [start].
///
/// The [start] value must be non-negative. The [values] iterable must have at
/// least [start] elements, and if [end] is specified, it must be greater than
/// or equal to [start] and [values] must have at least [end] elements.
@override
void addAll(Iterable<E> values, [int start = 0, int end]) {
RangeError.checkNotNegative(start, 'start');
if (end != null && start > end) {
throw RangeError.range(end, start, null, 'end');
}
_addAll(values, start, end);
}
/// Inserts all objects of [values] at position [index] in this list.
///
/// This adds values from [start] (inclusive) to [end] (exclusive) in
/// [values]. If [end] is omitted, it defaults to adding all elements of
/// [values] after [start].
///
/// The [start] value must be non-negative. The [values] iterable must have at
/// least [start] elements, and if [end] is specified, it must be greater than
/// or equal to [start] and [values] must have at least [end] elements.
@override
void insertAll(int index, Iterable<E> values, [int start = 0, int end]) {
RangeError.checkValidIndex(index, this, 'index', _length + 1);
RangeError.checkNotNegative(start, 'start');
if (end != null) {
if (start > end) {
throw RangeError.range(end, start, null, 'end');
}
if (start == end) return;
}
// If we're adding to the end of the list anyway, use [_addAll]. This lets
// us avoid converting [values] into a list even if [end] is null, since we
// can add values iteratively to the end of the list. We can't do so in the
// center because copying the trailing elements every time is non-linear.
if (index == _length) {
_addAll(values, start, end);
return;
}
if (end == null && values is List) {
end = values.length;
}
if (end != null) {
_insertKnownLength(index, values, start, end);
return;
}
// Add elements at end, growing as appropriate, then put them back at
// position [index] using flip-by-double-reverse.
var writeIndex = _length;
var skipCount = start;
for (var value in values) {
if (skipCount > 0) {
skipCount--;
continue;
}
if (writeIndex == _buffer.length) {
_grow(writeIndex);
}
_buffer[writeIndex++] = value;
}
if (skipCount > 0) {
throw StateError('Too few elements');
}
if (end != null && writeIndex < end) {
throw RangeError.range(end, start, writeIndex, 'end');
}
// Swap [index.._length) and [_length..writeIndex) by double-reversing.
_reverse(_buffer, index, _length);
_reverse(_buffer, _length, writeIndex);
_reverse(_buffer, index, writeIndex);
_length = writeIndex;
return;
}
// Reverses the range [start..end) of buffer.
static void _reverse(List buffer, int start, int end) {
end--; // Point to last element, not after last element.
while (start < end) {
var first = buffer[start];
var last = buffer[end];
buffer[end] = first;
buffer[start] = last;
start++;
end--;
}
}
/// Does the same thing as [addAll].
///
/// This allows [addAll] and [insertAll] to share implementation without a
/// subclass unexpectedly overriding both when it intended to only override
/// [addAll].
void _addAll(Iterable<E> values, [int start = 0, int end]) {
if (values is List) end ??= values.length;
// If we know the length of the segment to add, do so with [addRange]. This
// way we know how much to grow the buffer in advance, and it may be even
// more efficient for typed data input.
if (end != null) {
_insertKnownLength(_length, values, start, end);
return;
}
// Otherwise, just add values one at a time.
var i = 0;
for (var value in values) {
if (i >= start) add(value);
i++;
}
if (i < start) throw StateError('Too few elements');
}
/// Like [insertAll], but with a guaranteed non-`null` [start] and [end].
void _insertKnownLength(int index, Iterable<E> values, int start, int end) {
if (values is List) {
end ??= values.length;
if (start > values.length || end > values.length) {
throw StateError('Too few elements');
}
} else {
assert(end != null);
}
var valuesLength = end - start;
var newLength = _length + valuesLength;
_ensureCapacity(newLength);
_buffer.setRange(
index + valuesLength, _length + valuesLength, _buffer, index);
_buffer.setRange(index, index + valuesLength, values, start);
_length = newLength;
}
@override
void insert(int index, E element) {
if (index < 0 || index > _length) {
throw RangeError.range(index, 0, _length);
}
if (_length < _buffer.length) {
_buffer.setRange(index + 1, _length + 1, _buffer, index);
_buffer[index] = element;
_length++;
return;
}
var newBuffer = _createBiggerBuffer(null);
newBuffer.setRange(0, index, _buffer);
newBuffer.setRange(index + 1, _length + 1, _buffer, index);
newBuffer[index] = element;
_length++;
_buffer = newBuffer;
}
/// Ensures that [_buffer] is at least [requiredCapacity] long,
///
/// Grows the buffer if necessary, preserving existing data.
void _ensureCapacity(int requiredCapacity) {
if (requiredCapacity <= _buffer.length) return;
var newBuffer = _createBiggerBuffer(requiredCapacity);
newBuffer.setRange(0, _length, _buffer);
_buffer = newBuffer;
}
/// Create a bigger buffer.
///
/// This method determines how much bigger a bigger buffer should
/// be. If [requiredCapacity] is not null, it will be at least that
/// size. It will always have at least have double the capacity of
/// the current buffer.
List<E> _createBiggerBuffer(int requiredCapacity) {
var newLength = _buffer.length * 2;
if (requiredCapacity != null && newLength < requiredCapacity) {
newLength = requiredCapacity;
} else if (newLength < _initialLength) {
newLength = _initialLength;
}
return _createBuffer(newLength);
}
/// Grows the buffer.
///
/// This copies the first [length] elements into the new buffer.
void _grow(int length) {
_buffer = _createBiggerBuffer(null)..setRange(0, length, _buffer);
}
@override
void setRange(int start, int end, Iterable<E> source, [int skipCount = 0]) {
if (end > _length) throw RangeError.range(end, 0, _length);
_setRange(start, end, source, skipCount);
}
/// Like [setRange], but with no bounds checking.
void _setRange(int start, int end, Iterable<E> source, int skipCount) {
if (source is TypedDataBuffer<E>) {
_buffer.setRange(start, end, source._buffer, skipCount);
} else {
_buffer.setRange(start, end, source, skipCount);
}
}
// TypedData.
int get elementSizeInBytes => _typedBuffer.elementSizeInBytes;
int get lengthInBytes => _length * _typedBuffer.elementSizeInBytes;
int get offsetInBytes => _typedBuffer.offsetInBytes;
/// Returns the underlying [ByteBuffer].
///
/// The returned buffer may be replaced by operations that change the [length]
/// of this list.
///
/// The buffer may be larger than [lengthInBytes] bytes, but never smaller.
ByteBuffer get buffer => _typedBuffer.buffer;
// Specialization for the specific type.
// Return zero for integers, 0.0 for floats, etc.
// Used to fill buffer when changing length.
E get _defaultValue;
// Create a new typed list to use as buffer.
List<E> _createBuffer(int size);
}
abstract class _IntBuffer extends TypedDataBuffer<int> {
_IntBuffer(List<int> buffer) : super(buffer);
@override
int get _defaultValue => 0;
}
abstract class _FloatBuffer extends TypedDataBuffer<double> {
_FloatBuffer(List<double> buffer) : super(buffer);
@override
double get _defaultValue => 0.0;
}
class Uint8Buffer extends _IntBuffer {
Uint8Buffer([int initialLength = 0]) : super(Uint8List(initialLength));
@override
Uint8List _createBuffer(int size) => Uint8List(size);
}
class Int8Buffer extends _IntBuffer {
Int8Buffer([int initialLength = 0]) : super(Int8List(initialLength));
@override
Int8List _createBuffer(int size) => Int8List(size);
}
class Uint8ClampedBuffer extends _IntBuffer {
Uint8ClampedBuffer([int initialLength = 0])
: super(Uint8ClampedList(initialLength));
@override
Uint8ClampedList _createBuffer(int size) => Uint8ClampedList(size);
}
class Uint16Buffer extends _IntBuffer {
Uint16Buffer([int initialLength = 0]) : super(Uint16List(initialLength));
@override
Uint16List _createBuffer(int size) => Uint16List(size);
}
class Int16Buffer extends _IntBuffer {
Int16Buffer([int initialLength = 0]) : super(Int16List(initialLength));
@override
Int16List _createBuffer(int size) => Int16List(size);
}
class Uint32Buffer extends _IntBuffer {
Uint32Buffer([int initialLength = 0]) : super(Uint32List(initialLength));
@override
Uint32List _createBuffer(int size) => Uint32List(size);
}
class Int32Buffer extends _IntBuffer {
Int32Buffer([int initialLength = 0]) : super(Int32List(initialLength));
@override
Int32List _createBuffer(int size) => Int32List(size);
}
class Uint64Buffer extends _IntBuffer {
Uint64Buffer([int initialLength = 0]) : super(Uint64List(initialLength));
@override
Uint64List _createBuffer(int size) => Uint64List(size);
}
class Int64Buffer extends _IntBuffer {
Int64Buffer([int initialLength = 0]) : super(Int64List(initialLength));
@override
Int64List _createBuffer(int size) => Int64List(size);
}
class Float32Buffer extends _FloatBuffer {
Float32Buffer([int initialLength = 0]) : super(Float32List(initialLength));
@override
Float32List _createBuffer(int size) => Float32List(size);
}
class Float64Buffer extends _FloatBuffer {
Float64Buffer([int initialLength = 0]) : super(Float64List(initialLength));
@override
Float64List _createBuffer(int size) => Float64List(size);
}
class Int32x4Buffer extends TypedDataBuffer<Int32x4> {
static final Int32x4 _zero = Int32x4(0, 0, 0, 0);
Int32x4Buffer([int initialLength = 0]) : super(Int32x4List(initialLength));
@override
Int32x4 get _defaultValue => _zero;
@override
Int32x4List _createBuffer(int size) => Int32x4List(size);
}
class Float32x4Buffer extends TypedDataBuffer<Float32x4> {
Float32x4Buffer([int initialLength = 0])
: super(Float32x4List(initialLength));
@override
Float32x4 get _defaultValue => Float32x4.zero();
@override
Float32x4List _createBuffer(int size) => Float32x4List(size);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/pool/pool.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'package:async/async.dart';
import 'package:stack_trace/stack_trace.dart';
/// Manages an abstract pool of resources with a limit on how many may be in use
/// at once.
///
/// When a resource is needed, the user should call [request]. When the returned
/// future completes with a [PoolResource], the resource may be allocated. Once
/// the resource has been released, the user should call [PoolResource.release].
/// The pool will ensure that only a certain number of [PoolResource]s may be
/// allocated at once.
class Pool {
/// Completers for requests beyond the first [_maxAllocatedResources].
///
/// When an item is released, the next element of [_requestedResources] will
/// be completed.
final _requestedResources = Queue<Completer<PoolResource>>();
/// Callbacks that must be called before additional resources can be
/// allocated.
///
/// See [PoolResource.allowRelease].
final _onReleaseCallbacks = Queue<void Function()>();
/// Completers that will be completed once `onRelease` callbacks are done
/// running.
///
/// These are kept in a queue to ensure that the earliest request completes
/// first regardless of what order the `onRelease` callbacks complete in.
final _onReleaseCompleters = Queue<Completer<PoolResource>>();
/// The maximum number of resources that may be allocated at once.
final int _maxAllocatedResources;
/// The number of resources that are currently allocated.
int _allocatedResources = 0;
/// The timeout timer.
///
/// This timer is canceled as long as the pool is below the resource limit.
/// It's reset once the resource limit is reached and again every time an
/// resource is released or a new resource is requested. If it fires, that
/// indicates that the caller became deadlocked, likely due to files waiting
/// for additional files to be read before they could be closed.
///
/// This is `null` if this pool shouldn't time out.
RestartableTimer _timer;
/// The amount of time to wait before timing out the pending resources.
final Duration _timeout;
/// A [FutureGroup] that tracks all the `onRelease` callbacks for resources
/// that have been marked releasable.
///
/// This is `null` until [close] is called.
FutureGroup _closeGroup;
/// Whether [close] has been called.
bool get isClosed => _closeMemo.hasRun;
/// A future that completes once the pool is closed and all its outstanding
/// resources have been released.
///
/// If any [PoolResource.allowRelease] callback throws an exception after the
/// pool is closed, this completes with that exception.
Future get done => _closeMemo.future;
/// Creates a new pool with the given limit on how many resources may be
/// allocated at once.
///
/// If [timeout] is passed, then if that much time passes without any activity
/// all pending [request] futures will throw a [TimeoutException]. This is
/// intended to avoid deadlocks.
Pool(this._maxAllocatedResources, {Duration timeout}) : _timeout = timeout {
if (_maxAllocatedResources <= 0) {
throw ArgumentError.value(_maxAllocatedResources, 'maxAllocatedResources',
'Must be greater than zero.');
}
if (timeout != null) {
// Start the timer canceled since we only want to start counting down once
// we've run out of available resources.
_timer = RestartableTimer(timeout, _onTimeout)..cancel();
}
}
/// Request a [PoolResource].
///
/// If the maximum number of resources is already allocated, this will delay
/// until one of them is released.
Future<PoolResource> request() {
if (isClosed) {
throw StateError("request() may not be called on a closed Pool.");
}
if (_allocatedResources < _maxAllocatedResources) {
_allocatedResources++;
return Future.value(PoolResource._(this));
} else if (_onReleaseCallbacks.isNotEmpty) {
return _runOnRelease(_onReleaseCallbacks.removeFirst());
} else {
var completer = Completer<PoolResource>();
_requestedResources.add(completer);
_resetTimer();
return completer.future;
}
}
/// Requests a resource for the duration of [callback], which may return a
/// Future.
///
/// The return value of [callback] is piped to the returned Future.
Future<T> withResource<T>(FutureOr<T> Function() callback) async {
if (isClosed) {
throw StateError("withResource() may not be called on a closed Pool.");
}
var resource = await request();
try {
return await callback();
} finally {
resource.release();
}
}
/// Returns a [Stream] containing the result of [action] applied to each
/// element of [elements].
///
/// While [action] is invoked on each element of [elements] in order,
/// it's possible the return [Stream] may have items out-of-order – especially
/// if the completion time of [action] varies.
///
/// If [action] throws an error the source item along with the error object
/// and [StackTrace] are passed to [onError], if it is provided. If [onError]
/// returns `true`, the error is added to the returned [Stream], otherwise
/// it is ignored.
///
/// Errors thrown from iterating [elements] will not be passed to
/// [onError]. They will always be added to the returned stream as an error.
///
/// Note: all of the resources of the this [Pool] will be used when the
/// returned [Stream] is listened to until it is completed or canceled.
///
/// Note: if this [Pool] is closed before the returned [Stream] is listened
/// to, a [StateError] is thrown.
Stream<T> forEach<S, T>(
Iterable<S> elements, FutureOr<T> Function(S source) action,
{bool Function(S item, Object error, StackTrace stack) onError}) {
onError ??= (item, e, s) => true;
var cancelPending = false;
Completer resumeCompleter;
StreamController<T> controller;
Iterator<S> iterator;
Future<void> run(int i) async {
while (iterator.moveNext()) {
// caching `current` is necessary because there are async breaks
// in this code and `iterator` is shared across many workers
final current = iterator.current;
_resetTimer();
await resumeCompleter?.future;
if (cancelPending) {
break;
}
T value;
try {
value = await action(current);
} catch (e, stack) {
if (onError(current, e, stack)) {
controller.addError(e, stack);
}
continue;
}
controller.add(value);
}
}
Future doneFuture;
void onListen() {
assert(iterator == null);
iterator = elements.iterator;
assert(doneFuture == null);
doneFuture = Future.wait(
Iterable<int>.generate(_maxAllocatedResources)
.map((i) => withResource(() => run(i))),
eagerError: true)
.catchError(controller.addError);
doneFuture.whenComplete(controller.close);
}
controller = StreamController<T>(
sync: true,
onListen: onListen,
onCancel: () async {
assert(!cancelPending);
cancelPending = true;
await doneFuture;
},
onPause: () {
assert(resumeCompleter == null);
resumeCompleter = Completer();
},
onResume: () {
assert(resumeCompleter != null);
resumeCompleter.complete();
resumeCompleter = null;
},
);
return controller.stream;
}
/// Closes the pool so that no more resources are requested.
///
/// Existing resource requests remain unchanged.
///
/// Any resources that are marked as releasable using
/// [PoolResource.allowRelease] are released immediately. Once all resources
/// have been released and any `onRelease` callbacks have completed, the
/// returned future completes successfully. If any `onRelease` callback throws
/// an error, the returned future completes with that error.
///
/// This may be called more than once; it returns the same [Future] each time.
Future close() => _closeMemo.runOnce(() {
if (_closeGroup != null) return _closeGroup.future;
_resetTimer();
_closeGroup = FutureGroup();
for (var callback in _onReleaseCallbacks) {
_closeGroup.add(Future.sync(callback));
}
_allocatedResources -= _onReleaseCallbacks.length;
_onReleaseCallbacks.clear();
if (_allocatedResources == 0) _closeGroup.close();
return _closeGroup.future;
});
final _closeMemo = AsyncMemoizer();
/// If there are any pending requests, this will fire the oldest one.
void _onResourceReleased() {
_resetTimer();
if (_requestedResources.isNotEmpty) {
var pending = _requestedResources.removeFirst();
pending.complete(PoolResource._(this));
} else {
_allocatedResources--;
if (isClosed && _allocatedResources == 0) _closeGroup.close();
}
}
/// If there are any pending requests, this will fire the oldest one after
/// running [onRelease].
void _onResourceReleaseAllowed(Function() onRelease) {
_resetTimer();
if (_requestedResources.isNotEmpty) {
var pending = _requestedResources.removeFirst();
pending.complete(_runOnRelease(onRelease));
} else if (isClosed) {
_closeGroup.add(Future.sync(onRelease));
_allocatedResources--;
if (_allocatedResources == 0) _closeGroup.close();
} else {
var zone = Zone.current;
var registered = zone.registerCallback(onRelease);
_onReleaseCallbacks.add(() => zone.run(registered));
}
}
/// Runs [onRelease] and returns a Future that completes to a resource once an
/// [onRelease] callback completes.
///
/// Futures returned by [_runOnRelease] always complete in the order they were
/// created, even if earlier [onRelease] callbacks take longer to run.
Future<PoolResource> _runOnRelease(Function() onRelease) {
Future.sync(onRelease).then((value) {
_onReleaseCompleters.removeFirst().complete(PoolResource._(this));
}).catchError((error, StackTrace stackTrace) {
_onReleaseCompleters.removeFirst().completeError(error, stackTrace);
});
var completer = Completer<PoolResource>.sync();
_onReleaseCompleters.add(completer);
return completer.future;
}
/// A resource has been requested, allocated, or released.
void _resetTimer() {
if (_timer == null) return;
if (_requestedResources.isEmpty) {
_timer.cancel();
} else {
_timer.reset();
}
}
/// Handles [_timer] timing out by causing all pending resource completers to
/// emit exceptions.
void _onTimeout() {
for (var completer in _requestedResources) {
completer.completeError(
TimeoutException(
"Pool deadlock: all resources have been "
"allocated for too long.",
_timeout),
Chain.current());
}
_requestedResources.clear();
_timer = null;
}
}
/// A member of a [Pool].
///
/// A [PoolResource] is a token that indicates that a resource is allocated.
/// When the associated resource is released, the user should call [release].
class PoolResource {
final Pool _pool;
/// Whether `this` has been released yet.
bool _released = false;
PoolResource._(this._pool);
/// Tells the parent [Pool] that the resource associated with this resource is
/// no longer allocated, and that a new [PoolResource] may be allocated.
void release() {
if (_released) {
throw StateError("A PoolResource may only be released once.");
}
_released = true;
_pool._onResourceReleased();
}
/// Tells the parent [Pool] that the resource associated with this resource is
/// no longer necessary, but should remain allocated until more resources are
/// needed.
///
/// When [Pool.request] is called and there are no remaining available
/// resources, the [onRelease] callback is called. It should free the
/// resource, and it may return a Future or `null`. Once that completes, the
/// [Pool.request] call will complete to a new [PoolResource].
///
/// This is useful when a resource's main function is complete, but it may
/// produce additional information later on. For example, an isolate's task
/// may be complete, but it could still emit asynchronous errors.
void allowRelease(Function() onRelease) {
if (_released) {
throw StateError("A PoolResource may only be released once.");
}
_released = true;
_pool._onResourceReleaseAllowed(onRelease);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/import_table.dart | // 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.
library kernel.import_table;
import 'ast.dart';
abstract class ImportTable {
int getImportIndex(Library library);
}
class ComponentImportTable implements ImportTable {
final Map<Library, int> _libraryIndex = <Library, int>{};
ComponentImportTable(Component component) {
for (int i = 0; i < component.libraries.length; ++i) {
_libraryIndex[component.libraries[i]] = i;
}
}
int getImportIndex(Library library) => _libraryIndex[library] ?? -1;
}
class LibraryImportTable implements ImportTable {
final List<String> _importPaths = <String>[];
final List<Library> _importedLibraries = <Library>[];
final Map<Library, int> _libraryIndex = <Library, int>{};
factory LibraryImportTable(Library lib) {
return new _ImportTableBuilder(lib).build();
}
LibraryImportTable.empty();
/// The list of imports.
///
/// Should not be modified directly, as the index map would go out of sync.
List<String> get importPaths => _importPaths;
List<Library> get importedLibraries => _importedLibraries;
int addImport(Library target, String importPath) {
int index = _libraryIndex[target];
if (index != null) return index;
index = _importPaths.length;
_importPaths.add(importPath);
_importedLibraries.add(target);
_libraryIndex[target] = index;
return index;
}
/// Returns the index of the given import, or -1 if not found.
int getImportIndex(Library library) {
return _libraryIndex[library] ?? -1;
}
String getImportPath(Library library) {
return _importPaths[getImportIndex(library)];
}
}
/// Builds the import table for a given library.
class _ImportTableBuilder extends RecursiveVisitor {
final LibraryImportTable table = new LibraryImportTable.empty();
final Library referenceLibrary;
LibraryImportTable build() {
referenceLibrary.accept(this);
return table;
}
_ImportTableBuilder(this.referenceLibrary) {
table.addImport(referenceLibrary, '');
}
void addLibraryImport(Library target) {
if (target == referenceLibrary) return; // Self-reference is special.
var referenceUri = referenceLibrary.importUri;
var targetUri = target.importUri;
if (targetUri == null) {
throw '$referenceUri cannot refer to library without an import URI';
}
// To support using custom-uris in unit tests, we don't check directly
// whether the scheme is 'file:', but instead we check that is not 'dart:'
// or 'package:'.
bool isFileOrCustomScheme(uri) =>
uri.scheme != '' && uri.scheme != 'package' && uri.scheme != 'dart';
bool isTargetSchemeFileOrCustom = isFileOrCustomScheme(targetUri);
bool isReferenceSchemeFileOrCustom = isFileOrCustomScheme(referenceUri);
if (isTargetSchemeFileOrCustom && isReferenceSchemeFileOrCustom) {
String relativeUri = relativeUriPath(targetUri, referenceUri);
table.addImport(target, relativeUri);
} else if (isTargetSchemeFileOrCustom) {
// Cannot import a file:URI from a dart:URI or package:URI.
// We may want to remove this restriction, but for now it's just a sanity
// check.
throw '$referenceUri cannot refer to application library $targetUri';
} else {
table.addImport(target, target.importUri.toString());
}
}
visitClassReference(Class node) {
addLibraryImport(node.enclosingLibrary);
}
visitLibrary(Library node) {
super.visitLibrary(node);
for (Reference exportedReference in node.additionalExports) {
addLibraryImport(exportedReference.node.parent);
}
}
defaultMemberReference(Member node) {
addLibraryImport(node.enclosingLibrary);
}
visitName(Name name) {
if (name.library != null) {
addLibraryImport(name.library);
}
}
}
String relativeUriPath(Uri target, Uri ref) {
List<String> targetSegments = target.pathSegments;
List<String> refSegments = ref.pathSegments;
int to = refSegments.length;
if (targetSegments.length < to) to = targetSegments.length;
to--; // The last entry is the filename, here we compare only directories.
int same = -1;
for (int i = 0; i < to; i++) {
if (targetSegments[i] == refSegments[i]) {
same = i;
} else {
break;
}
}
if (same == targetSegments.length - 2 &&
targetSegments.length == refSegments.length) {
// Both parts have the same number of segments,
// and they agree on all directories.
if (targetSegments.last == "") return ".";
return targetSegments.last;
}
List<String> path = new List<String>();
int oked = same + 1;
while (oked < refSegments.length - 1) {
path.add("..");
oked++;
}
path.addAll(targetSegments.skip(same + 1));
if (path.isEmpty) path.add(".");
return path.join("/");
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/ast.dart | // 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 'transformations/flags.dart';
import 'text/ast_to_text.dart';
import 'type_algebra.dart';
import 'type_environment.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 and short-running test tools
/// as it can cause serious memory leaks.
///
/// Synthetic names are cached globally to retain consistency across different
/// [toString] calls (hence the memory leak).
///
/// Nodes that are named, such as [Class] and [Member], return their
/// (possibly synthesized) name, whereas other AST nodes return the complete
/// textual representation of their subtree.
String toString() => debugNodeToString(this);
}
/// 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;
}
abstract class FileUriNode extends TreeNode {
/// The URI of the source file this node was loaded from.
Uri get fileUri;
}
abstract class Annotatable {
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() {
if (canonicalName != null) {
return 'Reference to $canonicalName';
}
if (node != null) {
return 'Reference to $node';
}
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
// ------------------------------------------------------------------------
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;
// TODO(jensj): Do we have a better option than this?
static int defaultLanguageVersionMajor = 2;
static int defaultLanguageVersionMinor = 6;
int _languageVersionMajor;
int _languageVersionMinor;
int get languageVersionMajor =>
_languageVersionMajor ?? defaultLanguageVersionMajor;
int get languageVersionMinor =>
_languageVersionMinor ?? defaultLanguageVersionMinor;
void setLanguageVersion(int languageVersionMajor, int languageVersionMinor) {
if (languageVersionMajor == null || languageVersionMinor == null) {
throw new StateError("Trying to set langauge version 'null'");
}
_languageVersionMajor = languageVersionMajor;
_languageVersionMinor = languageVersionMinor;
}
static const int ExternalFlag = 1 << 0;
static const int SyntheticFlag = 1 << 1;
static const int NonNullableByDefaultFlag = 1 << 2;
int flags = 0;
/// If true, the library is part of another build unit and its contents
/// are only partially loaded.
///
/// Classes of an external library are loaded at one of the [ClassLevel]s
/// other than [ClassLevel.Body]. Members in an external library have no
/// body, but have their typed interface present.
///
/// If the library is non-external, then its classes are at [ClassLevel.Body]
/// and all members are loaded.
bool get isExternal => (flags & ExternalFlag) != 0;
void set isExternal(bool value) {
flags = value ? (flags | ExternalFlag) : (flags & ~ExternalFlag);
}
/// 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);
}
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,
bool isExternal: false,
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) {
this.isExternal = isExternal;
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);
}
}
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.
String toString() => debugLibraryName(this);
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
}
/// 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);
}
}
/// 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);
}
}
/// 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) {}
}
/// 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 function
// type. They are needed to keep such attributes as names and annotations.
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;
TypedefType get thisType {
return new TypedefType(this, _getAsTypeArguments(typeParameters));
}
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);
}
}
/// 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;
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);
}
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;
}
/// 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);
/// If true, the class is part of an external library, that is, it is defined
/// in another build unit. Only a subset of its members are present.
///
/// These classes should be loaded at either [ClassLevel.Type] or
/// [ClassLevel.Hierarchy] level.
bool get isInExternalLibrary => enclosingLibrary.isExternal;
Supertype get asRawSupertype {
return new Supertype(this,
new List<DartType>.filled(typeParameters.length, const DynamicType()));
}
Supertype get asThisSupertype {
return new Supertype(this, _getAsTypeArguments(typeParameters));
}
InterfaceType _thisType;
InterfaceType get thisType {
return _thisType ??=
new InterfaceType(this, _getAsTypeArguments(typeParameters));
}
InterfaceType _bottomType;
InterfaceType get bottomType {
return _bottomType ??= new InterfaceType(this,
new List<DartType>.filled(typeParameters.length, const BottomType()));
}
/// Returns a possibly synthesized name for this class, consistent with
/// the names used across all [toString] calls.
String toString() => debugQualifiedClassName(this);
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<Reference> 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);
}
}
}
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);
/// If true, the member is part of an external library, that is, it is defined
/// in another build unit. Such members have no body or initializer present
/// in the IR.
bool get isInExternalLibrary => enclosingLibrary.isExternal;
/// 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;
/// 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.
String toString() => debugQualifiedMemberName(this);
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;
}
}
/// 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 && !isFinal);
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;
/// 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;
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);
}
/// 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;
bool get isExternal => false;
void set isExternal(bool value) {
if (value) throw 'Fields cannot be external';
}
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 => isMutable ? 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;
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;
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;
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;
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;
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 isExtensionMember: false,
int transformerFlags: 0,
Uri fileUri,
Reference reference,
Member forwardingStubSuperTarget,
Member forwardingStubInterfaceTarget})
: this.byReference(name, kind, function,
isAbstract: isAbstract,
isStatic: isStatic,
isExternal: isExternal,
isConst: isConst,
isForwardingStub: isForwardingStub,
isForwardingSemiStub: isForwardingSemiStub,
isExtensionMember: isExtensionMember,
transformerFlags: transformerFlags,
fileUri: fileUri,
reference: reference,
forwardingStubSuperTargetReference:
getMemberReference(forwardingStubSuperTarget),
forwardingStubInterfaceTargetReference:
getMemberReference(forwardingStubInterfaceTarget));
Procedure.byReference(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 isExtensionMember: false,
int transformerFlags: 0,
Uri fileUri,
Reference reference,
this.forwardingStubSuperTargetReference,
this.forwardingStubInterfaceTargetReference})
: 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.isExtensionMember = isExtensionMember;
this.transformerFlags = transformerFlags;
}
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;
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;
// 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 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;
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);
}
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.functionType;
}
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) {}
}
/// 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;
}
}
}
/// 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;
}
}
}
/// 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;
}
}
}
/// 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;
}
}
}
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;
}
}
// ------------------------------------------------------------------------
// 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 get thisFunctionType {
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,
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 get functionType {
return typeParameters.isEmpty
? thisFunctionType
: getFreshTypeParameters(typeParameters)
.applyToFunctionType(thisFunctionType);
}
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;
}
}
}
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.
///
/// Shouldn't be used on code compiled in legacy mode, as this method assumes
/// the IR is strongly typed.
DartType getStaticType(TypeEnvironment types);
/// 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, TypeEnvironment types) {
// 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 types.coreTypes.legacyRawType(superclass);
}
var type = getStaticType(types);
while (type is TypeParameterType) {
type = (type as TypeParameterType).parameter.bound;
}
if (type == types.nullType) {
return superclass.bottomType;
}
if (type is InterfaceType) {
var upcastType = types.getTypeAsInstanceOf(type, superclass);
if (upcastType != null) return upcastType;
} else if (type is BottomType) {
return superclass.bottomType;
}
types.typeError(this, '$type is not a subtype of $superclass');
return types.coreTypes.legacyRawType(superclass);
}
R accept<R>(ExpressionVisitor<R> v);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg);
}
/// 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(TypeEnvironment types) => 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) {}
}
/// 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, [this.promotedType]);
DartType getStaticType(TypeEnvironment types) {
return promotedType ?? variable.type;
}
R accept<R>(ExpressionVisitor<R> v) => v.visitVariableGet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitVariableGet(this, arg);
visitChildren(Visitor v) {
promotedType?.accept(v);
}
transformChildren(Transformer v) {
if (promotedType != null) {
promotedType = v.visitDartType(promotedType);
}
}
}
/// Assign a local variable or function parameter.
///
/// Evaluates to the value of [value].
class VariableSet extends Expression {
VariableDeclaration variable;
Expression value;
VariableSet(this.variable, this.value) {
value?.parent = this;
}
DartType getStaticType(TypeEnvironment types) => value.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitVariableSet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitVariableSet(this, arg);
visitChildren(Visitor v) {
value?.accept(v);
}
transformChildren(Transformer v) {
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
}
/// Expression of form `x.field`.
///
/// This may invoke a getter, read a field, or tear off a method.
class PropertyGet extends Expression {
Expression receiver;
Name name;
Reference interfaceTargetReference;
PropertyGet(Expression receiver, Name name, [Member interfaceTarget])
: this.byReference(receiver, name, getMemberReference(interfaceTarget));
PropertyGet.byReference(
this.receiver, this.name, this.interfaceTargetReference) {
receiver?.parent = this;
}
Member get interfaceTarget => interfaceTargetReference?.asMember;
void set interfaceTarget(Member member) {
interfaceTargetReference = getMemberReference(member);
}
DartType getStaticType(TypeEnvironment types) {
var interfaceTarget = this.interfaceTarget;
if (interfaceTarget != null) {
Class superclass = interfaceTarget.enclosingClass;
var receiverType = receiver.getStaticTypeAsInstanceOf(superclass, types);
return Substitution.fromInterfaceType(receiverType)
.substituteType(interfaceTarget.getterType);
}
// Treat the properties of Object specially.
String nameString = name.name;
if (nameString == 'hashCode') {
return types.coreTypes.intLegacyRawType;
} else if (nameString == 'runtimeType') {
return types.coreTypes.typeLegacyRawType;
}
return const DynamicType();
}
R accept<R>(ExpressionVisitor<R> v) => v.visitPropertyGet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitPropertyGet(this, arg);
visitChildren(Visitor v) {
receiver?.accept(v);
name?.accept(v);
}
transformChildren(Transformer v) {
if (receiver != null) {
receiver = receiver.accept<TreeNode>(v);
receiver?.parent = this;
}
}
}
/// Expression of form `x.field = value`.
///
/// This may invoke a setter or assign a field.
///
/// Evaluates to the value of [value].
class PropertySet extends Expression {
Expression receiver;
Name name;
Expression value;
Reference interfaceTargetReference;
PropertySet(Expression receiver, Name name, Expression value,
[Member interfaceTarget])
: this.byReference(
receiver, name, value, getMemberReference(interfaceTarget));
PropertySet.byReference(
this.receiver, this.name, this.value, this.interfaceTargetReference) {
receiver?.parent = this;
value?.parent = this;
}
Member get interfaceTarget => interfaceTargetReference?.asMember;
void set interfaceTarget(Member member) {
interfaceTargetReference = getMemberReference(member);
}
DartType getStaticType(TypeEnvironment types) => value.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitPropertySet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitPropertySet(this, arg);
visitChildren(Visitor v) {
receiver?.accept(v);
name?.accept(v);
value?.accept(v);
}
transformChildren(Transformer v) {
if (receiver != null) {
receiver = receiver.accept<TreeNode>(v);
receiver?.parent = this;
}
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
}
/// Directly read a field, call a getter, or tear off a method.
class DirectPropertyGet extends Expression {
Expression receiver;
Reference targetReference;
DirectPropertyGet(Expression receiver, Member target)
: this.byReference(receiver, getMemberReference(target));
DirectPropertyGet.byReference(this.receiver, this.targetReference) {
receiver?.parent = this;
}
Member get target => targetReference?.asMember;
void set target(Member target) {
targetReference = getMemberReference(target);
}
visitChildren(Visitor v) {
receiver?.accept(v);
target?.acceptReference(v);
}
transformChildren(Transformer v) {
if (receiver != null) {
receiver = receiver.accept<TreeNode>(v);
receiver?.parent = this;
}
}
R accept<R>(ExpressionVisitor<R> v) => v.visitDirectPropertyGet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitDirectPropertyGet(this, arg);
DartType getStaticType(TypeEnvironment types) {
Class superclass = target.enclosingClass;
var receiverType = receiver.getStaticTypeAsInstanceOf(superclass, types);
return Substitution.fromInterfaceType(receiverType)
.substituteType(target.getterType);
}
}
/// Directly assign a field, or call a setter.
///
/// Evaluates to the value of [value].
class DirectPropertySet extends Expression {
Expression receiver;
Reference targetReference;
Expression value;
DirectPropertySet(Expression receiver, Member target, Expression value)
: this.byReference(receiver, getMemberReference(target), value);
DirectPropertySet.byReference(
this.receiver, this.targetReference, this.value) {
receiver?.parent = this;
value?.parent = this;
}
Member get target => targetReference?.asMember;
void set target(Member target) {
targetReference = getMemberReference(target);
}
visitChildren(Visitor v) {
receiver?.accept(v);
target?.acceptReference(v);
value?.accept(v);
}
transformChildren(Transformer v) {
if (receiver != null) {
receiver = receiver.accept<TreeNode>(v);
receiver?.parent = this;
}
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
R accept<R>(ExpressionVisitor<R> v) => v.visitDirectPropertySet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitDirectPropertySet(this, arg);
DartType getStaticType(TypeEnvironment types) => value.getStaticType(types);
}
/// Directly call an instance method, bypassing ordinary dispatch.
class DirectMethodInvocation extends InvocationExpression {
Expression receiver;
Reference targetReference;
Arguments arguments;
DirectMethodInvocation(
Expression receiver, Procedure target, Arguments arguments)
: this.byReference(receiver, getMemberReference(target), arguments);
DirectMethodInvocation.byReference(
this.receiver, this.targetReference, this.arguments) {
receiver?.parent = this;
arguments?.parent = this;
}
Procedure get target => targetReference?.asProcedure;
void set target(Procedure target) {
targetReference = getMemberReference(target);
}
Name get name => target?.name;
visitChildren(Visitor v) {
receiver?.accept(v);
target?.acceptReference(v);
arguments?.accept(v);
}
transformChildren(Transformer v) {
if (receiver != null) {
receiver = receiver.accept<TreeNode>(v);
receiver?.parent = this;
}
if (arguments != null) {
arguments = arguments.accept<TreeNode>(v);
arguments?.parent = this;
}
}
R accept<R>(ExpressionVisitor<R> v) => v.visitDirectMethodInvocation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitDirectMethodInvocation(this, arg);
DartType getStaticType(TypeEnvironment types) {
if (types.isOverloadedArithmeticOperator(target)) {
return types.getTypeOfOverloadedArithmetic(receiver.getStaticType(types),
arguments.positional[0].getStaticType(types));
}
Class superclass = target.enclosingClass;
var receiverType = receiver.getStaticTypeAsInstanceOf(superclass, types);
var returnType = Substitution.fromInterfaceType(receiverType)
.substituteType(target.function.returnType);
return Substitution.fromPairs(
target.function.typeParameters, arguments.types)
.substituteType(returnType);
}
}
/// Expression of form `super.field`.
///
/// This may invoke a getter, read a field, or tear off a method.
class SuperPropertyGet extends Expression {
Name name;
Reference interfaceTargetReference;
SuperPropertyGet(Name name, [Member interfaceTarget])
: this.byReference(name, getMemberReference(interfaceTarget));
SuperPropertyGet.byReference(this.name, this.interfaceTargetReference);
Member get interfaceTarget => interfaceTargetReference?.asMember;
void set interfaceTarget(Member member) {
interfaceTargetReference = getMemberReference(member);
}
DartType getStaticType(TypeEnvironment types) {
Class declaringClass = interfaceTarget.enclosingClass;
if (declaringClass.typeParameters.isEmpty) {
return interfaceTarget.getterType;
}
var receiver = types.getTypeAsInstanceOf(types.thisType, declaringClass);
return Substitution.fromInterfaceType(receiver)
.substituteType(interfaceTarget.getterType);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitSuperPropertyGet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitSuperPropertyGet(this, arg);
visitChildren(Visitor v) {
name?.accept(v);
}
transformChildren(Transformer v) {}
}
/// Expression of form `super.field = value`.
///
/// This may invoke a setter or assign a field.
///
/// Evaluates to the value of [value].
class SuperPropertySet extends Expression {
Name name;
Expression value;
Reference interfaceTargetReference;
SuperPropertySet(Name name, Expression value, Member interfaceTarget)
: this.byReference(name, value, getMemberReference(interfaceTarget));
SuperPropertySet.byReference(
this.name, this.value, this.interfaceTargetReference) {
value?.parent = this;
}
Member get interfaceTarget => interfaceTargetReference?.asMember;
void set interfaceTarget(Member member) {
interfaceTargetReference = getMemberReference(member);
}
DartType getStaticType(TypeEnvironment types) => value.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitSuperPropertySet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitSuperPropertySet(this, arg);
visitChildren(Visitor v) {
name?.accept(v);
value?.accept(v);
}
transformChildren(Transformer v) {
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
}
/// Read a static field, call a static getter, or tear off a static method.
class StaticGet extends Expression {
/// A static field, getter, or method (for tear-off).
Reference targetReference;
StaticGet(Member target) : this.byReference(getMemberReference(target));
StaticGet.byReference(this.targetReference);
Member get target => targetReference?.asMember;
void set target(Member target) {
targetReference = getMemberReference(target);
}
DartType getStaticType(TypeEnvironment types) => target.getterType;
R accept<R>(ExpressionVisitor<R> v) => v.visitStaticGet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitStaticGet(this, arg);
visitChildren(Visitor v) {
target?.acceptReference(v);
}
transformChildren(Transformer v) {}
}
/// Assign a static field or call a static setter.
///
/// Evaluates to the value of [value].
class StaticSet extends Expression {
/// A mutable static field or a static setter.
Reference targetReference;
Expression value;
StaticSet(Member target, Expression value)
: this.byReference(getMemberReference(target), value);
StaticSet.byReference(this.targetReference, this.value) {
value?.parent = this;
}
Member get target => targetReference?.asMember;
void set target(Member target) {
targetReference = getMemberReference(target);
}
DartType getStaticType(TypeEnvironment types) => value.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitStaticSet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitStaticSet(this, arg);
visitChildren(Visitor v) {
target?.acceptReference(v);
value?.accept(v);
}
transformChildren(Transformer v) {
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
}
/// The arguments to a function call, divided into type arguments,
/// positional arguments, and named arguments.
class Arguments extends TreeNode {
final List<DartType> types;
final List<Expression> positional;
List<NamedExpression> named;
Arguments(this.positional,
{List<DartType> types, List<NamedExpression> named})
: this.types = types ?? <DartType>[],
this.named = named ?? <NamedExpression>[] {
setParents(this.positional, this);
setParents(this.named, this);
}
Arguments.empty()
: types = <DartType>[],
positional = <Expression>[],
named = <NamedExpression>[];
factory Arguments.forwarded(FunctionNode function) {
return new Arguments(
function.positionalParameters.map((p) => new VariableGet(p)).toList(),
named: function.namedParameters
.map((p) => new NamedExpression(p.name, new VariableGet(p)))
.toList(),
types: function.typeParameters
.map((p) => new TypeParameterType(p))
.toList());
}
R accept<R>(TreeVisitor<R> v) => v.visitArguments(this);
visitChildren(Visitor v) {
visitList(types, v);
visitList(positional, v);
visitList(named, v);
}
transformChildren(Transformer v) {
transformTypeList(types, v);
transformList(positional, v, this);
transformList(named, v, this);
}
}
/// A named argument, `name: value`.
class NamedExpression extends TreeNode {
String name;
Expression value;
NamedExpression(this.name, this.value) {
value?.parent = this;
}
R accept<R>(TreeVisitor<R> v) => v.visitNamedExpression(this);
visitChildren(Visitor v) {
value?.accept(v);
}
transformChildren(Transformer v) {
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
}
/// Common super class for [DirectMethodInvocation], [MethodInvocation],
/// [SuperMethodInvocation], [StaticInvocation], and [ConstructorInvocation].
abstract class InvocationExpression extends Expression {
Arguments get arguments;
set arguments(Arguments value);
/// Name of the invoked method.
///
/// May be `null` if the target is a synthetic static member without a name.
Name get name;
}
/// Expression of form `x.foo(y)`.
class MethodInvocation extends InvocationExpression {
Expression receiver;
Name name;
Arguments arguments;
Reference interfaceTargetReference;
MethodInvocation(Expression receiver, Name name, Arguments arguments,
[Member interfaceTarget])
: this.byReference(
receiver, name, arguments, getMemberReference(interfaceTarget));
MethodInvocation.byReference(
this.receiver, this.name, this.arguments, this.interfaceTargetReference) {
receiver?.parent = this;
arguments?.parent = this;
}
Member get interfaceTarget => interfaceTargetReference?.asMember;
void set interfaceTarget(Member target) {
interfaceTargetReference = getMemberReference(target);
}
DartType getStaticType(TypeEnvironment types) {
var interfaceTarget = this.interfaceTarget;
if (interfaceTarget != null) {
if (interfaceTarget is Procedure &&
types.isOverloadedArithmeticOperator(interfaceTarget)) {
return types.getTypeOfOverloadedArithmetic(
receiver.getStaticType(types),
arguments.positional[0].getStaticType(types));
}
Class superclass = interfaceTarget.enclosingClass;
var receiverType = receiver.getStaticTypeAsInstanceOf(superclass, types);
var getterType = Substitution.fromInterfaceType(receiverType)
.substituteType(interfaceTarget.getterType);
if (getterType is FunctionType) {
return Substitution.fromPairs(
getterType.typeParameters, arguments.types)
.substituteType(getterType.returnType);
} else {
return const DynamicType();
}
}
if (name.name == 'call') {
var receiverType = receiver.getStaticType(types);
if (receiverType is FunctionType) {
if (receiverType.typeParameters.length != arguments.types.length) {
return const BottomType();
}
return Substitution.fromPairs(
receiverType.typeParameters, arguments.types)
.substituteType(receiverType.returnType);
}
}
if (name.name == '==') {
// We use this special case to simplify generation of '==' checks.
return types.coreTypes.boolLegacyRawType;
}
return const DynamicType();
}
R accept<R>(ExpressionVisitor<R> v) => v.visitMethodInvocation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitMethodInvocation(this, arg);
visitChildren(Visitor v) {
receiver?.accept(v);
name?.accept(v);
arguments?.accept(v);
}
transformChildren(Transformer v) {
if (receiver != null) {
receiver = receiver.accept<TreeNode>(v);
receiver?.parent = this;
}
if (arguments != null) {
arguments = arguments.accept<TreeNode>(v);
arguments?.parent = this;
}
}
}
/// Expression of form `super.foo(x)`.
///
/// The provided arguments might not match the parameters of the target.
class SuperMethodInvocation extends InvocationExpression {
Name name;
Arguments arguments;
Reference interfaceTargetReference;
SuperMethodInvocation(Name name, Arguments arguments,
[Procedure interfaceTarget])
: this.byReference(name, arguments, getMemberReference(interfaceTarget));
SuperMethodInvocation.byReference(
this.name, this.arguments, this.interfaceTargetReference) {
arguments?.parent = this;
}
Procedure get interfaceTarget => interfaceTargetReference?.asProcedure;
void set interfaceTarget(Procedure target) {
interfaceTargetReference = getMemberReference(target);
}
DartType getStaticType(TypeEnvironment types) {
if (interfaceTarget == null) return const DynamicType();
Class superclass = interfaceTarget.enclosingClass;
var receiverType = types.getTypeAsInstanceOf(types.thisType, superclass);
var returnType = Substitution.fromInterfaceType(receiverType)
.substituteType(interfaceTarget.function.returnType);
return Substitution.fromPairs(
interfaceTarget.function.typeParameters, arguments.types)
.substituteType(returnType);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitSuperMethodInvocation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitSuperMethodInvocation(this, arg);
visitChildren(Visitor v) {
name?.accept(v);
arguments?.accept(v);
}
transformChildren(Transformer v) {
if (arguments != null) {
arguments = arguments.accept<TreeNode>(v);
arguments?.parent = this;
}
}
}
/// Expression of form `foo(x)`, or `const foo(x)` if the target is an
/// external constant factory.
///
/// The provided arguments might not match the parameters of the target.
class StaticInvocation extends InvocationExpression {
Reference targetReference;
Arguments arguments;
/// True if this is a constant call to an external constant factory.
bool isConst;
Name get name => target?.name;
StaticInvocation(Procedure target, Arguments arguments, {bool isConst: false})
: this.byReference(getMemberReference(target), arguments,
isConst: isConst);
StaticInvocation.byReference(this.targetReference, this.arguments,
{this.isConst: false}) {
arguments?.parent = this;
}
Procedure get target => targetReference?.asProcedure;
void set target(Procedure target) {
targetReference = getMemberReference(target);
}
DartType getStaticType(TypeEnvironment types) {
return Substitution.fromPairs(
target.function.typeParameters, arguments.types)
.substituteType(target.function.returnType);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitStaticInvocation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitStaticInvocation(this, arg);
visitChildren(Visitor v) {
target?.acceptReference(v);
arguments?.accept(v);
}
transformChildren(Transformer v) {
if (arguments != null) {
arguments = arguments.accept<TreeNode>(v);
arguments?.parent = this;
}
}
}
/// Expression of form `new Foo(x)` or `const Foo(x)`.
///
/// The provided arguments might not match the parameters of the target.
//
// DESIGN TODO: Should we pass type arguments in a separate field
// `classTypeArguments`? They are quite different from type arguments to
// generic functions.
class ConstructorInvocation extends InvocationExpression {
Reference targetReference;
Arguments arguments;
bool isConst;
Name get name => target?.name;
ConstructorInvocation(Constructor target, Arguments arguments,
{bool isConst: false})
: this.byReference(getMemberReference(target), arguments,
isConst: isConst);
ConstructorInvocation.byReference(this.targetReference, this.arguments,
{this.isConst: false}) {
arguments?.parent = this;
}
Constructor get target => targetReference?.asConstructor;
void set target(Constructor target) {
targetReference = getMemberReference(target);
}
DartType getStaticType(TypeEnvironment types) {
return arguments.types.isEmpty
? types.coreTypes.legacyRawType(target.enclosingClass)
: new InterfaceType(
target.enclosingClass, arguments.types, Nullability.legacy);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitConstructorInvocation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitConstructorInvocation(this, arg);
visitChildren(Visitor v) {
target?.acceptReference(v);
arguments?.accept(v);
}
transformChildren(Transformer v) {
if (arguments != null) {
arguments = arguments.accept<TreeNode>(v);
arguments?.parent = this;
}
}
// TODO(dmitryas): Change the getter into a method that accepts a CoreTypes.
InterfaceType get constructedType {
Class enclosingClass = target.enclosingClass;
// TODO(dmitryas): Get raw type from a CoreTypes object if arguments is
// empty.
return arguments.types.isEmpty
? new InterfaceType(
enclosingClass, const <DartType>[], Nullability.legacy)
: new InterfaceType(
enclosingClass, arguments.types, Nullability.legacy);
}
}
/// An explicit type instantiation of a generic function.
class Instantiation extends Expression {
Expression expression;
final List<DartType> typeArguments;
Instantiation(this.expression, this.typeArguments) {
expression?.parent = this;
}
DartType getStaticType(TypeEnvironment types) {
FunctionType type = expression.getStaticType(types);
return Substitution.fromPairs(type.typeParameters, typeArguments)
.substituteType(type.withoutTypeParameters);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitInstantiation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitInstantiation(this, arg);
visitChildren(Visitor v) {
expression?.accept(v);
visitList(typeArguments, v);
}
transformChildren(Transformer v) {
if (expression != null) {
expression = expression.accept<TreeNode>(v);
expression?.parent = this;
}
transformTypeList(typeArguments, v);
}
}
/// Expression of form `!x`.
///
/// The `is!` and `!=` operators are desugared into [Not] nodes with `is` and
/// `==` expressions inside, respectively.
class Not extends Expression {
Expression operand;
Not(this.operand) {
operand?.parent = this;
}
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.boolLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitNot(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) => v.visitNot(this, arg);
visitChildren(Visitor v) {
operand?.accept(v);
}
transformChildren(Transformer v) {
if (operand != null) {
operand = operand.accept<TreeNode>(v);
operand?.parent = this;
}
}
}
/// Expression of form `x && y` or `x || y`
class LogicalExpression extends Expression {
Expression left;
String operator; // && or || or ??
Expression right;
LogicalExpression(this.left, this.operator, this.right) {
left?.parent = this;
right?.parent = this;
}
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.boolLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitLogicalExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitLogicalExpression(this, arg);
visitChildren(Visitor v) {
left?.accept(v);
right?.accept(v);
}
transformChildren(Transformer v) {
if (left != null) {
left = left.accept<TreeNode>(v);
left?.parent = this;
}
if (right != null) {
right = right.accept<TreeNode>(v);
right?.parent = this;
}
}
}
/// Expression of form `x ? y : z`.
class ConditionalExpression extends Expression {
Expression condition;
Expression then;
Expression otherwise;
/// The static type of the expression. Should not be `null`.
DartType staticType;
ConditionalExpression(
this.condition, this.then, this.otherwise, this.staticType) {
condition?.parent = this;
then?.parent = this;
otherwise?.parent = this;
}
DartType getStaticType(TypeEnvironment types) => staticType;
R accept<R>(ExpressionVisitor<R> v) => v.visitConditionalExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitConditionalExpression(this, arg);
visitChildren(Visitor v) {
condition?.accept(v);
then?.accept(v);
otherwise?.accept(v);
staticType?.accept(v);
}
transformChildren(Transformer v) {
if (condition != null) {
condition = condition.accept<TreeNode>(v);
condition?.parent = this;
}
if (then != null) {
then = then.accept<TreeNode>(v);
then?.parent = this;
}
if (otherwise != null) {
otherwise = otherwise.accept<TreeNode>(v);
otherwise?.parent = this;
}
if (staticType != null) {
staticType = v.visitDartType(staticType);
}
}
}
/// Convert expressions to strings and concatenate them. Semantically, calls
/// `toString` on every argument, checks that a string is returned, and returns
/// the concatenation of all the strings.
///
/// If [expressions] is empty then an empty string is returned.
///
/// These arise from string interpolations and adjacent string literals.
class StringConcatenation extends Expression {
final List<Expression> expressions;
StringConcatenation(this.expressions) {
setParents(expressions, this);
}
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.stringLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitStringConcatenation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitStringConcatenation(this, arg);
visitChildren(Visitor v) {
visitList(expressions, v);
}
transformChildren(Transformer v) {
transformList(expressions, v, this);
}
}
/// Concatenate lists into a single list.
///
/// If [lists] is empty then an empty list is returned.
///
/// These arise from spread and control-flow elements in const list literals.
/// They are only present before constant evaluation, or within unevaluated
/// constants in constant expressions.
class ListConcatenation extends Expression {
DartType typeArgument;
final List<Expression> lists;
ListConcatenation(this.lists, {this.typeArgument: const DynamicType()}) {
setParents(lists, this);
}
DartType getStaticType(TypeEnvironment types) {
return types.literalListType(typeArgument);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitListConcatenation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitListConcatenation(this, arg);
visitChildren(Visitor v) {
typeArgument?.accept(v);
visitList(lists, v);
}
transformChildren(Transformer v) {
typeArgument = v.visitDartType(typeArgument);
transformList(lists, v, this);
}
}
/// Concatenate sets into a single set.
///
/// If [sets] is empty then an empty set is returned.
///
/// These arise from spread and control-flow elements in const set literals.
/// They are only present before constant evaluation, or within unevaluated
/// constants in constant expressions.
///
/// Duplicated values in or across the sets will result in a compile-time error
/// during constant evaluation.
class SetConcatenation extends Expression {
DartType typeArgument;
final List<Expression> sets;
SetConcatenation(this.sets, {this.typeArgument: const DynamicType()}) {
setParents(sets, this);
}
DartType getStaticType(TypeEnvironment types) {
return types.literalSetType(typeArgument);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitSetConcatenation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitSetConcatenation(this, arg);
visitChildren(Visitor v) {
typeArgument?.accept(v);
visitList(sets, v);
}
transformChildren(Transformer v) {
typeArgument = v.visitDartType(typeArgument);
transformList(sets, v, this);
}
}
/// Concatenate maps into a single map.
///
/// If [maps] is empty then an empty map is returned.
///
/// These arise from spread and control-flow elements in const map literals.
/// They are only present before constant evaluation, or within unevaluated
/// constants in constant expressions.
///
/// Duplicated keys in or across the maps will result in a compile-time error
/// during constant evaluation.
class MapConcatenation extends Expression {
DartType keyType;
DartType valueType;
final List<Expression> maps;
MapConcatenation(this.maps,
{this.keyType: const DynamicType(),
this.valueType: const DynamicType()}) {
setParents(maps, this);
}
DartType getStaticType(TypeEnvironment types) {
return types.literalMapType(keyType, valueType);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitMapConcatenation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitMapConcatenation(this, arg);
visitChildren(Visitor v) {
keyType?.accept(v);
valueType?.accept(v);
visitList(maps, v);
}
transformChildren(Transformer v) {
keyType = v.visitDartType(keyType);
valueType = v.visitDartType(valueType);
transformList(maps, v, this);
}
}
/// Create an instance directly from the field values.
///
/// These expressions arise from const constructor calls when one or more field
/// initializing expressions, field initializers, assert initializers or unused
/// arguments contain unevaluated expressions. They only ever occur within
/// unevaluated constants in constant expressions.
class InstanceCreation extends Expression {
final Reference classReference;
final List<DartType> typeArguments;
final Map<Reference, Expression> fieldValues;
final List<AssertStatement> asserts;
final List<Expression> unusedArguments;
InstanceCreation(this.classReference, this.typeArguments, this.fieldValues,
this.asserts, this.unusedArguments);
Class get classNode => classReference.asClass;
DartType getStaticType(TypeEnvironment types) {
return typeArguments.isEmpty
? types.coreTypes.legacyRawType(classNode)
: new InterfaceType(classNode, typeArguments);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitInstanceCreation(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitInstanceCreation(this, arg);
visitChildren(Visitor v) {
classReference.asClass.acceptReference(v);
visitList(typeArguments, v);
for (final Reference reference in fieldValues.keys) {
reference.asField.acceptReference(v);
}
for (final Expression value in fieldValues.values) {
value.accept(v);
}
visitList(asserts, v);
visitList(unusedArguments, v);
}
transformChildren(Transformer v) {
fieldValues.forEach((Reference fieldRef, Expression value) {
Expression transformed = value.accept<TreeNode>(v);
if (transformed != null && !identical(value, transformed)) {
fieldValues[fieldRef] = transformed;
transformed.parent = this;
}
});
transformList(asserts, v, this);
transformList(unusedArguments, v, this);
}
}
/// A marker indicating that a subexpression originates in a different source
/// file than the surrounding context.
///
/// These expressions arise from inlining of const variables during constant
/// evaluation. They only ever occur within unevaluated constants in constant
/// expressions.
class FileUriExpression extends Expression implements FileUriNode {
/// The URI of the source file in which the subexpression is located.
/// Can be different from the file containing the [FileUriExpression].
Uri fileUri;
Expression expression;
FileUriExpression(this.expression, this.fileUri) {
expression.parent = this;
}
DartType getStaticType(TypeEnvironment types) =>
expression.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitFileUriExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitFileUriExpression(this, arg);
visitChildren(Visitor v) {
expression.accept(v);
}
transformChildren(Transformer v) {
expression = expression.accept<TreeNode>(v)..parent = this;
}
Location _getLocationInEnclosingFile(int offset) {
return _getLocationInComponent(enclosingComponent, fileUri, offset);
}
}
/// Expression of form `x is T`.
class IsExpression extends Expression {
Expression operand;
DartType type;
IsExpression(this.operand, this.type) {
operand?.parent = this;
}
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.boolLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitIsExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitIsExpression(this, arg);
visitChildren(Visitor v) {
operand?.accept(v);
type?.accept(v);
}
transformChildren(Transformer v) {
if (operand != null) {
operand = operand.accept<TreeNode>(v);
operand?.parent = this;
}
type = v.visitDartType(type);
}
}
/// Expression of form `x as T`.
class AsExpression extends Expression {
int flags = 0;
Expression operand;
DartType type;
AsExpression(this.operand, this.type) {
operand?.parent = this;
}
// Must match serialized bit positions.
static const int FlagTypeError = 1 << 0;
/// Indicates the type of error that should be thrown if the check fails.
///
/// `true` means that a TypeError should be thrown. `false` means that a
/// CastError should be thrown.
bool get isTypeError => flags & FlagTypeError != 0;
void set isTypeError(bool value) {
flags = value ? (flags | FlagTypeError) : (flags & ~FlagTypeError);
}
DartType getStaticType(TypeEnvironment types) => type;
R accept<R>(ExpressionVisitor<R> v) => v.visitAsExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitAsExpression(this, arg);
visitChildren(Visitor v) {
operand?.accept(v);
type?.accept(v);
}
transformChildren(Transformer v) {
if (operand != null) {
operand = operand.accept<TreeNode>(v);
operand?.parent = this;
}
type = v.visitDartType(type);
}
}
/// Null check expression of form `x!`.
///
/// This expression was added as part of NNBD and is currently only created when
/// the 'non-nullable' experimental feature is enabled.
class NullCheck extends Expression {
Expression operand;
NullCheck(this.operand) {
operand?.parent = this;
}
DartType getStaticType(TypeEnvironment types) =>
// TODO(johnniwinther): Return `NonNull(operand.getStaticType(types))`.
operand.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitNullCheck(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitNullCheck(this, arg);
visitChildren(Visitor v) {
operand?.accept(v);
}
transformChildren(Transformer v) {
if (operand != null) {
operand = operand.accept<TreeNode>(v);
operand?.parent = this;
}
}
}
/// An integer, double, boolean, string, or null constant.
abstract class BasicLiteral extends Expression {
Object get value;
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
class StringLiteral extends BasicLiteral {
String value;
StringLiteral(this.value);
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.stringLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitStringLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitStringLiteral(this, arg);
}
class IntLiteral extends BasicLiteral {
/// Note that this value holds a uint64 value.
/// E.g. "0x8000000000000000" will be saved as "-9223372036854775808" despite
/// technically (on some platforms, particularly Javascript) being positive.
/// If the number is meant to be negative it will be wrapped in a "unary-".
int value;
IntLiteral(this.value);
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.intLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitIntLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitIntLiteral(this, arg);
}
class DoubleLiteral extends BasicLiteral {
double value;
DoubleLiteral(this.value);
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.doubleLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitDoubleLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitDoubleLiteral(this, arg);
}
class BoolLiteral extends BasicLiteral {
bool value;
BoolLiteral(this.value);
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.boolLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitBoolLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitBoolLiteral(this, arg);
}
class NullLiteral extends BasicLiteral {
Object get value => null;
DartType getStaticType(TypeEnvironment types) => types.nullType;
R accept<R>(ExpressionVisitor<R> v) => v.visitNullLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitNullLiteral(this, arg);
}
class SymbolLiteral extends Expression {
String value; // Everything strictly after the '#'.
SymbolLiteral(this.value);
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.symbolLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitSymbolLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitSymbolLiteral(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
class TypeLiteral extends Expression {
DartType type;
TypeLiteral(this.type);
DartType getStaticType(TypeEnvironment types) =>
types.coreTypes.typeLegacyRawType;
R accept<R>(ExpressionVisitor<R> v) => v.visitTypeLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitTypeLiteral(this, arg);
visitChildren(Visitor v) {
type?.accept(v);
}
transformChildren(Transformer v) {
type = v.visitDartType(type);
}
}
class ThisExpression extends Expression {
DartType getStaticType(TypeEnvironment types) => types.thisType;
R accept<R>(ExpressionVisitor<R> v) => v.visitThisExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitThisExpression(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
class Rethrow extends Expression {
DartType getStaticType(TypeEnvironment types) => const BottomType();
R accept<R>(ExpressionVisitor<R> v) => v.visitRethrow(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitRethrow(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
class Throw extends Expression {
Expression expression;
Throw(this.expression) {
expression?.parent = this;
}
DartType getStaticType(TypeEnvironment types) => const BottomType();
R accept<R>(ExpressionVisitor<R> v) => v.visitThrow(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) => v.visitThrow(this, arg);
visitChildren(Visitor v) {
expression?.accept(v);
}
transformChildren(Transformer v) {
if (expression != null) {
expression = expression.accept<TreeNode>(v);
expression?.parent = this;
}
}
}
class ListLiteral extends Expression {
bool isConst;
DartType typeArgument; // Not null, defaults to DynamicType.
final List<Expression> expressions;
ListLiteral(this.expressions,
{this.typeArgument: const DynamicType(), this.isConst: false}) {
assert(typeArgument != null);
setParents(expressions, this);
}
DartType getStaticType(TypeEnvironment types) {
return types.literalListType(typeArgument);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitListLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitListLiteral(this, arg);
visitChildren(Visitor v) {
typeArgument?.accept(v);
visitList(expressions, v);
}
transformChildren(Transformer v) {
typeArgument = v.visitDartType(typeArgument);
transformList(expressions, v, this);
}
}
class SetLiteral extends Expression {
bool isConst;
DartType typeArgument; // Not null, defaults to DynamicType.
final List<Expression> expressions;
SetLiteral(this.expressions,
{this.typeArgument: const DynamicType(), this.isConst: false}) {
assert(typeArgument != null);
setParents(expressions, this);
}
DartType getStaticType(TypeEnvironment types) {
return types.literalSetType(typeArgument);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitSetLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitSetLiteral(this, arg);
visitChildren(Visitor v) {
typeArgument?.accept(v);
visitList(expressions, v);
}
transformChildren(Transformer v) {
typeArgument = v.visitDartType(typeArgument);
transformList(expressions, v, this);
}
}
class MapLiteral extends Expression {
bool isConst;
DartType keyType; // Not null, defaults to DynamicType.
DartType valueType; // Not null, defaults to DynamicType.
final List<MapEntry> entries;
MapLiteral(this.entries,
{this.keyType: const DynamicType(),
this.valueType: const DynamicType(),
this.isConst: false}) {
assert(keyType != null);
assert(valueType != null);
setParents(entries, this);
}
DartType getStaticType(TypeEnvironment types) {
return types.literalMapType(keyType, valueType);
}
R accept<R>(ExpressionVisitor<R> v) => v.visitMapLiteral(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitMapLiteral(this, arg);
visitChildren(Visitor v) {
keyType?.accept(v);
valueType?.accept(v);
visitList(entries, v);
}
transformChildren(Transformer v) {
keyType = v.visitDartType(keyType);
valueType = v.visitDartType(valueType);
transformList(entries, v, this);
}
}
class MapEntry extends TreeNode {
Expression key;
Expression value;
MapEntry(this.key, this.value) {
key?.parent = this;
value?.parent = this;
}
R accept<R>(TreeVisitor<R> v) => v.visitMapEntry(this);
visitChildren(Visitor v) {
key?.accept(v);
value?.accept(v);
}
transformChildren(Transformer v) {
if (key != null) {
key = key.accept<TreeNode>(v);
key?.parent = this;
}
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
}
/// Expression of form `await x`.
class AwaitExpression extends Expression {
Expression operand;
AwaitExpression(this.operand) {
operand?.parent = this;
}
DartType getStaticType(TypeEnvironment types) {
return types.unfutureType(operand.getStaticType(types));
}
R accept<R>(ExpressionVisitor<R> v) => v.visitAwaitExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitAwaitExpression(this, arg);
visitChildren(Visitor v) {
operand?.accept(v);
}
transformChildren(Transformer v) {
if (operand != null) {
operand = operand.accept<TreeNode>(v);
operand?.parent = this;
}
}
}
/// Common super-interface for [FunctionExpression] and [FunctionDeclaration].
abstract class LocalFunction implements TreeNode {
FunctionNode get function;
}
/// Expression of form `(x,y) => ...` or `(x,y) { ... }`
///
/// The arrow-body form `=> e` is desugared into `return e;`.
class FunctionExpression extends Expression implements LocalFunction {
FunctionNode function;
FunctionExpression(this.function) {
function?.parent = this;
}
DartType getStaticType(TypeEnvironment types) => function.functionType;
R accept<R>(ExpressionVisitor<R> v) => v.visitFunctionExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitFunctionExpression(this, arg);
visitChildren(Visitor v) {
function?.accept(v);
}
transformChildren(Transformer v) {
if (function != null) {
function = function.accept<TreeNode>(v);
function?.parent = this;
}
}
}
class ConstantExpression extends Expression {
Constant constant;
DartType type;
ConstantExpression(this.constant, [this.type = const DynamicType()]) {
assert(constant != null);
}
DartType getStaticType(TypeEnvironment types) => type;
R accept<R>(ExpressionVisitor<R> v) => v.visitConstantExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitConstantExpression(this, arg);
visitChildren(Visitor v) {
constant?.acceptReference(v);
type?.accept(v);
}
transformChildren(Transformer v) {
constant = v.visitConstant(constant);
type = v.visitDartType(type);
}
}
/// Synthetic expression of form `let v = x in y`
class Let extends Expression {
VariableDeclaration variable; // Must have an initializer.
Expression body;
Let(this.variable, this.body) {
variable?.parent = this;
body?.parent = this;
}
DartType getStaticType(TypeEnvironment types) => body.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitLet(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) => v.visitLet(this, arg);
visitChildren(Visitor v) {
variable?.accept(v);
body?.accept(v);
}
transformChildren(Transformer v) {
if (variable != null) {
variable = variable.accept<TreeNode>(v);
variable?.parent = this;
}
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
}
class BlockExpression extends Expression {
Block body;
Expression value;
BlockExpression(this.body, this.value) {
body?.parent = this;
value?.parent = this;
}
DartType getStaticType(TypeEnvironment types) => value.getStaticType(types);
R accept<R>(ExpressionVisitor<R> v) => v.visitBlockExpression(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitBlockExpression(this, arg);
visitChildren(Visitor v) {
body?.accept(v);
value?.accept(v);
}
transformChildren(Transformer v) {
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
if (value != null) {
value = value.accept<TreeNode>(v);
value?.parent = this;
}
}
}
/// Attempt to load the library referred to by a deferred import.
///
/// This instruction is concerned with:
/// - keeping track whether the deferred import is marked as 'loaded'
/// - keeping track of whether the library code has already been downloaded
/// - actually downloading and linking the library
///
/// Should return a future. The value in this future will be the same value
/// seen by callers of `loadLibrary` functions.
///
/// On backends that link the entire program eagerly, this instruction needs
/// to mark the deferred import as 'loaded' and return a future.
class LoadLibrary extends Expression {
/// Reference to a deferred import in the enclosing library.
LibraryDependency import;
LoadLibrary(this.import);
DartType getStaticType(TypeEnvironment types) {
return types.futureType(const DynamicType());
}
R accept<R>(ExpressionVisitor<R> v) => v.visitLoadLibrary(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitLoadLibrary(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
/// Checks that the given deferred import has been marked as 'loaded'.
class CheckLibraryIsLoaded extends Expression {
/// Reference to a deferred import in the enclosing library.
LibraryDependency import;
CheckLibraryIsLoaded(this.import);
DartType getStaticType(TypeEnvironment types) {
return types.coreTypes.objectLegacyRawType;
}
R accept<R>(ExpressionVisitor<R> v) => v.visitCheckLibraryIsLoaded(this);
R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) =>
v.visitCheckLibraryIsLoaded(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
// ------------------------------------------------------------------------
// STATEMENTS
// ------------------------------------------------------------------------
abstract class Statement extends TreeNode {
R accept<R>(StatementVisitor<R> v);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg);
}
class ExpressionStatement extends Statement {
Expression expression;
ExpressionStatement(this.expression) {
expression?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitExpressionStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitExpressionStatement(this, arg);
visitChildren(Visitor v) {
expression?.accept(v);
}
transformChildren(Transformer v) {
if (expression != null) {
expression = expression.accept<TreeNode>(v);
expression?.parent = this;
}
}
}
class Block extends Statement {
final List<Statement> statements;
Block(this.statements) {
// Ensure statements is mutable.
assert((statements
..add(null)
..removeLast()) !=
null);
setParents(statements, this);
}
R accept<R>(StatementVisitor<R> v) => v.visitBlock(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) => v.visitBlock(this, arg);
visitChildren(Visitor v) {
visitList(statements, v);
}
transformChildren(Transformer v) {
transformList(statements, v, this);
}
void addStatement(Statement node) {
statements.add(node);
node.parent = this;
}
}
/// A block that is only executed when asserts are enabled.
///
/// Sometimes arbitrary statements must be guarded by whether asserts are
/// enabled. For example, when a subexpression of an assert in async code is
/// linearized and named, it can produce such a block of statements.
class AssertBlock extends Statement {
final List<Statement> statements;
AssertBlock(this.statements) {
// Ensure statements is mutable.
assert((statements
..add(null)
..removeLast()) !=
null);
setParents(statements, this);
}
R accept<R>(StatementVisitor<R> v) => v.visitAssertBlock(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitAssertBlock(this, arg);
transformChildren(Transformer v) {
transformList(statements, v, this);
}
visitChildren(Visitor v) {
visitList(statements, v);
}
void addStatement(Statement node) {
statements.add(node);
node.parent = this;
}
}
class EmptyStatement extends Statement {
R accept<R>(StatementVisitor<R> v) => v.visitEmptyStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitEmptyStatement(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
class AssertStatement extends Statement {
Expression condition;
Expression message; // May be null.
int conditionStartOffset;
int conditionEndOffset;
AssertStatement(this.condition,
{this.message, this.conditionStartOffset, this.conditionEndOffset}) {
condition?.parent = this;
message?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitAssertStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitAssertStatement(this, arg);
visitChildren(Visitor v) {
condition?.accept(v);
message?.accept(v);
}
transformChildren(Transformer v) {
if (condition != null) {
condition = condition.accept<TreeNode>(v);
condition?.parent = this;
}
if (message != null) {
message = message.accept<TreeNode>(v);
message?.parent = this;
}
}
}
/// A target of a [Break] statement.
///
/// The label itself has no name; breaks reference the statement directly.
///
/// The frontend does not generate labeled statements without uses.
class LabeledStatement extends Statement {
Statement body;
LabeledStatement(this.body) {
body?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitLabeledStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitLabeledStatement(this, arg);
visitChildren(Visitor v) {
body?.accept(v);
}
transformChildren(Transformer v) {
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
}
/// Breaks out of an enclosing [LabeledStatement].
///
/// Both `break` and loop `continue` statements are translated into this node.
///
/// For example, the following loop with a `continue` will be desugared:
///
/// while(x) {
/// if (y) continue;
/// BODY'
/// }
///
/// ==>
///
/// while(x) {
/// L: {
/// if (y) break L;
/// BODY'
/// }
/// }
//
class BreakStatement extends Statement {
LabeledStatement target;
BreakStatement(this.target);
R accept<R>(StatementVisitor<R> v) => v.visitBreakStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitBreakStatement(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
class WhileStatement extends Statement {
Expression condition;
Statement body;
WhileStatement(this.condition, this.body) {
condition?.parent = this;
body?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitWhileStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitWhileStatement(this, arg);
visitChildren(Visitor v) {
condition?.accept(v);
body?.accept(v);
}
transformChildren(Transformer v) {
if (condition != null) {
condition = condition.accept<TreeNode>(v);
condition?.parent = this;
}
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
}
class DoStatement extends Statement {
Statement body;
Expression condition;
DoStatement(this.body, this.condition) {
body?.parent = this;
condition?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitDoStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitDoStatement(this, arg);
visitChildren(Visitor v) {
body?.accept(v);
condition?.accept(v);
}
transformChildren(Transformer v) {
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
if (condition != null) {
condition = condition.accept<TreeNode>(v);
condition?.parent = this;
}
}
}
class ForStatement extends Statement {
final List<VariableDeclaration> variables; // May be empty, but not null.
Expression condition; // May be null.
final List<Expression> updates; // May be empty, but not null.
Statement body;
ForStatement(this.variables, this.condition, this.updates, this.body) {
setParents(variables, this);
condition?.parent = this;
setParents(updates, this);
body?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitForStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitForStatement(this, arg);
visitChildren(Visitor v) {
visitList(variables, v);
condition?.accept(v);
visitList(updates, v);
body?.accept(v);
}
transformChildren(Transformer v) {
transformList(variables, v, this);
if (condition != null) {
condition = condition.accept<TreeNode>(v);
condition?.parent = this;
}
transformList(updates, v, this);
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
}
class ForInStatement extends Statement {
/// Offset in the source file it comes from.
///
/// Valid values are from 0 and up, or -1 ([TreeNode.noOffset]) if the file
/// offset is not available (this is the default if none is specifically set).
int bodyOffset = TreeNode.noOffset;
VariableDeclaration variable; // Has no initializer.
Expression iterable;
Statement body;
bool isAsync; // True if this is an 'await for' loop.
ForInStatement(this.variable, this.iterable, this.body,
{this.isAsync: false}) {
variable?.parent = this;
iterable?.parent = this;
body?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitForInStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitForInStatement(this, arg);
void visitChildren(Visitor v) {
variable?.accept(v);
iterable?.accept(v);
body?.accept(v);
}
void transformChildren(Transformer v) {
if (variable != null) {
variable = variable.accept<TreeNode>(v);
variable?.parent = this;
}
if (iterable != null) {
iterable = iterable.accept<TreeNode>(v);
iterable?.parent = this;
}
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
}
/// Statement of form `switch (e) { case x: ... }`.
///
/// Adjacent case clauses have been merged into a single [SwitchCase]. A runtime
/// exception must be thrown if one [SwitchCase] falls through to another case.
class SwitchStatement extends Statement {
Expression expression;
final List<SwitchCase> cases;
SwitchStatement(this.expression, this.cases) {
expression?.parent = this;
setParents(cases, this);
}
R accept<R>(StatementVisitor<R> v) => v.visitSwitchStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitSwitchStatement(this, arg);
visitChildren(Visitor v) {
expression?.accept(v);
visitList(cases, v);
}
transformChildren(Transformer v) {
if (expression != null) {
expression = expression.accept<TreeNode>(v);
expression?.parent = this;
}
transformList(cases, v, this);
}
}
/// A group of `case` clauses and/or a `default` clause.
///
/// This is a potential target of [ContinueSwitchStatement].
class SwitchCase extends TreeNode {
final List<Expression> expressions;
final List<int> expressionOffsets;
Statement body;
bool isDefault;
SwitchCase(this.expressions, this.expressionOffsets, this.body,
{this.isDefault: false}) {
setParents(expressions, this);
body?.parent = this;
}
SwitchCase.defaultCase(this.body)
: isDefault = true,
expressions = <Expression>[],
expressionOffsets = <int>[] {
body?.parent = this;
}
SwitchCase.empty()
: expressions = <Expression>[],
expressionOffsets = <int>[],
body = null,
isDefault = false;
R accept<R>(TreeVisitor<R> v) => v.visitSwitchCase(this);
visitChildren(Visitor v) {
visitList(expressions, v);
body?.accept(v);
}
transformChildren(Transformer v) {
transformList(expressions, v, this);
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
}
/// Jump to a case in an enclosing switch.
class ContinueSwitchStatement extends Statement {
SwitchCase target;
ContinueSwitchStatement(this.target);
R accept<R>(StatementVisitor<R> v) => v.visitContinueSwitchStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitContinueSwitchStatement(this, arg);
visitChildren(Visitor v) {}
transformChildren(Transformer v) {}
}
class IfStatement extends Statement {
Expression condition;
Statement then;
Statement otherwise;
IfStatement(this.condition, this.then, this.otherwise) {
condition?.parent = this;
then?.parent = this;
otherwise?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitIfStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitIfStatement(this, arg);
visitChildren(Visitor v) {
condition?.accept(v);
then?.accept(v);
otherwise?.accept(v);
}
transformChildren(Transformer v) {
if (condition != null) {
condition = condition.accept<TreeNode>(v);
condition?.parent = this;
}
if (then != null) {
then = then.accept<TreeNode>(v);
then?.parent = this;
}
if (otherwise != null) {
otherwise = otherwise.accept<TreeNode>(v);
otherwise?.parent = this;
}
}
}
class ReturnStatement extends Statement {
Expression expression; // May be null.
ReturnStatement([this.expression]) {
expression?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitReturnStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitReturnStatement(this, arg);
visitChildren(Visitor v) {
expression?.accept(v);
}
transformChildren(Transformer v) {
if (expression != null) {
expression = expression.accept<TreeNode>(v);
expression?.parent = this;
}
}
}
class TryCatch extends Statement {
Statement body;
List<Catch> catches;
bool isSynthetic;
TryCatch(this.body, this.catches, {this.isSynthetic: false}) {
body?.parent = this;
setParents(catches, this);
}
R accept<R>(StatementVisitor<R> v) => v.visitTryCatch(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitTryCatch(this, arg);
visitChildren(Visitor v) {
body?.accept(v);
visitList(catches, v);
}
transformChildren(Transformer v) {
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
transformList(catches, v, this);
}
}
class Catch extends TreeNode {
DartType guard; // Not null, defaults to dynamic.
VariableDeclaration exception; // May be null.
VariableDeclaration stackTrace; // May be null.
Statement body;
Catch(this.exception, this.body,
{this.guard: const DynamicType(), this.stackTrace}) {
assert(guard != null);
exception?.parent = this;
stackTrace?.parent = this;
body?.parent = this;
}
R accept<R>(TreeVisitor<R> v) => v.visitCatch(this);
visitChildren(Visitor v) {
guard?.accept(v);
exception?.accept(v);
stackTrace?.accept(v);
body?.accept(v);
}
transformChildren(Transformer v) {
guard = v.visitDartType(guard);
if (exception != null) {
exception = exception.accept<TreeNode>(v);
exception?.parent = this;
}
if (stackTrace != null) {
stackTrace = stackTrace.accept<TreeNode>(v);
stackTrace?.parent = this;
}
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
}
}
class TryFinally extends Statement {
Statement body;
Statement finalizer;
TryFinally(this.body, this.finalizer) {
body?.parent = this;
finalizer?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitTryFinally(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitTryFinally(this, arg);
visitChildren(Visitor v) {
body?.accept(v);
finalizer?.accept(v);
}
transformChildren(Transformer v) {
if (body != null) {
body = body.accept<TreeNode>(v);
body?.parent = this;
}
if (finalizer != null) {
finalizer = finalizer.accept<TreeNode>(v);
finalizer?.parent = this;
}
}
}
/// Statement of form `yield x` or `yield* x`.
///
/// For native yield semantics see `AsyncMarker.SyncYielding`.
class YieldStatement extends Statement {
Expression expression;
int flags = 0;
YieldStatement(this.expression,
{bool isYieldStar: false, bool isNative: false}) {
expression?.parent = this;
this.isYieldStar = isYieldStar;
this.isNative = isNative;
}
static const int FlagYieldStar = 1 << 0;
static const int FlagNative = 1 << 1;
bool get isYieldStar => flags & FlagYieldStar != 0;
bool get isNative => flags & FlagNative != 0;
void set isYieldStar(bool value) {
flags = value ? (flags | FlagYieldStar) : (flags & ~FlagYieldStar);
}
void set isNative(bool value) {
flags = value ? (flags | FlagNative) : (flags & ~FlagNative);
}
R accept<R>(StatementVisitor<R> v) => v.visitYieldStatement(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitYieldStatement(this, arg);
visitChildren(Visitor v) {
expression?.accept(v);
}
transformChildren(Transformer v) {
if (expression != null) {
expression = expression.accept<TreeNode>(v);
expression?.parent = this;
}
}
}
/// Declaration of a local variable.
///
/// This may occur as a statement, but is also used in several non-statement
/// contexts, such as in [ForStatement], [Catch], and [FunctionNode].
///
/// When this occurs as a statement, it must be a direct child of a [Block].
//
// DESIGN TODO: Should we remove the 'final' modifier from variables?
class VariableDeclaration extends Statement {
/// Offset of the equals sign in the source file it comes from.
///
/// Valid values are from 0 and up, or -1 ([TreeNode.noOffset])
/// if the equals sign offset is not available (e.g. if not initialized)
/// (this is the default if none is specifically set).
int fileEqualsOffset = TreeNode.noOffset;
/// List of metadata annotations on the variable declaration.
///
/// This defaults to an immutable empty list. Use [addAnnotation] to add
/// annotations if needed.
List<Expression> annotations = const <Expression>[];
/// For named parameters, this is the name of the parameter. No two named
/// parameters (in the same parameter list) can have the same name.
///
/// In all other cases, the name is cosmetic, may be empty or null,
/// and is not necessarily unique.
String name;
int flags = 0;
DartType type; // Not null, defaults to dynamic.
/// Offset of the declaration, set and used when writing the binary.
int binaryOffsetNoTag = -1;
/// For locals, this is the initial value.
/// For parameters, this is the default value.
///
/// Should be null in other cases.
Expression initializer; // May be null.
VariableDeclaration(this.name,
{this.initializer,
this.type: const DynamicType(),
int flags: -1,
bool isFinal: false,
bool isConst: false,
bool isFieldFormal: false,
bool isCovariant: false,
bool isLate: false,
bool isRequired: false}) {
assert(type != null);
initializer?.parent = this;
if (flags != -1) {
this.flags = flags;
} else {
this.isFinal = isFinal;
this.isConst = isConst;
this.isFieldFormal = isFieldFormal;
this.isCovariant = isCovariant;
this.isLate = isLate;
this.isRequired = isRequired;
}
}
/// Creates a synthetic variable with the given expression as initializer.
VariableDeclaration.forValue(this.initializer,
{bool isFinal: true,
bool isConst: false,
bool isFieldFormal: false,
bool isLate: false,
bool isRequired: false,
this.type: const DynamicType()}) {
assert(type != null);
initializer?.parent = this;
this.isFinal = isFinal;
this.isConst = isConst;
this.isFieldFormal = isFieldFormal;
this.isLate = isLate;
this.isRequired = isRequired;
}
static const int FlagFinal = 1 << 0; // Must match serialized bit positions.
static const int FlagConst = 1 << 1;
static const int FlagFieldFormal = 1 << 2;
static const int FlagCovariant = 1 << 3;
static const int FlagInScope = 1 << 4; // Temporary flag used by verifier.
static const int FlagGenericCovariantImpl = 1 << 5;
static const int FlagLate = 1 << 6;
static const int FlagRequired = 1 << 7;
bool get isFinal => flags & FlagFinal != 0;
bool get isConst => flags & FlagConst != 0;
/// Whether the parameter is declared with the `covariant` keyword.
bool get isCovariant => flags & FlagCovariant != 0;
/// Whether the variable is declared as a field formal parameter of
/// a constructor.
@informative
bool get isFieldFormal => flags & FlagFieldFormal != 0;
/// If this [VariableDeclaration] is a parameter of a method, indicates
/// whether the method implementation 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 variable is declared with the `late` keyword.
///
/// The `late` modifier is only supported on local variables and not on
/// parameters.
bool get isLate => flags & FlagLate != 0;
/// Whether the parameter is declared with the `required` keyword.
///
/// The `required` modifier is only supported on named parameters and not on
/// positional parameters and local variables.
bool get isRequired => flags & FlagRequired != 0;
void set isFinal(bool value) {
flags = value ? (flags | FlagFinal) : (flags & ~FlagFinal);
}
void set isConst(bool value) {
flags = value ? (flags | FlagConst) : (flags & ~FlagConst);
}
void set isCovariant(bool value) {
flags = value ? (flags | FlagCovariant) : (flags & ~FlagCovariant);
}
@informative
void set isFieldFormal(bool value) {
flags = value ? (flags | FlagFieldFormal) : (flags & ~FlagFieldFormal);
}
void set isGenericCovariantImpl(bool value) {
flags = value
? (flags | FlagGenericCovariantImpl)
: (flags & ~FlagGenericCovariantImpl);
}
void set isLate(bool value) {
flags = value ? (flags | FlagLate) : (flags & ~FlagLate);
}
void set isRequired(bool value) {
flags = value ? (flags | FlagRequired) : (flags & ~FlagRequired);
}
void addAnnotation(Expression annotation) {
if (annotations.isEmpty) {
annotations = <Expression>[];
}
annotations.add(annotation..parent = this);
}
R accept<R>(StatementVisitor<R> v) => v.visitVariableDeclaration(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitVariableDeclaration(this, arg);
visitChildren(Visitor v) {
visitList(annotations, v);
type?.accept(v);
initializer?.accept(v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
type = v.visitDartType(type);
if (initializer != null) {
initializer = initializer.accept<TreeNode>(v);
initializer?.parent = this;
}
}
/// Returns a possibly synthesized name for this variable, consistent with
/// the names used across all [toString] calls.
String toString() => debugVariableDeclarationName(this);
}
/// Declaration a local function.
///
/// The body of the function may use [variable] as its self-reference.
class FunctionDeclaration extends Statement implements LocalFunction {
VariableDeclaration variable; // Is final and has no initializer.
FunctionNode function;
FunctionDeclaration(this.variable, this.function) {
variable?.parent = this;
function?.parent = this;
}
R accept<R>(StatementVisitor<R> v) => v.visitFunctionDeclaration(this);
R accept1<R, A>(StatementVisitor1<R, A> v, A arg) =>
v.visitFunctionDeclaration(this, arg);
visitChildren(Visitor v) {
variable?.accept(v);
function?.accept(v);
}
transformChildren(Transformer v) {
if (variable != null) {
variable = variable.accept<TreeNode>(v);
variable?.parent = this;
}
if (function != null) {
function = function.accept<TreeNode>(v);
function?.parent = this;
}
}
}
// ------------------------------------------------------------------------
// NAMES
// ------------------------------------------------------------------------
/// A public name, or a private name qualified by a library.
///
/// Names are only used for expressions with dynamic dispatch, as all
/// statically resolved references are represented in nameless form.
///
/// [Name]s are immutable and compare based on structural equality, and they
/// are not AST nodes.
///
/// The [toString] method returns a human-readable string that includes the
/// library name for private names; uniqueness is not guaranteed.
abstract class Name implements Node {
final int hashCode;
final String name;
Reference get libraryName;
Library get library;
bool get isPrivate;
Name._internal(this.hashCode, this.name);
factory Name(String name, [Library library]) =>
new Name.byReference(name, library?.reference);
factory Name.byReference(String name, Reference libraryName) {
/// Use separate subclasses for the public and private case to save memory
/// for public names.
if (name.startsWith('_')) {
assert(libraryName != null);
return new _PrivateName(name, libraryName);
} else {
return new _PublicName(name);
}
}
bool operator ==(other) {
return other is Name && name == other.name && library == other.library;
}
R accept<R>(Visitor<R> v) => v.visitName(this);
visitChildren(Visitor v) {
// DESIGN TODO: Should we visit the library as a library reference?
}
}
class _PrivateName extends Name {
final Reference libraryName;
bool get isPrivate => true;
_PrivateName(String name, Reference libraryName)
: this.libraryName = libraryName,
super._internal(_computeHashCode(name, libraryName), name);
String toString() => library != null ? '$library::$name' : name;
Library get library => libraryName.asLibrary;
static int _computeHashCode(String name, Reference libraryName) {
// TODO(dmitryas): Factor in [libraryName] in a non-deterministic way into
// the result. Note, the previous code here was the following:
// return 131 * name.hashCode + 17 * libraryName.asLibrary._libraryId;
return name.hashCode;
}
}
class _PublicName extends Name {
Reference get libraryName => null;
Library get library => null;
bool get isPrivate => false;
_PublicName(String name) : super._internal(name.hashCode, name);
String toString() => name;
}
// ------------------------------------------------------------------------
// TYPES
// ------------------------------------------------------------------------
/// Represents nullability of a type.
enum Nullability {
/// Nullable types are marked with the '?' modifier.
///
/// Null, dynamic, and void are nullable by default.
nullable,
/// Non-nullable types are types that aren't marked with the '?' modifier.
///
/// Note that Null, dynamic, and void that are nullable by default. Note also
/// that some types denoted by a type parameter without the '?' modifier can
/// be something else rather than non-nullable.
nonNullable,
/// Non-legacy types that are neither nullable, nor non-nullable.
///
/// An example of such type is type T in the example below. Note that both
/// int and int? can be passed in for T, so an attempt to assign null to x is
/// a compile-time error as well as assigning x to y.
///
/// class A<T extends Object?> {
/// foo(T x) {
/// x = null; // Compile-time error.
/// Object y = x; // Compile-time error.
/// }
/// }
neither,
/// Types in opt-out libraries are 'legacy' types.
///
/// They are both subtypes and supertypes of the nullable and non-nullable
/// versions of the type.
legacy
}
/// A syntax-independent notion of a type.
///
/// [DartType]s are not AST nodes and may be shared between different parents.
///
/// [DartType] objects should be treated as unmodifiable objects, although
/// immutability is not enforced for List fields, and [TypeParameter]s are
/// cyclic structures that are constructed by mutation.
///
/// The `==` operator on [DartType]s compare based on type equality, not
/// object identity.
abstract class DartType extends Node {
const DartType();
R accept<R>(DartTypeVisitor<R> v);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg);
bool operator ==(Object other);
Nullability get nullability;
/// If this is a typedef type, repeatedly unfolds its type definition until
/// the root term is not a typedef type, otherwise returns the type itself.
///
/// Will never return a typedef type.
DartType get unalias => this;
/// If this is a typedef type, unfolds its type definition once, otherwise
/// returns the type itself.
DartType get unaliasOnce => this;
/// Creates a copy of the type with the given [nullability] if possible.
///
/// Some types have fixed nullabilities, such as `dynamic`, `invalid-type`,
/// `void`, or `bottom`.
DartType withNullability(Nullability nullability);
}
/// The type arising from invalid type annotations.
///
/// Can usually be treated as 'dynamic', but should occasionally be handled
/// differently, e.g. `x is ERROR` should evaluate to false.
class InvalidType extends DartType {
final int hashCode = 12345;
const InvalidType();
R accept<R>(DartTypeVisitor<R> v) => v.visitInvalidType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitInvalidType(this, arg);
visitChildren(Visitor v) {}
bool operator ==(Object other) => other is InvalidType;
Nullability get nullability => throw "InvalidType doesn't have nullability";
InvalidType withNullability(Nullability nullability) => this;
}
class DynamicType extends DartType {
final int hashCode = 54321;
const DynamicType();
R accept<R>(DartTypeVisitor<R> v) => v.visitDynamicType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitDynamicType(this, arg);
visitChildren(Visitor v) {}
bool operator ==(Object other) => other is DynamicType;
Nullability get nullability => Nullability.nullable;
DynamicType withNullability(Nullability nullability) => this;
}
class VoidType extends DartType {
final int hashCode = 123121;
const VoidType();
R accept<R>(DartTypeVisitor<R> v) => v.visitVoidType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitVoidType(this, arg);
visitChildren(Visitor v) {}
bool operator ==(Object other) => other is VoidType;
Nullability get nullability => Nullability.nullable;
VoidType withNullability(Nullability nullability) => this;
}
class BottomType extends DartType {
final int hashCode = 514213;
const BottomType();
R accept<R>(DartTypeVisitor<R> v) => v.visitBottomType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitBottomType(this, arg);
visitChildren(Visitor v) {}
bool operator ==(Object other) => other is BottomType;
Nullability get nullability => Nullability.nonNullable;
BottomType withNullability(Nullability nullability) => this;
}
class InterfaceType extends DartType {
Reference className;
final Nullability nullability;
final List<DartType> typeArguments;
/// The [typeArguments] list must not be modified after this call. If the
/// list is omitted, 'dynamic' type arguments are filled in.
InterfaceType(Class classNode,
[List<DartType> typeArguments,
Nullability nullability = Nullability.legacy])
: this.byReference(getClassReference(classNode),
typeArguments ?? _defaultTypeArguments(classNode), nullability);
InterfaceType.byReference(this.className, this.typeArguments,
[this.nullability = Nullability.legacy]);
Class get classNode => className.asClass;
static List<DartType> _defaultTypeArguments(Class classNode) {
if (classNode.typeParameters.length == 0) {
// Avoid allocating a list in this very common case.
return const <DartType>[];
} else {
return new List<DartType>.filled(
classNode.typeParameters.length, const DynamicType());
}
}
R accept<R>(DartTypeVisitor<R> v) => v.visitInterfaceType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitInterfaceType(this, arg);
visitChildren(Visitor v) {
classNode.acceptReference(v);
visitList(typeArguments, v);
}
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other is InterfaceType) {
if (className != other.className) return false;
if (typeArguments.length != other.typeArguments.length) return false;
for (int i = 0; i < typeArguments.length; ++i) {
if (typeArguments[i] != other.typeArguments[i]) return false;
}
return true;
} else {
return false;
}
}
int get hashCode {
int hash = 0x3fffffff & className.hashCode;
for (int i = 0; i < typeArguments.length; ++i) {
hash = 0x3fffffff & (hash * 31 + (hash ^ typeArguments[i].hashCode));
}
return hash;
}
InterfaceType withNullability(Nullability nullability) {
return nullability == this.nullability
? this
: new InterfaceType.byReference(className, typeArguments, nullability);
}
}
/// A possibly generic function type.
class FunctionType extends DartType {
final List<TypeParameter> typeParameters;
final int requiredParameterCount;
final List<DartType> positionalParameters;
final List<NamedType> namedParameters; // Must be sorted.
final Nullability nullability;
/// The [Typedef] this function type is created for.
final TypedefType typedefType;
final DartType returnType;
int _hashCode;
FunctionType(List<DartType> positionalParameters, this.returnType,
{this.namedParameters: const <NamedType>[],
this.typeParameters: const <TypeParameter>[],
this.nullability: Nullability.legacy,
int requiredParameterCount,
this.typedefType})
: this.positionalParameters = positionalParameters,
this.requiredParameterCount =
requiredParameterCount ?? positionalParameters.length;
Reference get typedefReference => typedefType?.typedefReference;
Typedef get typedef => typedefReference?.asTypedef;
R accept<R>(DartTypeVisitor<R> v) => v.visitFunctionType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitFunctionType(this, arg);
visitChildren(Visitor v) {
visitList(typeParameters, v);
visitList(positionalParameters, v);
visitList(namedParameters, v);
typedefType?.accept(v);
returnType.accept(v);
}
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other is FunctionType) {
if (typeParameters.length != other.typeParameters.length ||
requiredParameterCount != other.requiredParameterCount ||
positionalParameters.length != other.positionalParameters.length ||
namedParameters.length != other.namedParameters.length) {
return false;
}
if (typeParameters.isEmpty) {
for (int i = 0; i < positionalParameters.length; ++i) {
if (positionalParameters[i] != other.positionalParameters[i]) {
return false;
}
}
for (int i = 0; i < namedParameters.length; ++i) {
if (namedParameters[i] != other.namedParameters[i]) {
return false;
}
}
return returnType == other.returnType;
} else {
// Structural equality does not tell us if two generic function types
// are the same type. If they are unifiable without substituting any
// type variables, they are equal.
return unifyTypes(this, other, new Set<TypeParameter>()) != null;
}
} else {
return false;
}
}
/// Returns a variant of this function type that does not declare any type
/// parameters.
///
/// Any uses of its type parameters become free variables in the returned
/// type.
FunctionType get withoutTypeParameters {
if (typeParameters.isEmpty) return this;
return new FunctionType(positionalParameters, returnType,
requiredParameterCount: requiredParameterCount,
namedParameters: namedParameters,
typedefType: null);
}
/// Looks up the type of the named parameter with the given name.
///
/// Returns `null` if there is no named parameter with the given name.
DartType getNamedParameter(String name) {
int lower = 0;
int upper = namedParameters.length - 1;
while (lower <= upper) {
int pivot = (lower + upper) ~/ 2;
var namedParameter = namedParameters[pivot];
int comparison = name.compareTo(namedParameter.name);
if (comparison == 0) {
return namedParameter.type;
} else if (comparison < 0) {
upper = pivot - 1;
} else {
lower = pivot + 1;
}
}
return null;
}
int get hashCode => _hashCode ??= _computeHashCode();
int _computeHashCode() {
int hash = 1237;
hash = 0x3fffffff & (hash * 31 + requiredParameterCount);
for (int i = 0; i < typeParameters.length; ++i) {
TypeParameter parameter = typeParameters[i];
_temporaryHashCodeTable[parameter] = _temporaryHashCodeTable.length;
hash = 0x3fffffff & (hash * 31 + parameter.bound.hashCode);
}
for (int i = 0; i < positionalParameters.length; ++i) {
hash = 0x3fffffff & (hash * 31 + positionalParameters[i].hashCode);
}
for (int i = 0; i < namedParameters.length; ++i) {
hash = 0x3fffffff & (hash * 31 + namedParameters[i].hashCode);
}
hash = 0x3fffffff & (hash * 31 + returnType.hashCode);
for (int i = 0; i < typeParameters.length; ++i) {
// Remove the type parameters from the scope again.
_temporaryHashCodeTable.remove(typeParameters[i]);
}
return hash;
}
FunctionType withNullability(Nullability nullability) {
if (nullability == this.nullability) return this;
FunctionType result = FunctionType(positionalParameters, returnType,
namedParameters: namedParameters,
typeParameters: typeParameters,
nullability: nullability,
requiredParameterCount: requiredParameterCount,
typedefType: typedefType?.withNullability(nullability));
if (typeParameters.isEmpty) return result;
return getFreshTypeParameters(typeParameters).applyToFunctionType(result);
}
}
/// A use of a [Typedef] as a type.
///
/// The underlying type can be extracted using [unalias].
class TypedefType extends DartType {
final Nullability nullability;
final Reference typedefReference;
final List<DartType> typeArguments;
TypedefType(Typedef typedefNode,
[List<DartType> typeArguments,
Nullability nullability = Nullability.legacy])
: this.byReference(typedefNode.reference,
typeArguments ?? const <DartType>[], nullability);
TypedefType.byReference(this.typedefReference, this.typeArguments,
[this.nullability = Nullability.legacy]);
Typedef get typedefNode => typedefReference.asTypedef;
R accept<R>(DartTypeVisitor<R> v) => v.visitTypedefType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitTypedefType(this, arg);
visitChildren(Visitor v) {
visitList(typeArguments, v);
v.visitTypedefReference(typedefNode);
}
DartType get unaliasOnce {
return Substitution.fromTypedefType(this)
.substituteType(typedefNode.type)
.withNullability(nullability);
}
DartType get unalias {
return unaliasOnce.unalias;
}
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other is TypedefType) {
if (typedefReference != other.typedefReference ||
typeArguments.length != other.typeArguments.length) {
return false;
}
for (int i = 0; i < typeArguments.length; ++i) {
if (typeArguments[i] != other.typeArguments[i]) return false;
}
return true;
}
return false;
}
int get hashCode {
int hash = 0x3fffffff & typedefNode.hashCode;
for (int i = 0; i < typeArguments.length; ++i) {
hash = 0x3fffffff & (hash * 31 + (hash ^ typeArguments[i].hashCode));
}
return hash;
}
TypedefType withNullability(Nullability nullability) {
return nullability == this.nullability
? this
: new TypedefType.byReference(
typedefReference, typeArguments, nullability);
}
}
/// A named parameter in [FunctionType].
class NamedType extends Node implements Comparable<NamedType> {
// Flag used for serialization if [isRequired].
static const int FlagRequiredNamedType = 1 << 0;
final String name;
final DartType type;
final bool isRequired;
NamedType(this.name, this.type, {this.isRequired: false});
bool operator ==(Object other) {
return other is NamedType &&
name == other.name &&
type == other.type &&
isRequired == other.isRequired;
}
int get hashCode {
return name.hashCode * 31 + type.hashCode * 37 + isRequired.hashCode * 41;
}
int compareTo(NamedType other) => name.compareTo(other.name);
R accept<R>(Visitor<R> v) => v.visitNamedType(this);
void visitChildren(Visitor v) {
type.accept(v);
}
}
/// Stores the hash code of function type parameters while computing the hash
/// code of a [FunctionType] object.
///
/// This ensures that distinct [FunctionType] objects get the same hash code
/// if they represent the same type, even though their type parameters are
/// represented by different objects.
final Map<TypeParameter, int> _temporaryHashCodeTable = <TypeParameter, int>{};
/// Reference to a type variable.
///
/// A type variable has an optional bound because type promotion can change the
/// bound. A bound of `null` indicates that the bound has not been promoted and
/// is the same as the [TypeParameter]'s bound. This allows one to detect
/// whether the bound has been promoted. The case of promoted bound can be
/// viewed as representing an intersection type between the type-parameter type
/// and the promoted bound.
class TypeParameterType extends DartType {
/// Nullability of the type-parameter type or of its part of the intersection.
///
/// Declarations of type-parameter types can set the nullability of a
/// type-parameter type to [Nullability.nullable] (if the `?` marker is used)
/// or [Nullability.legacy] (if the type comes from a library opted out from
/// NNBD). Otherwise, it's defined indirectly via the nullability of the
/// bound of [parameter]. In cases when the [TypeParameterType] represents an
/// intersection between a type-parameter type and [promotedBound],
/// [typeParameterTypeNullability] represents the nullability of the left-hand
/// side of the intersection.
Nullability typeParameterTypeNullability;
TypeParameter parameter;
/// An optional promoted bound on the type parameter.
///
/// 'null' indicates that the type parameter's bound has not been promoted and
/// is therefore the same as the bound of [parameter].
DartType promotedBound;
TypeParameterType(this.parameter,
[this.promotedBound,
this.typeParameterTypeNullability = Nullability.legacy]);
R accept<R>(DartTypeVisitor<R> v) => v.visitTypeParameterType(this);
R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) =>
v.visitTypeParameterType(this, arg);
visitChildren(Visitor v) {}
bool operator ==(Object other) {
return other is TypeParameterType && parameter == other.parameter;
}
int get hashCode => _temporaryHashCodeTable[parameter] ?? parameter.hashCode;
/// Returns the bound of the type parameter, accounting for promotions.
DartType get bound => promotedBound ?? parameter.bound;
/// Nullability of the type, calculated from its parts.
///
/// [nullability] is calculated from [typeParameterTypeNullability] and the
/// nullability of [promotedBound] if it's present.
///
/// For example, in the following program [typeParameterTypeNullability] of
/// both `x` and `y` is [Nullability.neither], because it's copied from that
/// of `bar` and T has a nullable type as its bound. However, despite
/// [nullability] of `x` is [Nullability.neither], [nullability] of `y` is
/// [Nullability.nonNullable] because of its [promotedBound].
///
/// class A<T extends Object?> {
/// foo(T bar) {
/// var x = bar;
/// if (bar is int) {
/// var y = bar;
/// }
/// }
/// }
Nullability get nullability {
return getNullability(
typeParameterTypeNullability ?? computeNullabilityFromBound(parameter),
promotedBound);
}
/// Gets a new [TypeParameterType] with given [typeParameterTypeNullability].
///
/// In contrast with other types, [TypeParameterType.withNullability] doesn't
/// set the overall nullability of the returned type but sets that of the
/// left-hand side of the intersection type. In case [promotedBound] is null,
/// it is an equivalent of setting the overall nullability.
TypeParameterType withNullability(Nullability typeParameterTypeNullability) {
return typeParameterTypeNullability == this.typeParameterTypeNullability
? this
: new TypeParameterType(
parameter, promotedBound, typeParameterTypeNullability);
}
/// Gets the nullability of a type-parameter type based on the bound.
///
/// This is a helper function to be used when the bound of the type parameter
/// is changing or is being set for the first time, and the update on some
/// type-parameter types is required.
static Nullability computeNullabilityFromBound(TypeParameter typeParameter) {
// If the bound is nullable or 'neither', both nullable and non-nullable
// types can be passed in for the type parameter, making the corresponding
// type parameter types 'neither.' Otherwise, the nullability matches that
// of the bound.
DartType bound = typeParameter.bound;
if (bound == null) {
throw new StateError("Can't compute nullability from an absent bound.");
}
Nullability boundNullability =
bound is InvalidType ? Nullability.neither : bound.nullability;
return boundNullability == Nullability.nullable ||
boundNullability == Nullability.neither
? Nullability.neither
: boundNullability;
}
/// Gets nullability of [TypeParameterType] from arguments to its constructor.
///
/// The method combines [typeParameterTypeNullability] and the nullability of
/// [promotedBound] to yield the nullability of the intersection type. If the
/// right-hand side of the intersection is absent (that is, if [promotedBound]
/// is null), the nullability of the intersection type is simply
/// [typeParameterTypeNullability].
static Nullability getNullability(
Nullability typeParameterTypeNullability, DartType promotedBound) {
// If promotedBound is null, getNullability simply returns the nullability
// of the type parameter type.
Nullability lhsNullability = typeParameterTypeNullability;
if (promotedBound == null) {
return lhsNullability;
}
// If promotedBound isn't null, getNullability returns the nullability of an
// intersection of the left-hand side (referred to as LHS below) and the
// right-hand side (referred to as RHS below). Note that RHS is always a
// subtype of the bound of the type parameter.
// The code below implements the rule for the nullability of an intersection
// type as per the following table:
//
// | LHS \ RHS | ! | ? | * | % |
// |-----------|-----|-----|-----|-----|
// | ! | ! | N/A | N/A | ! |
// | ? | N/A | N/A | N/A | N/A |
// | * | N/A | N/A | * | N/A |
// | % | ! | % | N/A | % |
//
// In the table, LHS corresponds to lhsNullability in the code below; RHS
// corresponds to promotedBound.nullability; !, ?, *, and % correspond to
// nonNullable, nullable, legacy, and neither values of the Nullability
// enum.
//
// Whenever there's N/A in the table, it means that the corresponding
// combination of the LHS and RHS nullability is not possible when compiling
// from Dart source files, so we can define it to be whatever is faster and
// more convenient to implement. The verifier should check that the cases
// marked as N/A never occur in the output of the CFE.
//
// The code below uses the following extension of the table function:
//
// | LHS \ RHS | ! | ? | * | % |
// |-----------|-----|-----|-----|-----|
// | ! | ! | ! | ! | ! |
// | ? | ! | * | * | % |
// | * | ! | * | * | % |
// | % | ! | % | % | % |
// Intersection with a non-nullable type always yields a non-nullable type,
// as it's the most restrictive kind of types.
if (lhsNullability == Nullability.nonNullable ||
promotedBound.nullability == Nullability.nonNullable) {
return Nullability.nonNullable;
}
// If the nullability of LHS is 'neither,' the nullability of the
// intersection is also 'neither' if RHS is 'neither' or nullable.
//
// Consider the following example:
//
// class A<X extends Object?, Y extends X> {
// foo(X x) {
// if (x is Y) {
// x = null; // Compile-time error. Consider X = Y = int.
// Object a = x; // Compile-time error. Consider X = Y = int?.
// }
// if (x is int?) {
// x = null; // Compile-time error. Consider X = int.
// Object b = x; // Compile-time error. Consider X = int?.
// }
// }
// }
if (lhsNullability == Nullability.neither ||
promotedBound.nullability == Nullability.neither) {
return Nullability.neither;
}
return Nullability.legacy;
}
}
/// Value set for variance of a type parameter X in a type term T.
class Variance {
/// Used when X does not occur free in T.
static const int unrelated = 0;
/// Used when X occurs free in T, and U <: V implies [U/X]T <: [V/X]T.
static const int covariant = 1;
/// Used when X occurs free in T, and U <: V implies [V/X]T <: [U/X]T.
static const int contravariant = 2;
/// Used when there exists a pair U and V such that U <: V, but [U/X]T and
/// [V/X]T are incomparable.
static const int invariant = 3;
/// Variance values form a lattice where [unrelated] is the top, [invariant]
/// is the bottom, and [covariant] and [contravariant] are incomparable.
/// [meet] calculates the meet of two elements of such lattice. It can be
/// used, for example, to calculate the variance of a typedef type parameter
/// if it's encountered on the r.h.s. of the typedef multiple times.
static int meet(int a, int b) => a | b;
/// Combines variances of X in T and Y in S into variance of X in [Y/T]S.
///
/// Consider the following examples:
///
/// * variance of X in Function(X) is [contravariant], variance of Y in
/// List<Y> is [covariant], so variance of X in List<Function(X)> is
/// [contravariant];
///
/// * variance of X in List<X> is [covariant], variance of Y in Function(Y) is
/// [contravariant], so variance of X in Function(List<X>) is [contravariant];
///
/// * variance of X in Function(X) is [contravariant], variance of Y in
/// Function(Y) is [contravariant], so variance of X in Function(Function(X))
/// is [covariant];
///
/// * let the following be declared:
///
/// typedef F<Z> = Function();
///
/// then variance of X in F<X> is [unrelated], variance of Y in List<Y> is
/// [covariant], so variance of X in List<F<X>> is [unrelated];
///
/// * let the following be declared:
///
/// typedef G<Z> = Z Function(Z);
///
/// then variance of X in List<X> is [covariant], variance of Y in G<Y> is
/// [invariant], so variance of `X` in `G<List<X>>` is [invariant].
static int combine(int a, int b) {
if (a == unrelated || b == unrelated) return unrelated;
if (a == invariant || b == invariant) return invariant;
return a == b ? covariant : contravariant;
}
static int fromString(String variance) {
if (variance == "in") {
return contravariant;
} else if (variance == "inout") {
return invariant;
} else if (variance == "out") {
return covariant;
} else {
return unrelated;
}
}
}
/// Declaration of a type variable.
///
/// Type parameters declared in a [Class] or [FunctionNode] are part of the AST,
/// have a parent pointer to its declaring class or function, and will be seen
/// by tree visitors.
///
/// Type parameters declared by a [FunctionType] are orphans and have a `null`
/// parent pointer. [TypeParameter] objects should not be shared between
/// different [FunctionType] objects.
class TypeParameter extends TreeNode {
int flags = 0;
/// List of metadata annotations on the type parameter.
///
/// This defaults to an immutable empty list. Use [addAnnotation] to add
/// annotations if needed.
List<Expression> annotations = const <Expression>[];
String name; // Cosmetic name.
/// The bound on the type variable.
///
/// Should not be null except temporarily during IR construction. Should
/// be set to the root class for type parameters without an explicit bound.
DartType bound;
/// The default value of the type variable. It is used to provide the
/// corresponding missing type argument in type annotations and as the
/// fall-back type value in type inference at compile time. At run time,
/// [defaultType] is used by the backends in place of the missing type
/// argument of a dynamic invocation of a generic function.
DartType defaultType;
/// Describes variance of the type parameter w.r.t. declaration on which it is
/// defined. It's always [Variance.covariant] for classes, and for typedefs
/// it's the variance of the type parameters in the type term on the r.h.s. of
/// the typedef.
int variance = Variance.covariant;
TypeParameter([this.name, this.bound, this.defaultType]);
// Must match serialized bit positions.
static const int FlagGenericCovariantImpl = 1 << 0;
/// If this [TypeParameter] is a type parameter of a generic method, indicates
/// whether the method implementation 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;
void set isGenericCovariantImpl(bool value) {
flags = value
? (flags | FlagGenericCovariantImpl)
: (flags & ~FlagGenericCovariantImpl);
}
void addAnnotation(Expression annotation) {
if (annotations.isEmpty) {
annotations = <Expression>[];
}
annotations.add(annotation..parent = this);
}
R accept<R>(TreeVisitor<R> v) => v.visitTypeParameter(this);
visitChildren(Visitor v) {
visitList(annotations, v);
bound.accept(v);
defaultType?.accept(v);
}
transformChildren(Transformer v) {
transformList(annotations, v, this);
bound = v.visitDartType(bound);
if (defaultType != null) {
defaultType = v.visitDartType(defaultType);
}
}
/// Returns a possibly synthesized name for this type parameter, consistent
/// with the names used across all [toString] calls.
String toString() => debugQualifiedTypeParameterName(this);
bool get isFunctionTypeTypeParameter => parent == null;
}
class Supertype extends Node {
Reference className;
final List<DartType> typeArguments;
Supertype(Class classNode, List<DartType> typeArguments)
: this.byReference(getClassReference(classNode), typeArguments);
Supertype.byReference(this.className, this.typeArguments);
Class get classNode => className.asClass;
R accept<R>(Visitor<R> v) => v.visitSupertype(this);
visitChildren(Visitor v) {
classNode.acceptReference(v);
visitList(typeArguments, v);
}
InterfaceType get asInterfaceType {
return new InterfaceType(classNode, typeArguments);
}
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other is Supertype) {
if (className != other.className) return false;
if (typeArguments.length != other.typeArguments.length) return false;
for (int i = 0; i < typeArguments.length; ++i) {
if (typeArguments[i] != other.typeArguments[i]) return false;
}
return true;
} else {
return false;
}
}
int get hashCode {
int hash = 0x3fffffff & className.hashCode;
for (int i = 0; i < typeArguments.length; ++i) {
hash = 0x3fffffff & (hash * 31 + (hash ^ typeArguments[i].hashCode));
}
return hash;
}
}
// ------------------------------------------------------------------------
// CONSTANTS
// ------------------------------------------------------------------------
abstract class Constant extends Node {
/// Calls the `visit*ConstantReference()` method on visitor [v] for all
/// constants referenced in this constant.
///
/// (Note that a constant can be seen as a DAG (directed acyclic graph) and
/// not a tree!)
visitChildren(Visitor v);
/// Calls the `visit*Constant()` method on the visitor [v].
R accept<R>(ConstantVisitor<R> v);
/// Calls the `visit*ConstantReference()` method on the visitor [v].
R acceptReference<R>(Visitor<R> v);
/// The Kernel AST will reference [Constant]s via [ConstantExpression]s. The
/// constants are not required to be canonicalized, but they have to be deeply
/// comparable via hashCode/==!
int get hashCode;
bool operator ==(Object other);
/// Gets the type of this constant.
DartType getType(TypeEnvironment types);
Expression asExpression() {
return new ConstantExpression(this);
}
}
abstract class PrimitiveConstant<T> extends Constant {
final T value;
PrimitiveConstant(this.value);
String toString() => '$value';
int get hashCode => value.hashCode;
bool operator ==(Object other) =>
other is PrimitiveConstant<T> && other.value == value;
}
class NullConstant extends PrimitiveConstant<Null> {
NullConstant() : super(null);
visitChildren(Visitor v) {}
R accept<R>(ConstantVisitor<R> v) => v.visitNullConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitNullConstantReference(this);
DartType getType(TypeEnvironment types) => types.nullType;
}
class BoolConstant extends PrimitiveConstant<bool> {
BoolConstant(bool value) : super(value);
visitChildren(Visitor v) {}
R accept<R>(ConstantVisitor<R> v) => v.visitBoolConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitBoolConstantReference(this);
DartType getType(TypeEnvironment types) => types.coreTypes.boolLegacyRawType;
}
/// An integer constant on a non-JS target.
class IntConstant extends PrimitiveConstant<int> {
IntConstant(int value) : super(value);
visitChildren(Visitor v) {}
R accept<R>(ConstantVisitor<R> v) => v.visitIntConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitIntConstantReference(this);
DartType getType(TypeEnvironment types) => types.coreTypes.intLegacyRawType;
}
/// A double constant on a non-JS target or any numeric constant on a JS target.
class DoubleConstant extends PrimitiveConstant<double> {
DoubleConstant(double value) : super(value);
visitChildren(Visitor v) {}
R accept<R>(ConstantVisitor<R> v) => v.visitDoubleConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitDoubleConstantReference(this);
int get hashCode => value.isNaN ? 199 : super.hashCode;
bool operator ==(Object other) =>
other is DoubleConstant && identical(value, other.value);
DartType getType(TypeEnvironment types) =>
types.coreTypes.doubleLegacyRawType;
}
class StringConstant extends PrimitiveConstant<String> {
StringConstant(String value) : super(value) {
assert(value != null);
}
visitChildren(Visitor v) {}
R accept<R>(ConstantVisitor<R> v) => v.visitStringConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitStringConstantReference(this);
DartType getType(TypeEnvironment types) =>
types.coreTypes.stringLegacyRawType;
}
class SymbolConstant extends Constant {
final String name;
final Reference libraryReference;
SymbolConstant(this.name, this.libraryReference);
visitChildren(Visitor v) {}
R accept<R>(ConstantVisitor<R> v) => v.visitSymbolConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitSymbolConstantReference(this);
String toString() {
return libraryReference != null
? '#${libraryReference.asLibrary.importUri}::$name'
: '#$name';
}
int get hashCode => _Hash.hash2(name, libraryReference);
bool operator ==(Object other) =>
identical(this, other) ||
(other is SymbolConstant &&
other.name == name &&
other.libraryReference == libraryReference);
DartType getType(TypeEnvironment types) =>
types.coreTypes.symbolLegacyRawType;
}
class MapConstant extends Constant {
final DartType keyType;
final DartType valueType;
final List<ConstantMapEntry> entries;
MapConstant(this.keyType, this.valueType, this.entries);
visitChildren(Visitor v) {
keyType.accept(v);
valueType.accept(v);
for (final ConstantMapEntry entry in entries) {
entry.key.acceptReference(v);
entry.value.acceptReference(v);
}
}
R accept<R>(ConstantVisitor<R> v) => v.visitMapConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitMapConstantReference(this);
String toString() => '${this.runtimeType}<$keyType, $valueType>($entries)';
int _cachedHashCode;
int get hashCode {
return _cachedHashCode ??= _Hash.combine2Finish(
keyType.hashCode, valueType.hashCode, _Hash.combineListHash(entries));
}
bool operator ==(Object other) =>
identical(this, other) ||
(other is MapConstant &&
other.keyType == keyType &&
other.valueType == valueType &&
listEquals(other.entries, entries));
DartType getType(TypeEnvironment types) =>
types.literalMapType(keyType, valueType);
}
class ConstantMapEntry {
final Constant key;
final Constant value;
ConstantMapEntry(this.key, this.value);
String toString() => '$key: $value';
int get hashCode => _Hash.hash2(key, value);
bool operator ==(Object other) =>
other is ConstantMapEntry && other.key == key && other.value == value;
}
class ListConstant extends Constant {
final DartType typeArgument;
final List<Constant> entries;
ListConstant(this.typeArgument, this.entries);
visitChildren(Visitor v) {
typeArgument.accept(v);
for (final Constant constant in entries) {
constant.acceptReference(v);
}
}
R accept<R>(ConstantVisitor<R> v) => v.visitListConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitListConstantReference(this);
String toString() => '${this.runtimeType}<$typeArgument>($entries)';
int _cachedHashCode;
int get hashCode {
return _cachedHashCode ??= _Hash.combineFinish(
typeArgument.hashCode, _Hash.combineListHash(entries));
}
bool operator ==(Object other) =>
identical(this, other) ||
(other is ListConstant &&
other.typeArgument == typeArgument &&
listEquals(other.entries, entries));
DartType getType(TypeEnvironment types) =>
types.literalListType(typeArgument);
}
class SetConstant extends Constant {
final DartType typeArgument;
final List<Constant> entries;
SetConstant(this.typeArgument, this.entries);
visitChildren(Visitor v) {
typeArgument.accept(v);
for (final Constant constant in entries) {
constant.acceptReference(v);
}
}
R accept<R>(ConstantVisitor<R> v) => v.visitSetConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitSetConstantReference(this);
String toString() => '${this.runtimeType}<$typeArgument>($entries)';
int _cachedHashCode;
int get hashCode {
return _cachedHashCode ??= _Hash.combineFinish(
typeArgument.hashCode, _Hash.combineListHash(entries));
}
bool operator ==(Object other) =>
identical(this, other) ||
(other is SetConstant &&
other.typeArgument == typeArgument &&
listEquals(other.entries, entries));
DartType getType(TypeEnvironment types) => types.literalSetType(typeArgument);
}
class InstanceConstant extends Constant {
final Reference classReference;
final List<DartType> typeArguments;
final Map<Reference, Constant> fieldValues;
InstanceConstant(this.classReference, this.typeArguments, this.fieldValues);
Class get classNode => classReference.asClass;
visitChildren(Visitor v) {
classReference.asClass.acceptReference(v);
visitList(typeArguments, v);
for (final Reference reference in fieldValues.keys) {
reference.asField.acceptReference(v);
}
for (final Constant constant in fieldValues.values) {
constant.acceptReference(v);
}
}
R accept<R>(ConstantVisitor<R> v) => v.visitInstanceConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitInstanceConstantReference(this);
String toString() {
final sb = new StringBuffer();
sb.write('${classReference.asClass}');
if (!classReference.asClass.typeParameters.isEmpty) {
sb.write('<');
sb.write(typeArguments.map((type) => type.toString()).join(', '));
sb.write('>');
}
sb.write(' {');
fieldValues.forEach((Reference fieldRef, Constant constant) {
sb.write('${fieldRef.asField.name}: $constant, ');
});
sb.write('}');
return sb.toString();
}
int _cachedHashCode;
int get hashCode {
return _cachedHashCode ??= _Hash.combine2Finish(
classReference.hashCode,
listHashCode(typeArguments),
_Hash.combineMapHashUnordered(fieldValues));
}
bool operator ==(Object other) {
return identical(this, other) ||
(other is InstanceConstant &&
other.classReference == classReference &&
listEquals(other.typeArguments, typeArguments) &&
mapEquals(other.fieldValues, fieldValues));
}
DartType getType(TypeEnvironment types) =>
new InterfaceType(classNode, typeArguments);
}
class PartialInstantiationConstant extends Constant {
final TearOffConstant tearOffConstant;
final List<DartType> types;
PartialInstantiationConstant(this.tearOffConstant, this.types);
visitChildren(Visitor v) {
tearOffConstant.acceptReference(v);
visitList(types, v);
}
R accept<R>(ConstantVisitor<R> v) =>
v.visitPartialInstantiationConstant(this);
R acceptReference<R>(Visitor<R> v) =>
v.visitPartialInstantiationConstantReference(this);
String toString() {
return '${runtimeType}(${tearOffConstant.procedure}<${types.join(', ')}>)';
}
int get hashCode => _Hash.combineFinish(
tearOffConstant.hashCode, _Hash.combineListHash(types));
bool operator ==(Object other) {
return other is PartialInstantiationConstant &&
other.tearOffConstant == tearOffConstant &&
listEquals(other.types, types);
}
DartType getType(TypeEnvironment typeEnvironment) {
final FunctionType type = tearOffConstant.getType(typeEnvironment);
final mapping = <TypeParameter, DartType>{};
for (final parameter in type.typeParameters) {
mapping[parameter] = types[mapping.length];
}
return substitute(type.withoutTypeParameters, mapping);
}
}
class TearOffConstant extends Constant {
final Reference procedureReference;
TearOffConstant(Procedure procedure)
: procedureReference = procedure.reference {
assert(procedure.isStatic);
}
TearOffConstant.byReference(this.procedureReference);
Procedure get procedure => procedureReference?.asProcedure;
visitChildren(Visitor v) {
procedureReference.asProcedure.acceptReference(v);
}
R accept<R>(ConstantVisitor<R> v) => v.visitTearOffConstant(this);
R acceptReference<R>(Visitor<R> v) => v.visitTearOffConstantReference(this);
String toString() {
return '${runtimeType}(${procedure})';
}
int get hashCode => procedureReference.hashCode;
bool operator ==(Object other) {
return other is TearOffConstant &&
other.procedureReference == procedureReference;
}
FunctionType getType(TypeEnvironment types) =>
procedure.function.functionType;
}
class TypeLiteralConstant extends Constant {
final DartType type;
TypeLiteralConstant(this.type);
visitChildren(Visitor v) {
type.accept(v);
}
R accept<R>(ConstantVisitor<R> v) => v.visitTypeLiteralConstant(this);
R acceptReference<R>(Visitor<R> v) =>
v.visitTypeLiteralConstantReference(this);
String toString() => '${runtimeType}(${type})';
int get hashCode => type.hashCode;
bool operator ==(Object other) {
return other is TypeLiteralConstant && other.type == type;
}
DartType getType(TypeEnvironment types) => types.coreTypes.typeLegacyRawType;
}
class UnevaluatedConstant extends Constant {
final Expression expression;
UnevaluatedConstant(this.expression) {
expression?.parent = null;
}
visitChildren(Visitor v) {
expression.accept(v);
}
R accept<R>(ConstantVisitor<R> v) => v.visitUnevaluatedConstant(this);
R acceptReference<R>(Visitor<R> v) =>
v.visitUnevaluatedConstantReference(this);
DartType getType(TypeEnvironment types) => expression.getStaticType(types);
@override
Expression asExpression() => expression;
}
// ------------------------------------------------------------------------
// COMPONENT
// ------------------------------------------------------------------------
/// A way to bundle up libraries in a component.
class Component extends TreeNode {
final CanonicalName root;
/// Problems in this [Component] 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<Library> libraries;
/// Map from a source file URI to a line-starts table and source code.
/// Given a source file URI and a offset in that file one can translate
/// it to a line:column position in that file.
final Map<Uri, Source> uriToSource;
/// Mapping between string tags and [MetadataRepository] corresponding to
/// those tags.
final Map<String, MetadataRepository<dynamic>> metadata =
<String, MetadataRepository<dynamic>>{};
/// Reference to the main method in one of the libraries.
Reference mainMethodName;
Component(
{CanonicalName nameRoot,
List<Library> libraries,
Map<Uri, Source> uriToSource})
: root = nameRoot ?? new CanonicalName.root(),
libraries = libraries ?? <Library>[],
uriToSource = uriToSource ?? <Uri, Source>{} {
adoptChildren();
}
void adoptChildren() {
if (libraries != null) {
for (int i = 0; i < libraries.length; ++i) {
// The libraries are owned by this component, and so are their canonical
// names if they exist.
Library library = libraries[i];
library.parent = this;
CanonicalName name = library.reference.canonicalName;
if (name != null && name.parent != root) {
root.adoptChild(name);
}
}
}
}
void computeCanonicalNames() {
for (int i = 0; i < libraries.length; ++i) {
computeCanonicalNamesForLibrary(libraries[i]);
}
}
void computeCanonicalNamesForLibrary(Library library) {
root.getChildFromUri(library.importUri).bindTo(library.reference);
library.computeCanonicalNames();
}
void unbindCanonicalNames() {
// TODO(jensj): Get rid of this.
for (int i = 0; i < libraries.length; i++) {
Library lib = libraries[i];
for (int j = 0; j < lib.classes.length; j++) {
Class c = lib.classes[j];
c.dirty = true;
}
}
root.unbindAll();
}
Procedure get mainMethod => mainMethodName?.asProcedure;
void set mainMethod(Procedure main) {
mainMethodName = getMemberReference(main);
}
R accept<R>(TreeVisitor<R> v) => v.visitComponent(this);
visitChildren(Visitor v) {
visitList(libraries, v);
mainMethod?.acceptReference(v);
}
transformChildren(Transformer v) {
transformList(libraries, v, this);
}
Component get enclosingComponent => this;
/// Translates an offset to line and column numbers in the given file.
Location getLocation(Uri file, int offset) {
return uriToSource[file]?.getLocation(file, offset);
}
void addMetadataRepository(MetadataRepository repository) {
metadata[repository.tag] = repository;
}
}
/// A tuple with file, line, and column number, for displaying human-readable
/// locations.
class Location {
final Uri file;
final int line; // 1-based.
final int column; // 1-based.
Location(this.file, this.line, this.column);
String toString() => '$file:$line:$column';
}
abstract class MetadataRepository<T> {
/// Unique string tag associated with this repository.
String get tag;
/// Mutable mapping between nodes and their metadata.
Map<TreeNode, T> get mapping;
/// Write [metadata] object corresponding to the given [Node] into
/// the given [BinarySink].
///
/// Metadata is serialized immediately before serializing [node],
/// so implementation of this method can use serialization context of
/// [node]'s parents (such as declared type parameters and variables).
/// In order to use scope declared by the [node] itself, implementation of
/// this method can use [BinarySink.enterScope] and [BinarySink.leaveScope]
/// methods.
///
/// [metadata] must be an object owned by this repository.
void writeToBinary(T metadata, Node node, BinarySink sink);
/// Construct a metadata object from its binary payload read from the
/// given [BinarySource].
///
/// Metadata is deserialized immediately after deserializing [node],
/// so it can use deserialization context of [node]'s parents.
/// In order to use scope declared by the [node] itself, implementation of
/// this method can use [BinarySource.enterScope] and
/// [BinarySource.leaveScope] methods.
T readFromBinary(Node node, BinarySource source);
/// Method to check whether a node can have metadata attached to it
/// or referenced from the metadata payload.
///
/// Currently due to binary format specifics Catch and MapEntry nodes
/// can't have metadata attached to them. Also, metadata is not saved on
/// Block nodes inside BlockExpressions.
static bool isSupported(TreeNode node) {
return !(node is MapEntry ||
node is Catch ||
(node is Block && node.parent is BlockExpression));
}
}
abstract class BinarySink {
int getBufferOffset();
void writeByte(int byte);
void writeBytes(List<int> bytes);
void writeUInt32(int value);
void writeUInt30(int value);
/// Write List<Byte> into the sink.
void writeByteList(List<int> bytes);
void writeNullAllowedCanonicalNameReference(CanonicalName name);
void writeStringReference(String str);
void writeName(Name node);
void writeDartType(DartType type);
void writeNode(Node node);
void enterScope(
{List<TypeParameter> typeParameters,
bool memberScope: false,
bool variableScope: false});
void leaveScope(
{List<TypeParameter> typeParameters,
bool memberScope: false,
bool variableScope: false});
}
abstract class BinarySource {
int get currentOffset;
List<int> get bytes;
int readByte();
List<int> readBytes(int length);
int readUInt();
int readUint32();
/// Read List<Byte> from the source.
List<int> readByteList();
CanonicalName readCanonicalNameReference();
String readStringReference();
Name readName();
DartType readDartType();
FunctionNode readFunctionNode();
void enterScope({List<TypeParameter> typeParameters});
void leaveScope({List<TypeParameter> typeParameters});
}
// ------------------------------------------------------------------------
// INTERNAL FUNCTIONS
// ------------------------------------------------------------------------
void setParents(List<TreeNode> nodes, TreeNode parent) {
for (int i = 0; i < nodes.length; ++i) {
nodes[i].parent = parent;
}
}
void visitList(List<Node> nodes, Visitor visitor) {
for (int i = 0; i < nodes.length; ++i) {
nodes[i].accept(visitor);
}
}
void visitIterable(Iterable<Node> nodes, Visitor visitor) {
for (var node in nodes) {
node.accept(visitor);
}
}
void transformTypeList(List<DartType> nodes, Transformer visitor) {
int storeIndex = 0;
for (int i = 0; i < nodes.length; ++i) {
var result = visitor.visitDartType(nodes[i]);
if (result != null) {
nodes[storeIndex] = result;
++storeIndex;
}
}
if (storeIndex < nodes.length) {
nodes.length = storeIndex;
}
}
void transformSupertypeList(List<Supertype> nodes, Transformer visitor) {
int storeIndex = 0;
for (int i = 0; i < nodes.length; ++i) {
var result = visitor.visitSupertype(nodes[i]);
if (result != null) {
nodes[storeIndex] = result;
++storeIndex;
}
}
if (storeIndex < nodes.length) {
nodes.length = storeIndex;
}
}
void transformList(List<TreeNode> nodes, Transformer visitor, TreeNode parent) {
int storeIndex = 0;
for (int i = 0; i < nodes.length; ++i) {
var result = nodes[i].accept(visitor);
if (result != null) {
nodes[storeIndex] = result;
result.parent = parent;
++storeIndex;
}
}
if (storeIndex < nodes.length) {
nodes.length = storeIndex;
}
}
List<DartType> _getAsTypeArguments(List<TypeParameter> typeParameters) {
if (typeParameters.isEmpty) return const <DartType>[];
return new List<DartType>.generate(
typeParameters.length, (i) => new TypeParameterType(typeParameters[i]),
growable: false);
}
class _ChildReplacer extends Transformer {
final TreeNode child;
final TreeNode replacement;
_ChildReplacer(this.child, this.replacement);
@override
defaultTreeNode(TreeNode node) {
if (node == child) {
return replacement;
} else {
return node;
}
}
}
class Source {
final List<int> lineStarts;
final List<int> source;
final Uri importUri;
final Uri fileUri;
String cachedText;
Source(this.lineStarts, this.source, this.importUri, this.fileUri);
/// Return the text corresponding to [line] which is a 1-based line
/// number. The returned line contains no line separators.
String getTextLine(int line) {
if (source == null ||
source.isEmpty ||
lineStarts == null ||
lineStarts.isEmpty) return null;
RangeError.checkValueInInterval(line, 1, lineStarts.length, 'line');
cachedText ??= utf8.decode(source, allowMalformed: true);
// -1 as line numbers start at 1.
int index = line - 1;
if (index + 1 == lineStarts.length) {
// Last line.
return cachedText.substring(lineStarts[index]);
} else if (index < lineStarts.length) {
// We subtract 1 from the next line for two reasons:
// 1. If the file isn't terminated by a newline, that index is invalid.
// 2. To remove the newline at the end of the line.
int endOfLine = lineStarts[index + 1] - 1;
if (endOfLine > index && cachedText[endOfLine - 1] == "\r") {
--endOfLine; // Windows line endings.
}
return cachedText.substring(lineStarts[index], endOfLine);
}
// This shouldn't happen: should have been caught by the range check above.
throw "Internal error";
}
/// Translates an offset to line and column numbers in the given file.
Location getLocation(Uri file, int offset) {
if (lineStarts == null || lineStarts.isEmpty) {
return new Location(file, TreeNode.noOffset, TreeNode.noOffset);
}
RangeError.checkValueInInterval(offset, 0, lineStarts.last, 'offset');
int low = 0, high = lineStarts.length - 1;
while (low < high) {
int mid = high - ((high - low) >> 1); // Get middle, rounding up.
int pivot = lineStarts[mid];
if (pivot <= offset) {
low = mid;
} else {
high = mid - 1;
}
}
int lineIndex = low;
int lineStart = lineStarts[lineIndex];
int lineNumber = 1 + lineIndex;
int columnNumber = 1 + offset - lineStart;
return new Location(file, lineNumber, columnNumber);
}
}
/// Returns the [Reference] object for the given member.
///
/// Returns `null` if the member is `null`.
Reference getMemberReference(Member member) {
return member?.reference;
}
/// Returns the [Reference] object for the given class.
///
/// Returns `null` if the class is `null`.
Reference getClassReference(Class class_) {
return class_?.reference;
}
/// Returns the canonical name of [member], or throws an exception if the
/// member has not been assigned a canonical name yet.
///
/// Returns `null` if the member is `null`.
CanonicalName getCanonicalNameOfMember(Member member) {
if (member == null) return null;
if (member.canonicalName == null) {
throw '$member has no canonical name';
}
return member.canonicalName;
}
/// Returns the canonical name of [class_], or throws an exception if the
/// class has not been assigned a canonical name yet.
///
/// Returns `null` if the class is `null`.
CanonicalName getCanonicalNameOfClass(Class class_) {
if (class_ == null) return null;
if (class_.canonicalName == null) {
throw '$class_ has no canonical name';
}
return class_.canonicalName;
}
/// Returns the canonical name of [extension], or throws an exception if the
/// class has not been assigned a canonical name yet.
///
/// Returns `null` if the extension is `null`.
CanonicalName getCanonicalNameOfExtension(Extension extension) {
if (extension == null) return null;
if (extension.canonicalName == null) {
throw '$extension has no canonical name';
}
return extension.canonicalName;
}
/// Returns the canonical name of [library], or throws an exception if the
/// library has not been assigned a canonical name yet.
///
/// Returns `null` if the library is `null`.
CanonicalName getCanonicalNameOfLibrary(Library library) {
if (library == null) return null;
if (library.canonicalName == null) {
throw '$library has no canonical name';
}
return library.canonicalName;
}
/// Murmur-inspired hashing, with a fall-back to Jenkins-inspired hashing when
/// compiled to JavaScript.
///
/// A hash function should be constructed of several [combine] calls followed by
/// a [finish] call.
class _Hash {
static const int M = 0x9ddfea08eb382000 + 0xd69;
static const bool intIs64Bit = (1 << 63) != 0;
/// Primitive hash combining step.
static int combine(int value, int hash) {
if (intIs64Bit) {
value *= M;
value ^= _shru(value, 47);
value *= M;
hash ^= value;
hash *= M;
} else {
// Fall back to Jenkins-inspired hashing on JavaScript platforms.
hash = 0x1fffffff & (hash + value);
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
hash = hash ^ (hash >> 6);
}
return hash;
}
/// Primitive hash finalization step.
static int finish(int hash) {
if (intIs64Bit) {
hash ^= _shru(hash, 44);
hash *= M;
hash ^= _shru(hash, 41);
} else {
// Fall back to Jenkins-inspired hashing on JavaScript platforms.
hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
hash = hash ^ (hash >> 11);
hash = 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
}
return hash;
}
static int combineFinish(int value, int hash) {
return finish(combine(value, hash));
}
static int combine2(int value1, int value2, int hash) {
return combine(value2, combine(value1, hash));
}
static int combine2Finish(int value1, int value2, int hash) {
return finish(combine2(value1, value2, hash));
}
static int hash2(Object object1, Object object2) {
return combine2Finish(object2.hashCode, object2.hashCode, 0);
}
static int combineListHash(List list, [int hash = 1]) {
for (var item in list) {
hash = _Hash.combine(item.hashCode, hash);
}
return hash;
}
static int combineList(List<int> hashes, int hash) {
for (var item in hashes) {
hash = combine(item, hash);
}
return hash;
}
static int combineMapHashUnordered(Map map, [int hash = 2]) {
if (map == null || map.isEmpty) return hash;
List<int> entryHashes = List(map.length);
int i = 0;
for (var entry in map.entries) {
entryHashes[i++] = combine(entry.key.hashCode, entry.value.hashCode);
}
entryHashes.sort();
return combineList(entryHashes, hash);
}
// TODO(sra): Replace with '>>>'.
static int _shru(int v, int n) {
assert(n >= 1);
assert(intIs64Bit);
return ((v >> 1) & (0x7fffFFFFffffF000 + 0xFFF)) >> (n - 1);
}
}
int listHashCode(List list) {
return _Hash.finish(_Hash.combineListHash(list));
}
int mapHashCode(Map map) {
return mapHashCodeUnordered(map);
}
int mapHashCodeOrdered(Map map, [int hash = 2]) {
for (final Object x in map.keys) hash = _Hash.combine(x.hashCode, hash);
for (final Object x in map.values) hash = _Hash.combine(x.hashCode, hash);
return _Hash.finish(hash);
}
int mapHashCodeUnordered(Map map) {
return _Hash.finish(_Hash.combineMapHashUnordered(map));
}
bool listEquals(List a, List b) {
if (a.length != b.length) return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
bool mapEquals(Map a, Map b) {
if (a.length != b.length) return false;
for (final Object key in a.keys) {
if (!b.containsKey(key) || a[key] != b[key]) return false;
}
return true;
}
/// Returns the canonical name of [typedef_], or throws an exception if the
/// typedef has not been assigned a canonical name yet.
///
/// Returns `null` if the typedef is `null`.
CanonicalName getCanonicalNameOfTypedef(Typedef typedef_) {
if (typedef_ == null) return null;
if (typedef_.canonicalName == null) {
throw '$typedef_ has no canonical name';
}
return typedef_.canonicalName;
}
/// Annotation describing information which is not part of Dart semantics; in
/// other words, if this information (or any information it refers to) changes,
/// static analysis and runtime behavior of the library are unaffected.
const informative = null;
Location _getLocationInComponent(Component component, Uri fileUri, int offset) {
if (component != null) {
return component.getLocation(fileUri, offset);
} else {
return new Location(fileUri, TreeNode.noOffset, TreeNode.noOffset);
}
}
/// Convert the synthetic name of an implicit mixin application class
/// into a name suitable for user-faced strings.
///
/// For example, when compiling "class A extends S with M1, M2", the
/// two synthetic classes will be named "_A&S&M1" and "_A&S&M1&M2".
/// This function will return "S with M1" and "S with M1, M2", respectively.
String demangleMixinApplicationName(String name) {
List<String> nameParts = name.split('&');
if (nameParts.length < 2 || name == "&") return name;
String demangledName = nameParts[1];
for (int i = 2; i < nameParts.length; i++) {
demangledName += (i == 2 ? " with " : ", ") + nameParts[i];
}
return demangledName;
}
/// Extract from the synthetic name of an implicit mixin application class
/// the name of the final subclass of the mixin application.
///
/// For example, when compiling "class A extends S with M1, M2", the
/// two synthetic classes will be named "_A&S&M1" and "_A&S&M1&M2".
/// This function will return "A" for both classes.
String demangleMixinApplicationSubclassName(String name) {
List<String> nameParts = name.split('&');
if (nameParts.length < 2) return name;
assert(nameParts[0].startsWith('_'));
return nameParts[0].substring(1);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/type_algebra.dart | // 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.
library kernel.type_algebra;
import 'ast.dart';
import 'clone.dart';
/// Returns a type where all occurrences of the given type parameters have been
/// replaced with the corresponding types.
///
/// This will copy only the subterms of [type] that contain substituted
/// variables; all other [DartType] objects will be reused.
///
/// In particular, if no variables were substituted, this is guaranteed to
/// return the [type] instance (not a copy), so the caller may use [identical]
/// to efficiently check if a distinct type was created.
DartType substitute(DartType type, Map<TypeParameter, DartType> substitution) {
if (substitution.isEmpty) return type;
return Substitution.fromMap(substitution).substituteType(type);
}
/// Returns a mapping from the type parameters declared on the class of [type]
/// to the actual type arguments provided in [type].
///
/// This can be passed as argument to [substitute].
Map<TypeParameter, DartType> getSubstitutionMap(Supertype type) {
return type.typeArguments.isEmpty
? const <TypeParameter, DartType>{}
: new Map<TypeParameter, DartType>.fromIterables(
type.classNode.typeParameters, type.typeArguments);
}
Map<TypeParameter, DartType> getUpperBoundSubstitutionMap(Class host) {
if (host.typeParameters.isEmpty) return const <TypeParameter, DartType>{};
var result = <TypeParameter, DartType>{};
for (var parameter in host.typeParameters) {
result[parameter] = const DynamicType();
}
for (var parameter in host.typeParameters) {
result[parameter] = substitute(parameter.bound, result);
}
return result;
}
/// Like [substitute], except when a type in the [substitution] map references
/// another substituted type variable, the mapping for that type is recursively
/// inserted.
///
/// For example `Set<G>` substituted with `{T -> String, G -> List<T>}` results
/// in `Set<List<String>>`.
///
/// Returns `null` if the substitution map contains a cycle reachable from a
/// type variable in [type] (the resulting type would be infinite).
///
/// The [substitution] map will be mutated so that the right-hand sides may
/// be remapped to the deeply substituted type, but only for the keys that are
/// reachable from [type].
///
/// As with [substitute], this is guaranteed to return the same instance if no
/// substitution was performed.
DartType substituteDeep(
DartType type, Map<TypeParameter, DartType> substitution) {
if (substitution.isEmpty) return type;
var substitutor = new _DeepTypeSubstitutor(substitution);
var result = substitutor.visit(type);
return substitutor.isInfinite ? null : result;
}
/// Returns true if [type] contains a reference to any of the given [variables].
///
/// It is an error to call this with a [type] that contains a [FunctionType]
/// that declares one of the parameters in [variables].
bool containsTypeVariable(DartType type, Set<TypeParameter> variables) {
if (variables.isEmpty) return false;
return new _OccurrenceVisitor(variables).visit(type);
}
/// Returns `true` if [type] contains any free type variables, that is, type
/// variable for function types whose function type is part of [type].
bool containsFreeFunctionTypeVariables(DartType type) {
return new _FreeFunctionTypeVariableVisitor().visit(type);
}
/// Given a set of type variables, finds a substitution of those variables such
/// that the two given types becomes equal, or returns `null` if no such
/// substitution exists.
///
/// For example, unifying `List<T>` with `List<String>`, where `T` is a
/// quantified variable, yields the substitution `T = String`.
///
/// If successful, this equation holds:
///
/// substitute(type1, substitution) == substitute(type2, substitution)
///
/// The unification can fail for two reasons:
/// - incompatible types, e.g. `List<T>` cannot be unified with `Set<T>`.
/// - infinite types: e.g. `T` cannot be unified with `List<T>` because it
/// would create the infinite type `List<List<List<...>>>`.
Map<TypeParameter, DartType> unifyTypes(
DartType type1, DartType type2, Set<TypeParameter> quantifiedVariables) {
var unifier = new _TypeUnification(type1, type2, quantifiedVariables);
return unifier.success ? unifier.substitution : null;
}
/// Generates a fresh copy of the given type parameters, with their bounds
/// substituted to reference the new parameters.
///
/// The returned object contains the fresh type parameter list as well as a
/// mapping to be used for replacing other types to use the new type parameters.
FreshTypeParameters getFreshTypeParameters(List<TypeParameter> typeParameters) {
var freshParameters = new List<TypeParameter>.generate(
typeParameters.length, (i) => new TypeParameter(typeParameters[i].name),
growable: true);
var map = <TypeParameter, DartType>{};
for (int i = 0; i < typeParameters.length; ++i) {
map[typeParameters[i]] = new TypeParameterType(freshParameters[i]);
}
CloneVisitor cloner;
for (int i = 0; i < typeParameters.length; ++i) {
TypeParameter typeParameter = typeParameters[i];
TypeParameter freshTypeParameter = freshParameters[i];
freshTypeParameter.bound = substitute(typeParameter.bound, map);
freshTypeParameter.defaultType = typeParameter.defaultType != null
? substitute(typeParameter.defaultType, map)
: null;
if (typeParameter.annotations.isNotEmpty) {
// Annotations can't refer to type parameters, so the cloner shouldn't
// perform the substitution.
// TODO(dmitryas): Consider rewriting getFreshTypeParameters using cloner
// for copying typeParameters as well.
cloner ??= new CloneVisitor();
for (Expression annotation in typeParameter.annotations) {
freshTypeParameter.addAnnotation(cloner.clone(annotation));
}
}
}
return new FreshTypeParameters(freshParameters, Substitution.fromMap(map));
}
class FreshTypeParameters {
final List<TypeParameter> freshTypeParameters;
final Substitution substitution;
FreshTypeParameters(this.freshTypeParameters, this.substitution);
FunctionType applyToFunctionType(FunctionType type) => new FunctionType(
type.positionalParameters.map(substitute).toList(),
substitute(type.returnType),
namedParameters: type.namedParameters.map(substituteNamed).toList(),
typeParameters: freshTypeParameters,
requiredParameterCount: type.requiredParameterCount,
typedefType:
type.typedefType == null ? null : substitute(type.typedefType),
nullability: type.nullability);
DartType substitute(DartType type) => substitution.substituteType(type);
NamedType substituteNamed(NamedType type) =>
new NamedType(type.name, substitute(type.type),
isRequired: type.isRequired);
Supertype substituteSuper(Supertype type) {
return substitution.substituteSupertype(type);
}
}
// ------------------------------------------------------------------------
// IMPLEMENTATION
// ------------------------------------------------------------------------
abstract class Substitution {
const Substitution();
static const Substitution empty = _NullSubstitution.instance;
/// Substitutes each parameter to the type it maps to in [map].
static Substitution fromMap(Map<TypeParameter, DartType> map) {
if (map.isEmpty) return _NullSubstitution.instance;
return new _MapSubstitution(map, map);
}
static Substitution filtered(Substitution sub, TypeParameterFilter filter) {
return new _FilteredSubstitution(sub, filter);
}
/// Substitutes all occurrences of the given type parameters with the
/// corresponding upper or lower bound, depending on the variance of the
/// context where it occurs.
///
/// For example the type `(T) => T` with the bounds `bottom <: T <: num`
/// becomes `(bottom) => num` (in this example, `num` is the upper bound,
/// and `bottom` is the lower bound).
///
/// This is a way to obtain an upper bound for a type while eliminating all
/// references to certain type variables.
static Substitution fromUpperAndLowerBounds(
Map<TypeParameter, DartType> upper, Map<TypeParameter, DartType> lower) {
if (upper.isEmpty && lower.isEmpty) return _NullSubstitution.instance;
return new _MapSubstitution(upper, lower);
}
/// Substitutes the type parameters on the class of [supertype] with the
/// type arguments provided in [supertype].
static Substitution fromSupertype(Supertype supertype) {
if (supertype.typeArguments.isEmpty) return _NullSubstitution.instance;
return fromMap(new Map<TypeParameter, DartType>.fromIterables(
supertype.classNode.typeParameters, supertype.typeArguments));
}
/// Substitutes the type parameters on the class of [type] with the
/// type arguments provided in [type].
static Substitution fromInterfaceType(InterfaceType type) {
if (type.typeArguments.isEmpty) return _NullSubstitution.instance;
return fromMap(new Map<TypeParameter, DartType>.fromIterables(
type.classNode.typeParameters, type.typeArguments));
}
/// Substitutes the type parameters on the typedef of [type] with the
/// type arguments provided in [type].
static Substitution fromTypedefType(TypedefType type) {
if (type.typeArguments.isEmpty) return _NullSubstitution.instance;
return fromMap(new Map<TypeParameter, DartType>.fromIterables(
type.typedefNode.typeParameters, type.typeArguments));
}
/// Substitutes the Nth parameter in [parameters] with the Nth type in
/// [types].
static Substitution fromPairs(
List<TypeParameter> parameters, List<DartType> types) {
// TODO(asgerf): Investigate if it is more efficient to implement
// substitution based on parallel pairwise lists instead of Maps.
assert(parameters.length == types.length);
if (parameters.isEmpty) return _NullSubstitution.instance;
return fromMap(
new Map<TypeParameter, DartType>.fromIterables(parameters, types));
}
/// Substitutes the type parameters on the class with bottom or dynamic,
/// depending on the covariance of its use.
static Substitution bottomForClass(Class class_) {
if (class_.typeParameters.isEmpty) return _NullSubstitution.instance;
return new _ClassBottomSubstitution(class_);
}
/// Substitutes covariant uses of [class_]'s type parameters with the upper
/// bound of that type parameter. Recursive references in the bound have
/// been replaced by dynamic.
static Substitution upperBoundForClass(Class class_) {
if (class_.typeParameters.isEmpty) return _NullSubstitution.instance;
var upper = <TypeParameter, DartType>{};
for (var parameter in class_.typeParameters) {
upper[parameter] = const DynamicType();
}
for (var parameter in class_.typeParameters) {
upper[parameter] = substitute(parameter.bound, upper);
}
return fromUpperAndLowerBounds(upper, {});
}
/// Substitutes both variables from [first] and [second], favoring those from
/// [first] if they overlap.
///
/// Neither substitution is applied to the results of the other, so this does
/// *not* correspond to a sequence of two substitutions. For example,
/// combining `{T -> List<G>}` with `{G -> String}` does not correspond to
/// `{T -> List<String>}` because the result from substituting `T` is not
/// searched for occurences of `G`.
static Substitution combine(Substitution first, Substitution second) {
if (first == _NullSubstitution.instance) return second;
if (second == _NullSubstitution.instance) return first;
return new _CombinedSubstitution(first, second);
}
DartType getSubstitute(TypeParameter parameter, bool upperBound);
DartType substituteType(DartType node, {bool contravariant: false}) {
return new _TopSubstitutor(this, contravariant).visit(node);
}
Supertype substituteSupertype(Supertype node) {
return new _TopSubstitutor(this, false).visitSupertype(node);
}
}
class _NullSubstitution extends Substitution {
static const _NullSubstitution instance = const _NullSubstitution();
const _NullSubstitution();
DartType getSubstitute(TypeParameter parameter, bool upperBound) {
return new TypeParameterType(parameter);
}
@override
DartType substituteType(DartType node, {bool contravariant: false}) => node;
@override
Supertype substituteSupertype(Supertype node) => node;
@override
String toString() => "Substitution.empty";
}
class _MapSubstitution extends Substitution {
final Map<TypeParameter, DartType> upper;
final Map<TypeParameter, DartType> lower;
_MapSubstitution(this.upper, this.lower);
DartType getSubstitute(TypeParameter parameter, bool upperBound) {
return upperBound ? upper[parameter] : lower[parameter];
}
@override
String toString() => "_MapSubstitution($upper, $lower)";
}
class _TopSubstitutor extends _TypeSubstitutor {
final Substitution substitution;
_TopSubstitutor(this.substitution, bool contravariant) : super(null) {
if (contravariant) {
invertVariance();
}
}
DartType lookup(TypeParameter parameter, bool upperBound) {
return substitution.getSubstitute(parameter, upperBound);
}
TypeParameter freshTypeParameter(TypeParameter node) {
throw 'Create a fresh environment first';
}
}
class _ClassBottomSubstitution extends Substitution {
final Class class_;
_ClassBottomSubstitution(this.class_);
DartType getSubstitute(TypeParameter parameter, bool upperBound) {
if (parameter.parent == class_) {
return upperBound ? const BottomType() : const DynamicType();
}
return null;
}
}
class _CombinedSubstitution extends Substitution {
final Substitution first, second;
_CombinedSubstitution(this.first, this.second);
DartType getSubstitute(TypeParameter parameter, bool upperBound) {
return first.getSubstitute(parameter, upperBound) ??
second.getSubstitute(parameter, upperBound);
}
}
typedef bool TypeParameterFilter(TypeParameter P);
class _FilteredSubstitution extends Substitution {
final Substitution base;
final TypeParameterFilter filterFn;
_FilteredSubstitution(this.base, this.filterFn);
DartType getSubstitute(TypeParameter parameter, bool upperBound) {
return filterFn(parameter)
? base.getSubstitute(parameter, upperBound)
: _NullSubstitution.instance.getSubstitute(parameter, upperBound);
}
}
class _InnerTypeSubstitutor extends _TypeSubstitutor {
final Map<TypeParameter, DartType> substitution = <TypeParameter, DartType>{};
_InnerTypeSubstitutor(_TypeSubstitutor outer) : super(outer);
DartType lookup(TypeParameter parameter, bool upperBound) {
return substitution[parameter];
}
TypeParameter freshTypeParameter(TypeParameter node) {
var fresh = new TypeParameter(node.name);
substitution[node] = new TypeParameterType(fresh);
fresh.bound = visit(node.bound);
if (node.defaultType != null) {
fresh.defaultType = visit(node.defaultType);
}
return fresh;
}
}
abstract class _TypeSubstitutor extends DartTypeVisitor<DartType> {
final _TypeSubstitutor outer;
bool covariantContext = true;
_TypeSubstitutor(this.outer) {
covariantContext = outer == null ? true : outer.covariantContext;
}
DartType lookup(TypeParameter parameter, bool upperBound);
/// The number of times a variable from this environment has been used in
/// a substitution.
///
/// There is a strict requirement that we must return the same instance for
/// types that were not altered by the substitution. This counter lets us
/// check quickly if anything happened in a substitution.
int useCounter = 0;
_InnerTypeSubstitutor newInnerEnvironment() {
return new _InnerTypeSubstitutor(this);
}
void invertVariance() {
covariantContext = !covariantContext;
}
Supertype visitSupertype(Supertype node) {
if (node.typeArguments.isEmpty) return node;
int before = useCounter;
var typeArguments = node.typeArguments.map(visit).toList();
if (useCounter == before) return node;
return new Supertype(node.classNode, typeArguments);
}
NamedType visitNamedType(NamedType node) {
int before = useCounter;
var type = visit(node.type);
if (useCounter == before) return node;
return new NamedType(node.name, type, isRequired: node.isRequired);
}
DartType visit(DartType node) => node.accept(this);
DartType visitInvalidType(InvalidType node) => node;
DartType visitDynamicType(DynamicType node) => node;
DartType visitVoidType(VoidType node) => node;
DartType visitBottomType(BottomType node) => node;
DartType visitInterfaceType(InterfaceType node) {
if (node.typeArguments.isEmpty) return node;
int before = useCounter;
var typeArguments = node.typeArguments.map(visit).toList();
if (useCounter == before) return node;
return new InterfaceType(node.classNode, typeArguments, node.nullability);
}
DartType visitTypedefType(TypedefType node) {
if (node.typeArguments.isEmpty) return node;
int before = useCounter;
var typeArguments = node.typeArguments.map(visit).toList();
if (useCounter == before) return node;
return new TypedefType(node.typedefNode, typeArguments, node.nullability);
}
List<TypeParameter> freshTypeParameters(List<TypeParameter> parameters) {
if (parameters.isEmpty) return const <TypeParameter>[];
return parameters.map(freshTypeParameter).toList();
}
TypeParameter freshTypeParameter(TypeParameter node);
DartType visitFunctionType(FunctionType node) {
// This is a bit tricky because we have to generate fresh type parameters
// in order to change the bounds. At the same time, if the function type
// was unaltered, we have to return the [node] object (not a copy!).
// Substituting a type for a fresh type variable should not be confused with
// a "real" substitution.
//
// Create an inner environment to generate fresh type parameters. The use
// counter on the inner environment tells if the fresh type parameters have
// any uses, but does not tell if the resulting function type is distinct.
// Our own use counter will get incremented if something from our
// environment has been used inside the function.
assert(
node.typeParameters.every((TypeParameter parameter) =>
lookup(parameter, true) == null &&
lookup(parameter, false) == null),
"Function type variables cannot be substituted while still attached "
"to the function. Perform substitution on "
"`FunctionType.withoutTypeParameters` instead.");
var inner = node.typeParameters.isEmpty ? this : newInnerEnvironment();
int before = this.useCounter;
// Invert the variance when translating parameters.
inner.invertVariance();
var typeParameters = inner.freshTypeParameters(node.typeParameters);
var positionalParameters = node.positionalParameters.isEmpty
? const <DartType>[]
: node.positionalParameters.map(inner.visit).toList();
var namedParameters = node.namedParameters.isEmpty
? const <NamedType>[]
: node.namedParameters.map(inner.visitNamedType).toList();
inner.invertVariance();
var returnType = inner.visit(node.returnType);
DartType typedefType =
node.typedefType == null ? null : inner.visit(node.typedefType);
if (this.useCounter == before) return node;
return new FunctionType(positionalParameters, returnType,
namedParameters: namedParameters,
typeParameters: typeParameters,
requiredParameterCount: node.requiredParameterCount,
typedefType: typedefType,
nullability: node.nullability);
}
void bumpCountersUntil(_TypeSubstitutor target) {
var node = this;
while (node != target) {
++node.useCounter;
node = node.outer;
}
++target.useCounter;
}
DartType getSubstitute(TypeParameter variable) {
var environment = this;
while (environment != null) {
DartType replacement = environment.lookup(variable, covariantContext);
if (replacement != null) {
bumpCountersUntil(environment);
return replacement;
}
environment = environment.outer;
}
return null;
}
/// Combines nullabilities of types during type substitution.
///
/// In a type substitution, for example, when `int` is substituted for `T` in
/// `List<T?>`, the nullability of the occurrence of the type parameter should
/// be combined with the nullability of the type that is being substituted for
/// that type parameter. In the example above it's the nullability of `T?`
/// and `int`. The function computes the nullability for the replacement as
/// per the following table:
///
/// | arg \ var | ! | ? | * | % |
/// |-----------|-----|-----|-----|-----|
/// | ! | ! | ? | * | ! |
/// | ? | N/A | ? | ? | ? |
/// | * | * | ? | * | * |
/// | % | N/A | ? | * | % |
///
/// Here `!` denotes `Nullability.nonNullable`, `?` denotes
/// `Nullability.nullable`, `*` denotes `Nullability.legacy`, and `%` denotes
/// `Nullability.neither`. The table elements marked with N/A denote the
/// cases that should yield a type error before the substitution is performed.
static Nullability combineNullabilitiesForSubstitution(
Nullability a, Nullability b) {
// In the table above we may extend the function given by it, replacing N/A
// with whatever is easier to implement. In this implementation, we extend
// the table function as follows:
//
// | arg \ var | ! | ? | * | % |
// |-----------|-----|-----|-----|-----|
// | ! | ! | ? | * | ! |
// | ? | ? | ? | ? | ? |
// | * | * | ? | * | * |
// | % | % | ? | * | % |
//
if (a == Nullability.nullable || b == Nullability.nullable) {
return Nullability.nullable;
}
if (a == Nullability.legacy || b == Nullability.legacy) {
return Nullability.legacy;
}
return a;
}
DartType visitTypeParameterType(TypeParameterType node) {
DartType replacement = getSubstitute(node.parameter);
if (replacement is InvalidType) return replacement;
if (replacement != null) {
return replacement.withNullability(combineNullabilitiesForSubstitution(
replacement.nullability, node.nullability));
}
return node;
}
}
class _DeepTypeSubstitutor extends _InnerTypeSubstitutor {
int depth = 0;
bool isInfinite = false;
_DeepTypeSubstitutor(Map<TypeParameter, DartType> substitution,
[_DeepTypeSubstitutor outer])
: super(outer) {
this.substitution.addAll(substitution);
}
@override
_DeepTypeSubstitutor newInnerEnvironment() {
return new _DeepTypeSubstitutor(<TypeParameter, DartType>{}, this);
}
@override
DartType visitTypeParameterType(TypeParameterType node) {
DartType replacement = getSubstitute(node.parameter);
if (replacement == null) return node;
if (isInfinite) return replacement;
++depth;
if (depth > substitution.length) {
isInfinite = true;
--depth;
return replacement;
} else {
replacement = visit(replacement);
// Update type to the fully fleshed-out type.
substitution[node.parameter] = replacement;
--depth;
return replacement;
}
}
}
class _TypeUnification {
// Acyclic invariant: There are no cycles in the map, that is, all types can
// be resolved to finite types by substituting all contained type variables.
//
// The acyclic invariant holds everywhere except during cycle detection.
//
// It is not checked that the substitution satisfies the bound on the type
// parameter.
final Map<TypeParameter, DartType> substitution = <TypeParameter, DartType>{};
/// Variables that may be assigned freely in order to obtain unification.
///
/// These are sometimes referred to as existentially quantified variables.
final Set<TypeParameter> quantifiedVariables;
/// Variables that are bound by a function type inside one of the types.
/// These may not occur in a substitution, because these variables are not in
/// scope at the existentially quantified variables.
///
/// For example, suppose we are trying to satisfy the equation:
///
/// ∃S. <E>(E, S) => E = <E>(E, E) => E
///
/// That is, we must choose `S` such that the generic function type
/// `<E>(E, S) => E` becomes `<E>(E, E) => E`. Choosing `S = E` is not a
/// valid solution, because `E` is not in scope where `S` is quantified.
/// The two function types cannot be unified.
final Set<TypeParameter> _universallyQuantifiedVariables =
new Set<TypeParameter>();
bool success = true;
_TypeUnification(DartType type1, DartType type2, this.quantifiedVariables) {
_unify(type1, type2);
if (success && substitution.length >= 2) {
for (var key in substitution.keys) {
substitution[key] = substituteDeep(substitution[key], substitution);
}
}
}
DartType _substituteHead(TypeParameterType type) {
for (int i = 0; i <= substitution.length; ++i) {
DartType nextType = substitution[type.parameter];
if (nextType == null) return type;
if (nextType is TypeParameterType) {
type = nextType;
} else {
return nextType;
}
}
// The cycle should have been found by _trySubstitution when the cycle
// was created.
throw 'Unexpected cycle found during unification';
}
bool _unify(DartType type1, DartType type2) {
if (!success) return false;
type1 = type1 is TypeParameterType ? _substituteHead(type1) : type1;
type2 = type2 is TypeParameterType ? _substituteHead(type2) : type2;
if (type1 is DynamicType && type2 is DynamicType) return true;
if (type1 is VoidType && type2 is VoidType) return true;
if (type1 is InvalidType && type2 is InvalidType) return true;
if (type1 is BottomType && type2 is BottomType) return true;
if (type1 is InterfaceType && type2 is InterfaceType) {
if (type1.classNode != type2.classNode) return _fail();
assert(type1.typeArguments.length == type2.typeArguments.length);
for (int i = 0; i < type1.typeArguments.length; ++i) {
if (!_unify(type1.typeArguments[i], type2.typeArguments[i])) {
return false;
}
}
return true;
}
if (type1 is FunctionType && type2 is FunctionType) {
if (type1.typeParameters.length != type2.typeParameters.length ||
type1.positionalParameters.length !=
type2.positionalParameters.length ||
type1.namedParameters.length != type2.namedParameters.length ||
type1.requiredParameterCount != type2.requiredParameterCount) {
return _fail();
}
// When unifying two generic functions, transform the equation like this:
//
// ∃S. <E>(fn1) = <T>(fn2)
// ==>
// ∃S. ∀G. fn1[G/E] = fn2[G/T]
//
// That is, assume some fixed identical choice of type parameters for both
// functions and try to unify the instantiated function types.
assert(!type1.typeParameters.any(quantifiedVariables.contains));
assert(!type2.typeParameters.any(quantifiedVariables.contains));
var leftInstance = <TypeParameter, DartType>{};
var rightInstance = <TypeParameter, DartType>{};
for (int i = 0; i < type1.typeParameters.length; ++i) {
var instantiator = new TypeParameter(type1.typeParameters[i].name);
var instantiatorType = new TypeParameterType(instantiator);
leftInstance[type1.typeParameters[i]] = instantiatorType;
rightInstance[type2.typeParameters[i]] = instantiatorType;
_universallyQuantifiedVariables.add(instantiator);
}
for (int i = 0; i < type1.typeParameters.length; ++i) {
var left = substitute(type1.typeParameters[i].bound, leftInstance);
var right = substitute(type2.typeParameters[i].bound, rightInstance);
if (!_unify(left, right)) return false;
}
for (int i = 0; i < type1.positionalParameters.length; ++i) {
var left = substitute(type1.positionalParameters[i], leftInstance);
var right = substitute(type2.positionalParameters[i], rightInstance);
if (!_unify(left, right)) return false;
}
for (int i = 0; i < type1.namedParameters.length; ++i) {
if (type1.namedParameters[i].name != type2.namedParameters[i].name) {
return false;
}
var left = substitute(type1.namedParameters[i].type, leftInstance);
var right = substitute(type2.namedParameters[i].type, rightInstance);
if (!_unify(left, right)) return false;
}
var leftReturn = substitute(type1.returnType, leftInstance);
var rightReturn = substitute(type2.returnType, rightInstance);
if (!_unify(leftReturn, rightReturn)) return false;
return true;
}
if (type1 is TypeParameterType &&
type2 is TypeParameterType &&
type1.parameter == type2.parameter) {
return true;
}
if (type1 is TypeParameterType &&
quantifiedVariables.contains(type1.parameter)) {
return _trySubstitution(type1.parameter, type2);
}
if (type2 is TypeParameterType &&
quantifiedVariables.contains(type2.parameter)) {
return _trySubstitution(type2.parameter, type1);
}
return _fail();
}
bool _trySubstitution(TypeParameter variable, DartType type) {
if (containsTypeVariable(type, _universallyQuantifiedVariables)) {
return _fail();
}
// Set the plain substitution first and then generate the deep
// substitution to detect cycles.
substitution[variable] = type;
DartType deepSubstitute = substituteDeep(type, substitution);
if (deepSubstitute == null) return _fail();
substitution[variable] = deepSubstitute;
return true;
}
bool _fail() {
return success = false;
}
}
class _OccurrenceVisitor implements DartTypeVisitor<bool> {
final Set<TypeParameter> variables;
_OccurrenceVisitor(this.variables);
bool visit(DartType node) => node.accept(this);
bool visitNamedType(NamedType node) {
return visit(node.type);
}
bool defaultDartType(DartType node) {
throw new UnsupportedError("Unsupported type $node (${node.runtimeType}.");
}
bool visitBottomType(BottomType node) => false;
bool visitInvalidType(InvalidType node) => false;
bool visitDynamicType(DynamicType node) => false;
bool visitVoidType(VoidType node) => false;
bool visitInterfaceType(InterfaceType node) {
return node.typeArguments.any(visit);
}
bool visitTypedefType(TypedefType node) {
return node.typeArguments.any(visit);
}
bool visitFunctionType(FunctionType node) {
return node.typeParameters.any(handleTypeParameter) ||
node.positionalParameters.any(visit) ||
node.namedParameters.any(visitNamedType) ||
visit(node.returnType);
}
bool visitTypeParameterType(TypeParameterType node) {
return variables == null || variables.contains(node.parameter);
}
bool handleTypeParameter(TypeParameter node) {
assert(!variables.contains(node));
if (node.bound.accept(this)) return true;
if (node.defaultType == null) return false;
return node.defaultType.accept(this);
}
}
class _FreeFunctionTypeVariableVisitor implements DartTypeVisitor<bool> {
final Set<TypeParameter> variables = new Set<TypeParameter>();
_FreeFunctionTypeVariableVisitor();
bool visit(DartType node) => node.accept(this);
bool defaultDartType(DartType node) {
throw new UnsupportedError("Unsupported type $node (${node.runtimeType}.");
}
bool visitNamedType(NamedType node) {
return visit(node.type);
}
bool visitBottomType(BottomType node) => false;
bool visitInvalidType(InvalidType node) => false;
bool visitDynamicType(DynamicType node) => false;
bool visitVoidType(VoidType node) => false;
bool visitInterfaceType(InterfaceType node) {
return node.typeArguments.any(visit);
}
bool visitTypedefType(TypedefType node) {
return node.typeArguments.any(visit);
}
bool visitFunctionType(FunctionType node) {
variables.addAll(node.typeParameters);
bool result = node.typeParameters.any(handleTypeParameter) ||
node.positionalParameters.any(visit) ||
node.namedParameters.any(visitNamedType) ||
visit(node.returnType);
variables.removeAll(node.typeParameters);
return result;
}
bool visitTypeParameterType(TypeParameterType node) {
return node.parameter.parent == null && !variables.contains(node.parameter);
}
bool handleTypeParameter(TypeParameter node) {
assert(variables.contains(node));
if (node.bound.accept(this)) return true;
if (node.defaultType == null) return false;
return node.defaultType.accept(this);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/core_types.dart | // 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.
library kernel.core_types;
import 'ast.dart';
import 'library_index.dart';
/// Provides access to the classes and libraries in the core libraries.
class CoreTypes {
static final Map<String, List<String>> requiredClasses = {
'dart:core': [
'Object',
'Null',
'bool',
'int',
'num',
'double',
'String',
'List',
'Map',
'Iterable',
'Iterator',
'Symbol',
'Type',
'Function',
'Invocation',
'FallThroughError',
],
'dart:_internal': [
'Symbol',
],
'dart:async': [
'Future',
'Stream',
]
};
final LibraryIndex index;
Library _coreLibrary;
Class _objectClass;
Class _nullClass;
Class _boolClass;
Class _intClass;
Class _numClass;
Class _doubleClass;
Class _stringClass;
Class _listClass;
Class _setClass;
Class _mapClass;
Class _iterableClass;
Class _iteratorClass;
Class _symbolClass;
Class _typeClass;
Class _functionClass;
Class _invocationClass;
Class _invocationMirrorClass;
Constructor _invocationMirrorWithTypeConstructor;
Constructor _noSuchMethodErrorDefaultConstructor;
Procedure _listFromConstructor;
Procedure _listUnmodifiableConstructor;
Procedure _identicalProcedure;
Constructor _fallThroughErrorUrlAndLineConstructor;
Procedure _objectEquals;
Procedure _mapUnmodifiable;
Class _internalSymbolClass;
Library _asyncLibrary;
Class _futureClass;
Class _stackTraceClass;
Class _streamClass;
Class _asyncAwaitCompleterClass;
Class _futureOrClass;
Constructor _asyncAwaitCompleterConstructor;
Procedure _completeOnAsyncReturnProcedure;
Procedure _completerCompleteError;
Constructor _syncIterableDefaultConstructor;
Constructor _streamIteratorDefaultConstructor;
Constructor _asyncStarStreamControllerDefaultConstructor;
Procedure _asyncStarListenHelperProcedure;
Procedure _asyncStarMoveNextHelperProcedure;
Procedure _asyncStackTraceHelperProcedure;
Procedure _asyncThenWrapperHelperProcedure;
Procedure _asyncErrorWrapperHelperProcedure;
Procedure _awaitHelperProcedure;
Procedure _boolFromEnvironment;
/// The `dart:mirrors` library, or `null` if the component does not use it.
Library _mirrorsLibrary;
Class _pragmaClass;
Field _pragmaName;
Field _pragmaOptions;
Constructor _pragmaConstructor;
InterfaceType _objectLegacyRawType;
InterfaceType _objectNullableRawType;
InterfaceType _objectNonNullableRawType;
InterfaceType _nullType;
InterfaceType _boolLegacyRawType;
InterfaceType _boolNullableRawType;
InterfaceType _boolNonNullableRawType;
InterfaceType _intLegacyRawType;
InterfaceType _intNullableRawType;
InterfaceType _intNonNullableRawType;
InterfaceType _numLegacyRawType;
InterfaceType _numNullableRawType;
InterfaceType _numNonNullableRawType;
InterfaceType _doubleLegacyRawType;
InterfaceType _doubleNullableRawType;
InterfaceType _doubleNonNullableRawType;
InterfaceType _stringLegacyRawType;
InterfaceType _stringNullableRawType;
InterfaceType _stringNonNullableRawType;
InterfaceType _listLegacyRawType;
InterfaceType _listNullableRawType;
InterfaceType _listNonNullableRawType;
InterfaceType _setLegacyRawType;
InterfaceType _setNullableRawType;
InterfaceType _setNonNullableRawType;
InterfaceType _mapLegacyRawType;
InterfaceType _mapNullableRawType;
InterfaceType _mapNonNullableRawType;
InterfaceType _iterableLegacyRawType;
InterfaceType _iterableNullableRawType;
InterfaceType _iterableNonNullableRawType;
InterfaceType _iteratorLegacyRawType;
InterfaceType _iteratorNullableRawType;
InterfaceType _iteratorNonNullableRawType;
InterfaceType _symbolLegacyRawType;
InterfaceType _symbolNullableRawType;
InterfaceType _symbolNonNullableRawType;
InterfaceType _typeLegacyRawType;
InterfaceType _typeNullableRawType;
InterfaceType _typeNonNullableRawType;
InterfaceType _functionLegacyRawType;
InterfaceType _functionNullableRawType;
InterfaceType _functionNonNullableRawType;
InterfaceType _invocationLegacyRawType;
InterfaceType _invocationNullableRawType;
InterfaceType _invocationNonNullableRawType;
InterfaceType _invocationMirrorLegacyRawType;
InterfaceType _invocationMirrorNullableRawType;
InterfaceType _invocationMirrorNonNullableRawType;
InterfaceType _futureLegacyRawType;
InterfaceType _futureNullableRawType;
InterfaceType _futureNonNullableRawType;
InterfaceType _stackTraceLegacyRawType;
InterfaceType _stackTraceNullableRawType;
InterfaceType _stackTraceNonNullableRawType;
InterfaceType _streamLegacyRawType;
InterfaceType _streamNullableRawType;
InterfaceType _streamNonNullableRawType;
InterfaceType _asyncAwaitCompleterLegacyRawType;
InterfaceType _asyncAwaitCompleterNullableRawType;
InterfaceType _asyncAwaitCompleterNonNullableRawType;
InterfaceType _futureOrLegacyRawType;
InterfaceType _futureOrNullableRawType;
InterfaceType _futureOrNonNullableRawType;
InterfaceType _pragmaLegacyRawType;
InterfaceType _pragmaNullableRawType;
InterfaceType _pragmaNonNullableRawType;
final Map<Class, InterfaceType> _legacyRawTypes =
new Map<Class, InterfaceType>.identity();
final Map<Class, InterfaceType> _nullableRawTypes =
new Map<Class, InterfaceType>.identity();
final Map<Class, InterfaceType> _nonNullableRawTypes =
new Map<Class, InterfaceType>.identity();
CoreTypes(Component component)
: index = new LibraryIndex.coreLibraries(component);
Procedure get asyncErrorWrapperHelperProcedure {
return _asyncErrorWrapperHelperProcedure ??=
index.getTopLevelMember('dart:async', '_asyncErrorWrapperHelper');
}
Library get asyncLibrary {
return _asyncLibrary ??= index.getLibrary('dart:async');
}
Member get asyncStarStreamControllerAdd {
return index.getMember('dart:async', '_AsyncStarStreamController', 'add');
}
Member get asyncStarStreamControllerAddError {
return index.getMember(
'dart:async', '_AsyncStarStreamController', 'addError');
}
Member get asyncStarStreamControllerAddStream {
return index.getMember(
'dart:async', '_AsyncStarStreamController', 'addStream');
}
Class get asyncStarStreamControllerClass {
return index.getClass('dart:async', '_AsyncStarStreamController');
}
Member get asyncStarStreamControllerClose {
return index.getMember('dart:async', '_AsyncStarStreamController', 'close');
}
Constructor get asyncStarStreamControllerDefaultConstructor {
return _asyncStarStreamControllerDefaultConstructor ??=
index.getMember('dart:async', '_AsyncStarStreamController', '');
}
Member get asyncStarStreamControllerStream {
return index.getMember(
'dart:async', '_AsyncStarStreamController', 'get:stream');
}
Procedure get asyncStarListenHelper {
return _asyncStarListenHelperProcedure ??=
index.getTopLevelMember('dart:async', '_asyncStarListenHelper');
}
Procedure get asyncStarMoveNextHelper {
return _asyncStarMoveNextHelperProcedure ??=
index.getTopLevelMember('dart:async', '_asyncStarMoveNextHelper');
}
Procedure get asyncStackTraceHelperProcedure {
return _asyncStackTraceHelperProcedure ??=
index.getTopLevelMember('dart:async', '_asyncStackTraceHelper');
}
Procedure get asyncThenWrapperHelperProcedure {
return _asyncThenWrapperHelperProcedure ??=
index.getTopLevelMember('dart:async', '_asyncThenWrapperHelper');
}
Procedure get awaitHelperProcedure {
return _awaitHelperProcedure ??=
index.getTopLevelMember('dart:async', '_awaitHelper');
}
Class get boolClass {
return _boolClass ??= index.getClass('dart:core', 'bool');
}
Class get asyncAwaitCompleterClass {
return _asyncAwaitCompleterClass ??=
index.getClass('dart:async', '_AsyncAwaitCompleter');
}
Constructor get asyncAwaitCompleterConstructor {
return _asyncAwaitCompleterConstructor ??=
index.getMember('dart:async', '_AsyncAwaitCompleter', '');
}
Member get completeOnAsyncReturn {
return _completeOnAsyncReturnProcedure ??=
index.getTopLevelMember('dart:async', '_completeOnAsyncReturn');
}
Procedure get completerCompleteError {
return _completerCompleteError ??=
index.getMember('dart:async', 'Completer', 'completeError');
}
Member get completerFuture {
return index.getMember('dart:async', 'Completer', 'get:future');
}
Library get coreLibrary {
return _coreLibrary ??= index.getLibrary('dart:core');
}
Class get doubleClass {
return _doubleClass ??= index.getClass('dart:core', 'double');
}
Class get functionClass {
return _functionClass ??= index.getClass('dart:core', 'Function');
}
Class get futureClass {
return _futureClass ??= index.getClass('dart:core', 'Future');
}
Class get futureOrClass {
return _futureOrClass ??= (index.tryGetClass('dart:core', 'FutureOr') ??
index.getClass('dart:async', 'FutureOr'));
}
Procedure get identicalProcedure {
return _identicalProcedure ??=
index.getTopLevelMember('dart:core', 'identical');
}
Class get intClass {
return _intClass ??= index.getClass('dart:core', 'int');
}
Class get internalSymbolClass {
return _internalSymbolClass ??= index.getClass('dart:_internal', 'Symbol');
}
Class get invocationClass {
return _invocationClass ??= index.getClass('dart:core', 'Invocation');
}
Class get invocationMirrorClass {
return _invocationMirrorClass ??=
index.getClass('dart:core', '_InvocationMirror');
}
Constructor get invocationMirrorWithTypeConstructor {
return _invocationMirrorWithTypeConstructor ??=
index.getMember('dart:core', '_InvocationMirror', '_withType');
}
Class get iterableClass {
return _iterableClass ??= index.getClass('dart:core', 'Iterable');
}
Class get iteratorClass {
return _iteratorClass ??= index.getClass('dart:core', 'Iterator');
}
Class get listClass {
return _listClass ??= index.getClass('dart:core', 'List');
}
Procedure get listFromConstructor {
return _listFromConstructor ??=
index.getMember('dart:core', 'List', 'from');
}
Procedure get listUnmodifiableConstructor {
return _listUnmodifiableConstructor ??=
index.getMember('dart:core', 'List', 'unmodifiable');
}
Class get setClass {
return _setClass ??= index.getClass('dart:core', 'Set');
}
Class get mapClass {
return _mapClass ??= index.getClass('dart:core', 'Map');
}
Procedure get mapUnmodifiable {
return _mapUnmodifiable ??=
index.getMember('dart:core', 'Map', 'unmodifiable');
}
Library get mirrorsLibrary {
return _mirrorsLibrary ??= index.tryGetLibrary('dart:mirrors');
}
Constructor get noSuchMethodErrorDefaultConstructor {
return _noSuchMethodErrorDefaultConstructor ??=
// TODO(regis): Replace 'withInvocation' with '' after dart2js is fixed.
index.getMember('dart:core', 'NoSuchMethodError', 'withInvocation');
}
Class get nullClass {
return _nullClass ??= index.getClass('dart:core', 'Null');
}
Class get numClass {
return _numClass ??= index.getClass('dart:core', 'num');
}
Class get objectClass {
return _objectClass ??= index.getClass('dart:core', 'Object');
}
Procedure get objectEquals {
return _objectEquals ??= index.getMember('dart:core', 'Object', '==');
}
Class get pragmaClass {
return _pragmaClass ??= index.getClass('dart:core', 'pragma');
}
Field get pragmaName {
return _pragmaName ??= index.getMember('dart:core', 'pragma', 'name');
}
Field get pragmaOptions {
return _pragmaOptions ??= index.getMember('dart:core', 'pragma', 'options');
}
Constructor get pragmaConstructor {
return _pragmaConstructor ??= index.getMember('dart:core', 'pragma', '_');
}
Class get stackTraceClass {
return _stackTraceClass ??= index.getClass('dart:core', 'StackTrace');
}
Class get streamClass {
return _streamClass ??= index.getClass('dart:core', 'Stream');
}
Member get streamIteratorSubscription {
return index.getMember('dart:async', '_StreamIterator', '_subscription');
}
Member get streamIteratorCancel {
return index.getMember('dart:async', '_StreamIterator', 'cancel');
}
Class get streamIteratorClass {
return index.getClass('dart:async', '_StreamIterator');
}
Constructor get streamIteratorDefaultConstructor {
return _streamIteratorDefaultConstructor ??=
index.getMember('dart:async', '_StreamIterator', '');
}
Member get streamIteratorMoveNext {
return index.getMember('dart:async', '_StreamIterator', 'moveNext');
}
Member get streamIteratorCurrent {
return index.getMember('dart:async', '_StreamIterator', 'get:current');
}
Class get stringClass {
return _stringClass ??= index.getClass('dart:core', 'String');
}
Class get symbolClass {
return _symbolClass ??= index.getClass('dart:core', 'Symbol');
}
Constructor get syncIterableDefaultConstructor {
return _syncIterableDefaultConstructor ??=
index.getMember('dart:core', '_SyncIterable', '');
}
Class get syncIteratorClass {
return index.getClass('dart:core', '_SyncIterator');
}
Member get syncIteratorCurrent {
return index.getMember('dart:core', '_SyncIterator', '_current');
}
Member get syncIteratorYieldEachIterable {
return index.getMember('dart:core', '_SyncIterator', '_yieldEachIterable');
}
Class get typeClass {
return _typeClass ??= index.getClass('dart:core', 'Type');
}
Constructor get fallThroughErrorUrlAndLineConstructor {
return _fallThroughErrorUrlAndLineConstructor ??=
index.getMember('dart:core', 'FallThroughError', '_create');
}
Procedure get boolFromEnvironment {
return _boolFromEnvironment ??=
index.getMember('dart:core', 'bool', 'fromEnvironment');
}
InterfaceType get objectLegacyRawType {
return _objectLegacyRawType ??= _legacyRawTypes[objectClass] ??=
new InterfaceType(objectClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get objectNullableRawType {
return _objectNullableRawType ??= _nullableRawTypes[objectClass] ??=
new InterfaceType(
objectClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get objectNonNullableRawType {
return _objectNonNullableRawType ??= _nonNullableRawTypes[objectClass] ??=
new InterfaceType(
objectClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType objectRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return objectLegacyRawType;
case Nullability.nullable:
return objectNullableRawType;
case Nullability.nonNullable:
return objectNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
/// Null is always nullable, so there's only one raw type for that class.
InterfaceType get nullType {
return _nullType ??= _nullableRawTypes[nullClass] ??=
new InterfaceType(nullClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get boolLegacyRawType {
return _boolLegacyRawType ??= _legacyRawTypes[boolClass] ??=
new InterfaceType(boolClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get boolNullableRawType {
return _boolNullableRawType ??= _nullableRawTypes[boolClass] ??=
new InterfaceType(boolClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get boolNonNullableRawType {
return _boolNonNullableRawType ??= _nonNullableRawTypes[boolClass] ??=
new InterfaceType(
boolClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType boolRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return boolLegacyRawType;
case Nullability.nullable:
return boolNullableRawType;
case Nullability.nonNullable:
return boolNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get intLegacyRawType {
return _intLegacyRawType ??= _legacyRawTypes[intClass] ??=
new InterfaceType(intClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get intNullableRawType {
return _intNullableRawType ??= _nullableRawTypes[intClass] ??=
new InterfaceType(intClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get intNonNullableRawType {
return _intNonNullableRawType ??= _nonNullableRawTypes[intClass] ??=
new InterfaceType(
intClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType intRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return intLegacyRawType;
case Nullability.nullable:
return intNullableRawType;
case Nullability.nonNullable:
return intNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get numLegacyRawType {
return _numLegacyRawType ??= _legacyRawTypes[numClass] ??=
new InterfaceType(numClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get numNullableRawType {
return _numNullableRawType ??= _nullableRawTypes[numClass] ??=
new InterfaceType(numClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get numNonNullableRawType {
return _numNonNullableRawType ??= _nonNullableRawTypes[numClass] ??=
new InterfaceType(
numClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType numRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return numLegacyRawType;
case Nullability.nullable:
return numNullableRawType;
case Nullability.nonNullable:
return numNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get doubleLegacyRawType {
return _doubleLegacyRawType ??= _legacyRawTypes[doubleClass] ??=
new InterfaceType(doubleClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get doubleNullableRawType {
return _doubleNullableRawType ??= _nullableRawTypes[doubleClass] ??=
new InterfaceType(
doubleClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get doubleNonNullableRawType {
return _doubleNonNullableRawType ??= _nonNullableRawTypes[doubleClass] ??=
new InterfaceType(
doubleClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType doubleRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return doubleLegacyRawType;
case Nullability.nullable:
return doubleNullableRawType;
case Nullability.nonNullable:
return doubleNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get stringLegacyRawType {
return _stringLegacyRawType ??= _legacyRawTypes[stringClass] ??=
new InterfaceType(stringClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get stringNullableRawType {
return _stringNullableRawType ??= _nullableRawTypes[stringClass] ??=
new InterfaceType(
stringClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get stringNonNullableRawType {
return _stringNonNullableRawType ??= _nonNullableRawTypes[stringClass] ??=
new InterfaceType(
stringClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType stringRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return stringLegacyRawType;
case Nullability.nullable:
return stringNullableRawType;
case Nullability.nonNullable:
return stringNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get listLegacyRawType {
return _listLegacyRawType ??= _legacyRawTypes[listClass] ??=
new InterfaceType(listClass, const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get listNullableRawType {
return _listNullableRawType ??= _nullableRawTypes[listClass] ??=
new InterfaceType(listClass, const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get listNonNullableRawType {
return _listNonNullableRawType ??= _nonNullableRawTypes[listClass] ??=
new InterfaceType(listClass, const <DartType>[const DynamicType()],
Nullability.nonNullable);
}
InterfaceType listRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return listLegacyRawType;
case Nullability.nullable:
return listNullableRawType;
case Nullability.nonNullable:
return listNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get setLegacyRawType {
return _setLegacyRawType ??= _legacyRawTypes[setClass] ??=
new InterfaceType(setClass, const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get setNullableRawType {
return _setNullableRawType ??= _nullableRawTypes[setClass] ??=
new InterfaceType(setClass, const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get setNonNullableRawType {
return _setNonNullableRawType ??= _nonNullableRawTypes[setClass] ??=
new InterfaceType(setClass, const <DartType>[const DynamicType()],
Nullability.nonNullable);
}
InterfaceType setRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return setLegacyRawType;
case Nullability.nullable:
return setNullableRawType;
case Nullability.nonNullable:
return setNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get mapLegacyRawType {
return _mapLegacyRawType ??= _legacyRawTypes[mapClass] ??=
new InterfaceType(
mapClass,
const <DartType>[const DynamicType(), const DynamicType()],
Nullability.legacy);
}
InterfaceType get mapNullableRawType {
return _mapNullableRawType ??= _nullableRawTypes[mapClass] ??=
new InterfaceType(
mapClass,
const <DartType>[const DynamicType(), const DynamicType()],
Nullability.nullable);
}
InterfaceType get mapNonNullableRawType {
return _mapNonNullableRawType ??= _nonNullableRawTypes[mapClass] ??=
new InterfaceType(
mapClass,
const <DartType>[const DynamicType(), const DynamicType()],
Nullability.nonNullable);
}
InterfaceType mapRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return mapLegacyRawType;
case Nullability.nullable:
return mapNullableRawType;
case Nullability.nonNullable:
return mapNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get iterableLegacyRawType {
return _iterableLegacyRawType ??= _legacyRawTypes[iterableClass] ??=
new InterfaceType(iterableClass, const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get iterableNullableRawType {
return _iterableNullableRawType ??= _nullableRawTypes[iterableClass] ??=
new InterfaceType(iterableClass, const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get iterableNonNullableRawType {
return _iterableNonNullableRawType ??=
_nonNullableRawTypes[iterableClass] ??= new InterfaceType(iterableClass,
const <DartType>[const DynamicType()], Nullability.nonNullable);
}
InterfaceType iterableRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return iterableLegacyRawType;
case Nullability.nullable:
return iterableNullableRawType;
case Nullability.nonNullable:
return iterableNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get iteratorLegacyRawType {
return _iteratorLegacyRawType ??= _legacyRawTypes[iteratorClass] ??=
new InterfaceType(iteratorClass, const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get iteratorNullableRawType {
return _iteratorNullableRawType ??= _nullableRawTypes[iteratorClass] ??=
new InterfaceType(iteratorClass, const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get iteratorNonNullableRawType {
return _iteratorNonNullableRawType ??=
_nonNullableRawTypes[iteratorClass] ??= new InterfaceType(iteratorClass,
const <DartType>[const DynamicType()], Nullability.nonNullable);
}
InterfaceType iteratorRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return iteratorLegacyRawType;
case Nullability.nullable:
return iteratorNullableRawType;
case Nullability.nonNullable:
return iteratorNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get symbolLegacyRawType {
return _symbolLegacyRawType ??= _legacyRawTypes[symbolClass] ??=
new InterfaceType(symbolClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get symbolNullableRawType {
return _symbolNullableRawType ??= _nullableRawTypes[symbolClass] ??=
new InterfaceType(
symbolClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get symbolNonNullableRawType {
return _symbolNonNullableRawType ??= _nonNullableRawTypes[symbolClass] ??=
new InterfaceType(
symbolClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType symbolRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return symbolLegacyRawType;
case Nullability.nullable:
return symbolNullableRawType;
case Nullability.nonNullable:
return symbolNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get typeLegacyRawType {
return _typeLegacyRawType ??= _legacyRawTypes[typeClass] ??=
new InterfaceType(typeClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get typeNullableRawType {
return _typeNullableRawType ??= _nullableRawTypes[typeClass] ??=
new InterfaceType(typeClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get typeNonNullableRawType {
return _typeNonNullableRawType ??= _nonNullableRawTypes[typeClass] ??=
new InterfaceType(
typeClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType typeRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return typeLegacyRawType;
case Nullability.nullable:
return typeNullableRawType;
case Nullability.nonNullable:
return typeNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get functionLegacyRawType {
return _functionLegacyRawType ??= _legacyRawTypes[functionClass] ??=
new InterfaceType(
functionClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get functionNullableRawType {
return _functionNullableRawType ??= _nullableRawTypes[functionClass] ??=
new InterfaceType(
functionClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get functionNonNullableRawType {
return _functionNonNullableRawType ??=
_nonNullableRawTypes[functionClass] ??= new InterfaceType(
functionClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType functionRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return functionLegacyRawType;
case Nullability.nullable:
return functionNullableRawType;
case Nullability.nonNullable:
return functionNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get invocationLegacyRawType {
return _invocationLegacyRawType ??= _legacyRawTypes[invocationClass] ??=
new InterfaceType(
invocationClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get invocationNullableRawType {
return _invocationNullableRawType ??= _nullableRawTypes[invocationClass] ??=
new InterfaceType(
invocationClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get invocationNonNullableRawType {
return _invocationNonNullableRawType ??=
_nonNullableRawTypes[invocationClass] ??= new InterfaceType(
invocationClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType invocationRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return invocationLegacyRawType;
case Nullability.nullable:
return invocationNullableRawType;
case Nullability.nonNullable:
return invocationNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get invocationMirrorLegacyRawType {
return _invocationMirrorLegacyRawType ??=
_legacyRawTypes[invocationMirrorClass] ??= new InterfaceType(
invocationMirrorClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get invocationMirrorNullableRawType {
return _invocationMirrorNullableRawType ??=
_nullableRawTypes[invocationMirrorClass] ??= new InterfaceType(
invocationMirrorClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get invocationMirrorNonNullableRawType {
return _invocationMirrorNonNullableRawType ??=
_nonNullableRawTypes[invocationMirrorClass] ??= new InterfaceType(
invocationMirrorClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType invocationMirrorRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return invocationMirrorLegacyRawType;
case Nullability.nullable:
return invocationMirrorNullableRawType;
case Nullability.nonNullable:
return invocationMirrorNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get futureLegacyRawType {
return _futureLegacyRawType ??= _legacyRawTypes[futureClass] ??=
new InterfaceType(futureClass, const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get futureNullableRawType {
return _futureNullableRawType ??= _nullableRawTypes[futureClass] ??=
new InterfaceType(futureClass, const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get futureNonNullableRawType {
return _futureNonNullableRawType ??= _nonNullableRawTypes[futureClass] ??=
new InterfaceType(futureClass, const <DartType>[const DynamicType()],
Nullability.nonNullable);
}
InterfaceType futureRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return futureLegacyRawType;
case Nullability.nullable:
return futureNullableRawType;
case Nullability.nonNullable:
return futureNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get stackTraceLegacyRawType {
return _stackTraceLegacyRawType ??= _legacyRawTypes[stackTraceClass] ??=
new InterfaceType(
stackTraceClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get stackTraceNullableRawType {
return _stackTraceNullableRawType ??= _nullableRawTypes[stackTraceClass] ??=
new InterfaceType(
stackTraceClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get stackTraceNonNullableRawType {
return _stackTraceNonNullableRawType ??=
_nonNullableRawTypes[stackTraceClass] ??= new InterfaceType(
stackTraceClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType stackTraceRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return stackTraceLegacyRawType;
case Nullability.nullable:
return stackTraceNullableRawType;
case Nullability.nonNullable:
return stackTraceNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get streamLegacyRawType {
return _streamLegacyRawType ??= _legacyRawTypes[streamClass] ??=
new InterfaceType(streamClass, const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get streamNullableRawType {
return _streamNullableRawType ??= _nullableRawTypes[streamClass] ??=
new InterfaceType(streamClass, const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get streamNonNullableRawType {
return _streamNonNullableRawType ??= _nonNullableRawTypes[streamClass] ??=
new InterfaceType(streamClass, const <DartType>[const DynamicType()],
Nullability.nonNullable);
}
InterfaceType streamRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return streamLegacyRawType;
case Nullability.nullable:
return streamNullableRawType;
case Nullability.nonNullable:
return streamNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get asyncAwaitCompleterLegacyRawType {
return _asyncAwaitCompleterLegacyRawType ??=
_legacyRawTypes[asyncAwaitCompleterClass] ??= new InterfaceType(
asyncAwaitCompleterClass,
const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get asyncAwaitCompleterNullableRawType {
return _asyncAwaitCompleterNullableRawType ??=
_nullableRawTypes[asyncAwaitCompleterClass] ??= new InterfaceType(
asyncAwaitCompleterClass,
const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get asyncAwaitCompleterNonNullableRawType {
return _asyncAwaitCompleterNonNullableRawType ??=
_nonNullableRawTypes[asyncAwaitCompleterClass] ??= new InterfaceType(
asyncAwaitCompleterClass,
const <DartType>[const DynamicType()],
Nullability.nonNullable);
}
InterfaceType asyncAwaitCompleterRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return asyncAwaitCompleterLegacyRawType;
case Nullability.nullable:
return asyncAwaitCompleterNullableRawType;
case Nullability.nonNullable:
return asyncAwaitCompleterNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get futureOrLegacyRawType {
return _futureOrLegacyRawType ??= _legacyRawTypes[futureOrClass] ??=
new InterfaceType(futureOrClass, const <DartType>[const DynamicType()],
Nullability.legacy);
}
InterfaceType get futureOrNullableRawType {
return _futureOrNullableRawType ??= _nullableRawTypes[futureOrClass] ??=
new InterfaceType(futureOrClass, const <DartType>[const DynamicType()],
Nullability.nullable);
}
InterfaceType get futureOrNonNullableRawType {
return _futureOrNonNullableRawType ??=
_nonNullableRawTypes[futureOrClass] ??= new InterfaceType(futureOrClass,
const <DartType>[const DynamicType()], Nullability.nonNullable);
}
InterfaceType futureOrRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return futureOrLegacyRawType;
case Nullability.nullable:
return futureOrNullableRawType;
case Nullability.nonNullable:
return futureOrNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType get pragmaLegacyRawType {
return _pragmaLegacyRawType ??= _legacyRawTypes[pragmaClass] ??=
new InterfaceType(pragmaClass, const <DartType>[], Nullability.legacy);
}
InterfaceType get pragmaNullableRawType {
return _pragmaNullableRawType ??= _nullableRawTypes[pragmaClass] ??=
new InterfaceType(
pragmaClass, const <DartType>[], Nullability.nullable);
}
InterfaceType get pragmaNonNullableRawType {
return _pragmaNonNullableRawType ??= _nonNullableRawTypes[pragmaClass] ??=
new InterfaceType(
pragmaClass, const <DartType>[], Nullability.nonNullable);
}
InterfaceType pragmaRawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return pragmaLegacyRawType;
case Nullability.nullable:
return pragmaNullableRawType;
case Nullability.nonNullable:
return pragmaNonNullableRawType;
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
InterfaceType legacyRawType(Class klass) {
// TODO(dmitryas): Consider using computeBounds instead of DynamicType here.
return _legacyRawTypes[klass] ??= new InterfaceType(
klass,
new List<DartType>.filled(
klass.typeParameters.length, const DynamicType()),
Nullability.legacy);
}
InterfaceType nullableRawType(Class klass) {
// TODO(dmitryas): Consider using computeBounds instead of DynamicType here.
return _nullableRawTypes[klass] ??= new InterfaceType(
klass,
new List<DartType>.filled(
klass.typeParameters.length, const DynamicType()),
Nullability.nullable);
}
InterfaceType nonNullableRawType(Class klass) {
// TODO(dmitryas): Consider using computeBounds instead of DynamicType here.
return _nonNullableRawTypes[klass] ??= new InterfaceType(
klass,
new List<DartType>.filled(
klass.typeParameters.length, const DynamicType()),
Nullability.nonNullable);
}
InterfaceType rawType(Class klass, Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return legacyRawType(klass);
case Nullability.nullable:
return nullableRawType(klass);
case Nullability.nonNullable:
return nonNullableRawType(klass);
case Nullability.neither:
default:
throw new StateError(
"Unsupported nullability $nullability on an InterfaceType.");
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/type_checker.dart | // 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.
library kernel.type_checker;
import 'ast.dart';
import 'class_hierarchy.dart';
import 'core_types.dart';
import 'type_algebra.dart';
import 'type_environment.dart';
/// Performs type checking on the kernel IR.
///
/// A concrete subclass of [TypeChecker] must implement [checkAssignable] and
/// [fail] in order to deal with subtyping requirements and error handling.
abstract class TypeChecker {
final CoreTypes coreTypes;
final ClassHierarchy hierarchy;
final bool ignoreSdk;
TypeEnvironment environment;
TypeChecker(this.coreTypes, this.hierarchy, {this.ignoreSdk: true})
: environment = new TypeEnvironment(coreTypes, hierarchy);
void checkComponent(Component component) {
for (var library in component.libraries) {
if (ignoreSdk && library.importUri.scheme == 'dart') continue;
for (var class_ in library.classes) {
hierarchy.forEachOverridePair(class_,
(Member ownMember, Member superMember, bool isSetter) {
checkOverride(class_, ownMember, superMember, isSetter);
});
}
}
var visitor = new TypeCheckingVisitor(this, environment, hierarchy);
for (var library in component.libraries) {
if (ignoreSdk && library.importUri.scheme == 'dart') continue;
for (var class_ in library.classes) {
environment.thisType = class_.thisType;
for (var field in class_.fields) {
visitor.visitField(field);
}
for (var constructor in class_.constructors) {
visitor.visitConstructor(constructor);
}
for (var procedure in class_.procedures) {
visitor.visitProcedure(procedure);
}
}
environment.thisType = null;
for (var procedure in library.procedures) {
visitor.visitProcedure(procedure);
}
for (var field in library.fields) {
visitor.visitField(field);
}
}
}
DartType getterType(Class host, Member member) {
var hostType = hierarchy.getClassAsInstanceOf(host, member.enclosingClass);
var substitution = Substitution.fromSupertype(hostType);
return substitution.substituteType(member.getterType);
}
DartType setterType(Class host, Member member) {
var hostType = hierarchy.getClassAsInstanceOf(host, member.enclosingClass);
var substitution = Substitution.fromSupertype(hostType);
return substitution.substituteType(member.setterType, contravariant: true);
}
/// Check that [ownMember] of [host] can override [superMember].
void checkOverride(
Class host, Member ownMember, Member superMember, bool isSetter) {
if (isSetter) {
checkAssignable(ownMember, setterType(host, superMember),
setterType(host, ownMember));
} else {
checkAssignable(ownMember, getterType(host, ownMember),
getterType(host, superMember));
}
}
/// Check that [from] is a subtype of [to].
///
/// [where] is an AST node indicating roughly where the check is required.
void checkAssignable(TreeNode where, DartType from, DartType to);
/// Checks that [expression], which has type [from], can be assigned to [to].
///
/// Should return a downcast if necessary, or [expression] if no cast is
/// needed.
Expression checkAndDowncastExpression(
Expression expression, DartType from, DartType to) {
checkAssignable(expression, from, to);
return expression;
}
/// Check unresolved invocation (one that has no interfaceTarget)
/// and report an error if necessary.
void checkUnresolvedInvocation(DartType receiver, TreeNode where) {
// By default we ignore unresolved method invocations.
}
/// Indicates that type checking failed.
void fail(TreeNode where, String message);
}
class TypeCheckingVisitor
implements
ExpressionVisitor<DartType>,
StatementVisitor<Null>,
MemberVisitor<Null>,
InitializerVisitor<Null> {
final TypeChecker checker;
final TypeEnvironment environment;
final ClassHierarchy hierarchy;
CoreTypes get coreTypes => environment.coreTypes;
Class get currentClass => environment.thisType.classNode;
TypeCheckingVisitor(this.checker, this.environment, this.hierarchy);
void checkAssignable(TreeNode where, DartType from, DartType to) {
checker.checkAssignable(where, from, to);
}
void checkUnresolvedInvocation(DartType receiver, TreeNode where) {
checker.checkUnresolvedInvocation(receiver, where);
}
Expression checkAndDowncastExpression(Expression from, DartType to) {
var parent = from.parent;
var type = visitExpression(from);
var result = checker.checkAndDowncastExpression(from, type, to);
result.parent = parent;
return result;
}
void checkExpressionNoDowncast(Expression expression, DartType to) {
checkAssignable(expression, visitExpression(expression), to);
}
void fail(TreeNode node, String message) {
checker.fail(node, message);
}
DartType visitExpression(Expression node) => node.accept(this);
void visitStatement(Statement node) {
node.accept(this);
}
void visitInitializer(Initializer node) {
node.accept(this);
}
defaultMember(Member node) => throw 'Unused';
DartType defaultBasicLiteral(BasicLiteral node) {
return defaultExpression(node);
}
DartType defaultExpression(Expression node) {
throw 'Unexpected expression ${node.runtimeType}';
}
defaultStatement(Statement node) {
throw 'Unexpected statement ${node.runtimeType}';
}
defaultInitializer(Initializer node) {
throw 'Unexpected initializer ${node.runtimeType}';
}
visitField(Field node) {
if (node.initializer != null) {
node.initializer =
checkAndDowncastExpression(node.initializer, node.type);
}
}
visitConstructor(Constructor node) {
environment.returnType = null;
environment.yieldType = null;
node.initializers.forEach(visitInitializer);
handleFunctionNode(node.function);
}
visitProcedure(Procedure node) {
environment.returnType = _getInternalReturnType(node.function);
environment.yieldType = _getYieldType(node.function);
handleFunctionNode(node.function);
}
visitRedirectingFactoryConstructor(RedirectingFactoryConstructor node) {
environment.returnType = null;
environment.yieldType = null;
}
void handleFunctionNode(FunctionNode node) {
var oldAsyncMarker = environment.currentAsyncMarker;
environment.currentAsyncMarker = node.asyncMarker;
node.positionalParameters
.skip(node.requiredParameterCount)
.forEach(handleOptionalParameter);
node.namedParameters.forEach(handleOptionalParameter);
if (node.body != null) {
visitStatement(node.body);
}
environment.currentAsyncMarker = oldAsyncMarker;
}
void handleNestedFunctionNode(FunctionNode node) {
var oldReturn = environment.returnType;
var oldYield = environment.yieldType;
environment.returnType = _getInternalReturnType(node);
environment.yieldType = _getYieldType(node);
handleFunctionNode(node);
environment.returnType = oldReturn;
environment.yieldType = oldYield;
}
void handleOptionalParameter(VariableDeclaration parameter) {
if (parameter.initializer != null) {
// Default parameter values cannot be downcast.
checkExpressionNoDowncast(parameter.initializer, parameter.type);
}
}
Substitution getReceiverType(
TreeNode access, Expression receiver, Member member) {
var type = visitExpression(receiver);
Class superclass = member.enclosingClass;
if (superclass.supertype == null) {
return Substitution.empty; // Members on Object are always accessible.
}
while (type is TypeParameterType) {
type = (type as TypeParameterType).bound;
}
if (type is BottomType) {
// The bottom type is a subtype of all types, so it should be allowed.
return Substitution.bottomForClass(superclass);
}
if (type is InterfaceType) {
// The receiver type should implement the interface declaring the member.
var upcastType = hierarchy.getTypeAsInstanceOf(type, superclass);
if (upcastType != null) {
return Substitution.fromInterfaceType(upcastType);
}
}
if (type is FunctionType && superclass == coreTypes.functionClass) {
assert(type.typeParameters.isEmpty);
return Substitution.empty;
}
// Note that we do not allow 'dynamic' here. Dynamic calls should not
// have a declared interface target.
fail(access, '$member is not accessible on a receiver of type $type');
return Substitution.bottomForClass(superclass); // Continue type checking.
}
Substitution getSuperReceiverType(Member member) {
return Substitution.fromSupertype(
hierarchy.getClassAsInstanceOf(currentClass, member.enclosingClass));
}
DartType handleCall(Arguments arguments, DartType functionType,
{Substitution receiver: Substitution.empty,
List<TypeParameter> typeParameters}) {
if (functionType is FunctionType) {
typeParameters ??= functionType.typeParameters;
if (arguments.positional.length < functionType.requiredParameterCount) {
fail(arguments, 'Too few positional arguments');
return const BottomType();
}
if (arguments.positional.length >
functionType.positionalParameters.length) {
fail(arguments, 'Too many positional arguments');
return const BottomType();
}
var typeArguments = arguments.types;
if (typeArguments.length != typeParameters.length) {
fail(arguments, 'Wrong number of type arguments');
return const BottomType();
}
Substitution substitution = _instantiateFunction(
typeParameters, typeArguments, arguments,
receiverSubstitution: receiver);
for (int i = 0; i < arguments.positional.length; ++i) {
var expectedType = substitution.substituteType(
functionType.positionalParameters[i],
contravariant: true);
arguments.positional[i] =
checkAndDowncastExpression(arguments.positional[i], expectedType);
}
for (int i = 0; i < arguments.named.length; ++i) {
var argument = arguments.named[i];
bool found = false;
for (int j = 0; j < functionType.namedParameters.length; ++j) {
if (argument.name == functionType.namedParameters[j].name) {
var expectedType = substitution.substituteType(
functionType.namedParameters[j].type,
contravariant: true);
argument.value =
checkAndDowncastExpression(argument.value, expectedType);
found = true;
break;
}
}
if (!found) {
fail(argument.value, 'Unexpected named parameter: ${argument.name}');
return const BottomType();
}
}
return substitution.substituteType(functionType.returnType);
} else {
// Note: attempting to resolve .call() on [functionType] could lead to an
// infinite regress, so just assume `dynamic`.
return const DynamicType();
}
}
DartType _getInternalReturnType(FunctionNode function) {
switch (function.asyncMarker) {
case AsyncMarker.Sync:
return function.returnType;
case AsyncMarker.Async:
Class container = coreTypes.futureClass;
DartType returnType = function.returnType;
if (returnType is InterfaceType && returnType.classNode == container) {
return returnType.typeArguments.single;
}
return const DynamicType();
case AsyncMarker.SyncStar:
case AsyncMarker.AsyncStar:
return null;
case AsyncMarker.SyncYielding:
TreeNode parent = function.parent;
while (parent is! FunctionNode) {
parent = parent.parent;
}
final enclosingFunction = parent as FunctionNode;
if (enclosingFunction.dartAsyncMarker == AsyncMarker.SyncStar) {
return coreTypes.boolLegacyRawType;
}
return null;
default:
throw 'Unexpected async marker: ${function.asyncMarker}';
}
}
DartType _getYieldType(FunctionNode function) {
switch (function.asyncMarker) {
case AsyncMarker.Sync:
case AsyncMarker.Async:
return null;
case AsyncMarker.SyncStar:
case AsyncMarker.AsyncStar:
Class container = function.asyncMarker == AsyncMarker.SyncStar
? coreTypes.iterableClass
: coreTypes.streamClass;
DartType returnType = function.returnType;
if (returnType is InterfaceType && returnType.classNode == container) {
return returnType.typeArguments.single;
}
return const DynamicType();
case AsyncMarker.SyncYielding:
return function.returnType;
default:
throw 'Unexpected async marker: ${function.asyncMarker}';
}
}
Substitution _instantiateFunction(List<TypeParameter> typeParameters,
List<DartType> typeArguments, TreeNode where,
{Substitution receiverSubstitution}) {
var instantiation = Substitution.fromPairs(typeParameters, typeArguments);
var substitution = receiverSubstitution == null
? instantiation
: Substitution.combine(receiverSubstitution, instantiation);
for (int i = 0; i < typeParameters.length; ++i) {
var argument = typeArguments[i];
var bound = substitution.substituteType(typeParameters[i].bound);
checkAssignable(where, argument, bound);
}
return substitution;
}
@override
DartType visitAsExpression(AsExpression node) {
visitExpression(node.operand);
return node.type;
}
@override
DartType visitAwaitExpression(AwaitExpression node) {
return environment.unfutureType(visitExpression(node.operand));
}
@override
DartType visitBoolLiteral(BoolLiteral node) {
return environment.coreTypes.boolLegacyRawType;
}
@override
DartType visitConditionalExpression(ConditionalExpression node) {
node.condition = checkAndDowncastExpression(
node.condition, environment.coreTypes.boolLegacyRawType);
node.then = checkAndDowncastExpression(node.then, node.staticType);
node.otherwise =
checkAndDowncastExpression(node.otherwise, node.staticType);
return node.staticType;
}
@override
DartType visitConstructorInvocation(ConstructorInvocation node) {
Constructor target = node.target;
Arguments arguments = node.arguments;
Class class_ = target.enclosingClass;
handleCall(arguments, target.function.thisFunctionType,
typeParameters: class_.typeParameters);
return new InterfaceType(target.enclosingClass, arguments.types);
}
@override
DartType visitDirectMethodInvocation(DirectMethodInvocation node) {
return handleCall(node.arguments, node.target.getterType,
receiver: getReceiverType(node, node.receiver, node.target));
}
@override
DartType visitDirectPropertyGet(DirectPropertyGet node) {
var receiver = getReceiverType(node, node.receiver, node.target);
return receiver.substituteType(node.target.getterType);
}
@override
DartType visitDirectPropertySet(DirectPropertySet node) {
var receiver = getReceiverType(node, node.receiver, node.target);
var value = visitExpression(node.value);
checkAssignable(node, value,
receiver.substituteType(node.target.setterType, contravariant: true));
return value;
}
@override
DartType visitDoubleLiteral(DoubleLiteral node) {
return environment.coreTypes.doubleLegacyRawType;
}
@override
DartType visitFunctionExpression(FunctionExpression node) {
handleNestedFunctionNode(node.function);
return node.function.thisFunctionType;
}
@override
DartType visitIntLiteral(IntLiteral node) {
return environment.coreTypes.intLegacyRawType;
}
@override
DartType visitInvalidExpression(InvalidExpression node) {
return const DynamicType();
}
@override
DartType visitIsExpression(IsExpression node) {
visitExpression(node.operand);
return environment.coreTypes.boolLegacyRawType;
}
@override
DartType visitLet(Let node) {
var value = visitExpression(node.variable.initializer);
if (node.variable.type is DynamicType) {
node.variable.type = value;
}
return visitExpression(node.body);
}
@override
DartType visitBlockExpression(BlockExpression node) {
visitStatement(node.body);
return visitExpression(node.value);
}
@override
DartType visitInstantiation(Instantiation node) {
DartType type = visitExpression(node.expression);
if (type is! FunctionType) {
fail(node, 'Not a function type: $type');
return const BottomType();
}
FunctionType functionType = type;
if (functionType.typeParameters.length != node.typeArguments.length) {
fail(node, 'Wrong number of type arguments');
return const BottomType();
}
return _instantiateFunction(
functionType.typeParameters, node.typeArguments, node)
.substituteType(functionType.withoutTypeParameters);
}
@override
DartType visitListLiteral(ListLiteral node) {
for (int i = 0; i < node.expressions.length; ++i) {
node.expressions[i] =
checkAndDowncastExpression(node.expressions[i], node.typeArgument);
}
return environment.literalListType(node.typeArgument);
}
@override
DartType visitSetLiteral(SetLiteral node) {
for (int i = 0; i < node.expressions.length; ++i) {
node.expressions[i] =
checkAndDowncastExpression(node.expressions[i], node.typeArgument);
}
return environment.literalSetType(node.typeArgument);
}
@override
DartType visitLogicalExpression(LogicalExpression node) {
node.left = checkAndDowncastExpression(
node.left, environment.coreTypes.boolLegacyRawType);
node.right = checkAndDowncastExpression(
node.right, environment.coreTypes.boolLegacyRawType);
return environment.coreTypes.boolLegacyRawType;
}
@override
DartType visitMapLiteral(MapLiteral node) {
for (var entry in node.entries) {
entry.key = checkAndDowncastExpression(entry.key, node.keyType);
entry.value = checkAndDowncastExpression(entry.value, node.valueType);
}
return environment.literalMapType(node.keyType, node.valueType);
}
DartType handleDynamicCall(DartType receiver, Arguments arguments) {
arguments.positional.forEach(visitExpression);
arguments.named.forEach((NamedExpression n) => visitExpression(n.value));
return const DynamicType();
}
DartType handleFunctionCall(
TreeNode access, FunctionType function, Arguments arguments) {
if (function.requiredParameterCount > arguments.positional.length) {
fail(access, 'Too few positional arguments');
return const BottomType();
}
if (function.positionalParameters.length < arguments.positional.length) {
fail(access, 'Too many positional arguments');
return const BottomType();
}
if (function.typeParameters.length != arguments.types.length) {
fail(access, 'Wrong number of type arguments');
return const BottomType();
}
var instantiation =
Substitution.fromPairs(function.typeParameters, arguments.types);
for (int i = 0; i < arguments.positional.length; ++i) {
var expectedType = instantiation.substituteType(
function.positionalParameters[i],
contravariant: true);
arguments.positional[i] =
checkAndDowncastExpression(arguments.positional[i], expectedType);
}
for (int i = 0; i < arguments.named.length; ++i) {
var argument = arguments.named[i];
var parameterType = function.getNamedParameter(argument.name);
if (parameterType != null) {
var expectedType =
instantiation.substituteType(parameterType, contravariant: true);
argument.value =
checkAndDowncastExpression(argument.value, expectedType);
} else {
fail(argument.value, 'Unexpected named parameter: ${argument.name}');
return const BottomType();
}
}
return instantiation.substituteType(function.returnType);
}
@override
DartType visitMethodInvocation(MethodInvocation node) {
var target = node.interfaceTarget;
if (target == null) {
var receiver = visitExpression(node.receiver);
if (node.name.name == '==') {
visitExpression(node.arguments.positional.single);
return environment.coreTypes.boolLegacyRawType;
}
if (node.name.name == 'call' && receiver is FunctionType) {
return handleFunctionCall(node, receiver, node.arguments);
}
checkUnresolvedInvocation(receiver, node);
return handleDynamicCall(receiver, node.arguments);
} else if (target is Procedure &&
environment.isOverloadedArithmeticOperator(target)) {
assert(node.arguments.positional.length == 1);
var receiver = visitExpression(node.receiver);
var argument = visitExpression(node.arguments.positional[0]);
return environment.getTypeOfOverloadedArithmetic(receiver, argument);
} else {
return handleCall(node.arguments, target.getterType,
receiver: getReceiverType(node, node.receiver, node.interfaceTarget));
}
}
@override
DartType visitPropertyGet(PropertyGet node) {
if (node.interfaceTarget == null) {
final receiver = visitExpression(node.receiver);
checkUnresolvedInvocation(receiver, node);
return const DynamicType();
} else {
var receiver = getReceiverType(node, node.receiver, node.interfaceTarget);
return receiver.substituteType(node.interfaceTarget.getterType);
}
}
@override
DartType visitPropertySet(PropertySet node) {
var value = visitExpression(node.value);
if (node.interfaceTarget != null) {
var receiver = getReceiverType(node, node.receiver, node.interfaceTarget);
checkAssignable(
node.value,
value,
receiver.substituteType(node.interfaceTarget.setterType,
contravariant: true));
} else {
final receiver = visitExpression(node.receiver);
checkUnresolvedInvocation(receiver, node);
}
return value;
}
@override
DartType visitNot(Not node) {
visitExpression(node.operand);
return environment.coreTypes.boolLegacyRawType;
}
@override
DartType visitNullCheck(NullCheck node) {
// TODO(johnniwinther): Return `NonNull(visitExpression(types))`.
return visitExpression(node.operand);
}
@override
DartType visitNullLiteral(NullLiteral node) {
return const BottomType();
}
@override
DartType visitRethrow(Rethrow node) {
return const BottomType();
}
@override
DartType visitStaticGet(StaticGet node) {
return node.target.getterType;
}
@override
DartType visitStaticInvocation(StaticInvocation node) {
return handleCall(node.arguments, node.target.getterType);
}
@override
DartType visitStaticSet(StaticSet node) {
var value = visitExpression(node.value);
checkAssignable(node.value, value, node.target.setterType);
return value;
}
@override
DartType visitStringConcatenation(StringConcatenation node) {
node.expressions.forEach(visitExpression);
return environment.coreTypes.stringLegacyRawType;
}
@override
DartType visitListConcatenation(ListConcatenation node) {
DartType type = environment.literalListType(node.typeArgument);
for (Expression part in node.lists) {
DartType partType = visitExpression(part);
checkAssignable(node, type, partType);
}
return type;
}
@override
DartType visitSetConcatenation(SetConcatenation node) {
DartType type = environment.literalSetType(node.typeArgument);
for (Expression part in node.sets) {
DartType partType = visitExpression(part);
checkAssignable(node, type, partType);
}
return type;
}
@override
DartType visitMapConcatenation(MapConcatenation node) {
DartType type = environment.literalMapType(node.keyType, node.valueType);
for (Expression part in node.maps) {
DartType partType = visitExpression(part);
checkAssignable(node, type, partType);
}
return type;
}
@override
DartType visitInstanceCreation(InstanceCreation node) {
Substitution substitution = Substitution.fromPairs(
node.classNode.typeParameters, node.typeArguments);
node.fieldValues.forEach((Reference fieldRef, Expression value) {
DartType fieldType = substitution.substituteType(fieldRef.asField.type);
DartType valueType = visitExpression(value);
checkAssignable(node, fieldType, valueType);
});
return new InterfaceType(node.classNode, node.typeArguments);
}
@override
DartType visitFileUriExpression(FileUriExpression node) {
return visitExpression(node.expression);
}
@override
DartType visitStringLiteral(StringLiteral node) {
return environment.coreTypes.stringLegacyRawType;
}
@override
DartType visitSuperMethodInvocation(SuperMethodInvocation node) {
if (node.interfaceTarget == null) {
checkUnresolvedInvocation(environment.thisType, node);
return handleDynamicCall(environment.thisType, node.arguments);
} else {
return handleCall(node.arguments, node.interfaceTarget.getterType,
receiver: getSuperReceiverType(node.interfaceTarget));
}
}
@override
DartType visitSuperPropertyGet(SuperPropertyGet node) {
if (node.interfaceTarget == null) {
checkUnresolvedInvocation(environment.thisType, node);
return const DynamicType();
} else {
var receiver = getSuperReceiverType(node.interfaceTarget);
return receiver.substituteType(node.interfaceTarget.getterType);
}
}
@override
DartType visitSuperPropertySet(SuperPropertySet node) {
var value = visitExpression(node.value);
if (node.interfaceTarget != null) {
var receiver = getSuperReceiverType(node.interfaceTarget);
checkAssignable(
node.value,
value,
receiver.substituteType(node.interfaceTarget.setterType,
contravariant: true));
} else {
checkUnresolvedInvocation(environment.thisType, node);
}
return value;
}
@override
DartType visitSymbolLiteral(SymbolLiteral node) {
return environment.coreTypes.symbolLegacyRawType;
}
@override
DartType visitThisExpression(ThisExpression node) {
return environment.thisType;
}
@override
DartType visitThrow(Throw node) {
visitExpression(node.expression);
return const BottomType();
}
@override
DartType visitTypeLiteral(TypeLiteral node) {
return environment.coreTypes.typeLegacyRawType;
}
@override
DartType visitVariableGet(VariableGet node) {
return node.promotedType ?? node.variable.type;
}
@override
DartType visitVariableSet(VariableSet node) {
var value = visitExpression(node.value);
checkAssignable(node.value, value, node.variable.type);
return value;
}
@override
DartType visitLoadLibrary(LoadLibrary node) {
return environment.futureType(const DynamicType());
}
@override
DartType visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) {
return environment.coreTypes.objectLegacyRawType;
}
@override
visitConstantExpression(ConstantExpression node) {
return node.type;
}
@override
visitAssertStatement(AssertStatement node) {
visitExpression(node.condition);
if (node.message != null) {
visitExpression(node.message);
}
}
@override
visitBlock(Block node) {
node.statements.forEach(visitStatement);
}
@override
visitAssertBlock(AssertBlock node) {
node.statements.forEach(visitStatement);
}
@override
visitBreakStatement(BreakStatement node) {}
@override
visitContinueSwitchStatement(ContinueSwitchStatement node) {}
@override
visitDoStatement(DoStatement node) {
visitStatement(node.body);
node.condition = checkAndDowncastExpression(
node.condition, environment.coreTypes.boolLegacyRawType);
}
@override
visitEmptyStatement(EmptyStatement node) {}
@override
visitExpressionStatement(ExpressionStatement node) {
visitExpression(node.expression);
}
@override
visitForInStatement(ForInStatement node) {
var iterable = visitExpression(node.iterable);
// TODO(asgerf): Store interface targets on for-in loops or desugar them,
// instead of doing the ad-hoc resolution here.
if (node.isAsync) {
checkAssignable(node, getStreamElementType(iterable), node.variable.type);
} else {
checkAssignable(
node, getIterableElementType(iterable), node.variable.type);
}
visitStatement(node.body);
}
static final Name iteratorName = new Name('iterator');
static final Name currentName = new Name('current');
DartType getIterableElementType(DartType iterable) {
if (iterable is InterfaceType) {
var iteratorGetter =
hierarchy.getInterfaceMember(iterable.classNode, iteratorName);
if (iteratorGetter == null) return const DynamicType();
var castedIterable = hierarchy.getTypeAsInstanceOf(
iterable, iteratorGetter.enclosingClass);
var iteratorType = Substitution.fromInterfaceType(castedIterable)
.substituteType(iteratorGetter.getterType);
if (iteratorType is InterfaceType) {
var currentGetter =
hierarchy.getInterfaceMember(iteratorType.classNode, currentName);
if (currentGetter == null) return const DynamicType();
var castedIteratorType = hierarchy.getTypeAsInstanceOf(
iteratorType, currentGetter.enclosingClass);
return Substitution.fromInterfaceType(castedIteratorType)
.substituteType(currentGetter.getterType);
}
}
return const DynamicType();
}
DartType getStreamElementType(DartType stream) {
if (stream is InterfaceType) {
var asStream =
hierarchy.getTypeAsInstanceOf(stream, coreTypes.streamClass);
if (asStream == null) return const DynamicType();
return asStream.typeArguments.single;
}
return const DynamicType();
}
@override
visitForStatement(ForStatement node) {
node.variables.forEach(visitVariableDeclaration);
if (node.condition != null) {
node.condition = checkAndDowncastExpression(
node.condition, environment.coreTypes.boolLegacyRawType);
}
node.updates.forEach(visitExpression);
visitStatement(node.body);
}
@override
visitFunctionDeclaration(FunctionDeclaration node) {
handleNestedFunctionNode(node.function);
}
@override
visitIfStatement(IfStatement node) {
node.condition = checkAndDowncastExpression(
node.condition, environment.coreTypes.boolLegacyRawType);
visitStatement(node.then);
if (node.otherwise != null) {
visitStatement(node.otherwise);
}
}
@override
visitLabeledStatement(LabeledStatement node) {
visitStatement(node.body);
}
@override
visitReturnStatement(ReturnStatement node) {
if (node.expression != null) {
if (environment.returnType == null) {
fail(node, 'Return of a value from void method');
} else {
var type = visitExpression(node.expression);
if (environment.currentAsyncMarker == AsyncMarker.Async) {
type = environment.unfutureType(type);
}
checkAssignable(node.expression, type, environment.returnType);
}
}
}
@override
visitSwitchStatement(SwitchStatement node) {
visitExpression(node.expression);
for (var switchCase in node.cases) {
switchCase.expressions.forEach(visitExpression);
visitStatement(switchCase.body);
}
}
@override
visitTryCatch(TryCatch node) {
visitStatement(node.body);
for (var catchClause in node.catches) {
visitStatement(catchClause.body);
}
}
@override
visitTryFinally(TryFinally node) {
visitStatement(node.body);
visitStatement(node.finalizer);
}
@override
visitVariableDeclaration(VariableDeclaration node) {
if (node.initializer != null) {
node.initializer =
checkAndDowncastExpression(node.initializer, node.type);
}
}
@override
visitWhileStatement(WhileStatement node) {
node.condition = checkAndDowncastExpression(
node.condition, environment.coreTypes.boolLegacyRawType);
visitStatement(node.body);
}
@override
visitYieldStatement(YieldStatement node) {
if (node.isYieldStar) {
Class container = environment.currentAsyncMarker == AsyncMarker.AsyncStar
? coreTypes.streamClass
: coreTypes.iterableClass;
var type = visitExpression(node.expression);
var asContainer = type is InterfaceType
? hierarchy.getTypeAsInstanceOf(type, container)
: null;
if (asContainer != null) {
checkAssignable(node.expression, asContainer.typeArguments[0],
environment.yieldType);
} else {
fail(node.expression, '$type is not an instance of $container');
}
} else {
node.expression =
checkAndDowncastExpression(node.expression, environment.yieldType);
}
}
@override
visitFieldInitializer(FieldInitializer node) {
node.value = checkAndDowncastExpression(node.value, node.field.type);
}
@override
visitRedirectingInitializer(RedirectingInitializer node) {
handleCall(node.arguments, node.target.getterType,
typeParameters: const <TypeParameter>[]);
}
@override
visitSuperInitializer(SuperInitializer node) {
handleCall(node.arguments, node.target.getterType,
typeParameters: const <TypeParameter>[],
receiver: getSuperReceiverType(node.target));
}
@override
visitLocalInitializer(LocalInitializer node) {
visitVariableDeclaration(node.variable);
}
@override
visitAssertInitializer(AssertInitializer node) {
visitAssertStatement(node.statement);
}
@override
visitInvalidInitializer(InvalidInitializer node) {}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/canonical_name.dart | // 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.
library kernel.canonical_name;
import 'ast.dart';
/// A string sequence that identifies a library, class, or member.
///
/// Canonical names are organized in a prefix tree. Each node knows its
/// parent, children, and the AST node it is currently bound to.
///
/// The following schema specifies how the canonical name of a given object
/// is defined:
///
/// Library:
/// URI of library
///
/// Class:
/// Canonical name of enclosing library
/// Name of class
///
/// Extension:
/// Canonical name of enclosing library
/// Name of extension
///
/// Constructor:
/// Canonical name of enclosing class or library
/// "@constructors"
/// Qualified name
///
/// Field:
/// Canonical name of enclosing class or library
/// "@fields"
/// Qualified name
///
/// Typedef:
/// Canonical name of enclosing class
/// "@typedefs"
/// Name text
///
/// Procedure that is not an accessor or factory:
/// Canonical name of enclosing class or library
/// "@methods"
/// Qualified name
///
/// Procedure that is a getter:
/// Canonical name of enclosing class or library
/// "@getters"
/// Qualified name
///
/// Procedure that is a setter:
/// Canonical name of enclosing class or library
/// "@setters"
/// Qualified name
///
/// Procedure that is a factory:
/// Canonical name of enclosing class
/// "@factories"
/// Qualified name
///
/// Qualified name:
/// if private: URI of library
/// Name text
///
/// The "qualified name" allows a member to have a name that is private to
/// a library other than the one containing that member.
class CanonicalName {
CanonicalName _parent;
CanonicalName get parent => _parent;
final String name;
CanonicalName _nonRootTop;
Map<String, CanonicalName> _children;
/// The library, class, or member bound to this name.
Reference reference;
/// Temporary index used during serialization.
int index = -1;
CanonicalName._(this._parent, this.name) {
assert(name != null);
assert(parent != null);
_nonRootTop = _parent.isRoot ? this : _parent._nonRootTop;
}
CanonicalName.root()
: _parent = null,
_nonRootTop = null,
name = '';
bool get isRoot => _parent == null;
CanonicalName get nonRootTop => _nonRootTop;
Iterable<CanonicalName> get children =>
_children?.values ?? const <CanonicalName>[];
Iterable<CanonicalName> get childrenOrNull => _children?.values;
bool hasChild(String name) {
return _children != null && _children.containsKey(name);
}
CanonicalName getChild(String name) {
var map = _children ??= <String, CanonicalName>{};
return map[name] ??= new CanonicalName._(this, name);
}
CanonicalName getChildFromUri(Uri uri) {
// Note that the Uri class caches its string representation, and all library
// URIs will be stringified for serialization anyway, so there is no
// significant cost for converting the Uri to a string here.
return getChild('$uri');
}
CanonicalName getChildFromQualifiedName(Name name) {
return name.isPrivate
? getChildFromUri(name.library.importUri).getChild(name.name)
: getChild(name.name);
}
CanonicalName getChildFromMember(Member member) {
return getChild(getMemberQualifier(member))
.getChildFromQualifiedName(member.name);
}
CanonicalName getChildFromFieldWithName(Name name) {
return getChild('@fields').getChildFromQualifiedName(name);
}
CanonicalName getChildFromTypedef(Typedef typedef_) {
return getChild('@typedefs').getChild(typedef_.name);
}
/// Take ownership of a child canonical name and its subtree.
///
/// The child name is removed as a child of its current parent and this name
/// becomes the new parent. Note that this moves the entire subtree rooted at
/// the child.
///
/// This method can be used to move subtrees within a canonical name tree or
/// else move them between trees. It is safe to call this method if the child
/// name is already a child of this name.
///
/// The precondition is that this name cannot have a (different) child with
/// the same name.
void adoptChild(CanonicalName child) {
if (child._parent == this) return;
if (_children != null && _children.containsKey(child.name)) {
throw 'Cannot add a child to $this because this name already has a '
'child named ${child.name}';
}
child._parent.removeChild(child.name);
child._parent = this;
if (_children == null) _children = <String, CanonicalName>{};
_children[child.name] = child;
}
void removeChild(String name) {
_children?.remove(name);
}
void bindTo(Reference target) {
if (reference == target) return;
if (reference != null) {
throw '$this is already bound';
}
if (target.canonicalName != null) {
throw 'Cannot bind $this to ${target.node}, target is already bound to '
'${target.canonicalName}';
}
target.canonicalName = this;
this.reference = target;
}
void unbind() {
if (reference == null) return;
assert(reference.canonicalName == this);
if (reference.node is Class) {
// TODO(jensj): Get rid of this. This is only needed because pkg:vm does
// weird stuff in transformations. `unbind` should probably be private.
Class c = reference.node;
c.ensureLoaded();
}
reference.canonicalName = null;
reference = null;
}
void unbindAll() {
unbind();
Iterable<CanonicalName> children_ = childrenOrNull;
if (children_ != null) {
for (CanonicalName child in children_) {
child.unbindAll();
}
}
}
String toString() => _parent == null ? 'root' : '$parent::$name';
Reference getReference() {
return reference ??= (new Reference()..canonicalName = this);
}
static String getMemberQualifier(Member member) {
if (member is Procedure) {
if (member.isGetter) return '@getters';
if (member.isSetter) return '@setters';
if (member.isFactory) return '@factories';
return '@methods';
}
if (member is Field) {
return '@fields';
}
if (member is Constructor) {
return '@constructors';
}
if (member is RedirectingFactoryConstructor) {
return '@factories';
}
throw 'Unexpected member: $member';
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/verifier.dart | // 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.
library kernel.checks;
import 'ast.dart';
import 'transformations/flags.dart';
void verifyComponent(Component component) {
VerifyingVisitor.check(component);
}
class VerificationError {
final TreeNode context;
final TreeNode node;
final String details;
VerificationError(this.context, this.node, this.details);
toString() {
Location location;
try {
location = node?.location ?? context?.location;
} catch (_) {
// TODO(ahe): Fix the compiler instead.
}
if (location != null) {
String file = location.file?.toString() ?? "";
return "$file:${location.line}:${location.column}: Verification error:"
" $details";
} else {
return "Verification error: $details\n"
"Context: '$context'.\n"
"Node: '$node'.";
}
}
}
enum TypedefState { Done, BeingChecked }
/// Checks that a kernel component is well-formed.
///
/// This does not include any kind of type checking.
class VerifyingVisitor extends RecursiveVisitor<void> {
final Set<Class> classes = new Set<Class>();
final Set<Typedef> typedefs = new Set<Typedef>();
Set<TypeParameter> typeParametersInScope = new Set<TypeParameter>();
final List<VariableDeclaration> variableStack = <VariableDeclaration>[];
final Map<Typedef, TypedefState> typedefState = <Typedef, TypedefState>{};
bool classTypeParametersAreInScope = false;
/// If true, relax certain checks for *outline* mode. For example, don't
/// attempt to validate constructor initializers.
bool isOutline = false;
bool inCatchBlock = false;
Library currentLibrary;
Member currentMember;
Class currentClass;
TreeNode currentParent;
TreeNode get context => currentMember ?? currentClass;
static void check(Component component) {
component.accept(new VerifyingVisitor());
}
defaultTreeNode(TreeNode node) {
visitChildren(node);
}
problem(TreeNode node, String details, {TreeNode context}) {
context ??= this.context;
throw new VerificationError(context, node, details);
}
TreeNode enterParent(TreeNode node) {
if (!identical(node.parent, currentParent)) {
problem(
node,
"Incorrect parent pointer on ${node.runtimeType}:"
" expected '${currentParent.runtimeType}',"
" but found: '${node.parent.runtimeType}'.",
context: currentParent);
}
var oldParent = currentParent;
currentParent = node;
return oldParent;
}
void exitParent(TreeNode oldParent) {
currentParent = oldParent;
}
int enterLocalScope() => variableStack.length;
void exitLocalScope(int stackHeight) {
for (int i = stackHeight; i < variableStack.length; ++i) {
undeclareVariable(variableStack[i]);
}
variableStack.length = stackHeight;
}
void visitChildren(TreeNode node) {
var oldParent = enterParent(node);
node.visitChildren(this);
exitParent(oldParent);
}
void visitWithLocalScope(TreeNode node) {
int stackHeight = enterLocalScope();
visitChildren(node);
exitLocalScope(stackHeight);
}
void declareMember(Member member) {
if (member.transformerFlags & TransformerFlag.seenByVerifier != 0) {
problem(member.function,
"Member '$member' has been declared more than once.");
}
member.transformerFlags |= TransformerFlag.seenByVerifier;
}
void undeclareMember(Member member) {
member.transformerFlags &= ~TransformerFlag.seenByVerifier;
}
void declareVariable(VariableDeclaration variable) {
if (variable.flags & VariableDeclaration.FlagInScope != 0) {
problem(variable, "Variable '$variable' declared more than once.");
}
variable.flags |= VariableDeclaration.FlagInScope;
variableStack.add(variable);
}
void undeclareVariable(VariableDeclaration variable) {
variable.flags &= ~VariableDeclaration.FlagInScope;
}
void declareTypeParameters(List<TypeParameter> parameters) {
for (int i = 0; i < parameters.length; ++i) {
var parameter = parameters[i];
if (parameter.bound == null) {
problem(
currentParent, "Missing bound for type parameter '$parameter'.");
}
if (!typeParametersInScope.add(parameter)) {
problem(parameter, "Type parameter '$parameter' redeclared.");
}
}
}
void undeclareTypeParameters(List<TypeParameter> parameters) {
typeParametersInScope.removeAll(parameters);
}
void checkVariableInScope(VariableDeclaration variable, TreeNode where) {
if (variable.flags & VariableDeclaration.FlagInScope == 0) {
problem(where, "Variable '$variable' used out of scope.");
}
}
visitComponent(Component component) {
try {
for (var library in component.libraries) {
for (var class_ in library.classes) {
if (!classes.add(class_)) {
problem(class_, "Class '$class_' declared more than once.");
}
}
for (var typedef_ in library.typedefs) {
if (!typedefs.add(typedef_)) {
problem(typedef_, "Typedef '$typedef_' declared more than once.");
}
}
library.members.forEach(declareMember);
for (var class_ in library.classes) {
class_.members.forEach(declareMember);
}
}
visitChildren(component);
} finally {
for (var library in component.libraries) {
library.members.forEach(undeclareMember);
for (var class_ in library.classes) {
class_.members.forEach(undeclareMember);
}
}
variableStack.forEach(undeclareVariable);
}
}
void visitLibrary(Library node) {
currentLibrary = node;
super.visitLibrary(node);
currentLibrary = null;
}
visitExtension(Extension node) {
declareTypeParameters(node.typeParameters);
final oldParent = enterParent(node);
node.visitChildren(this);
exitParent(oldParent);
undeclareTypeParameters(node.typeParameters);
}
void checkTypedef(Typedef node) {
var state = typedefState[node];
if (state == TypedefState.Done) return;
if (state == TypedefState.BeingChecked) {
problem(node, "The typedef '$node' refers to itself", context: node);
}
assert(state == null);
typedefState[node] = TypedefState.BeingChecked;
var savedTypeParameters = typeParametersInScope;
typeParametersInScope = node.typeParameters.toSet();
var savedParent = currentParent;
currentParent = node;
// Visit children without checking the parent pointer on the typedef itself
// since this can be called from a context other than its true parent.
node.visitChildren(this);
currentParent = savedParent;
typeParametersInScope = savedTypeParameters;
typedefState[node] = TypedefState.Done;
}
visitTypedef(Typedef node) {
checkTypedef(node);
// Enter and exit the node to check the parent pointer on the typedef node.
exitParent(enterParent(node));
}
visitField(Field node) {
currentMember = node;
var oldParent = enterParent(node);
bool isTopLevel = node.parent == currentLibrary;
if (isTopLevel && !node.isStatic) {
problem(node, "The top-level field '${node.name.name}' should be static",
context: node);
}
if (node.isConst && !node.isStatic) {
problem(node, "The const field '${node.name.name}' should be static",
context: node);
}
classTypeParametersAreInScope = !node.isStatic;
node.initializer?.accept(this);
node.type.accept(this);
classTypeParametersAreInScope = false;
visitList(node.annotations, this);
exitParent(oldParent);
currentMember = null;
}
visitProcedure(Procedure node) {
currentMember = node;
var oldParent = enterParent(node);
classTypeParametersAreInScope = !node.isStatic;
node.function.accept(this);
classTypeParametersAreInScope = false;
visitList(node.annotations, this);
exitParent(oldParent);
currentMember = null;
}
visitConstructor(Constructor node) {
currentMember = node;
classTypeParametersAreInScope = true;
// The constructor member needs special treatment due to parameters being
// in scope in the initializer list.
var oldParent = enterParent(node);
int stackHeight = enterLocalScope();
visitChildren(node.function);
visitList(node.initializers, this);
if (!isOutline) {
checkInitializers(node);
}
exitLocalScope(stackHeight);
classTypeParametersAreInScope = false;
visitList(node.annotations, this);
exitParent(oldParent);
classTypeParametersAreInScope = false;
currentMember = null;
}
visitClass(Class node) {
currentClass = node;
declareTypeParameters(node.typeParameters);
var oldParent = enterParent(node);
classTypeParametersAreInScope = false;
visitList(node.annotations, this);
classTypeParametersAreInScope = true;
visitList(node.typeParameters, this);
visitList(node.fields, this);
visitList(node.constructors, this);
visitList(node.procedures, this);
exitParent(oldParent);
undeclareTypeParameters(node.typeParameters);
currentClass = null;
}
visitFunctionNode(FunctionNode node) {
declareTypeParameters(node.typeParameters);
bool savedInCatchBlock = inCatchBlock;
inCatchBlock = false;
visitWithLocalScope(node);
inCatchBlock = savedInCatchBlock;
undeclareTypeParameters(node.typeParameters);
}
visitFunctionType(FunctionType node) {
for (int i = 1; i < node.namedParameters.length; ++i) {
if (node.namedParameters[i - 1].compareTo(node.namedParameters[i]) >= 0) {
problem(currentParent,
"Named parameters are not sorted on function type ($node).");
}
}
declareTypeParameters(node.typeParameters);
for (var typeParameter in node.typeParameters) {
typeParameter.bound?.accept(this);
}
visitList(node.positionalParameters, this);
visitList(node.namedParameters, this);
node.returnType.accept(this);
undeclareTypeParameters(node.typeParameters);
}
visitBlock(Block node) {
visitWithLocalScope(node);
}
visitForStatement(ForStatement node) {
visitWithLocalScope(node);
}
visitForInStatement(ForInStatement node) {
visitWithLocalScope(node);
}
visitLet(Let node) {
visitWithLocalScope(node);
}
visitBlockExpression(BlockExpression node) {
int stackHeight = enterLocalScope();
// Do not visit the block directly because the value expression needs to
// be in its scope.
TreeNode oldParent = enterParent(node);
enterParent(node.body);
for (int i = 0; i < node.body.statements.length; ++i) {
node.body.statements[i].accept(this);
}
exitParent(node);
node.value.accept(this);
exitParent(oldParent);
exitLocalScope(stackHeight);
}
visitCatch(Catch node) {
bool savedInCatchBlock = inCatchBlock;
inCatchBlock = true;
visitWithLocalScope(node);
inCatchBlock = savedInCatchBlock;
}
@override
visitRethrow(Rethrow node) {
if (!inCatchBlock) {
problem(node, "Rethrow must be inside a Catch block.");
}
}
visitVariableDeclaration(VariableDeclaration node) {
var parent = node.parent;
if (parent is! Block &&
!(parent is Catch && parent.body != node) &&
!(parent is FunctionNode && parent.body != node) &&
parent is! FunctionDeclaration &&
!(parent is ForStatement && parent.body != node) &&
!(parent is ForInStatement && parent.body != node) &&
parent is! Let &&
parent is! LocalInitializer) {
problem(
node,
"VariableDeclaration must be a direct child of a Block, "
"not ${parent.runtimeType}.");
}
visitChildren(node);
declareVariable(node);
}
visitVariableGet(VariableGet node) {
checkVariableInScope(node.variable, node);
visitChildren(node);
}
visitVariableSet(VariableSet node) {
checkVariableInScope(node.variable, node);
visitChildren(node);
}
@override
visitStaticGet(StaticGet node) {
visitChildren(node);
if (node.target == null) {
problem(node, "StaticGet without target.");
}
// Currently Constructor.hasGetter returns `false` even though fasta uses it
// as a getter for internal purposes:
//
// Fasta is letting all call site of a redirecting constructor be resolved
// to the real target. In order to resolve it, it seems to add a body into
// the redirecting-factory constructor which caches the target constructor.
// That cache is via a `StaticGet(real-constructor)` node, which we make
// here pass the verifier.
if (!node.target.hasGetter && node.target is! Constructor) {
problem(node, "StaticGet of '${node.target}' without getter.");
}
if (node.target.isInstanceMember) {
problem(node, "StaticGet of '${node.target}' that's an instance member.");
}
}
@override
visitStaticSet(StaticSet node) {
visitChildren(node);
if (node.target == null) {
problem(node, "StaticSet without target.");
}
if (!node.target.hasSetter) {
problem(node, "StaticSet to '${node.target}' without setter.");
}
if (node.target.isInstanceMember) {
problem(node, "StaticSet to '${node.target}' that's an instance member.");
}
}
@override
visitStaticInvocation(StaticInvocation node) {
checkTargetedInvocation(node.target, node);
if (node.target.isInstanceMember) {
problem(node,
"StaticInvocation of '${node.target}' that's an instance member.");
}
if (node.isConst &&
(!node.target.isConst ||
!node.target.isExternal ||
node.target.kind != ProcedureKind.Factory)) {
problem(
node,
"Constant StaticInvocation of '${node.target}' that isn't"
" a const external factory.");
}
}
void checkTargetedInvocation(Member target, InvocationExpression node) {
visitChildren(node);
if (target == null) {
problem(node, "${node.runtimeType} without target.");
}
if (target.function == null) {
problem(node, "${node.runtimeType} without function.");
}
if (!areArgumentsCompatible(node.arguments, target.function)) {
problem(node,
"${node.runtimeType} with incompatible arguments for '${target}'.");
}
int expectedTypeParameters = target is Constructor
? target.enclosingClass.typeParameters.length
: target.function.typeParameters.length;
if (node.arguments.types.length != expectedTypeParameters) {
problem(
node,
"${node.runtimeType} with wrong number of type arguments"
" for '${target}'.");
}
}
@override
visitDirectPropertyGet(DirectPropertyGet node) {
visitChildren(node);
if (node.target == null) {
problem(node, "DirectPropertyGet without target.");
}
if (!node.target.hasGetter) {
problem(node, "DirectPropertyGet of '${node.target}' without getter.");
}
if (!node.target.isInstanceMember) {
problem(
node,
"DirectPropertyGet of '${node.target}' that isn't an"
" instance member.");
}
}
@override
visitDirectPropertySet(DirectPropertySet node) {
visitChildren(node);
if (node.target == null) {
problem(node, "DirectPropertySet without target.");
}
if (!node.target.hasSetter) {
problem(node, "DirectPropertySet of '${node.target}' without setter.");
}
if (!node.target.isInstanceMember) {
problem(node, "DirectPropertySet of '${node.target}' that is static.");
}
}
@override
visitDirectMethodInvocation(DirectMethodInvocation node) {
checkTargetedInvocation(node.target, node);
if (node.receiver == null) {
problem(node, "DirectMethodInvocation without receiver.");
}
}
@override
visitConstructorInvocation(ConstructorInvocation node) {
checkTargetedInvocation(node.target, node);
if (node.target.enclosingClass.isAbstract) {
problem(node, "ConstructorInvocation of abstract class.");
}
if (node.isConst && !node.target.isConst) {
problem(
node,
"Constant ConstructorInvocation fo '${node.target}' that"
" isn't const.");
}
}
bool areArgumentsCompatible(Arguments arguments, FunctionNode function) {
if (arguments.positional.length < function.requiredParameterCount) {
return false;
}
if (arguments.positional.length > function.positionalParameters.length) {
return false;
}
namedLoop:
for (int i = 0; i < arguments.named.length; ++i) {
var argument = arguments.named[i];
String name = argument.name;
for (int j = 0; j < function.namedParameters.length; ++j) {
if (function.namedParameters[j].name == name) continue namedLoop;
}
return false;
}
return true;
}
@override
visitContinueSwitchStatement(ContinueSwitchStatement node) {
if (node.target == null) {
problem(node, "No target.");
} else if (node.target.parent == null) {
problem(node, "Target has no parent.");
} else {
SwitchStatement statement = node.target.parent;
for (SwitchCase switchCase in statement.cases) {
if (switchCase == node.target) return;
}
problem(node, "Switch case isn't child of parent.");
}
}
@override
defaultMemberReference(Member node) {
if (node.transformerFlags & TransformerFlag.seenByVerifier == 0) {
problem(
node, "Dangling reference to '$node', parent is: '${node.parent}'.");
}
}
@override
visitClassReference(Class node) {
if (!classes.contains(node)) {
problem(
node, "Dangling reference to '$node', parent is: '${node.parent}'.");
}
}
@override
visitTypedefReference(Typedef node) {
if (!typedefs.contains(node)) {
problem(
node, "Dangling reference to '$node', parent is: '${node.parent}'");
}
}
@override
visitTypeParameterType(TypeParameterType node) {
var parameter = node.parameter;
if (!typeParametersInScope.contains(parameter)) {
problem(
currentParent,
"Type parameter '$parameter' referenced out of"
" scope, parent is: '${parameter.parent}'.");
}
if (parameter.parent is Class && !classTypeParametersAreInScope) {
problem(
currentParent,
"Type parameter '$parameter' referenced from"
" static context, parent is: '${parameter.parent}'.");
}
}
@override
visitInterfaceType(InterfaceType node) {
node.visitChildren(this);
if (node.typeArguments.length != node.classNode.typeParameters.length) {
problem(
currentParent,
"Type $node provides ${node.typeArguments.length}"
" type arguments but the class declares"
" ${node.classNode.typeParameters.length} parameters.");
}
}
@override
visitTypedefType(TypedefType node) {
checkTypedef(node.typedefNode);
node.visitChildren(this);
if (node.typeArguments.length != node.typedefNode.typeParameters.length) {
problem(
currentParent,
"The typedef type $node provides ${node.typeArguments.length}"
" type arguments but the typedef declares"
" ${node.typedefNode.typeParameters.length} parameters.");
}
}
}
class CheckParentPointers extends Visitor {
static void check(TreeNode node) {
node.accept(new CheckParentPointers(node.parent));
}
TreeNode parent;
CheckParentPointers([this.parent]);
defaultTreeNode(TreeNode node) {
if (node.parent != parent) {
throw new VerificationError(
parent,
node,
"Parent pointer on '${node.runtimeType}' "
"is '${node.parent.runtimeType}' "
"but should be '${parent.runtimeType}'.");
}
var oldParent = parent;
parent = node;
node.visitChildren(this);
parent = oldParent;
}
}
void checkInitializers(Constructor constructor) {
// TODO(ahe): I'll add more here in other CLs.
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/external_name.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.external_name;
import 'ast.dart';
/// Returns external (native) name of given [Member].
String getExternalName(Member procedure) {
// Native procedures are marked as external and have an annotation,
// which looks like this:
//
// import 'dart:_internal' as internal;
//
// @internal.ExternalName("<name-of-native>")
// external Object foo(arg0, ...);
//
if (!procedure.isExternal) {
return null;
}
for (final Expression annotation in procedure.annotations) {
final value = _getExternalNameValue(annotation);
if (value != null) {
return value;
}
}
return null;
}
/// Returns native extension URIs for given [library].
List<String> getNativeExtensionUris(Library library) {
final uris = <String>[];
for (var annotation in library.annotations) {
final value = _getExternalNameValue(annotation);
if (value != null) {
uris.add(value);
}
}
return uris;
}
String _getExternalNameValue(Expression annotation) {
if (annotation is ConstructorInvocation) {
if (_isExternalName(annotation.target.enclosingClass)) {
return (annotation.arguments.positional.single as StringLiteral).value;
}
} else if (annotation is ConstantExpression) {
final constant = annotation.constant;
if (constant is InstanceConstant) {
if (_isExternalName(constant.classNode)) {
return (constant.fieldValues.values.single as StringConstant).value;
}
}
}
return null;
}
bool _isExternalName(Class klass) =>
klass.name == 'ExternalName' &&
klass.enclosingLibrary.importUri.toString() == 'dart:_internal';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/error_formatter.dart | #!/usr/bin/env dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:kernel/kernel.dart';
import 'package:kernel/naive_type_checker.dart';
import 'package:kernel/text/ast_to_text.dart';
class ErrorFormatter implements FailureListener {
List<String> failures = <String>[];
int get numberOfFailures => failures.length;
@override
void reportNotAssignable(TreeNode where, DartType from, DartType to) {
reportFailure(
where,
'${ansiBlue}${from}${ansiReset} ${ansiYellow}is not assignable to'
'${ansiReset} ${ansiBlue}${to}${ansiReset}');
}
@override
void reportInvalidOverride(
Member ownMember, Member superMember, String message) {
reportFailure(ownMember, '''
Incompatible override of ${superMember} with ${ownMember}:
${_realign(message, ' ')}''');
}
@override
void reportFailure(TreeNode where, String message) {
final dynamic context = where is Class || where is Library
? where
: _findEnclosingMember(where);
String sourceLocation = '<unknown source>';
String sourceLine = null;
// Try finding original source line.
final fileOffset = _findFileOffset(where);
if (fileOffset != TreeNode.noOffset) {
final fileUri = _fileUriOf(context);
final component = context.enclosingComponent;
final source = component.uriToSource[fileUri];
final location = component.getLocation(fileUri, fileOffset);
final lineStart = source.lineStarts[location.line - 1];
final lineEnd = (location.line < source.lineStarts.length)
? source.lineStarts[location.line]
: (source.source.length - 1);
if (lineStart < source.source.length &&
lineEnd < source.source.length &&
lineStart < lineEnd) {
sourceLocation = '${fileUri}:${location.line}';
sourceLine = new String.fromCharCodes(
source.source.getRange(lineStart, lineEnd));
}
}
// Find the name of the enclosing member.
var name = "", body = context;
if (context is Class || context is Library) {
name = context.name;
} else if (context is Procedure || context is Constructor) {
final parent = context.parent;
final parentName =
parent is Class ? parent.name : (parent as Library).name;
name = "${parentName}::${context.name.name}";
} else {
final field = context as Field;
if (where is Field) {
name = "${field.parent}.${field.name}";
} else {
name = "field initializer for ${field.parent}.${field.name}";
}
}
String failure = '''
-----------------------------------------------------------------------
In ${name} at ${sourceLocation}:
${message.replaceAll('\n', '\n ')}
Kernel:
|
| ${_realign(HighlightingPrinter.stringifyContainingLines(body, where))}
|
''';
if (sourceLine != null) {
failure = '''$failure
Source:
|
| ${_realign(sourceLine)}
|
''';
}
failures.add(failure);
}
static Uri _fileUriOf(FileUriNode node) {
return node.fileUri;
}
static String _realign(String str, [String prefix = '| ']) =>
str.trimRight().replaceAll('\n', '\n${prefix}');
static int _findFileOffset(TreeNode context) {
while (context != null && context.fileOffset == TreeNode.noOffset) {
context = context.parent;
}
return context?.fileOffset ?? TreeNode.noOffset;
}
static Member _findEnclosingMember(TreeNode n) {
var context = n;
while (context is! Member) {
context = context.parent;
}
return context;
}
}
/// Extension of a [Printer] that highlights the given node using ANSI
/// escape sequences.
class HighlightingPrinter extends Printer {
final highlight;
HighlightingPrinter(this.highlight)
: super(new StringBuffer(), syntheticNames: globalDebuggingNames);
@override
bool shouldHighlight(Node node) => highlight == node;
static const kHighlightStart = ansiRed;
static const kHighlightEnd = ansiReset;
@override
void startHighlight(Node node) {
sink.write(kHighlightStart);
}
@override
void endHighlight(Node node) {
sink.write(kHighlightEnd);
}
/// Stringify the given [node] but only return lines that contain string
/// representation of the [highlight] node.
static String stringifyContainingLines(Node node, Node highlight) {
if (node == highlight) {
final firstLine = debugNodeToString(node).split('\n').first;
return "${kHighlightStart}${firstLine}${kHighlightEnd}";
}
final HighlightingPrinter p = new HighlightingPrinter(highlight);
p.writeNode(node);
final String text = p.sink.toString();
return _onlyHighlightedLines(text).join('\n');
}
static Iterable<String> _onlyHighlightedLines(String text) sync* {
for (var line
in text.split('\n').skipWhile((l) => !l.contains(kHighlightStart))) {
yield line;
if (line.contains(kHighlightEnd)) {
break;
}
}
}
}
const ansiBlue = "\u001b[1;34m";
const ansiYellow = "\u001b[1;33m";
const ansiRed = "\u001b[1;31m";
const ansiReset = "\u001b[0;0m";
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/naive_type_checker.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'class_hierarchy.dart';
import 'core_types.dart';
import 'kernel.dart';
import 'type_checker.dart' as type_checker;
import 'type_algebra.dart';
import 'type_environment.dart';
abstract class FailureListener {
void reportFailure(TreeNode node, String message);
void reportNotAssignable(TreeNode node, DartType first, DartType second);
void reportInvalidOverride(Member member, Member inherited, String message);
}
class NaiveTypeChecker extends type_checker.TypeChecker {
final FailureListener failures;
NaiveTypeChecker(FailureListener failures, Component component,
{bool ignoreSdk: false})
: this._(
failures,
new CoreTypes(component),
new ClassHierarchy(component,
onAmbiguousSupertypes: (Class cls, Supertype s0, Supertype s1) {
failures.reportFailure(
cls, "$cls can't implement both $s1 and $s1");
}),
ignoreSdk);
NaiveTypeChecker._(this.failures, CoreTypes coreTypes,
ClassHierarchy hierarchy, bool ignoreSdk)
: super(coreTypes, hierarchy, ignoreSdk: ignoreSdk);
// TODO(vegorov) this only gets called for immediate overrides which leads
// to less strict checking that Dart 2.0 specification demands for covariant
// parameters.
@override
void checkOverride(
Class host, Member ownMember, Member superMember, bool isSetter) {
final ownMemberIsFieldOrAccessor =
ownMember is Field || (ownMember as Procedure).isAccessor;
final superMemberIsFieldOrAccessor =
superMember is Field || (superMember as Procedure).isAccessor;
// TODO: move to error reporting code
String _memberKind(Member m) {
if (m is Field) {
return 'field';
} else {
final p = m as Procedure;
if (p.isGetter) {
return 'getter';
} else if (p.isSetter) {
return 'setter';
} else {
return 'method';
}
}
}
// First check if we are overriding field/accessor with a normal method
// or other way around.
if (ownMemberIsFieldOrAccessor != superMemberIsFieldOrAccessor) {
return failures.reportInvalidOverride(ownMember, superMember, '''
${ownMember} is a ${_memberKind(ownMember)}
${superMember} is a ${_memberKind(superMember)}
''');
}
if (ownMemberIsFieldOrAccessor) {
if (isSetter) {
final DartType ownType = setterType(host, ownMember);
final DartType superType = setterType(host, superMember);
final isCovariant = ownMember is Field
? ownMember.isCovariant
: ownMember.function.positionalParameters[0].isCovariant;
if (!_isValidParameterOverride(isCovariant, ownType, superType)) {
if (isCovariant) {
return failures.reportInvalidOverride(ownMember, superMember, '''
${ownType} is neither a subtype nor supertype of ${superType}
''');
} else {
return failures.reportInvalidOverride(ownMember, superMember, '''
${ownType} is not a subtype of ${superType}
''');
}
}
} else {
final DartType ownType = getterType(host, ownMember);
final DartType superType = getterType(host, superMember);
if (!environment.isSubtypeOf(
ownType, superType, SubtypeCheckMode.ignoringNullabilities)) {
return failures.reportInvalidOverride(ownMember, superMember, '''
${ownType} is not a subtype of ${superType}
''');
}
}
} else {
final msg = _checkFunctionOverride(host, ownMember, superMember);
if (msg != null) {
return failures.reportInvalidOverride(ownMember, superMember, msg);
}
}
}
/// Check if [subtype] is subtype of [supertype] after applying
/// type parameter [substitution].
bool _isSubtypeOf(DartType subtype, DartType supertype) => environment
.isSubtypeOf(subtype, supertype, SubtypeCheckMode.ignoringNullabilities);
Substitution _makeSubstitutionForMember(Class host, Member member) {
final hostType =
hierarchy.getClassAsInstanceOf(host, member.enclosingClass);
return Substitution.fromSupertype(hostType);
}
/// Check if function node [ownMember] is a valid override for [superMember].
/// Returns [null] if override is valid or an error message.
///
/// Note: this function is a copy of [SubtypeTester._isFunctionSubtypeOf]
/// but it additionally accounts for parameter covariance.
String _checkFunctionOverride(
Class host, Member ownMember, Member superMember) {
final FunctionNode ownFunction = ownMember.function;
final FunctionNode superFunction = superMember.function;
Substitution ownSubstitution = _makeSubstitutionForMember(host, ownMember);
final Substitution superSubstitution =
_makeSubstitutionForMember(host, superMember);
if (ownFunction.requiredParameterCount >
superFunction.requiredParameterCount) {
return 'override has more required parameters';
}
if (ownFunction.positionalParameters.length <
superFunction.positionalParameters.length) {
return 'super method has more positional parameters';
}
if (ownFunction.typeParameters.length !=
superFunction.typeParameters.length) {
return 'methods have different type parameters counts';
}
if (ownFunction.typeParameters.isNotEmpty) {
final typeParameterMap = <TypeParameter, DartType>{};
for (int i = 0; i < ownFunction.typeParameters.length; ++i) {
var subParameter = ownFunction.typeParameters[i];
var superParameter = superFunction.typeParameters[i];
typeParameterMap[subParameter] = new TypeParameterType(superParameter);
}
ownSubstitution = Substitution.combine(
ownSubstitution, Substitution.fromMap(typeParameterMap));
for (int i = 0; i < ownFunction.typeParameters.length; ++i) {
var subParameter = ownFunction.typeParameters[i];
var superParameter = superFunction.typeParameters[i];
var subBound = ownSubstitution.substituteType(subParameter.bound);
if (!_isSubtypeOf(
superSubstitution.substituteType(superParameter.bound), subBound)) {
return 'type parameters have incompatible bounds';
}
}
}
if (!_isSubtypeOf(ownSubstitution.substituteType(ownFunction.returnType),
superSubstitution.substituteType(superFunction.returnType))) {
return 'return type of override ${ownFunction.returnType} is not a subtype'
' of ${superFunction.returnType}';
}
for (int i = 0; i < superFunction.positionalParameters.length; ++i) {
final ownParameter = ownFunction.positionalParameters[i];
final superParameter = superFunction.positionalParameters[i];
if (!_isValidParameterOverride(
ownParameter.isCovariant,
ownSubstitution.substituteType(ownParameter.type),
superSubstitution.substituteType(superParameter.type))) {
return '''
type of parameter ${ownParameter.name} is incompatible
override declares ${ownParameter.type}
super method declares ${superParameter.type}
''';
}
}
if (superFunction.namedParameters.isEmpty) {
return null;
}
// Note: FunctionNode.namedParameters are not sorted so we convert them
// to map to make lookup faster.
final ownParameters = new Map<String, VariableDeclaration>.fromIterable(
ownFunction.namedParameters,
key: (v) => v.name);
for (VariableDeclaration superParameter in superFunction.namedParameters) {
final ownParameter = ownParameters[superParameter.name];
if (ownParameter == null) {
return 'override is missing ${superParameter.name} parameter';
}
if (!_isValidParameterOverride(
ownParameter.isCovariant,
ownSubstitution.substituteType(ownParameter.type),
superSubstitution.substituteType(superParameter.type))) {
return '''
type of parameter ${ownParameter.name} is incompatible
override declares ${ownParameter.type}
super method declares ${superParameter.type}
''';
}
}
return null;
}
/// Checks whether parameter with [ownParameterType] type is a valid override
/// for parameter with [superParameterType] type taking into account its
/// covariance and applying type parameter [substitution] if necessary.
bool _isValidParameterOverride(bool isCovariant, DartType ownParameterType,
DartType superParameterType) {
if (_isSubtypeOf(superParameterType, ownParameterType)) {
return true;
} else if (isCovariant &&
_isSubtypeOf(ownParameterType, superParameterType)) {
return true;
} else {
return false;
}
}
@override
void checkAssignable(TreeNode where, DartType from, DartType to) {
// Note: we permit implicit downcasts.
if (from != to &&
!environment.isSubtypeOf(
from, to, SubtypeCheckMode.ignoringNullabilities) &&
!environment.isSubtypeOf(
to, from, SubtypeCheckMode.ignoringNullabilities)) {
failures.reportNotAssignable(where, from, to);
}
}
@override
void checkUnresolvedInvocation(DartType receiver, TreeNode where) {
if (receiver is DynamicType) {
return;
}
// Permit any invocation on Function type.
if (receiver == environment.coreTypes.functionLegacyRawType &&
where is MethodInvocation &&
where.name.name == 'call') {
return;
}
fail(where, 'Unresolved method invocation');
}
@override
void fail(TreeNode where, String message) {
failures.reportFailure(where, message);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/visitor.dart | // 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.
library kernel.ast.visitor;
import 'dart:core' hide MapEntry;
import 'dart:collection';
import 'ast.dart';
abstract class ExpressionVisitor<R> {
const ExpressionVisitor();
R defaultExpression(Expression node) => null;
R defaultBasicLiteral(BasicLiteral node) => defaultExpression(node);
R visitInvalidExpression(InvalidExpression node) => defaultExpression(node);
R visitVariableGet(VariableGet node) => defaultExpression(node);
R visitVariableSet(VariableSet node) => defaultExpression(node);
R visitPropertyGet(PropertyGet node) => defaultExpression(node);
R visitPropertySet(PropertySet node) => defaultExpression(node);
R visitDirectPropertyGet(DirectPropertyGet node) => defaultExpression(node);
R visitDirectPropertySet(DirectPropertySet node) => defaultExpression(node);
R visitSuperPropertyGet(SuperPropertyGet node) => defaultExpression(node);
R visitSuperPropertySet(SuperPropertySet node) => defaultExpression(node);
R visitStaticGet(StaticGet node) => defaultExpression(node);
R visitStaticSet(StaticSet node) => defaultExpression(node);
R visitMethodInvocation(MethodInvocation node) => defaultExpression(node);
R visitDirectMethodInvocation(DirectMethodInvocation node) =>
defaultExpression(node);
R visitSuperMethodInvocation(SuperMethodInvocation node) =>
defaultExpression(node);
R visitStaticInvocation(StaticInvocation node) => defaultExpression(node);
R visitConstructorInvocation(ConstructorInvocation node) =>
defaultExpression(node);
R visitNot(Not node) => defaultExpression(node);
R visitNullCheck(NullCheck node) => defaultExpression(node);
R visitLogicalExpression(LogicalExpression node) => defaultExpression(node);
R visitConditionalExpression(ConditionalExpression node) =>
defaultExpression(node);
R visitStringConcatenation(StringConcatenation node) =>
defaultExpression(node);
R visitListConcatenation(ListConcatenation node) => defaultExpression(node);
R visitSetConcatenation(SetConcatenation node) => defaultExpression(node);
R visitMapConcatenation(MapConcatenation node) => defaultExpression(node);
R visitInstanceCreation(InstanceCreation node) => defaultExpression(node);
R visitFileUriExpression(FileUriExpression node) => defaultExpression(node);
R visitIsExpression(IsExpression node) => defaultExpression(node);
R visitAsExpression(AsExpression node) => defaultExpression(node);
R visitSymbolLiteral(SymbolLiteral node) => defaultExpression(node);
R visitTypeLiteral(TypeLiteral node) => defaultExpression(node);
R visitThisExpression(ThisExpression node) => defaultExpression(node);
R visitRethrow(Rethrow node) => defaultExpression(node);
R visitThrow(Throw node) => defaultExpression(node);
R visitListLiteral(ListLiteral node) => defaultExpression(node);
R visitSetLiteral(SetLiteral node) => defaultExpression(node);
R visitMapLiteral(MapLiteral node) => defaultExpression(node);
R visitAwaitExpression(AwaitExpression node) => defaultExpression(node);
R visitFunctionExpression(FunctionExpression node) => defaultExpression(node);
R visitConstantExpression(ConstantExpression node) => defaultExpression(node);
R visitStringLiteral(StringLiteral node) => defaultBasicLiteral(node);
R visitIntLiteral(IntLiteral node) => defaultBasicLiteral(node);
R visitDoubleLiteral(DoubleLiteral node) => defaultBasicLiteral(node);
R visitBoolLiteral(BoolLiteral node) => defaultBasicLiteral(node);
R visitNullLiteral(NullLiteral node) => defaultBasicLiteral(node);
R visitLet(Let node) => defaultExpression(node);
R visitBlockExpression(BlockExpression node) => defaultExpression(node);
R visitInstantiation(Instantiation node) => defaultExpression(node);
R visitLoadLibrary(LoadLibrary node) => defaultExpression(node);
R visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) =>
defaultExpression(node);
}
abstract class StatementVisitor<R> {
const StatementVisitor();
R defaultStatement(Statement node) => null;
R visitExpressionStatement(ExpressionStatement node) =>
defaultStatement(node);
R visitBlock(Block node) => defaultStatement(node);
R visitAssertBlock(AssertBlock node) => defaultStatement(node);
R visitEmptyStatement(EmptyStatement node) => defaultStatement(node);
R visitAssertStatement(AssertStatement node) => defaultStatement(node);
R visitLabeledStatement(LabeledStatement node) => defaultStatement(node);
R visitBreakStatement(BreakStatement node) => defaultStatement(node);
R visitWhileStatement(WhileStatement node) => defaultStatement(node);
R visitDoStatement(DoStatement node) => defaultStatement(node);
R visitForStatement(ForStatement node) => defaultStatement(node);
R visitForInStatement(ForInStatement node) => defaultStatement(node);
R visitSwitchStatement(SwitchStatement node) => defaultStatement(node);
R visitContinueSwitchStatement(ContinueSwitchStatement node) =>
defaultStatement(node);
R visitIfStatement(IfStatement node) => defaultStatement(node);
R visitReturnStatement(ReturnStatement node) => defaultStatement(node);
R visitTryCatch(TryCatch node) => defaultStatement(node);
R visitTryFinally(TryFinally node) => defaultStatement(node);
R visitYieldStatement(YieldStatement node) => defaultStatement(node);
R visitVariableDeclaration(VariableDeclaration node) =>
defaultStatement(node);
R visitFunctionDeclaration(FunctionDeclaration node) =>
defaultStatement(node);
}
abstract class MemberVisitor<R> {
const MemberVisitor();
R defaultMember(Member node) => null;
R visitConstructor(Constructor node) => defaultMember(node);
R visitProcedure(Procedure node) => defaultMember(node);
R visitField(Field node) => defaultMember(node);
R visitRedirectingFactoryConstructor(RedirectingFactoryConstructor node) {
return defaultMember(node);
}
}
abstract class InitializerVisitor<R> {
const InitializerVisitor();
R defaultInitializer(Initializer node) => null;
R visitInvalidInitializer(InvalidInitializer node) =>
defaultInitializer(node);
R visitFieldInitializer(FieldInitializer node) => defaultInitializer(node);
R visitSuperInitializer(SuperInitializer node) => defaultInitializer(node);
R visitRedirectingInitializer(RedirectingInitializer node) =>
defaultInitializer(node);
R visitLocalInitializer(LocalInitializer node) => defaultInitializer(node);
R visitAssertInitializer(AssertInitializer node) => defaultInitializer(node);
}
class TreeVisitor<R>
implements
ExpressionVisitor<R>,
StatementVisitor<R>,
MemberVisitor<R>,
InitializerVisitor<R> {
const TreeVisitor();
R defaultTreeNode(TreeNode node) => null;
// Expressions
R defaultExpression(Expression node) => defaultTreeNode(node);
R defaultBasicLiteral(BasicLiteral node) => defaultExpression(node);
R visitInvalidExpression(InvalidExpression node) => defaultExpression(node);
R visitVariableGet(VariableGet node) => defaultExpression(node);
R visitVariableSet(VariableSet node) => defaultExpression(node);
R visitPropertyGet(PropertyGet node) => defaultExpression(node);
R visitPropertySet(PropertySet node) => defaultExpression(node);
R visitDirectPropertyGet(DirectPropertyGet node) => defaultExpression(node);
R visitDirectPropertySet(DirectPropertySet node) => defaultExpression(node);
R visitSuperPropertyGet(SuperPropertyGet node) => defaultExpression(node);
R visitSuperPropertySet(SuperPropertySet node) => defaultExpression(node);
R visitStaticGet(StaticGet node) => defaultExpression(node);
R visitStaticSet(StaticSet node) => defaultExpression(node);
R visitMethodInvocation(MethodInvocation node) => defaultExpression(node);
R visitDirectMethodInvocation(DirectMethodInvocation node) =>
defaultExpression(node);
R visitSuperMethodInvocation(SuperMethodInvocation node) =>
defaultExpression(node);
R visitStaticInvocation(StaticInvocation node) => defaultExpression(node);
R visitConstructorInvocation(ConstructorInvocation node) =>
defaultExpression(node);
R visitNot(Not node) => defaultExpression(node);
R visitNullCheck(NullCheck node) => defaultExpression(node);
R visitLogicalExpression(LogicalExpression node) => defaultExpression(node);
R visitConditionalExpression(ConditionalExpression node) =>
defaultExpression(node);
R visitStringConcatenation(StringConcatenation node) =>
defaultExpression(node);
R visitListConcatenation(ListConcatenation node) => defaultExpression(node);
R visitSetConcatenation(SetConcatenation node) => defaultExpression(node);
R visitMapConcatenation(MapConcatenation node) => defaultExpression(node);
R visitInstanceCreation(InstanceCreation node) => defaultExpression(node);
R visitFileUriExpression(FileUriExpression node) => defaultExpression(node);
R visitIsExpression(IsExpression node) => defaultExpression(node);
R visitAsExpression(AsExpression node) => defaultExpression(node);
R visitSymbolLiteral(SymbolLiteral node) => defaultExpression(node);
R visitTypeLiteral(TypeLiteral node) => defaultExpression(node);
R visitThisExpression(ThisExpression node) => defaultExpression(node);
R visitRethrow(Rethrow node) => defaultExpression(node);
R visitThrow(Throw node) => defaultExpression(node);
R visitListLiteral(ListLiteral node) => defaultExpression(node);
R visitSetLiteral(SetLiteral node) => defaultExpression(node);
R visitMapLiteral(MapLiteral node) => defaultExpression(node);
R visitAwaitExpression(AwaitExpression node) => defaultExpression(node);
R visitFunctionExpression(FunctionExpression node) => defaultExpression(node);
R visitConstantExpression(ConstantExpression node) => defaultExpression(node);
R visitStringLiteral(StringLiteral node) => defaultBasicLiteral(node);
R visitIntLiteral(IntLiteral node) => defaultBasicLiteral(node);
R visitDoubleLiteral(DoubleLiteral node) => defaultBasicLiteral(node);
R visitBoolLiteral(BoolLiteral node) => defaultBasicLiteral(node);
R visitNullLiteral(NullLiteral node) => defaultBasicLiteral(node);
R visitLet(Let node) => defaultExpression(node);
R visitBlockExpression(BlockExpression node) => defaultExpression(node);
R visitInstantiation(Instantiation node) => defaultExpression(node);
R visitLoadLibrary(LoadLibrary node) => defaultExpression(node);
R visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) =>
defaultExpression(node);
// Statements
R defaultStatement(Statement node) => defaultTreeNode(node);
R visitExpressionStatement(ExpressionStatement node) =>
defaultStatement(node);
R visitBlock(Block node) => defaultStatement(node);
R visitAssertBlock(AssertBlock node) => defaultStatement(node);
R visitEmptyStatement(EmptyStatement node) => defaultStatement(node);
R visitAssertStatement(AssertStatement node) => defaultStatement(node);
R visitLabeledStatement(LabeledStatement node) => defaultStatement(node);
R visitBreakStatement(BreakStatement node) => defaultStatement(node);
R visitWhileStatement(WhileStatement node) => defaultStatement(node);
R visitDoStatement(DoStatement node) => defaultStatement(node);
R visitForStatement(ForStatement node) => defaultStatement(node);
R visitForInStatement(ForInStatement node) => defaultStatement(node);
R visitSwitchStatement(SwitchStatement node) => defaultStatement(node);
R visitContinueSwitchStatement(ContinueSwitchStatement node) =>
defaultStatement(node);
R visitIfStatement(IfStatement node) => defaultStatement(node);
R visitReturnStatement(ReturnStatement node) => defaultStatement(node);
R visitTryCatch(TryCatch node) => defaultStatement(node);
R visitTryFinally(TryFinally node) => defaultStatement(node);
R visitYieldStatement(YieldStatement node) => defaultStatement(node);
R visitVariableDeclaration(VariableDeclaration node) =>
defaultStatement(node);
R visitFunctionDeclaration(FunctionDeclaration node) =>
defaultStatement(node);
// Members
R defaultMember(Member node) => defaultTreeNode(node);
R visitConstructor(Constructor node) => defaultMember(node);
R visitProcedure(Procedure node) => defaultMember(node);
R visitField(Field node) => defaultMember(node);
R visitRedirectingFactoryConstructor(RedirectingFactoryConstructor node) {
return defaultMember(node);
}
// Classes
R visitClass(Class node) => defaultTreeNode(node);
R visitExtension(Extension node) => defaultTreeNode(node);
// Initializers
R defaultInitializer(Initializer node) => defaultTreeNode(node);
R visitInvalidInitializer(InvalidInitializer node) =>
defaultInitializer(node);
R visitFieldInitializer(FieldInitializer node) => defaultInitializer(node);
R visitSuperInitializer(SuperInitializer node) => defaultInitializer(node);
R visitRedirectingInitializer(RedirectingInitializer node) =>
defaultInitializer(node);
R visitLocalInitializer(LocalInitializer node) => defaultInitializer(node);
R visitAssertInitializer(AssertInitializer node) => defaultInitializer(node);
// Other tree nodes
R visitLibrary(Library node) => defaultTreeNode(node);
R visitLibraryDependency(LibraryDependency node) => defaultTreeNode(node);
R visitCombinator(Combinator node) => defaultTreeNode(node);
R visitLibraryPart(LibraryPart node) => defaultTreeNode(node);
R visitTypedef(Typedef node) => defaultTreeNode(node);
R visitTypeParameter(TypeParameter node) => defaultTreeNode(node);
R visitFunctionNode(FunctionNode node) => defaultTreeNode(node);
R visitArguments(Arguments node) => defaultTreeNode(node);
R visitNamedExpression(NamedExpression node) => defaultTreeNode(node);
R visitSwitchCase(SwitchCase node) => defaultTreeNode(node);
R visitCatch(Catch node) => defaultTreeNode(node);
R visitMapEntry(MapEntry node) => defaultTreeNode(node);
R visitComponent(Component node) => defaultTreeNode(node);
}
class DartTypeVisitor<R> {
const DartTypeVisitor();
R defaultDartType(DartType node) => null;
R visitInvalidType(InvalidType node) => defaultDartType(node);
R visitDynamicType(DynamicType node) => defaultDartType(node);
R visitVoidType(VoidType node) => defaultDartType(node);
R visitBottomType(BottomType node) => defaultDartType(node);
R visitInterfaceType(InterfaceType node) => defaultDartType(node);
R visitFunctionType(FunctionType node) => defaultDartType(node);
R visitTypeParameterType(TypeParameterType node) => defaultDartType(node);
R visitTypedefType(TypedefType node) => defaultDartType(node);
}
class DartTypeVisitor1<R, T> {
R defaultDartType(DartType node, T arg) => null;
R visitInvalidType(InvalidType node, T arg) => defaultDartType(node, arg);
R visitDynamicType(DynamicType node, T arg) => defaultDartType(node, arg);
R visitVoidType(VoidType node, T arg) => defaultDartType(node, arg);
R visitBottomType(BottomType node, T arg) => defaultDartType(node, arg);
R visitInterfaceType(InterfaceType node, T arg) => defaultDartType(node, arg);
R visitFunctionType(FunctionType node, T arg) => defaultDartType(node, arg);
R visitTypeParameterType(TypeParameterType node, T arg) =>
defaultDartType(node, arg);
R visitTypedefType(TypedefType node, T arg) => defaultDartType(node, arg);
}
/// Visitor for [Constant] nodes.
///
/// Note: Constant nodes are _not_ trees but directed acyclic graphs. This
/// means that visiting a constant node without tracking which subnodes that
/// have already been visited might lead to exponential running times.
///
/// Use [ComputeOnceConstantVisitor] or [VisitOnceConstantVisitor] to visit
/// a constant node while ensuring each subnode is only visited once.
class ConstantVisitor<R> {
const ConstantVisitor();
R defaultConstant(Constant node) => null;
R visitNullConstant(NullConstant node) => defaultConstant(node);
R visitBoolConstant(BoolConstant node) => defaultConstant(node);
R visitIntConstant(IntConstant node) => defaultConstant(node);
R visitDoubleConstant(DoubleConstant node) => defaultConstant(node);
R visitStringConstant(StringConstant node) => defaultConstant(node);
R visitSymbolConstant(SymbolConstant node) => defaultConstant(node);
R visitMapConstant(MapConstant node) => defaultConstant(node);
R visitListConstant(ListConstant node) => defaultConstant(node);
R visitSetConstant(SetConstant node) => defaultConstant(node);
R visitInstanceConstant(InstanceConstant node) => defaultConstant(node);
R visitPartialInstantiationConstant(PartialInstantiationConstant node) =>
defaultConstant(node);
R visitTearOffConstant(TearOffConstant node) => defaultConstant(node);
R visitTypeLiteralConstant(TypeLiteralConstant node) => defaultConstant(node);
R visitUnevaluatedConstant(UnevaluatedConstant node) => defaultConstant(node);
}
abstract class _ConstantCallback<R> {
R defaultConstant(Constant node);
R visitNullConstant(NullConstant node);
R visitBoolConstant(BoolConstant node);
R visitIntConstant(IntConstant node);
R visitDoubleConstant(DoubleConstant node);
R visitStringConstant(StringConstant node);
R visitSymbolConstant(SymbolConstant node);
R visitMapConstant(MapConstant node);
R visitListConstant(ListConstant node);
R visitSetConstant(SetConstant node);
R visitInstanceConstant(InstanceConstant node);
R visitPartialInstantiationConstant(PartialInstantiationConstant node);
R visitTearOffConstant(TearOffConstant node);
R visitTypeLiteralConstant(TypeLiteralConstant node);
R visitUnevaluatedConstant(UnevaluatedConstant node);
}
class _ConstantCallbackVisitor<R> implements ConstantVisitor<R> {
final _ConstantCallback _callback;
_ConstantCallbackVisitor(this._callback);
@override
R visitUnevaluatedConstant(UnevaluatedConstant node) =>
_callback.visitUnevaluatedConstant(node);
@override
R visitTypeLiteralConstant(TypeLiteralConstant node) =>
_callback.visitTypeLiteralConstant(node);
@override
R visitTearOffConstant(TearOffConstant node) =>
_callback.visitTearOffConstant(node);
@override
R visitPartialInstantiationConstant(PartialInstantiationConstant node) =>
_callback.visitPartialInstantiationConstant(node);
@override
R visitInstanceConstant(InstanceConstant node) =>
_callback.visitInstanceConstant(node);
@override
R visitSetConstant(SetConstant node) => _callback.visitSetConstant(node);
@override
R visitListConstant(ListConstant node) => _callback.visitListConstant(node);
@override
R visitMapConstant(MapConstant node) => _callback.visitMapConstant(node);
@override
R visitSymbolConstant(SymbolConstant node) =>
_callback.visitSymbolConstant(node);
@override
R visitStringConstant(StringConstant node) =>
_callback.visitStringConstant(node);
@override
R visitDoubleConstant(DoubleConstant node) =>
_callback.visitDoubleConstant(node);
@override
R visitIntConstant(IntConstant node) => _callback.visitIntConstant(node);
@override
R visitBoolConstant(BoolConstant node) => _callback.visitBoolConstant(node);
@override
R visitNullConstant(NullConstant node) => _callback.visitNullConstant(node);
@override
R defaultConstant(Constant node) => _callback.defaultConstant(node);
}
/// Visitor-like class used for visiting a [Constant] node while computing a
/// value for each subnode. The visitor caches the computed values ensuring that
/// each subnode is only visited once.
class ComputeOnceConstantVisitor<R> implements _ConstantCallback<R> {
_ConstantCallbackVisitor<R> _visitor;
Map<Constant, R> cache = new LinkedHashMap.identity();
ComputeOnceConstantVisitor() {
_visitor = new _ConstantCallbackVisitor<R>(this);
}
/// Visits [node] if not already visited to compute a value for [node].
///
/// If the value has already been computed the cached value is returned immediately.
///
/// Call this method to compute values for subnodes recursively, while only
/// visiting each subnode once.
R visitConstant(Constant node) {
return cache[node] ??= node.accept(_visitor);
}
R defaultConstant(Constant node) => null;
R visitNullConstant(NullConstant node) => defaultConstant(node);
R visitBoolConstant(BoolConstant node) => defaultConstant(node);
R visitIntConstant(IntConstant node) => defaultConstant(node);
R visitDoubleConstant(DoubleConstant node) => defaultConstant(node);
R visitStringConstant(StringConstant node) => defaultConstant(node);
R visitSymbolConstant(SymbolConstant node) => defaultConstant(node);
R visitMapConstant(MapConstant node) => defaultConstant(node);
R visitListConstant(ListConstant node) => defaultConstant(node);
R visitSetConstant(SetConstant node) => defaultConstant(node);
R visitInstanceConstant(InstanceConstant node) => defaultConstant(node);
R visitPartialInstantiationConstant(PartialInstantiationConstant node) =>
defaultConstant(node);
R visitTearOffConstant(TearOffConstant node) => defaultConstant(node);
R visitTypeLiteralConstant(TypeLiteralConstant node) => defaultConstant(node);
R visitUnevaluatedConstant(UnevaluatedConstant node) => defaultConstant(node);
}
/// Visitor-like class used for visiting each subnode of a [Constant] node once.
///
/// The visitor records the visited node to ensure that each subnode is only
/// visited once.
class VisitOnceConstantVisitor implements _ConstantCallback<void> {
_ConstantCallbackVisitor<void> _visitor;
Set<Constant> cache = new LinkedHashSet.identity();
VisitOnceConstantVisitor() {
_visitor = new _ConstantCallbackVisitor<void>(this);
}
/// Visits [node] if not already visited.
///
/// Call this method to visit subnodes recursively, while only visiting each
/// subnode once.
void visitConstant(Constant node) {
if (cache.add(node)) {
node.accept(_visitor);
}
}
void defaultConstant(Constant node) => null;
void visitNullConstant(NullConstant node) => defaultConstant(node);
void visitBoolConstant(BoolConstant node) => defaultConstant(node);
void visitIntConstant(IntConstant node) => defaultConstant(node);
void visitDoubleConstant(DoubleConstant node) => defaultConstant(node);
void visitStringConstant(StringConstant node) => defaultConstant(node);
void visitSymbolConstant(SymbolConstant node) => defaultConstant(node);
void visitMapConstant(MapConstant node) => defaultConstant(node);
void visitListConstant(ListConstant node) => defaultConstant(node);
void visitSetConstant(SetConstant node) => defaultConstant(node);
void visitInstanceConstant(InstanceConstant node) => defaultConstant(node);
void visitPartialInstantiationConstant(PartialInstantiationConstant node) =>
defaultConstant(node);
void visitTearOffConstant(TearOffConstant node) => defaultConstant(node);
void visitTypeLiteralConstant(TypeLiteralConstant node) =>
defaultConstant(node);
void visitUnevaluatedConstant(UnevaluatedConstant node) =>
defaultConstant(node);
}
class MemberReferenceVisitor<R> {
const MemberReferenceVisitor();
R defaultMemberReference(Member node) => null;
R visitFieldReference(Field node) => defaultMemberReference(node);
R visitConstructorReference(Constructor node) => defaultMemberReference(node);
R visitProcedureReference(Procedure node) => defaultMemberReference(node);
R visitRedirectingFactoryConstructorReference(
RedirectingFactoryConstructor node) {
return defaultMemberReference(node);
}
}
class Visitor<R> extends TreeVisitor<R>
implements
DartTypeVisitor<R>,
ConstantVisitor<R>,
MemberReferenceVisitor<R> {
const Visitor();
/// The catch-all case, except for references.
R defaultNode(Node node) => null;
R defaultTreeNode(TreeNode node) => defaultNode(node);
// DartTypes
R defaultDartType(DartType node) => defaultNode(node);
R visitInvalidType(InvalidType node) => defaultDartType(node);
R visitDynamicType(DynamicType node) => defaultDartType(node);
R visitVoidType(VoidType node) => defaultDartType(node);
R visitBottomType(BottomType node) => defaultDartType(node);
R visitInterfaceType(InterfaceType node) => defaultDartType(node);
R visitFunctionType(FunctionType node) => defaultDartType(node);
R visitTypeParameterType(TypeParameterType node) => defaultDartType(node);
R visitTypedefType(TypedefType node) => defaultDartType(node);
// Constants
R defaultConstant(Constant node) => defaultNode(node);
R visitNullConstant(NullConstant node) => defaultConstant(node);
R visitBoolConstant(BoolConstant node) => defaultConstant(node);
R visitIntConstant(IntConstant node) => defaultConstant(node);
R visitDoubleConstant(DoubleConstant node) => defaultConstant(node);
R visitStringConstant(StringConstant node) => defaultConstant(node);
R visitSymbolConstant(SymbolConstant node) => defaultConstant(node);
R visitMapConstant(MapConstant node) => defaultConstant(node);
R visitListConstant(ListConstant node) => defaultConstant(node);
R visitSetConstant(SetConstant node) => defaultConstant(node);
R visitInstanceConstant(InstanceConstant node) => defaultConstant(node);
R visitPartialInstantiationConstant(PartialInstantiationConstant node) =>
defaultConstant(node);
R visitTearOffConstant(TearOffConstant node) => defaultConstant(node);
R visitTypeLiteralConstant(TypeLiteralConstant node) => defaultConstant(node);
R visitUnevaluatedConstant(UnevaluatedConstant node) => defaultConstant(node);
// Class references
R visitClassReference(Class node) => null;
R visitTypedefReference(Typedef node) => null;
// Constant references
R defaultConstantReference(Constant node) => null;
R visitNullConstantReference(NullConstant node) =>
defaultConstantReference(node);
R visitBoolConstantReference(BoolConstant node) =>
defaultConstantReference(node);
R visitIntConstantReference(IntConstant node) =>
defaultConstantReference(node);
R visitDoubleConstantReference(DoubleConstant node) =>
defaultConstantReference(node);
R visitStringConstantReference(StringConstant node) =>
defaultConstantReference(node);
R visitSymbolConstantReference(SymbolConstant node) =>
defaultConstantReference(node);
R visitMapConstantReference(MapConstant node) =>
defaultConstantReference(node);
R visitListConstantReference(ListConstant node) =>
defaultConstantReference(node);
R visitSetConstantReference(SetConstant node) =>
defaultConstantReference(node);
R visitInstanceConstantReference(InstanceConstant node) =>
defaultConstantReference(node);
R visitPartialInstantiationConstantReference(
PartialInstantiationConstant node) =>
defaultConstantReference(node);
R visitTearOffConstantReference(TearOffConstant node) =>
defaultConstantReference(node);
R visitTypeLiteralConstantReference(TypeLiteralConstant node) =>
defaultConstantReference(node);
R visitUnevaluatedConstantReference(UnevaluatedConstant node) =>
defaultConstantReference(node);
// Member references
R defaultMemberReference(Member node) => null;
R visitFieldReference(Field node) => defaultMemberReference(node);
R visitConstructorReference(Constructor node) => defaultMemberReference(node);
R visitProcedureReference(Procedure node) => defaultMemberReference(node);
R visitRedirectingFactoryConstructorReference(
RedirectingFactoryConstructor node) {
return defaultMemberReference(node);
}
R visitName(Name node) => defaultNode(node);
R visitSupertype(Supertype node) => defaultNode(node);
R visitNamedType(NamedType node) => defaultNode(node);
}
class RecursiveVisitor<R> extends Visitor<R> {
const RecursiveVisitor();
R defaultNode(Node node) {
node.visitChildren(this);
return null;
}
}
/// Visitor that recursively rewrites each node in tree.
///
/// Visit methods should return a new node, or the visited node (possibly
/// mutated), or any node from the visited node's subtree.
///
/// Each subclass is responsible for ensuring that the AST remains a tree.
///
/// For example, the following transformer replaces every occurrence of
/// `!(x && y)` with `(!x || !y)`:
///
/// class NegationSinker extends Transformer {
/// @override
/// Node visitNot(Not node) {
/// var operand = node.operand.accept(this); // Remember to visit.
/// if (operand is LogicalExpression && operand.operator == '&&') {
/// return new LogicalExpression(
/// new Not(operand.left),
/// '||',
/// new Not(operand.right));
/// }
/// return node;
/// }
/// }
///
class Transformer extends TreeVisitor<TreeNode> {
const Transformer();
/// Replaces a use of a type.
///
/// By default, recursion stops at this point.
DartType visitDartType(DartType node) => node;
Constant visitConstant(Constant node) => node;
Supertype visitSupertype(Supertype node) => node;
TreeNode defaultTreeNode(TreeNode node) {
node.transformChildren(this);
return node;
}
}
abstract class ExpressionVisitor1<R, T> {
const ExpressionVisitor1();
R defaultExpression(Expression node, T arg) => null;
R defaultBasicLiteral(BasicLiteral node, T arg) =>
defaultExpression(node, arg);
R visitInvalidExpression(InvalidExpression node, T arg) =>
defaultExpression(node, arg);
R visitVariableGet(VariableGet node, T arg) => defaultExpression(node, arg);
R visitVariableSet(VariableSet node, T arg) => defaultExpression(node, arg);
R visitPropertyGet(PropertyGet node, T arg) => defaultExpression(node, arg);
R visitPropertySet(PropertySet node, T arg) => defaultExpression(node, arg);
R visitDirectPropertyGet(DirectPropertyGet node, T arg) =>
defaultExpression(node, arg);
R visitDirectPropertySet(DirectPropertySet node, T arg) =>
defaultExpression(node, arg);
R visitSuperPropertyGet(SuperPropertyGet node, T arg) =>
defaultExpression(node, arg);
R visitSuperPropertySet(SuperPropertySet node, T arg) =>
defaultExpression(node, arg);
R visitStaticGet(StaticGet node, T arg) => defaultExpression(node, arg);
R visitStaticSet(StaticSet node, T arg) => defaultExpression(node, arg);
R visitMethodInvocation(MethodInvocation node, T arg) =>
defaultExpression(node, arg);
R visitDirectMethodInvocation(DirectMethodInvocation node, T arg) =>
defaultExpression(node, arg);
R visitSuperMethodInvocation(SuperMethodInvocation node, T arg) =>
defaultExpression(node, arg);
R visitStaticInvocation(StaticInvocation node, T arg) =>
defaultExpression(node, arg);
R visitConstructorInvocation(ConstructorInvocation node, T arg) =>
defaultExpression(node, arg);
R visitNot(Not node, T arg) => defaultExpression(node, arg);
R visitNullCheck(NullCheck node, T arg) => defaultExpression(node, arg);
R visitLogicalExpression(LogicalExpression node, T arg) =>
defaultExpression(node, arg);
R visitConditionalExpression(ConditionalExpression node, T arg) =>
defaultExpression(node, arg);
R visitStringConcatenation(StringConcatenation node, T arg) =>
defaultExpression(node, arg);
R visitListConcatenation(ListConcatenation node, T arg) =>
defaultExpression(node, arg);
R visitSetConcatenation(SetConcatenation node, T arg) =>
defaultExpression(node, arg);
R visitMapConcatenation(MapConcatenation node, T arg) =>
defaultExpression(node, arg);
R visitInstanceCreation(InstanceCreation node, T arg) =>
defaultExpression(node, arg);
R visitFileUriExpression(FileUriExpression node, T arg) =>
defaultExpression(node, arg);
R visitIsExpression(IsExpression node, T arg) => defaultExpression(node, arg);
R visitAsExpression(AsExpression node, T arg) => defaultExpression(node, arg);
R visitSymbolLiteral(SymbolLiteral node, T arg) =>
defaultExpression(node, arg);
R visitTypeLiteral(TypeLiteral node, T arg) => defaultExpression(node, arg);
R visitThisExpression(ThisExpression node, T arg) =>
defaultExpression(node, arg);
R visitConstantExpression(ConstantExpression node, T arg) =>
defaultExpression(node, arg);
R visitRethrow(Rethrow node, T arg) => defaultExpression(node, arg);
R visitThrow(Throw node, T arg) => defaultExpression(node, arg);
R visitListLiteral(ListLiteral node, T arg) => defaultExpression(node, arg);
R visitSetLiteral(SetLiteral node, T arg) => defaultExpression(node, arg);
R visitMapLiteral(MapLiteral node, T arg) => defaultExpression(node, arg);
R visitAwaitExpression(AwaitExpression node, T arg) =>
defaultExpression(node, arg);
R visitFunctionExpression(FunctionExpression node, T arg) =>
defaultExpression(node, arg);
R visitIntLiteral(IntLiteral node, T arg) => defaultBasicLiteral(node, arg);
R visitStringLiteral(StringLiteral node, T arg) =>
defaultBasicLiteral(node, arg);
R visitDoubleLiteral(DoubleLiteral node, T arg) =>
defaultBasicLiteral(node, arg);
R visitBoolLiteral(BoolLiteral node, T arg) => defaultBasicLiteral(node, arg);
R visitNullLiteral(NullLiteral node, T arg) => defaultBasicLiteral(node, arg);
R visitLet(Let node, T arg) => defaultExpression(node, arg);
R visitBlockExpression(BlockExpression node, T arg) =>
defaultExpression(node, arg);
R visitInstantiation(Instantiation node, T arg) =>
defaultExpression(node, arg);
R visitLoadLibrary(LoadLibrary node, T arg) => defaultExpression(node, arg);
R visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node, T arg) =>
defaultExpression(node, arg);
}
abstract class StatementVisitor1<R, T> {
const StatementVisitor1();
R defaultStatement(Statement node, T arg) => null;
R visitExpressionStatement(ExpressionStatement node, T arg) =>
defaultStatement(node, arg);
R visitBlock(Block node, T arg) => defaultStatement(node, arg);
R visitAssertBlock(AssertBlock node, T arg) => defaultStatement(node, arg);
R visitEmptyStatement(EmptyStatement node, T arg) =>
defaultStatement(node, arg);
R visitAssertStatement(AssertStatement node, T arg) =>
defaultStatement(node, arg);
R visitLabeledStatement(LabeledStatement node, T arg) =>
defaultStatement(node, arg);
R visitBreakStatement(BreakStatement node, T arg) =>
defaultStatement(node, arg);
R visitWhileStatement(WhileStatement node, T arg) =>
defaultStatement(node, arg);
R visitDoStatement(DoStatement node, T arg) => defaultStatement(node, arg);
R visitForStatement(ForStatement node, T arg) => defaultStatement(node, arg);
R visitForInStatement(ForInStatement node, T arg) =>
defaultStatement(node, arg);
R visitSwitchStatement(SwitchStatement node, T arg) =>
defaultStatement(node, arg);
R visitContinueSwitchStatement(ContinueSwitchStatement node, T arg) =>
defaultStatement(node, arg);
R visitIfStatement(IfStatement node, T arg) => defaultStatement(node, arg);
R visitReturnStatement(ReturnStatement node, T arg) =>
defaultStatement(node, arg);
R visitTryCatch(TryCatch node, T arg) => defaultStatement(node, arg);
R visitTryFinally(TryFinally node, T arg) => defaultStatement(node, arg);
R visitYieldStatement(YieldStatement node, T arg) =>
defaultStatement(node, arg);
R visitVariableDeclaration(VariableDeclaration node, T arg) =>
defaultStatement(node, arg);
R visitFunctionDeclaration(FunctionDeclaration node, T arg) =>
defaultStatement(node, arg);
}
abstract class BodyVisitor1<R, T> extends ExpressionVisitor1<R, T>
implements StatementVisitor1<R, T> {
const BodyVisitor1();
R defaultStatement(Statement node, T arg) => null;
R visitExpressionStatement(ExpressionStatement node, T arg) =>
defaultStatement(node, arg);
R visitBlock(Block node, T arg) => defaultStatement(node, arg);
R visitAssertBlock(AssertBlock node, T arg) => defaultStatement(node, arg);
R visitEmptyStatement(EmptyStatement node, T arg) =>
defaultStatement(node, arg);
R visitAssertStatement(AssertStatement node, T arg) =>
defaultStatement(node, arg);
R visitLabeledStatement(LabeledStatement node, T arg) =>
defaultStatement(node, arg);
R visitBreakStatement(BreakStatement node, T arg) =>
defaultStatement(node, arg);
R visitWhileStatement(WhileStatement node, T arg) =>
defaultStatement(node, arg);
R visitDoStatement(DoStatement node, T arg) => defaultStatement(node, arg);
R visitForStatement(ForStatement node, T arg) => defaultStatement(node, arg);
R visitForInStatement(ForInStatement node, T arg) =>
defaultStatement(node, arg);
R visitSwitchStatement(SwitchStatement node, T arg) =>
defaultStatement(node, arg);
R visitContinueSwitchStatement(ContinueSwitchStatement node, T arg) =>
defaultStatement(node, arg);
R visitIfStatement(IfStatement node, T arg) => defaultStatement(node, arg);
R visitReturnStatement(ReturnStatement node, T arg) =>
defaultStatement(node, arg);
R visitTryCatch(TryCatch node, T arg) => defaultStatement(node, arg);
R visitTryFinally(TryFinally node, T arg) => defaultStatement(node, arg);
R visitYieldStatement(YieldStatement node, T arg) =>
defaultStatement(node, arg);
R visitVariableDeclaration(VariableDeclaration node, T arg) =>
defaultStatement(node, arg);
R visitFunctionDeclaration(FunctionDeclaration node, T arg) =>
defaultStatement(node, arg);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/clone.dart | // 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.
library kernel.clone;
import 'dart:core' hide MapEntry;
import 'ast.dart';
import 'type_algebra.dart';
/// Visitor that return a clone of a tree, maintaining references to cloned
/// objects.
///
/// It is safe to clone members, but cloning a class or library is not
/// supported.
class CloneVisitor implements TreeVisitor<TreeNode> {
final Map<VariableDeclaration, VariableDeclaration> variables =
<VariableDeclaration, VariableDeclaration>{};
final Map<LabeledStatement, LabeledStatement> labels =
<LabeledStatement, LabeledStatement>{};
final Map<SwitchCase, SwitchCase> switchCases = <SwitchCase, SwitchCase>{};
final Map<TypeParameter, DartType> typeSubstitution;
final Map<TypeParameter, TypeParameter> typeParams;
bool cloneAnnotations;
/// Creates an instance of the cloning visitor for Kernel ASTs.
///
/// The boolean value of [cloneAnnotations] tells if the annotations on the
/// outline elements in the source AST should be cloned to the target AST. The
/// annotations in procedure bodies are cloned unconditionally.
CloneVisitor(
{Map<TypeParameter, DartType> typeSubstitution,
Map<TypeParameter, TypeParameter> typeParams,
this.cloneAnnotations = true})
: this.typeSubstitution = ensureMutable(typeSubstitution),
this.typeParams = typeParams ?? <TypeParameter, TypeParameter>{};
static Map<TypeParameter, DartType> ensureMutable(
Map<TypeParameter, DartType> map) {
// We need to mutate this map, so make sure we don't use a constant map.
if (map == null || map.isEmpty) {
return <TypeParameter, DartType>{};
}
return map;
}
TreeNode visitLibrary(Library node) {
throw 'Cloning of libraries is not implemented';
}
TreeNode visitClass(Class node) {
throw 'Cloning of classes is not implemented';
}
TreeNode visitExtension(Extension node) {
throw 'Cloning of extensions is not implemented';
}
// The currently active file uri where we are cloning [TreeNode]s from. If
// this is set to `null` we cannot clone file offsets to newly created nodes.
// The [_cloneFileOffset] helper function will ensure this.
Uri _activeFileUri;
// If we don't know the file uri we are cloning elements from, it's not safe
// to clone file offsets either.
int _cloneFileOffset(int fileOffset) {
return _activeFileUri == null ? TreeNode.noOffset : fileOffset;
}
T clone<T extends TreeNode>(T node) {
final Uri activeFileUriSaved = _activeFileUri;
if (node is FileUriNode) _activeFileUri = node.fileUri ?? _activeFileUri;
final TreeNode result = node.accept(this)
..fileOffset = _cloneFileOffset(node.fileOffset);
_activeFileUri = activeFileUriSaved;
return result;
}
TreeNode cloneOptional(TreeNode node) {
if (node == null) return null;
final Uri activeFileUriSaved = _activeFileUri;
if (node is FileUriNode) _activeFileUri = node.fileUri ?? _activeFileUri;
TreeNode result = node?.accept(this);
if (result != null) result.fileOffset = _cloneFileOffset(node.fileOffset);
_activeFileUri = activeFileUriSaved;
return result;
}
DartType visitType(DartType type) {
return substitute(type, typeSubstitution);
}
Constant visitConstant(Constant constant) {
return constant;
}
DartType visitOptionalType(DartType type) {
return type == null ? null : substitute(type, typeSubstitution);
}
visitInvalidExpression(InvalidExpression node) {
return new InvalidExpression(node.message);
}
visitVariableGet(VariableGet node) {
return new VariableGet(
variables[node.variable], visitOptionalType(node.promotedType));
}
visitVariableSet(VariableSet node) {
return new VariableSet(variables[node.variable], clone(node.value));
}
visitPropertyGet(PropertyGet node) {
return new PropertyGet.byReference(
clone(node.receiver), node.name, node.interfaceTargetReference);
}
visitPropertySet(PropertySet node) {
return new PropertySet.byReference(clone(node.receiver), node.name,
clone(node.value), node.interfaceTargetReference);
}
visitDirectPropertyGet(DirectPropertyGet node) {
return new DirectPropertyGet.byReference(
clone(node.receiver), node.targetReference);
}
visitDirectPropertySet(DirectPropertySet node) {
return new DirectPropertySet.byReference(
clone(node.receiver), node.targetReference, clone(node.value));
}
visitSuperPropertyGet(SuperPropertyGet node) {
return new SuperPropertyGet.byReference(
node.name, node.interfaceTargetReference);
}
visitSuperPropertySet(SuperPropertySet node) {
return new SuperPropertySet.byReference(
node.name, clone(node.value), node.interfaceTargetReference);
}
visitStaticGet(StaticGet node) {
return new StaticGet.byReference(node.targetReference);
}
visitStaticSet(StaticSet node) {
return new StaticSet.byReference(node.targetReference, clone(node.value));
}
visitMethodInvocation(MethodInvocation node) {
return new MethodInvocation.byReference(clone(node.receiver), node.name,
clone(node.arguments), node.interfaceTargetReference);
}
visitDirectMethodInvocation(DirectMethodInvocation node) {
return new DirectMethodInvocation.byReference(
clone(node.receiver), node.targetReference, clone(node.arguments));
}
visitSuperMethodInvocation(SuperMethodInvocation node) {
return new SuperMethodInvocation.byReference(
node.name, clone(node.arguments), node.interfaceTargetReference);
}
visitStaticInvocation(StaticInvocation node) {
return new StaticInvocation.byReference(
node.targetReference, clone(node.arguments),
isConst: node.isConst);
}
visitConstructorInvocation(ConstructorInvocation node) {
return new ConstructorInvocation.byReference(
node.targetReference, clone(node.arguments),
isConst: node.isConst);
}
visitNot(Not node) {
return new Not(clone(node.operand));
}
visitNullCheck(NullCheck node) {
return new NullCheck(clone(node.operand));
}
visitLogicalExpression(LogicalExpression node) {
return new LogicalExpression(
clone(node.left), node.operator, clone(node.right));
}
visitConditionalExpression(ConditionalExpression node) {
return new ConditionalExpression(clone(node.condition), clone(node.then),
clone(node.otherwise), visitOptionalType(node.staticType));
}
visitStringConcatenation(StringConcatenation node) {
return new StringConcatenation(node.expressions.map(clone).toList());
}
visitListConcatenation(ListConcatenation node) {
return new ListConcatenation(node.lists.map(clone).toList(),
typeArgument: visitType(node.typeArgument));
}
visitSetConcatenation(SetConcatenation node) {
return new SetConcatenation(node.sets.map(clone).toList(),
typeArgument: visitType(node.typeArgument));
}
visitMapConcatenation(MapConcatenation node) {
return new MapConcatenation(node.maps.map(clone).toList(),
keyType: visitType(node.keyType), valueType: visitType(node.valueType));
}
visitInstanceCreation(InstanceCreation node) {
final Map<Reference, Expression> fieldValues = <Reference, Expression>{};
node.fieldValues.forEach((Reference fieldRef, Expression value) {
fieldValues[fieldRef] = clone(value);
});
return new InstanceCreation(
node.classReference,
node.typeArguments.map(visitType).toList(),
fieldValues,
node.asserts.map(clone).toList(),
node.unusedArguments.map(clone).toList());
}
visitFileUriExpression(FileUriExpression node) {
return new FileUriExpression(clone(node.expression), _activeFileUri);
}
visitIsExpression(IsExpression node) {
return new IsExpression(clone(node.operand), visitType(node.type));
}
visitAsExpression(AsExpression node) {
return new AsExpression(clone(node.operand), visitType(node.type))
..flags = node.flags;
}
visitSymbolLiteral(SymbolLiteral node) {
return new SymbolLiteral(node.value);
}
visitTypeLiteral(TypeLiteral node) {
return new TypeLiteral(visitType(node.type));
}
visitThisExpression(ThisExpression node) {
return new ThisExpression();
}
visitRethrow(Rethrow node) {
return new Rethrow();
}
visitThrow(Throw node) {
return new Throw(cloneOptional(node.expression));
}
visitListLiteral(ListLiteral node) {
return new ListLiteral(node.expressions.map(clone).toList(),
typeArgument: visitType(node.typeArgument), isConst: node.isConst);
}
visitSetLiteral(SetLiteral node) {
return new SetLiteral(node.expressions.map(clone).toList(),
typeArgument: visitType(node.typeArgument), isConst: node.isConst);
}
visitMapLiteral(MapLiteral node) {
return new MapLiteral(node.entries.map(clone).toList(),
keyType: visitType(node.keyType),
valueType: visitType(node.valueType),
isConst: node.isConst);
}
visitMapEntry(MapEntry node) {
return new MapEntry(clone(node.key), clone(node.value));
}
visitAwaitExpression(AwaitExpression node) {
return new AwaitExpression(clone(node.operand));
}
visitFunctionExpression(FunctionExpression node) {
return new FunctionExpression(clone(node.function));
}
visitConstantExpression(ConstantExpression node) {
return new ConstantExpression(
visitConstant(node.constant), visitType(node.type));
}
visitStringLiteral(StringLiteral node) {
return new StringLiteral(node.value);
}
visitIntLiteral(IntLiteral node) {
return new IntLiteral(node.value);
}
visitDoubleLiteral(DoubleLiteral node) {
return new DoubleLiteral(node.value);
}
visitBoolLiteral(BoolLiteral node) {
return new BoolLiteral(node.value);
}
visitNullLiteral(NullLiteral node) {
return new NullLiteral();
}
visitLet(Let node) {
var newVariable = clone(node.variable);
return new Let(newVariable, clone(node.body));
}
visitBlockExpression(BlockExpression node) {
return new BlockExpression(clone(node.body), clone(node.value));
}
visitExpressionStatement(ExpressionStatement node) {
return new ExpressionStatement(clone(node.expression));
}
visitBlock(Block node) {
return new Block(node.statements.map(clone).toList());
}
visitAssertBlock(AssertBlock node) {
return new AssertBlock(node.statements.map(clone).toList());
}
visitEmptyStatement(EmptyStatement node) {
return new EmptyStatement();
}
visitAssertStatement(AssertStatement node) {
return new AssertStatement(clone(node.condition),
conditionStartOffset: node.conditionStartOffset,
conditionEndOffset: node.conditionEndOffset,
message: cloneOptional(node.message));
}
visitLabeledStatement(LabeledStatement node) {
LabeledStatement newNode = new LabeledStatement(null);
labels[node] = newNode;
newNode.body = clone(node.body)..parent = newNode;
return newNode;
}
visitBreakStatement(BreakStatement node) {
return new BreakStatement(labels[node.target]);
}
visitWhileStatement(WhileStatement node) {
return new WhileStatement(clone(node.condition), clone(node.body));
}
visitDoStatement(DoStatement node) {
return new DoStatement(clone(node.body), clone(node.condition));
}
visitForStatement(ForStatement node) {
var variables = node.variables.map(clone).toList();
return new ForStatement(variables, cloneOptional(node.condition),
node.updates.map(clone).toList(), clone(node.body));
}
visitForInStatement(ForInStatement node) {
var newVariable = clone(node.variable);
return new ForInStatement(
newVariable, clone(node.iterable), clone(node.body),
isAsync: node.isAsync);
}
visitSwitchStatement(SwitchStatement node) {
for (SwitchCase switchCase in node.cases) {
switchCases[switchCase] = new SwitchCase(
switchCase.expressions.map(clone).toList(),
new List<int>.from(switchCase.expressionOffsets),
null,
isDefault: switchCase.isDefault);
}
return new SwitchStatement(
clone(node.expression), node.cases.map(clone).toList());
}
visitSwitchCase(SwitchCase node) {
var switchCase = switchCases[node];
switchCase.body = clone(node.body)..parent = switchCase;
return switchCase;
}
visitContinueSwitchStatement(ContinueSwitchStatement node) {
return new ContinueSwitchStatement(switchCases[node.target]);
}
visitIfStatement(IfStatement node) {
return new IfStatement(
clone(node.condition), clone(node.then), cloneOptional(node.otherwise));
}
visitReturnStatement(ReturnStatement node) {
return new ReturnStatement(cloneOptional(node.expression));
}
visitTryCatch(TryCatch node) {
return new TryCatch(clone(node.body), node.catches.map(clone).toList(),
isSynthetic: node.isSynthetic);
}
visitCatch(Catch node) {
var newException = cloneOptional(node.exception);
var newStackTrace = cloneOptional(node.stackTrace);
return new Catch(newException, clone(node.body),
stackTrace: newStackTrace, guard: visitType(node.guard));
}
visitTryFinally(TryFinally node) {
return new TryFinally(clone(node.body), clone(node.finalizer));
}
visitYieldStatement(YieldStatement node) {
return new YieldStatement(clone(node.expression))..flags = node.flags;
}
visitVariableDeclaration(VariableDeclaration node) {
return variables[node] = new VariableDeclaration(node.name,
initializer: cloneOptional(node.initializer),
type: visitType(node.type))
..annotations = cloneAnnotations && !node.annotations.isEmpty
? node.annotations.map(clone).toList()
: const <Expression>[]
..flags = node.flags
..fileEqualsOffset = _cloneFileOffset(node.fileEqualsOffset);
}
visitFunctionDeclaration(FunctionDeclaration node) {
var newVariable = clone(node.variable);
return new FunctionDeclaration(newVariable, clone(node.function));
}
// Members
visitConstructor(Constructor node) {
return new Constructor(clone(node.function),
name: node.name,
isConst: node.isConst,
isExternal: node.isExternal,
isSynthetic: node.isSynthetic,
initializers: node.initializers.map(clone).toList(),
transformerFlags: node.transformerFlags,
fileUri: _activeFileUri)
..annotations = cloneAnnotations && !node.annotations.isEmpty
? node.annotations.map(clone).toList()
: const <Expression>[]
..fileOffset = _cloneFileOffset(node.fileOffset)
..fileEndOffset = _cloneFileOffset(node.fileEndOffset);
}
visitProcedure(Procedure node) {
return new Procedure(node.name, node.kind, clone(node.function),
transformerFlags: node.transformerFlags,
fileUri: _activeFileUri,
forwardingStubSuperTarget: node.forwardingStubSuperTarget,
forwardingStubInterfaceTarget: node.forwardingStubInterfaceTarget)
..annotations = cloneAnnotations && !node.annotations.isEmpty
? node.annotations.map(clone).toList()
: const <Expression>[]
..startFileOffset = _cloneFileOffset(node.startFileOffset)
..fileOffset = _cloneFileOffset(node.fileOffset)
..fileEndOffset = _cloneFileOffset(node.fileEndOffset)
..flags = node.flags;
}
visitField(Field node) {
return new Field(node.name,
type: visitType(node.type),
initializer: cloneOptional(node.initializer),
isCovariant: node.isCovariant,
isFinal: node.isFinal,
isConst: node.isConst,
isStatic: node.isStatic,
isLate: node.isLate,
hasImplicitGetter: node.hasImplicitGetter,
hasImplicitSetter: node.hasImplicitSetter,
transformerFlags: node.transformerFlags,
fileUri: _activeFileUri)
..annotations = cloneAnnotations && !node.annotations.isEmpty
? node.annotations.map(clone).toList()
: const <Expression>[]
..fileOffset = _cloneFileOffset(node.fileOffset)
..fileEndOffset = _cloneFileOffset(node.fileEndOffset)
..flags = node.flags;
}
visitRedirectingFactoryConstructor(RedirectingFactoryConstructor node) {
prepareTypeParameters(node.typeParameters);
return new RedirectingFactoryConstructor(node.targetReference,
name: node.name,
isConst: node.isConst,
isExternal: node.isExternal,
transformerFlags: node.transformerFlags,
typeArguments: node.typeArguments.map(visitType).toList(),
typeParameters: node.typeParameters.map(clone).toList(),
positionalParameters: node.positionalParameters.map(clone).toList(),
namedParameters: node.namedParameters.map(clone).toList(),
requiredParameterCount: node.requiredParameterCount,
fileUri: _activeFileUri)
..annotations = cloneAnnotations && !node.annotations.isEmpty
? node.annotations.map(clone).toList()
: const <Expression>[];
}
void prepareTypeParameters(List<TypeParameter> typeParameters) {
for (TypeParameter node in typeParameters) {
TypeParameter newNode = typeParams[node];
if (newNode == null) {
newNode = new TypeParameter(node.name);
typeParams[node] = newNode;
typeSubstitution[node] = new TypeParameterType(newNode);
}
}
}
visitTypeParameter(TypeParameter node) {
TypeParameter newNode = typeParams[node];
newNode.bound = visitType(node.bound);
if (node.defaultType != null) {
newNode.defaultType = visitType(node.defaultType);
}
return newNode
..annotations = cloneAnnotations && !node.annotations.isEmpty
? node.annotations.map(clone).toList()
: const <Expression>[]
..flags = node.flags;
}
TreeNode cloneFunctionNodeBody(FunctionNode node) {
bool savedCloneAnnotations = this.cloneAnnotations;
try {
this.cloneAnnotations = true;
return cloneOptional(node.body);
} finally {
this.cloneAnnotations = savedCloneAnnotations;
}
}
visitFunctionNode(FunctionNode node) {
prepareTypeParameters(node.typeParameters);
var typeParameters = node.typeParameters.map(clone).toList();
var positional = node.positionalParameters.map(clone).toList();
var named = node.namedParameters.map(clone).toList();
return new FunctionNode(cloneFunctionNodeBody(node),
typeParameters: typeParameters,
positionalParameters: positional,
namedParameters: named,
requiredParameterCount: node.requiredParameterCount,
returnType: visitType(node.returnType),
asyncMarker: node.asyncMarker,
dartAsyncMarker: node.dartAsyncMarker)
..fileOffset = _cloneFileOffset(node.fileOffset)
..fileEndOffset = _cloneFileOffset(node.fileEndOffset);
}
visitArguments(Arguments node) {
return new Arguments(node.positional.map(clone).toList(),
types: node.types.map(visitType).toList(),
named: node.named.map(clone).toList());
}
visitNamedExpression(NamedExpression node) {
return new NamedExpression(node.name, clone(node.value));
}
defaultBasicLiteral(BasicLiteral node) {
return defaultExpression(node);
}
defaultExpression(Expression node) {
throw 'Unimplemented clone for Kernel expression: $node';
}
defaultInitializer(Initializer node) {
throw 'Unimplemented clone for Kernel initializer: $node';
}
defaultMember(Member node) {
throw 'Unimplemented clone for Kernel member: $node';
}
defaultStatement(Statement node) {
throw 'Unimplemented clone for Kernel statement: $node';
}
defaultTreeNode(TreeNode node) {
throw 'Cloning Kernel non-members is not supported. '
'Tried cloning $node';
}
visitAssertInitializer(AssertInitializer node) {
return new AssertInitializer(clone(node.statement));
}
visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) {
return new CheckLibraryIsLoaded(node.import);
}
visitCombinator(Combinator node) {
return defaultTreeNode(node);
}
visitFieldInitializer(FieldInitializer node) {
return new FieldInitializer.byReference(
node.fieldReference, clone(node.value));
}
visitInstantiation(Instantiation node) {
return new Instantiation(
clone(node.expression), node.typeArguments.map(visitType).toList());
}
visitInvalidInitializer(InvalidInitializer node) {
return new InvalidInitializer();
}
visitLibraryDependency(LibraryDependency node) {
return defaultTreeNode(node);
}
visitLibraryPart(LibraryPart node) {
return defaultTreeNode(node);
}
visitLoadLibrary(LoadLibrary node) {
return new LoadLibrary(node.import);
}
visitLocalInitializer(LocalInitializer node) {
return new LocalInitializer(clone(node.variable));
}
visitComponent(Component node) {
return defaultTreeNode(node);
}
visitRedirectingInitializer(RedirectingInitializer node) {
return new RedirectingInitializer.byReference(
node.targetReference, clone(node.arguments));
}
visitSuperInitializer(SuperInitializer node) {
return new SuperInitializer.byReference(
node.targetReference, clone(node.arguments));
}
visitTypedef(Typedef node) {
return defaultTreeNode(node);
}
}
class CloneWithoutBody extends CloneVisitor {
CloneWithoutBody(
{Map<TypeParameter, DartType> typeSubstitution,
bool cloneAnnotations = true})
: super(
typeSubstitution: typeSubstitution,
cloneAnnotations: cloneAnnotations);
@override
TreeNode cloneFunctionNodeBody(FunctionNode node) => null;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/kernel.dart | // 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.
/// Conventions for paths:
///
/// - Use the [Uri] class for paths that may have the `file`, `dart` or
/// `package` scheme. Never use [Uri] for relative paths.
/// - Use [String]s for all filenames and paths that have no scheme prefix.
/// - Never translate a `dart:` or `package:` URI into a `file:` URI, instead
/// translate it to a [String] if the file system path is needed.
/// - Only use [File] from dart:io at the last moment when it is needed.
///
library kernel;
import 'ast.dart';
import 'binary/ast_to_binary.dart';
import 'binary/ast_from_binary.dart';
import 'dart:async';
import 'dart:io';
import 'text/ast_to_text.dart';
export 'ast.dart';
Component loadComponentFromBinary(String path, [Component component]) {
List<int> bytes = new File(path).readAsBytesSync();
return loadComponentFromBytes(bytes, component);
}
Component loadComponentFromBytes(List<int> bytes, [Component component]) {
component ??= new Component();
new BinaryBuilder(bytes).readComponent(component);
return component;
}
Component loadComponentSourceFromBytes(List<int> bytes, [Component component]) {
component ??= new Component();
new BinaryBuilder(bytes).readComponentSource(component);
return component;
}
Future writeComponentToBinary(Component component, String path) {
var sink;
if (path == 'null' || path == 'stdout') {
sink = stdout.nonBlocking;
} else {
sink = new File(path).openWrite();
}
var future;
try {
new BinaryPrinter(sink).writeComponentFile(component);
} finally {
if (sink == stdout.nonBlocking) {
future = sink.flush();
} else {
future = sink.close();
}
}
return future;
}
void writeLibraryToText(Library library, {String path}) {
StringBuffer buffer = new StringBuffer();
new Printer(buffer).writeLibraryFile(library);
if (path == null) {
print(buffer);
} else {
new File(path).writeAsStringSync('$buffer');
}
}
void writeComponentToText(Component component,
{String path,
bool showExternal: false,
bool showOffsets: false,
bool showMetadata: false}) {
StringBuffer buffer = new StringBuffer();
new Printer(buffer,
showExternal: showExternal,
showOffsets: showOffsets,
showMetadata: showMetadata)
.writeComponentFile(component);
if (path == null) {
print(buffer);
} else {
new File(path).writeAsStringSync('$buffer');
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/class_hierarchy.dart | // 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.
library kernel.class_hierarchy;
import 'dart:collection';
import 'dart:math';
import 'dart:typed_data';
import 'ast.dart';
import 'core_types.dart';
import 'src/heap.dart';
import 'type_algebra.dart';
typedef HandleAmbiguousSupertypes = void Function(Class, Supertype, Supertype);
abstract class MixinInferrer {
void infer(ClassHierarchy hierarchy, Class classNode);
}
/// Interface for answering various subclassing queries.
abstract class ClassHierarchy {
factory ClassHierarchy(Component component,
{HandleAmbiguousSupertypes onAmbiguousSupertypes,
MixinInferrer mixinInferrer}) {
onAmbiguousSupertypes ??= (Class cls, Supertype a, Supertype b) {
// See https://github.com/dart-lang/sdk/issues/32091
throw "$cls can't implement both $a and $b";
};
return new ClosedWorldClassHierarchy._internal(
onAmbiguousSupertypes, mixinInferrer)
.._initialize(component.libraries);
}
void set onAmbiguousSupertypes(
HandleAmbiguousSupertypes onAmbiguousSupertypes);
void set mixinInferrer(MixinInferrer mixinInferrer);
/// Given the [unordered] classes, return them in such order that classes
/// occur after their superclasses. If some superclasses are not in
/// [unordered], they are not included.
Iterable<Class> getOrderedClasses(Iterable<Class> unordered);
// Returns the instantiation of each generic supertype implemented by this
// class (e.g. getClassAsInstanceOf applied to all superclasses and
// interfaces).
List<Supertype> genericSupertypesOf(Class class_);
/// Returns the least upper bound of two interface types, as defined by Dart
/// 1.0.
///
/// Given two interfaces I and J, let S_I be the set of superinterfaces of I,
/// let S_J be the set of superinterfaces of J, and let
/// S = (I union S_I) intersect (J union S_J). Furthermore, we define
/// S_n = {T | T in S and depth(T) = n} for any finite n where depth(T) is
/// the number of steps in the longest inheritance path from T to Object. Let
/// q be the largest number such that S_q has cardinality one. The least
/// upper bound of I and J is the sole element of S_q.
///
/// This is called the "legacy" least upper bound to distinguish it from the
/// Dart 2 least upper bound, which has special behaviors in the case where
/// one type is a subtype of the other, or where both types are based on the
/// same class.
InterfaceType getLegacyLeastUpperBound(
InterfaceType type1, InterfaceType type2, CoreTypes coreTypes);
/// Returns the instantiation of [superclass] that is implemented by [class_],
/// or `null` if [class_] does not implement [superclass] at all.
Supertype getClassAsInstanceOf(Class class_, Class superclass);
/// Returns the instantiation of [superclass] that is implemented by [type],
/// or `null` if [type] does not implement [superclass] at all.
InterfaceType getTypeAsInstanceOf(InterfaceType type, Class superclass);
/// Returns the instantiation of [superclass] that is implemented by [type],
/// or `null` if [type] does not implement [superclass]. [superclass] must
/// be a generic class.
Supertype asInstantiationOf(Supertype type, Class superclass);
/// Returns the instance member that would respond to a dynamic dispatch of
/// [name] to an instance of [class_], or `null` if no such member exists.
///
/// If [setter] is `false`, the name is dispatched as a getter or call,
/// and will return a field, getter, method, or operator (or null).
///
/// If [setter] is `true`, the name is dispatched as a setter, roughly
/// corresponding to `name=` in the Dart specification, but note that the
/// returned member will not have a name ending with `=`. In this case,
/// a non-final field or setter (or null) will be returned.
///
/// If the class is abstract, abstract members are ignored and the dispatch
/// is resolved if the class was not abstract.
Member getDispatchTarget(Class class_, Name name, {bool setter: false});
/// Returns the list of potential targets of dynamic dispatch to an instance
/// of [class_].
///
/// If [setters] is `false`, only potential targets of a getter or call
/// dispatch are returned. If [setters] is `true`, only potential targets
/// of a setter dispatch are returned.
///
/// See [getDispatchTarget] for more details.
///
/// The returned list should not be modified.
List<Member> getDispatchTargets(Class class_, {bool setters: false});
/// Returns the possibly abstract interface member of [class_] with the given
/// [name].
///
/// If [setter] is `false`, only fields, methods, and getters with that name
/// will be found. If [setter] is `true`, only non-final fields and setters
/// will be found.
///
/// If multiple members with that name are inherited and not overridden, the
/// member from the first declared supertype is returned.
Member getInterfaceMember(Class class_, Name name, {bool setter: false});
/// Returns the list of members denoting the interface for [class_], which
/// may include abstract members.
///
/// The list may contain multiple members with a given name. This happens
/// when members are inherited through different supertypes and not overridden
/// in the class.
///
/// Also see [getInterfaceMember].
List<Member> getInterfaceMembers(Class class_, {bool setters: false});
/// Returns the list of members declared in [class_], including abstract
/// members.
///
/// Members are sorted by name so that they may be efficiently compared across
/// classes.
List<Member> getDeclaredMembers(Class class_, {bool setters: false});
/// True if [subclass] inherits from [superclass] though zero or more
/// `extends` relationships.
bool isSubclassOf(Class subclass, Class superclass);
/// True if [subtype] inherits from [superclass] though zero or more
/// `extends`, `with`, and `implements` relationships.
bool isSubtypeOf(Class subtype, Class superclass);
/// True if the given class is used as the right-hand operand to a
/// mixin application (i.e. [Class.mixedInType]).
bool isUsedAsMixin(Class class_);
/// Invokes [callback] for every member declared in or inherited by [class_]
/// that overrides or implements a member in a supertype of [class_]
/// (or in rare cases, overrides a member declared in [class_]).
///
/// We use the term "inheritable" for members that are candidates for
/// inheritance but may have been overridden. The "declared" members of a
/// mixin application are those declared in the mixed-in type. The callback is
/// invoked in the following cases:
///
/// 1. A member declared in the class overrides a member inheritable through
/// one of the supertypes of the class.
///
/// 2. A non-abstract member is inherited from a superclass, and in the
/// context of this class, it overrides an abstract member inheritable through
/// one of its superinterfaces.
///
/// 3. A non-abstract member is inherited from a superclass, and it overrides
/// an abstract member declared in this class.
///
/// This method will not report that a member overrides itself. A given pair
/// may be reported multiple times when there are multiple inheritance paths
/// to the overridden member.
///
/// It is possible for two methods to override one another in both directions.
///
/// By default getters and setters are overridden separately. The [isSetter]
/// callback parameter determines which type of access is being overridden.
void forEachOverridePair(Class class_,
callback(Member declaredMember, Member interfaceMember, bool isSetter));
/// This method is invoked by the client after a change: removal, addition,
/// or modification of classes (via libraries).
///
/// For modified classes specify a class as both removed and added: Some of
/// the information that this hierarchy might have cached, is not valid
/// anymore.
///
/// Note, that it is the clients responsibility to mark all subclasses as
/// changed too.
ClassHierarchy applyTreeChanges(Iterable<Library> removedLibraries,
Iterable<Library> ensureKnownLibraries,
{Component reissueAmbiguousSupertypesFor});
/// This method is invoked by the client after a member change on classes:
/// Some of the information that this hierarchy might have cached,
/// is not valid anymore.
/// Note, that it is the clients responsibility to mark all subclasses as
/// changed too, or - if [findDescendants] is true, the ClassHierarchy will
/// spend the time to find them for the caller.
ClassHierarchy applyMemberChanges(Iterable<Class> classes,
{bool findDescendants: false});
/// Merges two sorted lists.
///
/// If a given member occurs in both lists, the merge will attempt to exclude
/// the duplicate member, but is not strictly guaranteed to do so.
///
/// The sort has the following stability properties:
///
/// - If both x and y came from the same input list, and x preceded y in the
/// input list, x will precede y in the output list. This holds even if x
/// and y have matching names.
///
/// - If m is a contiguous subsequence of the output list containing at least
/// one element from each input list, and all elements of m have matching
/// names, then the elements of m from [first] will precede the elements of
/// m from [second].
static List<Member> mergeSortedLists(
List<Member> first, List<Member> second) {
if (first.isEmpty) return second;
if (second.isEmpty) return first;
List<Member> result = <Member>[]..length = first.length + second.length;
int storeIndex = 0;
int i = 0, j = 0;
while (i < first.length && j < second.length) {
Member firstMember = first[i];
Member secondMember = second[j];
int compare = ClassHierarchy.compareMembers(firstMember, secondMember);
if (compare <= 0) {
result[storeIndex++] = firstMember;
++i;
// If the same member occurs in both lists, skip the duplicate.
if (identical(firstMember, secondMember)) {
++j;
}
} else {
result[storeIndex++] = secondMember;
++j;
}
}
while (i < first.length) {
result[storeIndex++] = first[i++];
}
while (j < second.length) {
result[storeIndex++] = second[j++];
}
result.length = storeIndex;
return result;
}
/// Compares members by name, using the same sort order as
/// [getDeclaredMembers] and [getInterfaceMembers].
static int compareMembers(Member first, Member second) {
return compareNames(first.name, second.name);
}
/// Compares names, using the same sort order as [getDeclaredMembers] and
/// [getInterfaceMembers].
///
/// This is an arbitrary as-fast-as-possible sorting criterion.
static int compareNames(Name firstName, Name secondName) {
int firstHash = firstName.hashCode;
int secondHash = secondName.hashCode;
if (firstHash != secondHash) return firstHash - secondHash;
String firstString = firstName.name;
String secondString = secondName.name;
int firstLength = firstString.length;
int secondLength = secondString.length;
if (firstLength != secondLength) {
return firstLength - secondLength;
}
Library firstLibrary = firstName.library;
Library secondLibrary = secondName.library;
if (firstLibrary != secondLibrary) {
if (firstLibrary == null) return -1;
if (secondLibrary == null) return 1;
return firstLibrary.compareTo(secondLibrary);
}
for (int i = 0; i < firstLength; ++i) {
int firstUnit = firstString.codeUnitAt(i);
int secondUnit = secondString.codeUnitAt(i);
int delta = firstUnit - secondUnit;
if (delta != 0) return delta;
}
return 0;
}
/// Returns the member with the given name, or `null` if no member has the
/// name. In case the list contains multiple members with the given name,
/// the one that occurs first in the list is returned.
///
/// The list is assumed to be sorted according to [compareMembers].
static Member findMemberByName(List<Member> members, Name name) {
int low = 0, high = members.length - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
Member pivot = members[mid];
int comparison = compareNames(name, pivot.name);
if (comparison < 0) {
high = mid - 1;
} else if (comparison > 0) {
low = mid + 1;
} else if (high != mid) {
// Ensure we find the first element of the given name.
high = mid;
} else {
return pivot;
}
}
return null;
}
}
abstract class ClassHierarchySubtypes {
/// Returns the subtypes of [class_] as an interval list.
ClassSet getSubtypesOf(Class class_);
/// Returns the single concrete target for invocation of the given interface
/// target, or `null` if it could not be resolved or there are multiple
/// possible targets.
Member getSingleTargetForInterfaceInvocation(Member interfaceTarget,
{bool setter: false});
}
class _ClassInfoSubtype {
final _ClassInfo classInfo;
int topDownIndex = -1;
/// Top-down indices of all subclasses of this class, represented as
/// interleaved begin/end interval end points.
Uint32List subtypeIntervalList;
_ClassInfoSubtype(this.classInfo);
}
class _ClosedWorldClassHierarchySubtypes implements ClassHierarchySubtypes {
final ClosedWorldClassHierarchy hierarchy;
final List<Class> _classesByTopDownIndex;
final Map<Class, _ClassInfoSubtype> _infoMap = <Class, _ClassInfoSubtype>{};
bool invalidated = false;
_ClosedWorldClassHierarchySubtypes(this.hierarchy)
: _classesByTopDownIndex = new List<Class>(hierarchy._infoMap.length) {
hierarchy.allBetsOff = true;
if (hierarchy._infoMap.isNotEmpty) {
for (Class class_ in hierarchy._infoMap.keys) {
_infoMap[class_] = new _ClassInfoSubtype(hierarchy._infoMap[class_]);
}
_topDownSortVisit(_infoMap[hierarchy._infoMap.keys.first]);
}
}
/// Downwards traversal of the class hierarchy that orders classes so local
/// hierarchies have contiguous indices.
int _topDownSortIndex = 0;
void _topDownSortVisit(_ClassInfoSubtype subInfo) {
if (subInfo.topDownIndex != -1) return;
int index = _topDownSortIndex++;
subInfo.topDownIndex = index;
_classesByTopDownIndex[index] = subInfo.classInfo.classNode;
var subtypeSetBuilder = new _IntervalListBuilder()..addSingleton(index);
for (_ClassInfo subtype in subInfo.classInfo.directExtenders) {
_ClassInfoSubtype subtypeInfo = _infoMap[subtype.classNode];
_topDownSortVisit(subtypeInfo);
subtypeSetBuilder.addIntervalList(subtypeInfo.subtypeIntervalList);
}
for (_ClassInfo subtype in subInfo.classInfo.directMixers) {
_ClassInfoSubtype subtypeInfo = _infoMap[subtype.classNode];
_topDownSortVisit(subtypeInfo);
subtypeSetBuilder.addIntervalList(subtypeInfo.subtypeIntervalList);
}
for (_ClassInfo subtype in subInfo.classInfo.directImplementers) {
_ClassInfoSubtype subtypeInfo = _infoMap[subtype.classNode];
_topDownSortVisit(subtypeInfo);
subtypeSetBuilder.addIntervalList(subtypeInfo.subtypeIntervalList);
}
subInfo.subtypeIntervalList = subtypeSetBuilder.buildIntervalList();
}
@override
Member getSingleTargetForInterfaceInvocation(Member interfaceTarget,
{bool setter: false}) {
if (invalidated) throw "This data structure has been invalidated";
Name name = interfaceTarget.name;
Member target = null;
ClassSet subtypes = getSubtypesOf(interfaceTarget.enclosingClass);
for (Class c in subtypes) {
if (!c.isAbstract) {
Member candidate = hierarchy.getDispatchTarget(c, name, setter: setter);
if ((candidate != null) && !candidate.isAbstract) {
if (target == null) {
target = candidate;
} else if (target != candidate) {
return null;
}
}
}
}
return target;
}
@override
ClassSet getSubtypesOf(Class class_) {
if (invalidated) throw "This data structure has been invalidated";
Set<Class> result = new Set<Class>();
Uint32List list = _infoMap[class_].subtypeIntervalList;
for (int i = 0; i < list.length; i += 2) {
int from = list[i];
int to = list[i + 1];
for (int j = from; j < to; j++) {
result.add(_classesByTopDownIndex[j]);
}
}
return new ClassSet(result);
}
}
/// Implementation of [ClassHierarchy] for closed world.
class ClosedWorldClassHierarchy implements ClassHierarchy {
HandleAmbiguousSupertypes _onAmbiguousSupertypes;
HandleAmbiguousSupertypes _onAmbiguousSupertypesNotWrapped;
MixinInferrer mixinInferrer;
void set onAmbiguousSupertypes(
HandleAmbiguousSupertypes onAmbiguousSupertypes) {
_onAmbiguousSupertypesNotWrapped = onAmbiguousSupertypes;
_onAmbiguousSupertypes = (Class class_, Supertype a, Supertype b) {
onAmbiguousSupertypes(class_, a, b);
List<Supertype> recorded = _recordedAmbiguousSupertypes[class_];
if (recorded == null) {
recorded = new List<Supertype>();
_recordedAmbiguousSupertypes[class_] = recorded;
}
recorded.add(a);
recorded.add(b);
};
}
/// The insert order is important.
final Map<Class, _ClassInfo> _infoMap =
new LinkedHashMap<Class, _ClassInfo>();
_ClassInfo infoFor(Class c) {
_ClassInfo info = _infoMap[c];
info?.used = true;
return info;
}
List<Class> getUsedClasses() {
List<Class> result = new List<Class>();
for (_ClassInfo classInfo in _infoMap.values) {
if (classInfo.used) {
result.add(classInfo.classNode);
}
}
return result;
}
void resetUsed() {
for (_ClassInfo classInfo in _infoMap.values) {
classInfo.used = false;
}
allBetsOff = false;
}
final Set<Library> knownLibraries = new Set<Library>();
bool allBetsOff = false;
/// Recorded errors for classes we have already calculated the class hierarchy
/// for, but will have to be reissued when re-using the calculation.
final Map<Class, List<Supertype>> _recordedAmbiguousSupertypes =
new LinkedHashMap<Class, List<Supertype>>();
Iterable<Class> get classes {
allBetsOff = true;
return _infoMap.keys;
}
int get numberOfClasses {
allBetsOff = true;
return _infoMap.length;
}
_ClosedWorldClassHierarchySubtypes _cachedClassHierarchySubtypes;
ClosedWorldClassHierarchy._internal(
HandleAmbiguousSupertypes onAmbiguousSupertypes, this.mixinInferrer) {
this.onAmbiguousSupertypes = onAmbiguousSupertypes;
}
ClassHierarchySubtypes computeSubtypesInformation() {
_cachedClassHierarchySubtypes ??=
new _ClosedWorldClassHierarchySubtypes(this);
return _cachedClassHierarchySubtypes;
}
@override
Iterable<Class> getOrderedClasses(Iterable<Class> unordered) {
var unorderedSet = unordered.toSet();
for (Class c in unordered) _infoMap[c]?.used = true;
return _infoMap.keys.where(unorderedSet.contains);
}
@override
bool isSubclassOf(Class subclass, Class superclass) {
if (identical(subclass, superclass)) return true;
return infoFor(subclass).isSubclassOf(infoFor(superclass));
}
@override
bool isSubtypeOf(Class subtype, Class superclass) {
if (identical(subtype, superclass)) return true;
return infoFor(subtype).isSubtypeOf(infoFor(superclass));
}
@override
bool isUsedAsMixin(Class class_) {
return infoFor(class_).directMixers.isNotEmpty;
}
List<_ClassInfo> _getRankedSuperclassInfos(_ClassInfo info) {
if (info.leastUpperBoundInfos != null) return info.leastUpperBoundInfos;
var heap = new _LubHeap()..add(info);
var chain = <_ClassInfo>[];
info.leastUpperBoundInfos = chain;
_ClassInfo lastInfo = null;
while (heap.isNotEmpty) {
var nextInfo = heap.remove();
if (identical(nextInfo, lastInfo)) continue;
chain.add(nextInfo);
lastInfo = nextInfo;
var classNode = nextInfo.classNode;
void addToHeap(Supertype supertype) {
heap.add(infoFor(supertype.classNode));
}
if (classNode.supertype != null) addToHeap(classNode.supertype);
if (classNode.mixedInType != null) addToHeap(classNode.mixedInType);
classNode.implementedTypes.forEach(addToHeap);
}
return chain;
}
@override
InterfaceType getLegacyLeastUpperBound(
InterfaceType type1, InterfaceType type2, CoreTypes coreTypes) {
// The algorithm is: first we compute a list of superclasses for both types,
// ordered from greatest to least depth, and ordered by topological sort
// index within each depth. Due to the sort order, we can find the
// intersection of these lists by a simple walk.
//
// Then, for each class in the intersection, determine the exact type that
// is implemented by type1 and type2. If the types match, that type is a
// candidate (it's a member of S_n). As soon as we find a candidate which
// is unique for its depth, we return it.
//
// As an optimization, if the class for I is a subtype of the class for J,
// then we know that the list of superclasses of J is a subset of the list
// of superclasses for I; therefore it is sufficient to compute just the
// list of superclasses for J. To avoid complicating the code below (which
// intersects the two lists), we set both lists equal to the list of
// superclasses for J. And vice versa with the role of I and J swapped.
// Compute the list of superclasses for both types, with the above
// optimization.
_ClassInfo info1 = infoFor(type1.classNode);
_ClassInfo info2 = infoFor(type2.classNode);
List<_ClassInfo> classes1;
List<_ClassInfo> classes2;
if (identical(info1, info2) || info1.isSubtypeOf(info2)) {
classes1 = classes2 = _getRankedSuperclassInfos(info2);
} else if (info2.isSubtypeOf(info1)) {
classes1 = classes2 = _getRankedSuperclassInfos(info1);
} else {
classes1 = _getRankedSuperclassInfos(info1);
classes2 = _getRankedSuperclassInfos(info2);
}
// Walk the lists finding their intersection, looking for a depth that has a
// single candidate.
int i1 = 0;
int i2 = 0;
InterfaceType candidate = null;
int currentDepth = -1;
int numCandidatesAtThisDepth = 0;
while (true) {
_ClassInfo next = classes1[i1];
_ClassInfo next2 = classes2[i2];
if (!identical(next, next2)) {
if (_LubHeap.sortsBeforeStatic(next, next2)) {
++i1;
} else {
++i2;
}
continue;
}
++i2;
++i1;
if (next.depth != currentDepth) {
if (numCandidatesAtThisDepth == 1) return candidate;
currentDepth = next.depth;
numCandidatesAtThisDepth = 0;
candidate = null;
} else if (numCandidatesAtThisDepth > 1) {
continue;
}
// For each class in the intersection, find the exact type that is
// implemented by type1 and type2. If they match, it's a candidate.
//
// Two additional optimizations:
//
// - If this class lacks type parameters, we know there is a match without
// needing to substitute.
//
// - If the depth is 0, we have reached Object, so we can return it
// immediately. Since all interface types are subtypes of Object, this
// ensures the loop terminates.
if (next.classNode.typeParameters.isEmpty) {
// TODO(dmitryas): Update nullability as necessary for the LUB spec.
candidate = coreTypes.legacyRawType(next.classNode);
if (currentDepth == 0) return candidate;
++numCandidatesAtThisDepth;
} else {
var superType1 = identical(info1, next)
? type1
: Substitution.fromInterfaceType(type1).substituteType(
info1.genericSuperTypes[next.classNode].first.asInterfaceType);
var superType2 = identical(info2, next)
? type2
: Substitution.fromInterfaceType(type2).substituteType(
info2.genericSuperTypes[next.classNode].first.asInterfaceType);
if (superType1 == superType2) {
candidate = superType1;
++numCandidatesAtThisDepth;
}
}
}
}
@override
Supertype getClassAsInstanceOf(Class class_, Class superclass) {
if (identical(class_, superclass)) return class_.asThisSupertype;
_ClassInfo info = infoFor(class_);
if (info == null) {
throw "${class_.fileUri}: No class info for ${class_.name}";
}
_ClassInfo superInfo = infoFor(superclass);
if (superInfo == null) {
throw "${superclass.fileUri}: No class info for ${superclass.name}";
}
if (!info.isSubtypeOf(superInfo)) return null;
if (superclass.typeParameters.isEmpty) return superclass.asRawSupertype;
return info.genericSuperTypes[superclass]?.first;
}
@override
InterfaceType getTypeAsInstanceOf(InterfaceType type, Class superclass) {
Supertype castedType = getClassAsInstanceOf(type.classNode, superclass);
if (castedType == null) return null;
return Substitution.fromInterfaceType(type)
.substituteType(castedType.asInterfaceType);
}
@override
Member getDispatchTarget(Class class_, Name name, {bool setter: false}) {
List<Member> list =
_buildImplementedMembers(class_, infoFor(class_), setters: setter);
return ClassHierarchy.findMemberByName(list, name);
}
@override
List<Member> getDispatchTargets(Class class_, {bool setters: false}) {
return _buildImplementedMembers(class_, infoFor(class_), setters: setters);
}
@override
Member getInterfaceMember(Class class_, Name name, {bool setter: false}) {
List<Member> list = getInterfaceMembers(class_, setters: setter);
return ClassHierarchy.findMemberByName(list, name);
}
@override
List<Member> getInterfaceMembers(Class class_, {bool setters: false}) {
return _buildInterfaceMembers(class_, infoFor(class_), setters: setters);
}
@override
List<Member> getDeclaredMembers(Class class_, {bool setters: false}) {
return _buildDeclaredMembers(class_, infoFor(class_), setters: setters);
}
@override
void forEachOverridePair(Class class_,
callback(Member declaredMember, Member interfaceMember, bool isSetter),
{bool crossGettersSetters: false}) {
_ClassInfo info = infoFor(class_);
for (var supertype in class_.supers) {
var superclass = supertype.classNode;
var superGetters = getInterfaceMembers(superclass);
var superSetters = getInterfaceMembers(superclass, setters: true);
_reportOverrides(_buildDeclaredMembers(class_, info, setters: false),
superGetters, callback);
_reportOverrides(_buildDeclaredMembers(class_, info, setters: true),
superSetters, callback,
isSetter: true);
}
}
static void _reportOverrides(
List<Member> declaredList,
List<Member> inheritedList,
callback(Member declaredMember, Member interfaceMember, bool isSetter),
{bool isSetter: false}) {
int i = 0, j = 0;
while (i < declaredList.length && j < inheritedList.length) {
Member declared = declaredList[i];
Member inherited = inheritedList[j];
int comparison = ClassHierarchy.compareMembers(declared, inherited);
if (comparison < 0) {
++i;
} else if (comparison > 0) {
++j;
} else {
if (!identical(declared, inherited)) {
callback(declared, inherited, isSetter);
}
// A given declared member may override multiple interface members,
// so only move past the interface member.
++j;
}
}
}
@override
List<Supertype> genericSupertypesOf(Class class_) {
final supertypes = infoFor(class_).genericSuperTypes;
if (supertypes == null) return const <Supertype>[];
// Multiple supertypes can arise from ambiguous supertypes. The first
// supertype is the real one; the others are purely informational.
return supertypes.values.map((v) => v.first).toList();
}
@override
ClassHierarchy applyTreeChanges(Iterable<Library> removedLibraries,
Iterable<Library> ensureKnownLibraries,
{Component reissueAmbiguousSupertypesFor}) {
// Remove all references to the removed classes.
for (Library lib in removedLibraries) {
if (!knownLibraries.contains(lib)) continue;
for (Class class_ in lib.classes) {
_ClassInfo info = _infoMap[class_];
if (class_.supertype != null) {
_infoMap[class_.supertype.classNode]?.directExtenders?.remove(info);
}
if (class_.mixedInType != null) {
_infoMap[class_.mixedInType.classNode]?.directMixers?.remove(info);
}
for (var supertype in class_.implementedTypes) {
_infoMap[supertype.classNode]?.directImplementers?.remove(info);
}
_infoMap.remove(class_);
_recordedAmbiguousSupertypes.remove(class_);
}
knownLibraries.remove(lib);
}
// If we have a cached computation of subtypes, invalidate it and stop
// caching it.
if (_cachedClassHierarchySubtypes != null) {
_cachedClassHierarchySubtypes.invalidated = true;
}
if (_recordedAmbiguousSupertypes.isNotEmpty &&
reissueAmbiguousSupertypesFor != null) {
Set<Library> libs =
new Set<Library>.from(reissueAmbiguousSupertypesFor.libraries);
for (Class class_ in _recordedAmbiguousSupertypes.keys) {
if (!libs.contains(class_.enclosingLibrary)) continue;
List<Supertype> recorded = _recordedAmbiguousSupertypes[class_];
for (int i = 0; i < recorded.length; i += 2) {
_onAmbiguousSupertypesNotWrapped(
class_, recorded[i], recorded[i + 1]);
}
}
}
// Add the new classes.
List<Class> addedClassesSorted = new List<Class>();
int expectedStartIndex = _topSortIndex;
for (Library lib in ensureKnownLibraries) {
if (knownLibraries.contains(lib)) continue;
for (Class class_ in lib.classes) {
_topologicalSortVisit(class_, new Set<Class>(),
orderedList: addedClassesSorted);
}
knownLibraries.add(lib);
}
_initializeTopologicallySortedClasses(
addedClassesSorted, expectedStartIndex);
return this;
}
@override
ClassHierarchy applyMemberChanges(Iterable<Class> classes,
{bool findDescendants: false}) {
if (classes.isEmpty) return this;
List<_ClassInfo> infos = new List<_ClassInfo>();
if (findDescendants) {
Set<_ClassInfo> processedClasses = new Set<_ClassInfo>();
List<_ClassInfo> worklist = <_ClassInfo>[];
for (Class class_ in classes) {
_ClassInfo info = infoFor(class_);
worklist.add(info);
}
while (worklist.isNotEmpty) {
_ClassInfo info = worklist.removeLast();
if (processedClasses.add(info)) {
worklist.addAll(info.directExtenders);
worklist.addAll(info.directImplementers);
worklist.addAll(info.directMixers);
}
}
infos.addAll(processedClasses);
} else {
for (Class class_ in classes) {
_ClassInfo info = infoFor(class_);
infos.add(info);
}
}
infos.sort((_ClassInfo a, _ClassInfo b) {
return a.topologicalIndex - b.topologicalIndex;
});
for (_ClassInfo info in infos) {
info.lazyDeclaredGettersAndCalls = null;
info.lazyDeclaredSetters = null;
info.lazyImplementedGettersAndCalls = null;
info.lazyImplementedSetters = null;
info.lazyInterfaceGettersAndCalls = null;
info.lazyInterfaceSetters = null;
}
assert(sanityCheckAlsoKnowsParentAndLibrary());
return this;
}
bool sanityCheckAlsoKnowsParentAndLibrary() {
for (Class c in _infoMap.keys) {
if (!knownLibraries.contains(c.enclosingLibrary)) {
throw new StateError("Didn't know library of $c (from ${c.fileUri})");
}
if (c.supertype != null && _infoMap[c.supertype.classNode] == null) {
throw new StateError("Didn't know parent of $c (from ${c.fileUri})");
}
}
return true;
}
@override
Supertype asInstantiationOf(Supertype type, Class superclass) {
// This is similar to getTypeAsInstanceOf, except that it assumes that
// superclass is a generic class. It thus does not rely on being able
// to answer isSubtypeOf queries and so can be used before we have built
// the intervals needed for those queries.
assert(superclass.typeParameters.isNotEmpty);
if (type.classNode == superclass) {
return superclass.asThisSupertype;
}
var map = infoFor(type.classNode)?.genericSuperTypes;
return map == null ? null : map[superclass]?.first;
}
void _initialize(List<Library> libraries) {
// Build the class ordering based on a topological sort.
for (var library in libraries) {
for (var classNode in library.classes) {
_topologicalSortVisit(classNode, new Set<Class>());
}
knownLibraries.add(library);
}
_initializeTopologicallySortedClasses(_infoMap.keys, 0);
}
/// - Build index of direct children.
/// - Build list of super classes and super types.
/// - Infer and record supertypes for the classes.
/// - Record interface members.
/// - Perform some sanity checking.
/// Do this after the topological sort so that super types always occur
/// before subtypes.
void _initializeTopologicallySortedClasses(
Iterable<Class> classes, int expectedStartingTopologicalIndex) {
int i = expectedStartingTopologicalIndex;
for (Class class_ in classes) {
_ClassInfo info = _infoMap[class_];
if (class_.supertype != null) {
_infoMap[class_.supertype.classNode].directExtenders.add(info);
}
if (class_.mixedInType != null) {
_infoMap[class_.mixedInType.classNode].directMixers.add(info);
}
for (var supertype in class_.implementedTypes) {
_infoMap[supertype.classNode].directImplementers.add(info);
}
_collectSupersForClass(class_);
if (class_.supertype != null) {
_recordSuperTypes(info, class_.supertype);
}
if (class_.mixedInType != null) {
mixinInferrer?.infer(this, class_);
_recordSuperTypes(info, class_.mixedInType);
}
for (Supertype supertype in class_.implementedTypes) {
_recordSuperTypes(info, supertype);
}
if (info == null) {
throw "No info for ${class_.name} from ${class_.fileUri}.";
}
if (info.topologicalIndex != i) {
throw "Unexpected topologicalIndex (${info.topologicalIndex} != $i) "
"for ${class_.name} from ${class_.fileUri}.";
}
i++;
}
}
/// Upwards traversal of the class hierarchy that orders classes so super
/// types before their subtypes.
///
/// Returns the depth of the visited class (the number of steps in the longest
/// inheritance path to the root class).
int _topSortIndex = 0;
int _topologicalSortVisit(Class classNode, Set<Class> beingVisited,
{List<Class> orderedList}) {
var info = _infoMap[classNode];
if (info != null) {
return info.depth;
}
if (!beingVisited.add(classNode)) {
throw 'Cyclic inheritance involving ${classNode.name}';
}
info = new _ClassInfo(classNode);
int superDepth = -1;
if (classNode.supertype != null) {
superDepth = max(
superDepth,
_topologicalSortVisit(classNode.supertype.classNode, beingVisited,
orderedList: orderedList));
}
if (classNode.mixedInType != null) {
superDepth = max(
superDepth,
_topologicalSortVisit(classNode.mixedInType.classNode, beingVisited,
orderedList: orderedList));
}
for (var supertype in classNode.implementedTypes) {
superDepth = max(
superDepth,
_topologicalSortVisit(supertype.classNode, beingVisited,
orderedList: orderedList));
}
info.topologicalIndex = _topSortIndex++;
_infoMap[classNode] = info;
orderedList?.add(classNode);
beingVisited.remove(classNode);
return info.depth = superDepth + 1;
}
List<Member> _buildImplementedMembers(Class classNode, _ClassInfo info,
{bool setters}) {
if (info == null) {
throw "${classNode.fileUri}: No class info for ${classNode.name}";
}
List<Member> members = setters
? info.lazyImplementedSetters
: info.lazyImplementedGettersAndCalls;
if (members != null) return members;
List<Member> inherited;
if (classNode.supertype == null) {
inherited = const <Member>[];
} else {
Class superClassNode = classNode.supertype.classNode;
_ClassInfo superInfo = _infoMap[superClassNode];
inherited =
_buildImplementedMembers(superClassNode, superInfo, setters: setters);
}
members = _inheritMembers(
_buildDeclaredMembers(classNode, info, setters: setters), inherited,
skipAbstractMembers: true);
if (setters) {
info.lazyImplementedSetters = members;
} else {
info.lazyImplementedGettersAndCalls = members;
}
return members;
}
List<Member> _buildDeclaredMembers(Class classNode, _ClassInfo info,
{bool setters}) {
if (info == null) {
throw "${classNode.fileUri}: No class info for ${classNode.name}";
}
List<Member> members =
setters ? info.lazyDeclaredSetters : info.lazyDeclaredGettersAndCalls;
if (members != null) return members;
if (classNode.mixedInType != null) {
Class mixedInClassNode = classNode.mixedInType.classNode;
_ClassInfo mixedInInfo = _infoMap[mixedInClassNode];
members = <Member>[];
for (Member mixinMember in _buildDeclaredMembers(
mixedInClassNode, mixedInInfo,
setters: setters)) {
if (mixinMember is! Procedure ||
(mixinMember is Procedure &&
!mixinMember.isNoSuchMethodForwarder)) {
members.add(mixinMember);
}
}
} else {
members = new List<Member>();
for (Procedure procedure in classNode.procedures) {
if (procedure.isStatic) continue;
if (procedure.kind == ProcedureKind.Setter) {
if (setters) {
members.add(procedure);
}
} else {
if (!setters) {
members.add(procedure);
}
}
}
for (Field field in classNode.fields) {
if (field.isStatic) continue;
if (!setters && field.hasImplicitGetter) {
members.add(field);
}
if (setters && field.hasImplicitSetter) {
members.add(field);
}
}
members.sort(ClassHierarchy.compareMembers);
}
if (setters) {
info.lazyDeclaredSetters = members;
} else {
info.lazyDeclaredGettersAndCalls = members;
}
return members;
}
List<Member> _buildInterfaceMembers(Class classNode, _ClassInfo info,
{bool setters}) {
if (info == null) {
throw "${classNode.fileUri}: No class info for ${classNode.name}";
}
List<Member> members =
setters ? info.lazyInterfaceSetters : info.lazyInterfaceGettersAndCalls;
if (members != null) return members;
List<Member> allInheritedMembers = <Member>[];
List<Member> declared =
_buildDeclaredMembers(classNode, info, setters: setters);
void inheritFrom(Supertype type) {
if (type == null) return;
List<Member> inherited = _buildInterfaceMembers(
type.classNode, _infoMap[type.classNode],
setters: setters);
inherited = _getUnshadowedInheritedMembers(declared, inherited);
allInheritedMembers =
ClassHierarchy.mergeSortedLists(allInheritedMembers, inherited);
}
inheritFrom(classNode.supertype);
inheritFrom(classNode.mixedInType);
classNode.implementedTypes.forEach(inheritFrom);
members = _inheritMembers(declared, allInheritedMembers);
if (setters) {
info.lazyInterfaceSetters = members;
} else {
info.lazyInterfaceGettersAndCalls = members;
}
return members;
}
/// Computes the list of implemented members, based on the declared instance
/// members and inherited instance members.
///
/// Both lists must be sorted by name beforehand.
static List<Member> _inheritMembers(
List<Member> declared, List<Member> inherited,
{bool skipAbstractMembers: false}) {
List<Member> result = <Member>[]..length =
declared.length + inherited.length;
// Since both lists are sorted, we can fuse them like in merge sort.
int storeIndex = 0;
int i = 0, j = 0;
while (i < declared.length && j < inherited.length) {
Member declaredMember = declared[i];
Member inheritedMember = inherited[j];
if (skipAbstractMembers && declaredMember.isAbstract) {
++i;
continue;
}
if (skipAbstractMembers && inheritedMember.isAbstract) {
++j;
continue;
}
int comparison =
ClassHierarchy.compareMembers(declaredMember, inheritedMember);
if (comparison < 0) {
result[storeIndex++] = declaredMember;
++i;
} else if (comparison > 0) {
result[storeIndex++] = inheritedMember;
++j;
} else {
result[storeIndex++] = declaredMember;
++i;
++j; // Move past overridden member.
}
}
// One of the two lists is now exhausted, copy over the remains.
while (i < declared.length) {
Member declaredMember = declared[i++];
if (skipAbstractMembers && declaredMember.isAbstract) continue;
result[storeIndex++] = declaredMember;
}
while (j < inherited.length) {
Member inheritedMember = inherited[j++];
if (skipAbstractMembers && inheritedMember.isAbstract) continue;
result[storeIndex++] = inheritedMember;
}
result.length = storeIndex;
return result;
}
/// Returns the subset of members in [inherited] for which a member with the
/// same name does not occur in [declared].
///
/// The input lists must be sorted, and the returned list is sorted.
static List<Member> _getUnshadowedInheritedMembers(
List<Member> declared, List<Member> inherited) {
List<Member> result = <Member>[]..length = inherited.length;
int storeIndex = 0;
int i = 0, j = 0;
while (i < declared.length && j < inherited.length) {
Member declaredMember = declared[i];
Member inheritedMember = inherited[j];
int comparison =
ClassHierarchy.compareMembers(declaredMember, inheritedMember);
if (comparison < 0) {
++i;
} else if (comparison > 0) {
result[storeIndex++] = inheritedMember;
++j;
} else {
// Move past the shadowed member, but retain the declared member, as
// it may shadow multiple members.
++j;
}
}
// If the list of declared members is exhausted, copy over the remains of
// the inherited members.
while (j < inherited.length) {
result[storeIndex++] = inherited[j++];
}
result.length = storeIndex;
return result;
}
void _recordSuperTypes(_ClassInfo subInfo, Supertype supertype) {
_ClassInfo superInfo = _infoMap[supertype.classNode];
if (supertype.typeArguments.isEmpty) {
if (superInfo.genericSuperTypes == null) return;
// Copy over the super type entries.
subInfo.genericSuperTypes ??= <Class, List<Supertype>>{};
superInfo.genericSuperTypes?.forEach((Class key, List<Supertype> types) {
for (Supertype type in types) {
subInfo.recordGenericSuperType(key, type, _onAmbiguousSupertypes);
}
});
} else {
// Copy over all transitive generic super types, and substitute the
// free variables with those provided in [supertype].
Class superclass = supertype.classNode;
var substitution = Substitution.fromPairs(
superclass.typeParameters, supertype.typeArguments);
subInfo.genericSuperTypes ??= <Class, List<Supertype>>{};
superInfo.genericSuperTypes?.forEach((Class key, List<Supertype> types) {
for (Supertype type in types) {
subInfo.recordGenericSuperType(key,
substitution.substituteSupertype(type), _onAmbiguousSupertypes);
}
});
subInfo.recordGenericSuperType(
superclass, supertype, _onAmbiguousSupertypes);
}
}
/// Build lists of super types and super classes.
/// Note that the super class and super types of the class must already have
/// had their supers collected.
void _collectSupersForClass(Class class_) {
_ClassInfo info = _infoMap[class_];
var superclassSetBuilder = new _IntervalListBuilder()
..addSingleton(info.topologicalIndex);
var supertypeSetBuilder = new _IntervalListBuilder()
..addSingleton(info.topologicalIndex);
if (class_.supertype != null) {
_ClassInfo supertypeInfo = _infoMap[class_.supertype.classNode];
superclassSetBuilder
.addIntervalList(supertypeInfo.superclassIntervalList);
supertypeSetBuilder.addIntervalList(supertypeInfo.supertypeIntervalList);
}
if (class_.mixedInType != null) {
_ClassInfo mixedInTypeInfo = _infoMap[class_.mixedInType.classNode];
supertypeSetBuilder
.addIntervalList(mixedInTypeInfo.supertypeIntervalList);
}
for (Supertype supertype in class_.implementedTypes) {
_ClassInfo supertypeInfo = _infoMap[supertype.classNode];
supertypeSetBuilder.addIntervalList(supertypeInfo.supertypeIntervalList);
}
info.superclassIntervalList = superclassSetBuilder.buildIntervalList();
info.supertypeIntervalList = supertypeSetBuilder.buildIntervalList();
}
/// Creates a histogram such that index `N` contains the number of classes
/// that have `N` intervals in its supertype set.
///
/// The more numbers are condensed near the beginning, the more efficient the
/// internal data structure is.
List<int> getExpenseHistogram() {
var result = <int>[];
for (Class class_ in _infoMap.keys) {
var info = _infoMap[class_];
int intervals = info.supertypeIntervalList.length ~/ 2;
if (intervals >= result.length) {
int oldLength = result.length;
result.length = intervals + 1;
result.fillRange(oldLength, result.length, 0);
}
result[intervals] += 1;
}
return result;
}
/// Returns the average number of intervals per supertype relation (less
/// is better, 1.0 is bad).
///
/// This is an estimate of the memory use compared to a data structure that
/// enumerates all superclass/supertype pairs.
double getCompressionRatio() {
int intervals = 0;
int sizes = 0;
for (Class class_ in _infoMap.keys) {
var info = _infoMap[class_];
intervals += (info.superclassIntervalList.length +
info.supertypeIntervalList.length) ~/
2;
sizes += _intervalListSize(info.superclassIntervalList) +
_intervalListSize(info.supertypeIntervalList);
}
return sizes == 0 ? 1.0 : intervals / sizes;
}
/// Returns the number of entries in hash tables storing hierarchy data.
int getSuperTypeHashTableSize() {
int sum = 0;
for (Class class_ in _infoMap.keys) {
sum += _infoMap[class_].genericSuperTypes?.length ?? 0;
}
return sum;
}
}
class _IntervalListBuilder {
final List<int> events = <int>[];
void addInterval(int start, int end) {
// Add an event point for each interval end point, using the low bit to
// distinguish opening from closing end points. Closing end points should
// have the high bit to ensure they occur after an opening end point.
events.add(start << 1);
events.add((end << 1) + 1);
}
void addSingleton(int x) {
addInterval(x, x + 1);
}
void addIntervalList(Uint32List intervals) {
for (int i = 0; i < intervals.length; i += 2) {
addInterval(intervals[i], intervals[i + 1]);
}
}
Uint32List buildIntervalList() {
// Sort the event points and sweep left to right while tracking how many
// intervals we are currently inside. Record an interval end point when the
// number of intervals drop to zero or increase from zero to one.
// Event points are encoded so that an opening end point occur before a
// closing end point at the same value.
events.sort();
int insideCount = 0; // The number of intervals we are currently inside.
int storeIndex = 0;
for (int i = 0; i < events.length; ++i) {
int event = events[i];
if (event & 1 == 0) {
// Start point
++insideCount;
if (insideCount == 1) {
// Store the results temporarily back in the event array.
events[storeIndex++] = event >> 1;
}
} else {
// End point
--insideCount;
if (insideCount == 0) {
events[storeIndex++] = event >> 1;
}
}
}
// Copy the results over to a typed array of the correct length.
var result = new Uint32List(storeIndex);
for (int i = 0; i < storeIndex; ++i) {
result[i] = events[i];
}
return result;
}
}
bool _intervalListContains(Uint32List intervalList, int x) {
int low = 0, high = intervalList.length - 1;
if (high == -1 || x < intervalList[0] || intervalList[high] <= x) {
return false;
}
// Find the lower bound of x in the list.
// If the lower bound is at an even index, the lower bound is an opening point
// of an interval that contains x, otherwise it is a closing point of an
// interval below x and there is no interval containing x.
while (low < high) {
int mid = high - ((high - low) >> 1); // Get middle, rounding up.
int pivot = intervalList[mid];
if (pivot <= x) {
low = mid;
} else {
high = mid - 1;
}
}
return low == high && (low & 1) == 0;
}
int _intervalListSize(Uint32List intervalList) {
int size = 0;
for (int i = 0; i < intervalList.length; i += 2) {
size += intervalList[i + 1] - intervalList[i];
}
return size;
}
class _ClassInfo {
bool used = false;
final Class classNode;
int topologicalIndex = 0;
int depth = 0;
// Super types must always occur before subtypes in these lists.
// For example:
//
// class A extends Object
// class B extends Object implements A
//
// Here `A` must occur before `B` in the list of direct extenders of Object,
// because `B` is a subtype of `A`.
final Set<_ClassInfo> directExtenders = new LinkedHashSet<_ClassInfo>();
final Set<_ClassInfo> directMixers = new LinkedHashSet<_ClassInfo>();
final Set<_ClassInfo> directImplementers = new LinkedHashSet<_ClassInfo>();
Uint32List superclassIntervalList;
Uint32List supertypeIntervalList;
List<_ClassInfo> leastUpperBoundInfos;
/// Maps generic supertype classes to the instantiation implemented by this
/// class.
///
/// E.g. `List` maps to `List<String>` for a class that directly or indirectly
/// implements `List<String>`.
Map<Class, List<Supertype>> genericSuperTypes;
/// Instance fields, getters, methods, and operators declared in this class
/// or its mixed-in class, sorted according to [_compareMembers].
List<Member> lazyDeclaredGettersAndCalls;
/// Non-final instance fields and setters declared in this class or its
/// mixed-in class, sorted according to [_compareMembers].
List<Member> lazyDeclaredSetters;
/// Instance fields, getters, methods, and operators implemented by this class
/// (declared or inherited).
List<Member> lazyImplementedGettersAndCalls;
/// Non-final instance fields and setters implemented by this class
/// (declared or inherited).
List<Member> lazyImplementedSetters;
List<Member> lazyInterfaceGettersAndCalls;
List<Member> lazyInterfaceSetters;
_ClassInfo(this.classNode);
bool isSubclassOf(_ClassInfo other) {
return _intervalListContains(
superclassIntervalList, other.topologicalIndex);
}
bool isSubtypeOf(_ClassInfo other) {
return _intervalListContains(supertypeIntervalList, other.topologicalIndex);
}
void recordGenericSuperType(Class cls, Supertype type,
HandleAmbiguousSupertypes onAmbiguousSupertypes) {
List<Supertype> existing = genericSuperTypes[cls];
if (existing == null) {
genericSuperTypes[cls] = <Supertype>[type];
} else if (type != existing.first) {
existing.add(type);
onAmbiguousSupertypes(classNode, existing.first, type);
}
}
}
/// An immutable set of classes.
class ClassSet extends IterableBase<Class> {
final Set<Class> _classes;
ClassSet(this._classes);
bool contains(Object class_) {
return _classes.contains(class_);
}
ClassSet union(ClassSet other) {
Set<Class> result = new Set<Class>.from(_classes);
result.addAll(other._classes);
return new ClassSet(result);
}
@override
Iterator<Class> get iterator => _classes.iterator;
}
/// Heap for use in computing least upper bounds.
///
/// The heap is sorted such that classes that are deepest in the hierarchy
/// are removed first; in the case of ties, classes with lower topological sort
/// index are removed first.
class _LubHeap extends Heap<_ClassInfo> {
@override
bool sortsBefore(_ClassInfo a, _ClassInfo b) => sortsBeforeStatic(a, b);
static bool sortsBeforeStatic(_ClassInfo a, _ClassInfo b) {
if (a.depth > b.depth) return true;
if (a.depth < b.depth) return false;
return a.topologicalIndex < b.topologicalIndex;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/library_index.dart | // 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.
library kernel.library_index;
import 'ast.dart';
/// Provides name-based access to library, class, and member AST nodes.
///
/// When constructed, a given set of libraries are indexed immediately, and
/// will not be up-to-date with changes made after it was created.
class LibraryIndex {
static const String getterPrefix = 'get:';
static const String setterPrefix = 'set:';
/// A special class name that can be used to access the top-level members
/// of a library.
static const String topLevel = '::';
final Map<String, _ClassTable> _libraries = <String, _ClassTable>{};
/// Indexes the libraries with the URIs given in [libraryUris].
LibraryIndex(Component component, Iterable<String> libraryUris) {
var libraryUriSet = libraryUris.toSet();
for (var library in component.libraries) {
var uri = '${library.importUri}';
if (libraryUriSet.contains(uri)) {
_libraries[uri] = new _ClassTable(library);
}
}
}
/// Indexes the libraries with the URIs given in [libraryUris].
LibraryIndex.byUri(Component component, Iterable<Uri> libraryUris)
: this(component, libraryUris.map((uri) => '$uri'));
/// Indexes `dart:` libraries.
LibraryIndex.coreLibraries(Component component) {
for (var library in component.libraries) {
if (library.importUri.scheme == 'dart') {
_libraries['${library.importUri}'] = new _ClassTable(library);
}
}
}
/// Indexes the entire component.
///
/// Consider using another constructor to only index the libraries that
/// are needed.
LibraryIndex.all(Component component) {
for (var library in component.libraries) {
_libraries['${library.importUri}'] = new _ClassTable(library);
}
}
_ClassTable _getLibraryIndex(String uri) {
_ClassTable libraryIndex = _libraries[uri];
if (libraryIndex == null) {
throw "The library '$uri' has not been indexed";
}
return libraryIndex;
}
/// Returns the library with the given URI.
///
/// Throws an error if it does not exist.
Library getLibrary(String uri) => _getLibraryIndex(uri).library;
/// Like [getLibrary] but returns `null` if not found.
Library tryGetLibrary(String uri) => _libraries[uri]?.library;
/// True if the library with the given URI exists and was indexed.
bool containsLibrary(String uri) => _libraries.containsKey(uri);
/// Returns the class with the given name in the given library.
///
/// An error is thrown if the class is not found.
Class getClass(String library, String className) {
return _getLibraryIndex(library).getClass(className);
}
/// Like [getClass] but returns `null` if not found.
Class tryGetClass(String library, String className) {
return _libraries[library]?.tryGetClass(className);
}
/// Returns the member with the given name, in the given class, in the
/// given library.
///
/// If a getter or setter is wanted, the `get:` or `set:` prefix must be
/// added in front of the member name.
///
/// The special class name `::` can be used to access top-level members.
///
/// If the member name is private it is considered private to [library].
/// It is not possible with this class to lookup members whose name is private
/// to a library other than the one containing it.
///
/// An error is thrown if the member is not found.
Member getMember(String library, String className, String memberName) {
return _getLibraryIndex(library).getMember(className, memberName);
}
/// Like [getMember] but returns `null` if not found.
Member tryGetMember(String library, String className, String memberName) {
return _libraries[library]?.tryGetMember(className, memberName);
}
/// Returns the top-level member with the given name, in the given library.
///
/// If a getter or setter is wanted, the `get:` or `set:` prefix must be
/// added in front of the member name.
///
/// If the member name is private it is considered private to [library].
/// It is not possible with this class to lookup members whose name is private
/// to a library other than the one containing it.
///
/// An error is thrown if the member is not found.
Member getTopLevelMember(String library, String memberName) {
return getMember(library, topLevel, memberName);
}
/// Like [getTopLevelMember] but returns `null` if not found.
Member tryGetTopLevelMember(
String library, String className, String memberName) {
return tryGetMember(library, topLevel, memberName);
}
}
class _ClassTable {
final Library library;
Map<String, _MemberTable> _classes;
_ClassTable(this.library);
Map<String, _MemberTable> get classes {
if (_classes == null) {
_classes = <String, _MemberTable>{};
_classes[LibraryIndex.topLevel] = new _MemberTable.topLevel(this);
for (var class_ in library.classes) {
_classes[class_.name] = new _MemberTable(this, class_);
}
for (Reference reference in library.additionalExports) {
NamedNode node = reference.node;
if (node is Class) {
_classes[node.name] = new _MemberTable(this, node);
}
}
}
return _classes;
}
String get containerName {
// For useful error messages, it can be helpful to indicate if the library
// is external. If a class or member was not found in an external library,
// it might be that it exists in the actual library, but its interface was
// not included in this build unit.
return library.isExternal
? "external library '${library.importUri}'"
: "library '${library.importUri}'";
}
_MemberTable _getClassIndex(String name) {
var indexer = classes[name];
if (indexer == null) {
throw "Class '$name' not found in $containerName";
}
return indexer;
}
Class getClass(String name) {
return _getClassIndex(name).class_;
}
Class tryGetClass(String name) {
return classes[name]?.class_;
}
Member getMember(String className, String memberName) {
return _getClassIndex(className).getMember(memberName);
}
Member tryGetMember(String className, String memberName) {
return classes[className]?.tryGetMember(memberName);
}
}
class _MemberTable {
final _ClassTable parent;
final Class class_; // Null for top-level.
Map<String, Member> _members;
Library get library => parent.library;
_MemberTable(this.parent, this.class_);
_MemberTable.topLevel(this.parent) : class_ = null;
Map<String, Member> get members {
if (_members == null) {
_members = <String, Member>{};
if (class_ != null) {
class_.procedures.forEach(addMember);
class_.fields.forEach(addMember);
class_.constructors.forEach(addMember);
} else {
library.procedures.forEach(addMember);
library.fields.forEach(addMember);
}
}
return _members;
}
String getDisambiguatedName(Member member) {
if (member is Procedure) {
if (member.isGetter) return LibraryIndex.getterPrefix + member.name.name;
if (member.isSetter) return LibraryIndex.setterPrefix + member.name.name;
}
return member.name.name;
}
void addMember(Member member) {
if (member.name.isPrivate && member.name.library != library) {
// Members whose name is private to other libraries cannot currently
// be found with the LibraryIndex class.
return;
}
_members[getDisambiguatedName(member)] = member;
}
String get containerName {
if (class_ == null) {
return "top-level of ${parent.containerName}";
} else {
return "class '${class_.name}' in ${parent.containerName}";
}
}
Member getMember(String name) {
var member = members[name];
if (member == null) {
String message = "A member with disambiguated name '$name' was not found "
"in $containerName";
var getter = LibraryIndex.getterPrefix + name;
var setter = LibraryIndex.setterPrefix + name;
if (members[getter] != null || members[setter] != null) {
throw "$message. Did you mean '$getter' or '$setter'?";
}
throw message;
}
return member;
}
Member tryGetMember(String name) => members[name];
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/type_environment.dart | // 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.
library kernel.type_environment;
import 'ast.dart';
import 'class_hierarchy.dart';
import 'core_types.dart';
import 'type_algebra.dart';
import 'src/hierarchy_based_type_environment.dart'
show HierarchyBasedTypeEnvironment;
typedef void ErrorHandler(TreeNode node, String message);
abstract class TypeEnvironment extends SubtypeTester {
final CoreTypes coreTypes;
InterfaceType thisType;
DartType returnType;
DartType yieldType;
AsyncMarker currentAsyncMarker = AsyncMarker.Sync;
/// An error handler for use in debugging, or `null` if type errors should not
/// be tolerated. See [typeError].
ErrorHandler errorHandler;
TypeEnvironment.fromSubclass(this.coreTypes);
factory TypeEnvironment(CoreTypes coreTypes, ClassHierarchy hierarchy) {
return new HierarchyBasedTypeEnvironment(coreTypes, hierarchy);
}
Class get intClass => coreTypes.intClass;
Class get numClass => coreTypes.numClass;
Class get futureOrClass => coreTypes.futureOrClass;
InterfaceType get objectLegacyRawType => coreTypes.objectLegacyRawType;
InterfaceType get nullType => coreTypes.nullType;
InterfaceType get functionLegacyRawType => coreTypes.functionLegacyRawType;
InterfaceType literalListType(DartType elementType) {
return new InterfaceType(coreTypes.listClass, <DartType>[elementType]);
}
InterfaceType literalSetType(DartType elementType) {
return new InterfaceType(coreTypes.setClass, <DartType>[elementType]);
}
InterfaceType literalMapType(DartType key, DartType value) {
return new InterfaceType(coreTypes.mapClass, <DartType>[key, value]);
}
InterfaceType iterableType(DartType type) {
return new InterfaceType(coreTypes.iterableClass, <DartType>[type]);
}
InterfaceType streamType(DartType type) {
return new InterfaceType(coreTypes.streamClass, <DartType>[type]);
}
InterfaceType futureType(DartType type) {
return new InterfaceType(coreTypes.futureClass, <DartType>[type]);
}
/// Removes a level of `Future<>` types wrapping a type.
///
/// This implements the function `flatten` from the spec, which unwraps a
/// layer of Future or FutureOr from a type.
DartType unfutureType(DartType type) {
if (type is InterfaceType) {
if (type.classNode == coreTypes.futureOrClass ||
type.classNode == coreTypes.futureClass) {
return type.typeArguments[0];
}
// It is a compile-time error to implement, extend, or mixin FutureOr so
// we aren't concerned with it. If a class implements multiple
// instantiations of Future, getTypeAsInstanceOf is responsible for
// picking the least one in the sense required by the spec.
InterfaceType future = getTypeAsInstanceOf(type, coreTypes.futureClass);
if (future != null) {
return future.typeArguments[0];
}
}
return type;
}
/// Called if the computation of a static type failed due to a type error.
///
/// This should never happen in production. The frontend should report type
/// errors, and either recover from the error during translation or abort
/// compilation if unable to recover.
///
/// By default, this throws an exception, since programs in kernel are assumed
/// to be correctly typed.
///
/// An [errorHandler] may be provided in order to override the default
/// behavior and tolerate the presence of type errors. This can be useful for
/// debugging IR producers which are required to produce a strongly typed IR.
void typeError(TreeNode node, String message) {
if (errorHandler != null) {
errorHandler(node, message);
} else {
throw '$message in $node';
}
}
/// True if [member] is a binary operator that returns an `int` if both
/// operands are `int`, and otherwise returns `double`.
///
/// This is a case of type-based overloading, which in Dart is only supported
/// by giving special treatment to certain arithmetic operators.
bool isOverloadedArithmeticOperator(Procedure member) {
Class class_ = member.enclosingClass;
if (class_ == coreTypes.intClass || class_ == coreTypes.numClass) {
String name = member.name.name;
return name == '+' ||
name == '-' ||
name == '*' ||
name == 'remainder' ||
name == '%';
}
return false;
}
/// Returns the static return type of an overloaded arithmetic operator
/// (see [isOverloadedArithmeticOperator]) given the static type of the
/// operands.
///
/// If both types are `int`, the returned type is `int`.
/// If either type is `double`, the returned type is `double`.
/// If both types refer to the same type variable (typically with `num` as
/// the upper bound), then that type variable is returned.
/// Otherwise `num` is returned.
DartType getTypeOfOverloadedArithmetic(DartType type1, DartType type2) {
if (type1 == type2) return type1;
if (type1 == coreTypes.doubleLegacyRawType ||
type2 == coreTypes.doubleLegacyRawType)
return coreTypes.doubleLegacyRawType;
return coreTypes.numLegacyRawType;
}
}
/// The value enum for internal states of [IsSubtypeOf].
enum _IsSubtypeOfValues {
always,
onlyIfIgnoringNullabilities,
never,
}
/// Result of a nullability-aware subtype check.
///
/// It is assumed that if a subtype check succeeds for two types in full-NNBD
/// mode, it also succeeds for those two types if the nullability markers on the
/// types and all of their sub-terms are ignored (that is, in the pre-NNBD
/// mode). By contraposition, if a subtype check fails for two types when the
/// nullability markers are ignored, it should also fail for those types in
/// full-NNBD mode.
class IsSubtypeOf {
final _IsSubtypeOfValues _value;
/// Subtype check succeeds in both modes.
const IsSubtypeOf.always() : _value = _IsSubtypeOfValues.always;
/// Subtype check succeeds only if the nullability markers are ignored.
///
/// This implies that if the nullability markers aren't ignored, the subtype
/// check fails.
const IsSubtypeOf.onlyIfIgnoringNullabilities()
: _value = _IsSubtypeOfValues.onlyIfIgnoringNullabilities;
/// Subtype check fails in both modes.
const IsSubtypeOf.never() : _value = _IsSubtypeOfValues.never;
bool isSubtypeWhenIgnoringNullabilities() {
return _value != _IsSubtypeOfValues.never;
}
bool isSubtypeWhenUsingNullabilities() {
return _value == _IsSubtypeOfValues.always;
}
}
enum SubtypeCheckMode {
withNullabilities,
ignoringNullabilities,
}
/// The part of [TypeEnvironment] that deals with subtype tests.
///
/// This lives in a separate class so it can be tested independently of the SDK.
abstract class SubtypeTester {
InterfaceType get objectLegacyRawType;
InterfaceType get nullType;
InterfaceType get functionLegacyRawType;
Class get futureOrClass;
InterfaceType futureType(DartType type);
static List<Object> typeChecks;
InterfaceType getTypeAsInstanceOf(InterfaceType type, Class superclass);
/// Determines if the given type is at the top of the type hierarchy. May be
/// overridden in subclasses.
bool isTop(DartType type) {
return type is DynamicType ||
type is VoidType ||
type == objectLegacyRawType;
}
/// Can be use to collect type checks. To use:
/// 1. Rename `isSubtypeOf` to `_isSubtypeOf`.
/// 2. Rename `_collect_isSubtypeOf` to `isSubtypeOf`.
/// 3. Comment out the call to `_isSubtypeOf` below.
// ignore:unused_element
bool _collect_isSubtypeOf(DartType subtype, DartType supertype) {
bool result = true;
// result = _isSubtypeOf(subtype, supertype);
typeChecks ??= <Object>[];
typeChecks.add([subtype, supertype, result]);
return result;
}
/// Returns true if [subtype] is a subtype of [supertype].
bool isSubtypeOf(
DartType subtype, DartType supertype, SubtypeCheckMode mode) {
IsSubtypeOf result =
performNullabilityAwareSubtypeCheck(subtype, supertype);
switch (mode) {
case SubtypeCheckMode.ignoringNullabilities:
return result.isSubtypeWhenIgnoringNullabilities();
case SubtypeCheckMode.withNullabilities:
return result.isSubtypeWhenUsingNullabilities();
default:
throw new StateError("Unhandled subtype checking mode '$mode'");
}
}
/// Performs a nullability-aware subtype check.
///
/// The outcome is described in the comments to [IsSubtypeOf].
IsSubtypeOf performNullabilityAwareSubtypeCheck(
DartType subtype, DartType supertype) {
subtype = subtype.unalias;
supertype = supertype.unalias;
if (identical(subtype, supertype)) return const IsSubtypeOf.always();
if (subtype is BottomType) return const IsSubtypeOf.always();
if (subtype == nullType) {
// See rule 4 of the subtype rules from the Dart Language Specification.
return supertype is BottomType
? const IsSubtypeOf.never()
: const IsSubtypeOf.always();
}
if (isTop(supertype)) return const IsSubtypeOf.always();
// Handle FutureOr<T> union type.
if (subtype is InterfaceType &&
identical(subtype.classNode, futureOrClass)) {
var subtypeArg = subtype.typeArguments[0];
if (supertype is InterfaceType &&
identical(supertype.classNode, futureOrClass)) {
var supertypeArg = supertype.typeArguments[0];
// FutureOr<A> <: FutureOr<B> iff A <: B
return performNullabilityAwareSubtypeCheck(subtypeArg, supertypeArg);
}
// given t1 is Future<A> | A, then:
// (Future<A> | A) <: t2 iff Future<A> <: t2 and A <: t2.
var subtypeFuture = futureType(subtypeArg);
return performNullabilityAwareSubtypeCheck(subtypeFuture, supertype)
.isSubtypeWhenIgnoringNullabilities() &&
performNullabilityAwareSubtypeCheck(subtypeArg, supertype)
.isSubtypeWhenIgnoringNullabilities()
? const IsSubtypeOf.always()
: const IsSubtypeOf.never();
}
if (supertype is InterfaceType &&
identical(supertype.classNode, futureOrClass)) {
// given t2 is Future<A> | A, then:
// t1 <: (Future<A> | A) iff t1 <: Future<A> or t1 <: A
var supertypeArg = supertype.typeArguments[0];
var supertypeFuture = futureType(supertypeArg);
return performNullabilityAwareSubtypeCheck(subtype, supertypeFuture)
.isSubtypeWhenIgnoringNullabilities() ||
performNullabilityAwareSubtypeCheck(subtype, supertypeArg)
.isSubtypeWhenIgnoringNullabilities()
? const IsSubtypeOf.always()
: const IsSubtypeOf.never();
}
if (subtype is InterfaceType && supertype is InterfaceType) {
var upcastType = getTypeAsInstanceOf(subtype, supertype.classNode);
if (upcastType == null) return const IsSubtypeOf.never();
for (int i = 0; i < upcastType.typeArguments.length; ++i) {
// Termination: the 'supertype' parameter decreases in size.
if (!performNullabilityAwareSubtypeCheck(
upcastType.typeArguments[i], supertype.typeArguments[i])
.isSubtypeWhenIgnoringNullabilities()) {
return const IsSubtypeOf.never();
}
}
return const IsSubtypeOf.always();
}
if (subtype is TypeParameterType) {
if (supertype is TypeParameterType &&
subtype.parameter == supertype.parameter) {
if (supertype.promotedBound != null) {
return performNullabilityAwareSubtypeCheck(
subtype.bound, supertype.bound);
} else {
// Promoted bound should always be a subtype of the declared bound.
assert(subtype.promotedBound == null ||
performNullabilityAwareSubtypeCheck(
subtype.bound, supertype.bound)
.isSubtypeWhenIgnoringNullabilities());
return const IsSubtypeOf.always();
}
}
// Termination: if there are no cyclically bound type parameters, this
// recursive call can only occur a finite number of times, before reaching
// a shrinking recursive call (or terminating).
return performNullabilityAwareSubtypeCheck(subtype.bound, supertype);
}
if (subtype is FunctionType) {
if (supertype == functionLegacyRawType) return const IsSubtypeOf.always();
if (supertype is FunctionType) {
return _performNullabilityAwareFunctionSubtypeCheck(subtype, supertype);
}
}
return const IsSubtypeOf.never();
}
IsSubtypeOf _performNullabilityAwareFunctionSubtypeCheck(
FunctionType subtype, FunctionType supertype) {
if (subtype.requiredParameterCount > supertype.requiredParameterCount) {
return const IsSubtypeOf.never();
}
if (subtype.positionalParameters.length <
supertype.positionalParameters.length) {
return const IsSubtypeOf.never();
}
if (subtype.typeParameters.length != supertype.typeParameters.length) {
return const IsSubtypeOf.never();
}
if (subtype.typeParameters.isNotEmpty) {
var substitution = <TypeParameter, DartType>{};
for (int i = 0; i < subtype.typeParameters.length; ++i) {
var subParameter = subtype.typeParameters[i];
var superParameter = supertype.typeParameters[i];
substitution[subParameter] = new TypeParameterType(superParameter);
}
for (int i = 0; i < subtype.typeParameters.length; ++i) {
var subParameter = subtype.typeParameters[i];
var superParameter = supertype.typeParameters[i];
var subBound = substitute(subParameter.bound, substitution);
// Termination: if there are no cyclically bound type parameters, this
// recursive call can only occur a finite number of times before
// reaching a shrinking recursive call (or terminating).
// TODO(dmitryas): Replace it with one recursive descent instead of two.
if (!performNullabilityAwareSubtypeCheck(superParameter.bound, subBound)
.isSubtypeWhenIgnoringNullabilities() ||
!performNullabilityAwareSubtypeCheck(subBound, superParameter.bound)
.isSubtypeWhenIgnoringNullabilities()) {
return const IsSubtypeOf.never();
}
}
subtype = substitute(subtype.withoutTypeParameters, substitution);
}
if (!performNullabilityAwareSubtypeCheck(
subtype.returnType, supertype.returnType)
.isSubtypeWhenIgnoringNullabilities()) {
return const IsSubtypeOf.never();
}
for (int i = 0; i < supertype.positionalParameters.length; ++i) {
var supertypeParameter = supertype.positionalParameters[i];
var subtypeParameter = subtype.positionalParameters[i];
// Termination: Both types shrink in size.
if (!performNullabilityAwareSubtypeCheck(
supertypeParameter, subtypeParameter)
.isSubtypeWhenIgnoringNullabilities()) {
return const IsSubtypeOf.never();
}
}
int subtypeNameIndex = 0;
for (NamedType supertypeParameter in supertype.namedParameters) {
while (subtypeNameIndex < subtype.namedParameters.length &&
subtype.namedParameters[subtypeNameIndex].name !=
supertypeParameter.name) {
++subtypeNameIndex;
}
if (subtypeNameIndex == subtype.namedParameters.length) {
return const IsSubtypeOf.never();
}
NamedType subtypeParameter = subtype.namedParameters[subtypeNameIndex];
// Termination: Both types shrink in size.
if (!performNullabilityAwareSubtypeCheck(
supertypeParameter.type, subtypeParameter.type)
.isSubtypeWhenIgnoringNullabilities()) {
return const IsSubtypeOf.never();
}
}
return const IsSubtypeOf.always();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/testing/mock_sdk_component.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:kernel/ast.dart';
/// Returns a [Component] object containing empty definitions of core SDK classes.
Component createMockSdkComponent() {
var coreLib = new Library(Uri.parse('dart:core'), name: 'dart.core');
var asyncLib = new Library(Uri.parse('dart:async'), name: 'dart.async');
var internalLib =
new Library(Uri.parse('dart:_internal'), name: 'dart._internal');
Class addClass(Library lib, Class c) {
lib.addClass(c);
return c;
}
var objectClass = addClass(coreLib, new Class(name: 'Object'));
var objectType = new InterfaceType(objectClass);
TypeParameter typeParam(String name, [DartType bound]) {
return new TypeParameter(name, bound ?? objectType);
}
Class class_(String name,
{Supertype supertype,
List<TypeParameter> typeParameters,
List<Supertype> implementedTypes}) {
return new Class(
name: name,
supertype: supertype ?? objectClass.asThisSupertype,
typeParameters: typeParameters,
implementedTypes: implementedTypes);
}
addClass(coreLib, class_('Null'));
addClass(coreLib, class_('bool'));
var num = addClass(coreLib, class_('num'));
addClass(coreLib, class_('String'));
var iterable =
addClass(coreLib, class_('Iterable', typeParameters: [typeParam('T')]));
{
var T = typeParam('T');
addClass(
coreLib,
class_('List', typeParameters: [
T
], implementedTypes: [
new Supertype(iterable, [new TypeParameterType(T)])
]));
}
addClass(
coreLib, class_('Map', typeParameters: [typeParam('K'), typeParam('V')]));
addClass(coreLib, class_('int', supertype: num.asThisSupertype));
addClass(coreLib, class_('double', supertype: num.asThisSupertype));
addClass(coreLib, class_('Iterator', typeParameters: [typeParam('T')]));
addClass(coreLib, class_('Symbol'));
addClass(coreLib, class_('Type'));
addClass(coreLib, class_('Function'));
addClass(coreLib, class_('Invocation'));
addClass(asyncLib, class_('Future', typeParameters: [typeParam('T')]));
addClass(asyncLib, class_('FutureOr', typeParameters: [typeParam('T')]));
addClass(asyncLib, class_('Stream', typeParameters: [typeParam('T')]));
addClass(internalLib, class_('Symbol'));
return new Component(libraries: [coreLib, asyncLib, internalLib]);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/binary/ast_from_binary.dart | // 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.
library kernel.ast_from_binary;
import 'dart:core' hide MapEntry;
import 'dart:convert';
import 'dart:developer';
import 'dart:typed_data';
import '../ast.dart';
import '../src/bounds_checks.dart' show computeVariance;
import '../transformations/flags.dart';
import 'tag.dart';
class ParseError {
String filename;
int byteIndex;
String message;
String path;
ParseError(this.message, {this.filename, this.byteIndex, this.path});
String toString() => '$filename:$byteIndex: $message at $path';
}
class InvalidKernelVersionError {
final int version;
InvalidKernelVersionError(this.version);
String toString() {
return 'Unexpected Kernel version ${version} '
'(expected ${Tag.BinaryFormatVersion}).';
}
}
class CanonicalNameError {
final String message;
CanonicalNameError(this.message);
}
class CanonicalNameSdkError extends CanonicalNameError {
CanonicalNameSdkError(String message) : super(message);
}
class _ComponentIndex {
static const numberOfFixedFields = 9;
int binaryOffsetForSourceTable;
int binaryOffsetForCanonicalNames;
int binaryOffsetForMetadataPayloads;
int binaryOffsetForMetadataMappings;
int binaryOffsetForStringTable;
int binaryOffsetForConstantTable;
int mainMethodReference;
List<int> libraryOffsets;
int libraryCount;
int componentFileSizeInBytes;
}
class BinaryBuilder {
final List<VariableDeclaration> variableStack = <VariableDeclaration>[];
final List<LabeledStatement> labelStack = <LabeledStatement>[];
int labelStackBase = 0;
final List<SwitchCase> switchCaseStack = <SwitchCase>[];
final List<TypeParameter> typeParameterStack = <TypeParameter>[];
final String filename;
final List<int> _bytes;
int _byteOffset = 0;
final List<String> _stringTable = <String>[];
final List<Uri> _sourceUriTable = <Uri>[];
Map<int, Constant> _constantTable = <int, Constant>{};
List<CanonicalName> _linkTable;
int _transformerFlags = 0;
Library _currentLibrary;
int _componentStartOffset = 0;
// If something goes wrong, this list should indicate what library,
// class, and member was being built.
List<String> debugPath = <String>[];
bool _isReadingLibraryImplementation = false;
final bool alwaysCreateNewNamedNodes;
/// If binary contains metadata section with payloads referencing other nodes
/// such Kernel binary can't be read lazily because metadata cross references
/// will not be resolved correctly.
bool _disableLazyReading = false;
/// If binary contains metadata section with payloads referencing other nodes
/// such Kernel binary can't be read lazily because metadata cross references
/// will not be resolved correctly.
bool _disableLazyClassReading = false;
/// Note that [disableLazyClassReading] is incompatible
/// with checkCanonicalNames on readComponent.
BinaryBuilder(this._bytes,
{this.filename,
bool disableLazyReading = false,
bool disableLazyClassReading = false,
bool alwaysCreateNewNamedNodes})
: _disableLazyReading = disableLazyReading,
_disableLazyClassReading =
disableLazyReading || disableLazyClassReading,
this.alwaysCreateNewNamedNodes = alwaysCreateNewNamedNodes ?? false;
fail(String message) {
throw ParseError(message,
byteIndex: _byteOffset, filename: filename, path: debugPath.join('::'));
}
int get byteOffset => _byteOffset;
int readByte() => _bytes[_byteOffset++];
int readUInt() {
var byte = readByte();
if (byte & 0x80 == 0) {
// 0xxxxxxx
return byte;
} else if (byte & 0x40 == 0) {
// 10xxxxxx
return ((byte & 0x3F) << 8) | readByte();
} else {
// 11xxxxxx
return ((byte & 0x3F) << 24) |
(readByte() << 16) |
(readByte() << 8) |
readByte();
}
}
int readUint32() {
return (readByte() << 24) |
(readByte() << 16) |
(readByte() << 8) |
readByte();
}
final Float64List _doubleBuffer = new Float64List(1);
Uint8List _doubleBufferUint8;
double readDouble() {
_doubleBufferUint8 ??= _doubleBuffer.buffer.asUint8List();
_doubleBufferUint8[0] = readByte();
_doubleBufferUint8[1] = readByte();
_doubleBufferUint8[2] = readByte();
_doubleBufferUint8[3] = readByte();
_doubleBufferUint8[4] = readByte();
_doubleBufferUint8[5] = readByte();
_doubleBufferUint8[6] = readByte();
_doubleBufferUint8[7] = readByte();
return _doubleBuffer[0];
}
List<int> readBytes(int length) {
List<int> bytes = new Uint8List(length);
bytes.setRange(0, bytes.length, _bytes, _byteOffset);
_byteOffset += bytes.length;
return bytes;
}
List<int> readByteList() {
return readBytes(readUInt());
}
String readStringEntry(int numBytes) {
// Utf8Decoder will skip leading BOM characters, but we must preserve them.
// Collect leading BOMs before passing the bytes onto Utf8Decoder.
int numByteOrderMarks = 0;
while (_byteOffset + 2 < _bytes.length &&
_bytes[_byteOffset] == 0xef &&
_bytes[_byteOffset + 1] == 0xbb &&
_bytes[_byteOffset + 2] == 0xbf) {
++numByteOrderMarks;
_byteOffset += 3;
numBytes -= 3;
}
String string = const Utf8Decoder()
.convert(_bytes, _byteOffset, _byteOffset + numBytes);
_byteOffset += numBytes;
if (numByteOrderMarks > 0) {
return '\ufeff' * numByteOrderMarks + string;
}
return string;
}
/// Read metadataMappings section from the binary.
void _readMetadataMappings(
Component component, int binaryOffsetForMetadataPayloads) {
// Default reader ignores metadata section entirely.
}
/// Reads metadata for the given [node].
Node _associateMetadata(Node node, int nodeOffset) {
// Default reader ignores metadata section entirely.
return node;
}
void readStringTable(List<String> table) {
// Read the table of end offsets.
int length = readUInt();
List<int> endOffsets = new List<int>(length);
for (int i = 0; i < length; ++i) {
endOffsets[i] = readUInt();
}
// Read the UTF-8 encoded strings.
table.length = length;
int startOffset = 0;
for (int i = 0; i < length; ++i) {
table[i] = readStringEntry(endOffsets[i] - startOffset);
startOffset = endOffsets[i];
}
}
void readConstantTable() {
final int length = readUInt();
final int startOffset = byteOffset;
for (int i = 0; i < length; i++) {
_constantTable[byteOffset - startOffset] = readConstantTableEntry();
}
}
Constant readConstantTableEntry() {
final int constantTag = readByte();
switch (constantTag) {
case ConstantTag.NullConstant:
return new NullConstant();
case ConstantTag.BoolConstant:
return new BoolConstant(readByte() == 1);
case ConstantTag.IntConstant:
return new IntConstant((readExpression() as IntLiteral).value);
case ConstantTag.DoubleConstant:
return new DoubleConstant(readDouble());
case ConstantTag.StringConstant:
return new StringConstant(readStringReference());
case ConstantTag.SymbolConstant:
Reference libraryReference = readLibraryReference(allowNull: true);
return new SymbolConstant(readStringReference(), libraryReference);
case ConstantTag.MapConstant:
final DartType keyType = readDartType();
final DartType valueType = readDartType();
final int length = readUInt();
final List<ConstantMapEntry> entries =
new List<ConstantMapEntry>.filled(length, null, growable: true);
for (int i = 0; i < length; i++) {
final Constant key = readConstantReference();
final Constant value = readConstantReference();
entries[i] = new ConstantMapEntry(key, value);
}
return new MapConstant(keyType, valueType, entries);
case ConstantTag.ListConstant:
final DartType typeArgument = readDartType();
final int length = readUInt();
final List<Constant> entries =
new List<Constant>.filled(length, null, growable: true);
for (int i = 0; i < length; i++) {
entries[i] = readConstantReference();
}
return new ListConstant(typeArgument, entries);
case ConstantTag.SetConstant:
final DartType typeArgument = readDartType();
final int length = readUInt();
final List<Constant> entries =
new List<Constant>.filled(length, null, growable: true);
for (int i = 0; i < length; i++) {
entries[i] = readConstantReference();
}
return new SetConstant(typeArgument, entries);
case ConstantTag.InstanceConstant:
final Reference classReference = readClassReference();
final int typeArgumentCount = readUInt();
final List<DartType> typeArguments =
new List<DartType>.filled(typeArgumentCount, null, growable: true);
for (int i = 0; i < typeArgumentCount; i++) {
typeArguments[i] = readDartType();
}
final int fieldValueCount = readUInt();
final Map<Reference, Constant> fieldValues = <Reference, Constant>{};
for (int i = 0; i < fieldValueCount; i++) {
final Reference fieldRef =
readCanonicalNameReference().getReference();
final Constant constant = readConstantReference();
fieldValues[fieldRef] = constant;
}
return new InstanceConstant(classReference, typeArguments, fieldValues);
case ConstantTag.PartialInstantiationConstant:
final tearOffConstant = readConstantReference() as TearOffConstant;
final int length = readUInt();
final List<DartType> types = new List<DartType>(length);
for (int i = 0; i < length; i++) {
types[i] = readDartType();
}
return new PartialInstantiationConstant(tearOffConstant, types);
case ConstantTag.TearOffConstant:
final Reference reference = readCanonicalNameReference().getReference();
return new TearOffConstant.byReference(reference);
case ConstantTag.TypeLiteralConstant:
final DartType type = readDartType();
return new TypeLiteralConstant(type);
case ConstantTag.UnevaluatedConstant:
final Expression expression = readExpression();
return new UnevaluatedConstant(expression);
}
throw fail('unexpected constant tag: $constantTag');
}
Constant readConstantReference() {
final int offset = readUInt();
Constant constant = _constantTable[offset];
assert(constant != null);
return constant;
}
Uri readUriReference() {
return _sourceUriTable[readUInt()];
}
String readStringReference() {
return _stringTable[readUInt()];
}
List<String> readStringReferenceList() {
int length = readUInt();
List<String> result = new List<String>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readStringReference();
}
return result;
}
String readStringOrNullIfEmpty() {
var string = readStringReference();
return string.isEmpty ? null : string;
}
bool readAndCheckOptionTag() {
int tag = readByte();
if (tag == Tag.Nothing) {
return false;
} else if (tag == Tag.Something) {
return true;
} else {
throw fail('unexpected option tag: $tag');
}
}
List<Expression> readAnnotationList(TreeNode parent) {
int length = readUInt();
if (length == 0) return const <Expression>[];
List<Expression> list =
new List<Expression>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
list[i] = readExpression()..parent = parent;
}
return list;
}
void _fillTreeNodeList(
List<TreeNode> list, TreeNode buildObject(int index), TreeNode parent) {
var length = readUInt();
list.length = length;
for (int i = 0; i < length; ++i) {
TreeNode object = buildObject(i);
list[i] = object..parent = parent;
}
}
void _fillNonTreeNodeList(List<Node> list, Node buildObject()) {
var length = readUInt();
list.length = length;
for (int i = 0; i < length; ++i) {
Node object = buildObject();
list[i] = object;
}
}
void _skipNodeList(Node skipObject()) {
var length = readUInt();
for (int i = 0; i < length; ++i) {
skipObject();
}
}
/// Reads a list of named nodes, reusing any existing objects already in the
/// linking tree. The nodes are merged into [list], and if reading the library
/// implementation, the order is corrected.
///
/// [readObject] should read the object definition and its canonical name.
/// If an existing object is bound to the canonical name, the existing object
/// must be reused and returned.
void _mergeNamedNodeList(
List<NamedNode> list, NamedNode readObject(int index), TreeNode parent) {
if (_isReadingLibraryImplementation) {
// When reading the library implementation, overwrite the whole list
// with the new one.
_fillTreeNodeList(list, readObject, parent);
} else {
// When reading an external library, the results should either be:
// - merged with the existing external library definition (if any)
// - ignored if the library implementation is already in memory
int numberOfNodes = readUInt();
for (int i = 0; i < numberOfNodes; ++i) {
var value = readObject(i);
// We use the parent pointer of a node to determine if it already is in
// the AST and hence should not be added again.
if (value.parent == null) {
list.add(value..parent = parent);
}
}
}
}
void readLinkTable(CanonicalName linkRoot) {
int length = readUInt();
_linkTable = new List<CanonicalName>(length);
for (int i = 0; i < length; ++i) {
int biasedParentIndex = readUInt();
String name = readStringReference();
var parent =
biasedParentIndex == 0 ? linkRoot : _linkTable[biasedParentIndex - 1];
_linkTable[i] = parent.getChild(name);
}
}
List<int> _indexComponents() {
_checkEmptyInput();
int savedByteOffset = _byteOffset;
_byteOffset = _bytes.length - 4;
List<int> index = <int>[];
while (_byteOffset > 0) {
int size = readUint32();
int start = _byteOffset - size;
if (start < 0) {
throw fail("indicated size does not match file size");
}
index.add(size);
_byteOffset = start - 4;
}
_byteOffset = savedByteOffset;
return new List.from(index.reversed);
}
void _checkEmptyInput() {
if (_bytes.length == 0) throw new StateError("Empty input given.");
}
/// Deserializes a kernel component and stores it in [component].
///
/// When linking with a non-empty component, canonical names must have been
/// computed ahead of time.
///
/// The input bytes may contain multiple files concatenated.
void readComponent(Component component, {bool checkCanonicalNames: false}) {
Timeline.timeSync("BinaryBuilder.readComponent", () {
_checkEmptyInput();
// Check that we have a .dill file and it has the correct version before we
// start decoding it. Otherwise we will fail for cryptic reasons.
int offset = _byteOffset;
int magic = readUint32();
if (magic != Tag.ComponentFile) {
throw ArgumentError('Not a .dill file (wrong magic number).');
}
int version = readUint32();
if (version != Tag.BinaryFormatVersion) {
throw InvalidKernelVersionError(version);
}
_byteOffset = offset;
List<int> componentFileSizes = _indexComponents();
if (componentFileSizes.length > 1) {
_disableLazyReading = true;
_disableLazyClassReading = true;
}
int componentFileIndex = 0;
while (_byteOffset < _bytes.length) {
_readOneComponent(component, componentFileSizes[componentFileIndex]);
++componentFileIndex;
}
if (checkCanonicalNames) {
_checkCanonicalNameChildren(component.root);
}
});
}
/// Deserializes the source and stores it in [component].
///
/// The input bytes may contain multiple files concatenated.
void readComponentSource(Component component) {
List<int> componentFileSizes = _indexComponents();
if (componentFileSizes.length > 1) {
_disableLazyReading = true;
_disableLazyClassReading = true;
}
int componentFileIndex = 0;
while (_byteOffset < _bytes.length) {
_readOneComponentSource(
component, componentFileSizes[componentFileIndex]);
++componentFileIndex;
}
}
/// Reads a single component file from the input and loads it into [component],
/// overwriting and reusing any existing data in the component.
///
/// When linking with a non-empty component, canonical names must have been
/// computed ahead of time.
///
/// This should *only* be used when there is a reason to not allow
/// concatenated files.
void readSingleFileComponent(Component component,
{bool checkCanonicalNames: false}) {
List<int> componentFileSizes = _indexComponents();
if (componentFileSizes.isEmpty) throw fail("invalid component data");
_readOneComponent(component, componentFileSizes[0]);
if (_byteOffset < _bytes.length) {
if (_byteOffset + 3 < _bytes.length) {
int magic = readUint32();
if (magic == Tag.ComponentFile) {
throw 'Concatenated component file given when a single component '
'was expected.';
}
}
throw 'Unrecognized bytes following component data';
}
if (checkCanonicalNames) {
_checkCanonicalNameChildren(component.root);
}
}
void _checkCanonicalNameChildren(CanonicalName parent) {
Iterable<CanonicalName> parentChildren = parent.childrenOrNull;
if (parentChildren != null) {
for (CanonicalName child in parentChildren) {
if (child.name != '@methods' &&
child.name != '@typedefs' &&
child.name != '@fields' &&
child.name != '@getters' &&
child.name != '@setters' &&
child.name != '@factories' &&
child.name != '@constructors') {
bool checkReferenceNode = true;
if (child.reference == null) {
// OK for "if private: URI of library" part of "Qualified name"...
Iterable<CanonicalName> children = child.childrenOrNull;
if (parent.parent != null &&
children != null &&
children.isNotEmpty &&
children.first.name.startsWith("_")) {
// OK then.
checkReferenceNode = false;
} else {
throw buildCanonicalNameError(
"Null reference (${child.name}) ($child).", child);
}
}
if (checkReferenceNode) {
if (child.reference.canonicalName != child) {
throw new CanonicalNameError(
"Canonical name and reference doesn't agree.");
}
if (child.reference.node == null) {
throw buildCanonicalNameError(
"Reference is null (${child.name}) ($child).", child);
}
}
}
_checkCanonicalNameChildren(child);
}
}
}
CanonicalNameError buildCanonicalNameError(
String message, CanonicalName problemNode) {
// Special-case missing sdk entries as that is probably a change to the
// platform - that's something we might want to react differently to.
String libraryUri = problemNode?.nonRootTop?.name ?? "";
if (libraryUri.startsWith("dart:")) {
return new CanonicalNameSdkError(message);
}
return new CanonicalNameError(message);
}
_ComponentIndex _readComponentIndex(int componentFileSize) {
int savedByteIndex = _byteOffset;
_ComponentIndex result = new _ComponentIndex();
// There are two fields: file size and library count.
_byteOffset = _componentStartOffset + componentFileSize - (2) * 4;
result.libraryCount = readUint32();
// Library offsets are used for start and end offsets, so there is one extra
// element that this the end offset of the last library
result.libraryOffsets = new List<int>(result.libraryCount + 1);
result.componentFileSizeInBytes = readUint32();
if (result.componentFileSizeInBytes != componentFileSize) {
throw "Malformed binary: This component file's component index indicates that"
" the file size should be $componentFileSize but other component indexes"
" has indicated that the size should be "
"${result.componentFileSizeInBytes}.";
}
// Skip to the start of the index.
_byteOffset -=
((result.libraryCount + 1) + _ComponentIndex.numberOfFixedFields) * 4;
// Now read the component index.
result.binaryOffsetForSourceTable = _componentStartOffset + readUint32();
result.binaryOffsetForCanonicalNames = _componentStartOffset + readUint32();
result.binaryOffsetForMetadataPayloads =
_componentStartOffset + readUint32();
result.binaryOffsetForMetadataMappings =
_componentStartOffset + readUint32();
result.binaryOffsetForStringTable = _componentStartOffset + readUint32();
result.binaryOffsetForConstantTable = _componentStartOffset + readUint32();
result.mainMethodReference = readUint32();
for (int i = 0; i < result.libraryCount + 1; ++i) {
result.libraryOffsets[i] = _componentStartOffset + readUint32();
}
_byteOffset = savedByteIndex;
return result;
}
void _readOneComponentSource(Component component, int componentFileSize) {
_componentStartOffset = _byteOffset;
final int magic = readUint32();
if (magic != Tag.ComponentFile) {
throw ArgumentError('Not a .dill file (wrong magic number).');
}
final int formatVersion = readUint32();
if (formatVersion != Tag.BinaryFormatVersion) {
throw InvalidKernelVersionError(formatVersion);
}
// Read component index from the end of this ComponentFiles serialized data.
_ComponentIndex index = _readComponentIndex(componentFileSize);
_byteOffset = index.binaryOffsetForSourceTable;
Map<Uri, Source> uriToSource = readUriToSource();
_mergeUriToSource(component.uriToSource, uriToSource);
_byteOffset = _componentStartOffset + componentFileSize;
}
void _readOneComponent(Component component, int componentFileSize) {
_componentStartOffset = _byteOffset;
final int magic = readUint32();
if (magic != Tag.ComponentFile) {
throw ArgumentError('Not a .dill file (wrong magic number).');
}
final int formatVersion = readUint32();
if (formatVersion != Tag.BinaryFormatVersion) {
throw InvalidKernelVersionError(formatVersion);
}
List<String> problemsAsJson = readListOfStrings();
if (problemsAsJson != null) {
component.problemsAsJson ??= <String>[];
component.problemsAsJson.addAll(problemsAsJson);
}
// Read component index from the end of this ComponentFiles serialized data.
_ComponentIndex index = _readComponentIndex(componentFileSize);
_byteOffset = index.binaryOffsetForStringTable;
readStringTable(_stringTable);
_byteOffset = index.binaryOffsetForCanonicalNames;
readLinkTable(component.root);
// TODO(alexmarkov): reverse metadata mappings and read forwards
_byteOffset = index.binaryOffsetForStringTable; // Read backwards.
_readMetadataMappings(component, index.binaryOffsetForMetadataPayloads);
_associateMetadata(component, _componentStartOffset);
_byteOffset = index.binaryOffsetForSourceTable;
Map<Uri, Source> uriToSource = readUriToSource();
_mergeUriToSource(component.uriToSource, uriToSource);
_byteOffset = index.binaryOffsetForConstantTable;
readConstantTable();
int numberOfLibraries = index.libraryCount;
for (int i = 0; i < numberOfLibraries; ++i) {
_byteOffset = index.libraryOffsets[i];
readLibrary(component, index.libraryOffsets[i + 1]);
}
var mainMethod =
getMemberReferenceFromInt(index.mainMethodReference, allowNull: true);
component.mainMethodName ??= mainMethod;
_byteOffset = _componentStartOffset + componentFileSize;
assert(typeParameterStack.isEmpty);
}
/// Read a list of strings. If the list is empty, [null] is returned.
List<String> readListOfStrings() {
int length = readUInt();
if (length == 0) return null;
List<String> strings =
new List<String>.filled(length, null, growable: true);
for (int i = 0; i < length; i++) {
String s = const Utf8Decoder().convert(readByteList());
strings[i] = s;
}
return strings;
}
Map<Uri, Source> readUriToSource() {
int length = readUint32();
// Read data.
_sourceUriTable.length = length;
Map<Uri, Source> uriToSource = <Uri, Source>{};
for (int i = 0; i < length; ++i) {
List<int> uriBytes = readByteList();
Uri uri = uriBytes.isEmpty
? null
: Uri.parse(const Utf8Decoder().convert(uriBytes));
_sourceUriTable[i] = uri;
List<int> sourceCode = readByteList();
int lineCount = readUInt();
List<int> lineStarts = new List<int>(lineCount);
int previousLineStart = 0;
for (int j = 0; j < lineCount; ++j) {
int lineStart = readUInt() + previousLineStart;
lineStarts[j] = lineStart;
previousLineStart = lineStart;
}
List<int> importUriBytes = readByteList();
Uri importUri = importUriBytes.isEmpty
? null
: Uri.parse(const Utf8Decoder().convert(importUriBytes));
uriToSource[uri] = new Source(lineStarts, sourceCode, importUri, uri);
}
// Read index.
for (int i = 0; i < length; ++i) {
readUint32();
}
return uriToSource;
}
// Add everything from [src] into [dst], but don't overwrite a non-empty
// source with an empty source. Empty sources may be introduced by
// synthetic, copy-down implementations such as mixin applications or
// noSuchMethod forwarders.
void _mergeUriToSource(Map<Uri, Source> dst, Map<Uri, Source> src) {
if (dst.isEmpty) {
// Fast path for the common case of one component per binary.
dst.addAll(src);
} else {
src.forEach((Uri key, Source value) {
if (value.source.isNotEmpty || !dst.containsKey(key)) {
dst[key] = value;
}
});
}
}
CanonicalName readCanonicalNameReference() {
var index = readUInt();
if (index == 0) return null;
return _linkTable[index - 1];
}
CanonicalName getCanonicalNameReferenceFromInt(int index) {
if (index == 0) return null;
return _linkTable[index - 1];
}
Reference readLibraryReference({bool allowNull: false}) {
CanonicalName canonicalName = readCanonicalNameReference();
if (canonicalName != null) return canonicalName.getReference();
if (allowNull) return null;
throw 'Expected a library reference to be valid but was `null`.';
}
LibraryDependency readLibraryDependencyReference() {
int index = readUInt();
return _currentLibrary.dependencies[index];
}
Reference readClassReference({bool allowNull: false}) {
var name = readCanonicalNameReference();
if (name == null && !allowNull) {
throw 'Expected a class reference to be valid but was `null`.';
}
return name?.getReference();
}
Reference readMemberReference({bool allowNull: false}) {
var name = readCanonicalNameReference();
if (name == null && !allowNull) {
throw 'Expected a member reference to be valid but was `null`.';
}
return name?.getReference();
}
Reference getMemberReferenceFromInt(int index, {bool allowNull: false}) {
var name = getCanonicalNameReferenceFromInt(index);
if (name == null && !allowNull) {
throw 'Expected a member reference to be valid but was `null`.';
}
return name?.getReference();
}
Reference readTypedefReference() {
return readCanonicalNameReference()?.getReference();
}
Name readName() {
String text = readStringReference();
if (text.isNotEmpty && text[0] == '_') {
return new Name.byReference(text, readLibraryReference());
} else {
return new Name(text);
}
}
Library readLibrary(Component component, int endOffset) {
// Read index.
int savedByteOffset = _byteOffset;
// There is a field for the procedure count.
_byteOffset = endOffset - (1) * 4;
int procedureCount = readUint32();
List<int> procedureOffsets = new List<int>(procedureCount + 1);
// There is a field for the procedure count, that number + 1 (for the end)
// offsets, and then the class count (i.e. procedure count + 3 fields).
_byteOffset = endOffset - (procedureCount + 3) * 4;
int classCount = readUint32();
for (int i = 0; i < procedureCount + 1; i++) {
procedureOffsets[i] = _componentStartOffset + readUint32();
}
List<int> classOffsets = new List<int>(classCount + 1);
// There is a field for the procedure count, that number + 1 (for the end)
// offsets, then the class count and that number + 1 (for the end) offsets.
// (i.e. procedure count + class count + 4 fields).
_byteOffset = endOffset - (procedureCount + classCount + 4) * 4;
for (int i = 0; i < classCount + 1; i++) {
classOffsets[i] = _componentStartOffset + readUint32();
}
_byteOffset = savedByteOffset;
int flags = readByte();
bool isExternal = (flags & Library.ExternalFlag) != 0;
_isReadingLibraryImplementation = !isExternal;
int languageVersionMajor = readUInt();
int languageVersionMinor = readUInt();
var canonicalName = readCanonicalNameReference();
Reference reference = canonicalName.getReference();
Library library = reference.node;
if (alwaysCreateNewNamedNodes) {
library = null;
}
bool shouldWriteData = library == null || _isReadingLibraryImplementation;
if (library == null) {
library =
new Library(Uri.parse(canonicalName.name), reference: reference);
component.libraries.add(library..parent = component);
}
_currentLibrary = library;
String name = readStringOrNullIfEmpty();
// TODO(jensj): We currently save (almost the same) uri twice.
Uri fileUri = readUriReference();
List<String> problemsAsJson = readListOfStrings();
if (shouldWriteData) {
library.flags = flags;
library.setLanguageVersion(languageVersionMajor, languageVersionMinor);
library.name = name;
library.fileUri = fileUri;
library.problemsAsJson = problemsAsJson;
}
assert(() {
debugPath.add(library.name ?? library.importUri?.toString() ?? 'library');
return true;
}());
if (shouldWriteData) {
_fillTreeNodeList(
library.annotations, (index) => readExpression(), library);
} else {
_skipNodeList(readExpression);
}
_readLibraryDependencies(library);
_readAdditionalExports(library);
_readLibraryParts(library);
_mergeNamedNodeList(library.typedefs, (index) => readTypedef(), library);
_mergeNamedNodeList(library.classes, (index) {
_byteOffset = classOffsets[index];
return readClass(classOffsets[index + 1]);
}, library);
_byteOffset = classOffsets.last;
_mergeNamedNodeList(library.extensions, (index) {
return readExtension();
}, library);
_mergeNamedNodeList(library.fields, (index) => readField(), library);
_mergeNamedNodeList(library.procedures, (index) {
_byteOffset = procedureOffsets[index];
return readProcedure(procedureOffsets[index + 1]);
}, library);
_byteOffset = procedureOffsets.last;
assert(((_) => true)(debugPath.removeLast()));
_currentLibrary = null;
return library;
}
void _readLibraryDependencies(Library library) {
int length = readUInt();
library.dependencies.length = length;
for (int i = 0; i < length; ++i) {
library.dependencies[i] = readLibraryDependency(library);
}
}
LibraryDependency readLibraryDependency(Library library) {
var fileOffset = readOffset();
var flags = readByte();
var annotations = readExpressionList();
var targetLibrary = readLibraryReference(allowNull: true);
var prefixName = readStringOrNullIfEmpty();
var names = readCombinatorList();
return new LibraryDependency.byReference(
flags, annotations, targetLibrary, prefixName, names)
..fileOffset = fileOffset
..parent = library;
}
void _readAdditionalExports(Library library) {
int numExportedReference = readUInt();
if (numExportedReference != 0) {
for (int i = 0; i < numExportedReference; i++) {
CanonicalName exportedName = readCanonicalNameReference();
Reference reference = exportedName.getReference();
library.additionalExports.add(reference);
}
}
}
Combinator readCombinator() {
var isShow = readByte() == 1;
var names = readStringReferenceList();
return new Combinator(isShow, names);
}
List<Combinator> readCombinatorList() {
int length = readUInt();
List<Combinator> result =
new List<Combinator>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readCombinator();
}
return result;
}
void _readLibraryParts(Library library) {
int length = readUInt();
library.parts.length = length;
for (int i = 0; i < length; ++i) {
library.parts[i] = readLibraryPart(library);
}
}
LibraryPart readLibraryPart(Library library) {
List<Expression> annotations = readExpressionList();
String partUri = readStringReference();
return new LibraryPart(annotations, partUri)..parent = library;
}
Typedef readTypedef() {
var canonicalName = readCanonicalNameReference();
var reference = canonicalName.getReference();
Typedef node = reference.node;
if (alwaysCreateNewNamedNodes) {
node = null;
}
bool shouldWriteData = node == null || _isReadingLibraryImplementation;
if (node == null) {
node = new Typedef(null, null, reference: reference);
}
Uri fileUri = readUriReference();
int fileOffset = readOffset();
String name = readStringReference();
node.annotations = readAnnotationList(node);
readAndPushTypeParameterList(node.typeParameters, node);
var type = readDartType();
readAndPushTypeParameterList(node.typeParametersOfFunctionType, node);
node.positionalParameters.addAll(readAndPushVariableDeclarationList());
node.namedParameters.addAll(readAndPushVariableDeclarationList());
typeParameterStack.length = 0;
variableStack.length = 0;
for (int i = 0; i < node.typeParameters.length; ++i) {
node.typeParameters[i].variance =
computeVariance(node.typeParameters[i], type);
}
if (shouldWriteData) {
node.fileOffset = fileOffset;
node.name = name;
node.fileUri = fileUri;
node.type = type;
}
return node;
}
Class readClass(int endOffset) {
int tag = readByte();
assert(tag == Tag.Class);
// Read index.
int savedByteOffset = _byteOffset;
// There is a field for the procedure count.
_byteOffset = endOffset - (1) * 4;
int procedureCount = readUint32();
List<int> procedureOffsets = new List<int>(procedureCount + 1);
// There is a field for the procedure count, that number + 1 (for the end)
// offsets (i.e. procedure count + 2 fields).
_byteOffset = endOffset - (procedureCount + 2) * 4;
for (int i = 0; i < procedureCount + 1; i++) {
procedureOffsets[i] = _componentStartOffset + readUint32();
}
_byteOffset = savedByteOffset;
var canonicalName = readCanonicalNameReference();
var reference = canonicalName.getReference();
Class node = reference.node;
if (alwaysCreateNewNamedNodes) {
node = null;
}
bool shouldWriteData = node == null || _isReadingLibraryImplementation;
if (node == null) {
node = new Class(reference: reference)
..level = ClassLevel.Temporary
..dirty = false;
}
var fileUri = readUriReference();
node.startFileOffset = readOffset();
node.fileOffset = readOffset();
node.fileEndOffset = readOffset();
int flags = readByte();
node.flags = flags & ~Class.LevelMask;
int levelIndex = flags & Class.LevelMask;
var level = ClassLevel.values[levelIndex + 1];
if (level.index >= node.level.index) {
node.level = level;
}
var name = readStringOrNullIfEmpty();
var annotations = readAnnotationList(node);
assert(() {
debugPath.add(node.name ?? 'normal-class');
return true;
}());
assert(typeParameterStack.length == 0);
readAndPushTypeParameterList(node.typeParameters, node);
var supertype = readSupertypeOption();
var mixedInType = readSupertypeOption();
if (shouldWriteData) {
_fillNonTreeNodeList(node.implementedTypes, readSupertype);
} else {
_skipNodeList(readSupertype);
}
if (_disableLazyClassReading) {
readClassPartialContent(node, procedureOffsets);
} else {
_setLazyLoadClass(node, procedureOffsets);
}
typeParameterStack.length = 0;
assert(debugPath.removeLast() != null);
if (shouldWriteData) {
node.name = name;
node.fileUri = fileUri;
node.annotations = annotations;
node.supertype = supertype;
node.mixedInType = mixedInType;
}
_byteOffset = endOffset;
return node;
}
Extension readExtension() {
int tag = readByte();
assert(tag == Tag.Extension);
CanonicalName canonicalName = readCanonicalNameReference();
Reference reference = canonicalName.getReference();
Extension node = reference.node;
if (alwaysCreateNewNamedNodes) {
node = null;
}
bool shouldWriteData = node == null || _isReadingLibraryImplementation;
if (node == null) {
node = new Extension(reference: reference);
}
String name = readStringOrNullIfEmpty();
assert(() {
debugPath.add(node.name ?? 'extension');
return true;
}());
Uri fileUri = readUriReference();
node.fileOffset = readOffset();
readAndPushTypeParameterList(node.typeParameters, node);
DartType onType = readDartType();
typeParameterStack.length = 0;
if (shouldWriteData) {
node.name = name;
node.fileUri = fileUri;
node.onType = onType;
}
int length = readUInt();
for (int i = 0; i < length; i++) {
Name name = readName();
int kind = readByte();
int flags = readByte();
CanonicalName canonicalName = readCanonicalNameReference();
if (shouldWriteData) {
node.members.add(new ExtensionMemberDescriptor(
name: name,
kind: ExtensionMemberKind.values[kind],
member: canonicalName.getReference())
..flags = flags);
}
}
return node;
}
/// Reads the partial content of a class, namely fields, procedures,
/// constructors and redirecting factory constructors.
void readClassPartialContent(Class node, List<int> procedureOffsets) {
_mergeNamedNodeList(node.fieldsInternal, (index) => readField(), node);
_mergeNamedNodeList(
node.constructorsInternal, (index) => readConstructor(), node);
_mergeNamedNodeList(node.proceduresInternal, (index) {
_byteOffset = procedureOffsets[index];
return readProcedure(procedureOffsets[index + 1]);
}, node);
_byteOffset = procedureOffsets.last;
_mergeNamedNodeList(node.redirectingFactoryConstructorsInternal,
(index) => readRedirectingFactoryConstructor(), node);
}
/// Set the lazyBuilder on the class so it can be lazy loaded in the future.
void _setLazyLoadClass(Class node, List<int> procedureOffsets) {
final int savedByteOffset = _byteOffset;
final int componentStartOffset = _componentStartOffset;
final Library currentLibrary = _currentLibrary;
node.lazyBuilder = () {
_byteOffset = savedByteOffset;
_currentLibrary = currentLibrary;
assert(typeParameterStack.isEmpty);
_componentStartOffset = componentStartOffset;
typeParameterStack.addAll(node.typeParameters);
readClassPartialContent(node, procedureOffsets);
typeParameterStack.length = 0;
};
}
int getAndResetTransformerFlags() {
int flags = _transformerFlags;
_transformerFlags = 0;
return flags;
}
/// Adds the given flag to the current [Member.transformerFlags].
void addTransformerFlag(int flags) {
_transformerFlags |= flags;
}
Field readField() {
int tag = readByte();
assert(tag == Tag.Field);
var canonicalName = readCanonicalNameReference();
var reference = canonicalName.getReference();
Field node = reference.node;
if (alwaysCreateNewNamedNodes) {
node = null;
}
bool shouldWriteData = node == null || _isReadingLibraryImplementation;
if (node == null) {
node = new Field(null, reference: reference);
}
var fileUri = readUriReference();
int fileOffset = readOffset();
int fileEndOffset = readOffset();
int flags = readUInt();
var name = readName();
var annotations = readAnnotationList(node);
assert(() {
debugPath.add(node.name?.name ?? 'field');
return true;
}());
var type = readDartType();
var initializer = readExpressionOption();
int transformerFlags = getAndResetTransformerFlags();
assert(((_) => true)(debugPath.removeLast()));
if (shouldWriteData) {
node.fileOffset = fileOffset;
node.fileEndOffset = fileEndOffset;
node.flags = flags;
node.name = name;
node.fileUri = fileUri;
node.annotations = annotations;
node.type = type;
node.initializer = initializer;
node.initializer?.parent = node;
node.transformerFlags = transformerFlags;
}
return node;
}
Constructor readConstructor() {
int tag = readByte();
assert(tag == Tag.Constructor);
var canonicalName = readCanonicalNameReference();
var reference = canonicalName.getReference();
Constructor node = reference.node;
if (alwaysCreateNewNamedNodes) {
node = null;
}
bool shouldWriteData = node == null || _isReadingLibraryImplementation;
if (node == null) {
node = new Constructor(null, reference: reference);
}
var fileUri = readUriReference();
var startFileOffset = readOffset();
var fileOffset = readOffset();
var fileEndOffset = readOffset();
var flags = readByte();
var name = readName();
var annotations = readAnnotationList(node);
assert(() {
debugPath.add(node.name?.name ?? 'constructor');
return true;
}());
var function = readFunctionNode();
pushVariableDeclarations(function.positionalParameters);
pushVariableDeclarations(function.namedParameters);
if (shouldWriteData) {
_fillTreeNodeList(node.initializers, (index) => readInitializer(), node);
} else {
_skipNodeList(readInitializer);
}
variableStack.length = 0;
var transformerFlags = getAndResetTransformerFlags();
assert(((_) => true)(debugPath.removeLast()));
if (shouldWriteData) {
node.startFileOffset = startFileOffset;
node.fileOffset = fileOffset;
node.fileEndOffset = fileEndOffset;
node.flags = flags;
node.name = name;
node.fileUri = fileUri;
node.annotations = annotations;
node.function = function..parent = node;
node.transformerFlags = transformerFlags;
}
return node;
}
Procedure readProcedure(int endOffset) {
int tag = readByte();
assert(tag == Tag.Procedure);
var canonicalName = readCanonicalNameReference();
var reference = canonicalName.getReference();
Procedure node = reference.node;
if (alwaysCreateNewNamedNodes) {
node = null;
}
bool shouldWriteData = node == null || _isReadingLibraryImplementation;
if (node == null) {
node = new Procedure(null, null, null, reference: reference);
}
var fileUri = readUriReference();
var startFileOffset = readOffset();
var fileOffset = readOffset();
var fileEndOffset = readOffset();
int kindIndex = readByte();
var kind = ProcedureKind.values[kindIndex];
var flags = readUInt();
var name = readName();
var annotations = readAnnotationList(node);
assert(() {
debugPath.add(node.name?.name ?? 'procedure');
return true;
}());
int functionNodeSize = endOffset - _byteOffset;
// Read small factories up front. Postpone everything else.
bool readFunctionNodeNow =
(kind == ProcedureKind.Factory && functionNodeSize <= 50) ||
_disableLazyReading;
var forwardingStubSuperTargetReference =
readMemberReference(allowNull: true);
var forwardingStubInterfaceTargetReference =
readMemberReference(allowNull: true);
var function = readFunctionNodeOption(!readFunctionNodeNow, endOffset);
var transformerFlags = getAndResetTransformerFlags();
assert(((_) => true)(debugPath.removeLast()));
if (shouldWriteData) {
node.startFileOffset = startFileOffset;
node.fileOffset = fileOffset;
node.fileEndOffset = fileEndOffset;
node.kind = kind;
node.flags = flags;
node.name = name;
node.fileUri = fileUri;
node.annotations = annotations;
node.function = function;
function?.parent = node;
node.setTransformerFlagsWithoutLazyLoading(transformerFlags);
node.forwardingStubSuperTargetReference =
forwardingStubSuperTargetReference;
node.forwardingStubInterfaceTargetReference =
forwardingStubInterfaceTargetReference;
assert((node.forwardingStubSuperTargetReference != null) ||
!(node.isForwardingStub && node.function.body != null));
}
_byteOffset = endOffset;
return node;
}
RedirectingFactoryConstructor readRedirectingFactoryConstructor() {
int tag = readByte();
assert(tag == Tag.RedirectingFactoryConstructor);
var canonicalName = readCanonicalNameReference();
var reference = canonicalName.getReference();
RedirectingFactoryConstructor node = reference.node;
if (alwaysCreateNewNamedNodes) {
node = null;
}
bool shouldWriteData = node == null || _isReadingLibraryImplementation;
if (node == null) {
node = new RedirectingFactoryConstructor(null, reference: reference);
}
var fileUri = readUriReference();
var fileOffset = readOffset();
var fileEndOffset = readOffset();
var flags = readByte();
var name = readName();
var annotations = readAnnotationList(node);
assert(() {
debugPath.add(node.name?.name ?? 'redirecting-factory-constructor');
return true;
}());
var targetReference = readMemberReference();
var typeArguments = readDartTypeList();
int typeParameterStackHeight = typeParameterStack.length;
var typeParameters = readAndPushTypeParameterList();
readUInt(); // Total parameter count.
var requiredParameterCount = readUInt();
int variableStackHeight = variableStack.length;
var positional = readAndPushVariableDeclarationList();
var named = readAndPushVariableDeclarationList();
variableStack.length = variableStackHeight;
typeParameterStack.length = typeParameterStackHeight;
debugPath.removeLast();
if (shouldWriteData) {
node.fileOffset = fileOffset;
node.fileEndOffset = fileEndOffset;
node.flags = flags;
node.name = name;
node.fileUri = fileUri;
node.annotations = annotations;
node.targetReference = targetReference;
node.typeArguments.addAll(typeArguments);
node.typeParameters = typeParameters;
node.requiredParameterCount = requiredParameterCount;
node.positionalParameters = positional;
node.namedParameters = named;
}
return node;
}
Initializer readInitializer() {
int tag = readByte();
bool isSynthetic = readByte() == 1;
switch (tag) {
case Tag.InvalidInitializer:
return new InvalidInitializer();
case Tag.FieldInitializer:
var reference = readMemberReference();
var value = readExpression();
return new FieldInitializer.byReference(reference, value)
..isSynthetic = isSynthetic;
case Tag.SuperInitializer:
int offset = readOffset();
var reference = readMemberReference();
var arguments = readArguments();
return new SuperInitializer.byReference(reference, arguments)
..isSynthetic = isSynthetic
..fileOffset = offset;
case Tag.RedirectingInitializer:
int offset = readOffset();
return new RedirectingInitializer.byReference(
readMemberReference(), readArguments())
..fileOffset = offset;
case Tag.LocalInitializer:
return new LocalInitializer(readAndPushVariableDeclaration());
case Tag.AssertInitializer:
return new AssertInitializer(readStatement());
default:
throw fail('unexpected initializer tag: $tag');
}
}
FunctionNode readFunctionNodeOption(bool lazyLoadBody, int outerEndOffset) {
return readAndCheckOptionTag()
? readFunctionNode(
lazyLoadBody: lazyLoadBody, outerEndOffset: outerEndOffset)
: null;
}
FunctionNode readFunctionNode(
{bool lazyLoadBody: false, int outerEndOffset: -1}) {
int tag = readByte();
assert(tag == Tag.FunctionNode);
int offset = readOffset();
int endOffset = readOffset();
AsyncMarker asyncMarker = AsyncMarker.values[readByte()];
AsyncMarker dartAsyncMarker = AsyncMarker.values[readByte()];
int typeParameterStackHeight = typeParameterStack.length;
var typeParameters = readAndPushTypeParameterList();
readUInt(); // total parameter count.
var requiredParameterCount = readUInt();
int variableStackHeight = variableStack.length;
var positional = readAndPushVariableDeclarationList();
var named = readAndPushVariableDeclarationList();
var returnType = readDartType();
int oldLabelStackBase = labelStackBase;
if (lazyLoadBody && outerEndOffset > 0) {
lazyLoadBody = outerEndOffset - _byteOffset >
2; // e.g. outline has Tag.Something and Tag.EmptyStatement
}
var body;
if (!lazyLoadBody) {
labelStackBase = labelStack.length;
body = readStatementOption();
}
FunctionNode result = new FunctionNode(body,
typeParameters: typeParameters,
requiredParameterCount: requiredParameterCount,
positionalParameters: positional,
namedParameters: named,
returnType: returnType,
asyncMarker: asyncMarker,
dartAsyncMarker: dartAsyncMarker)
..fileOffset = offset
..fileEndOffset = endOffset;
if (lazyLoadBody) {
_setLazyLoadFunction(result, oldLabelStackBase, variableStackHeight);
}
labelStackBase = oldLabelStackBase;
variableStack.length = variableStackHeight;
typeParameterStack.length = typeParameterStackHeight;
return result;
}
void _setLazyLoadFunction(
FunctionNode result, int oldLabelStackBase, int variableStackHeight) {
final int savedByteOffset = _byteOffset;
final int componentStartOffset = _componentStartOffset;
final List<TypeParameter> typeParameters = typeParameterStack.toList();
final List<VariableDeclaration> variables = variableStack.toList();
final Library currentLibrary = _currentLibrary;
result.lazyBuilder = () {
_byteOffset = savedByteOffset;
_currentLibrary = currentLibrary;
typeParameterStack.clear();
typeParameterStack.addAll(typeParameters);
variableStack.clear();
variableStack.addAll(variables);
_componentStartOffset = componentStartOffset;
result.body = readStatementOption();
result.body?.parent = result;
labelStackBase = oldLabelStackBase;
variableStack.length = variableStackHeight;
typeParameterStack.clear();
if (result.parent is Procedure) {
Procedure parent = result.parent;
parent.transformerFlags |= getAndResetTransformerFlags();
}
};
}
void pushVariableDeclaration(VariableDeclaration variable) {
variableStack.add(variable);
}
void pushVariableDeclarations(List<VariableDeclaration> variables) {
variableStack.addAll(variables);
}
VariableDeclaration readVariableReference() {
int index = readUInt();
if (index >= variableStack.length) {
throw fail('unexpected variable index: $index');
}
return variableStack[index];
}
String logicalOperatorToString(int index) {
switch (index) {
case 0:
return '&&';
case 1:
return '||';
default:
throw fail('unexpected logical operator index: $index');
}
}
List<Expression> readExpressionList() {
int length = readUInt();
List<Expression> result =
new List<Expression>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readExpression();
}
return result;
}
Expression readExpressionOption() {
return readAndCheckOptionTag() ? readExpression() : null;
}
Expression readExpression() {
int tagByte = readByte();
int tag = tagByte & Tag.SpecializedTagHighBit == 0
? tagByte
: (tagByte & Tag.SpecializedTagMask);
switch (tag) {
case Tag.LoadLibrary:
return new LoadLibrary(readLibraryDependencyReference());
case Tag.CheckLibraryIsLoaded:
return new CheckLibraryIsLoaded(readLibraryDependencyReference());
case Tag.InvalidExpression:
int offset = readOffset();
return new InvalidExpression(readStringOrNullIfEmpty())
..fileOffset = offset;
case Tag.VariableGet:
int offset = readOffset();
readUInt(); // offset of the variable declaration in the binary.
return new VariableGet(readVariableReference(), readDartTypeOption())
..fileOffset = offset;
case Tag.SpecializedVariableGet:
int index = tagByte & Tag.SpecializedPayloadMask;
int offset = readOffset();
readUInt(); // offset of the variable declaration in the binary.
return new VariableGet(variableStack[index])..fileOffset = offset;
case Tag.VariableSet:
int offset = readOffset();
readUInt(); // offset of the variable declaration in the binary.
return new VariableSet(readVariableReference(), readExpression())
..fileOffset = offset;
case Tag.SpecializedVariableSet:
int index = tagByte & Tag.SpecializedPayloadMask;
int offset = readOffset();
readUInt(); // offset of the variable declaration in the binary.
return new VariableSet(variableStack[index], readExpression())
..fileOffset = offset;
case Tag.PropertyGet:
int offset = readOffset();
return new PropertyGet.byReference(
readExpression(), readName(), readMemberReference(allowNull: true))
..fileOffset = offset;
case Tag.PropertySet:
int offset = readOffset();
return new PropertySet.byReference(readExpression(), readName(),
readExpression(), readMemberReference(allowNull: true))
..fileOffset = offset;
case Tag.SuperPropertyGet:
int offset = readOffset();
addTransformerFlag(TransformerFlag.superCalls);
return new SuperPropertyGet.byReference(
readName(), readMemberReference(allowNull: true))
..fileOffset = offset;
case Tag.SuperPropertySet:
int offset = readOffset();
addTransformerFlag(TransformerFlag.superCalls);
return new SuperPropertySet.byReference(
readName(), readExpression(), readMemberReference(allowNull: true))
..fileOffset = offset;
case Tag.DirectPropertyGet:
int offset = readOffset();
return new DirectPropertyGet.byReference(
readExpression(), readMemberReference())
..fileOffset = offset;
case Tag.DirectPropertySet:
int offset = readOffset();
return new DirectPropertySet.byReference(
readExpression(), readMemberReference(), readExpression())
..fileOffset = offset;
case Tag.StaticGet:
int offset = readOffset();
return new StaticGet.byReference(readMemberReference())
..fileOffset = offset;
case Tag.StaticSet:
int offset = readOffset();
return new StaticSet.byReference(
readMemberReference(), readExpression())
..fileOffset = offset;
case Tag.MethodInvocation:
int offset = readOffset();
return new MethodInvocation.byReference(readExpression(), readName(),
readArguments(), readMemberReference(allowNull: true))
..fileOffset = offset;
case Tag.SuperMethodInvocation:
int offset = readOffset();
addTransformerFlag(TransformerFlag.superCalls);
return new SuperMethodInvocation.byReference(
readName(), readArguments(), readMemberReference(allowNull: true))
..fileOffset = offset;
case Tag.DirectMethodInvocation:
int offset = readOffset();
return new DirectMethodInvocation.byReference(
readExpression(), readMemberReference(), readArguments())
..fileOffset = offset;
case Tag.StaticInvocation:
int offset = readOffset();
return new StaticInvocation.byReference(
readMemberReference(), readArguments(),
isConst: false)
..fileOffset = offset;
case Tag.ConstStaticInvocation:
int offset = readOffset();
return new StaticInvocation.byReference(
readMemberReference(), readArguments(),
isConst: true)
..fileOffset = offset;
case Tag.ConstructorInvocation:
int offset = readOffset();
return new ConstructorInvocation.byReference(
readMemberReference(), readArguments(),
isConst: false)
..fileOffset = offset;
case Tag.ConstConstructorInvocation:
int offset = readOffset();
return new ConstructorInvocation.byReference(
readMemberReference(), readArguments(),
isConst: true)
..fileOffset = offset;
case Tag.Not:
return new Not(readExpression());
case Tag.NullCheck:
int offset = readOffset();
return new NullCheck(readExpression())..fileOffset = offset;
case Tag.LogicalExpression:
return new LogicalExpression(readExpression(),
logicalOperatorToString(readByte()), readExpression());
case Tag.ConditionalExpression:
return new ConditionalExpression(readExpression(), readExpression(),
readExpression(), readDartTypeOption());
case Tag.StringConcatenation:
int offset = readOffset();
return new StringConcatenation(readExpressionList())
..fileOffset = offset;
case Tag.ListConcatenation:
int offset = readOffset();
var typeArgument = readDartType();
return new ListConcatenation(readExpressionList(),
typeArgument: typeArgument)
..fileOffset = offset;
case Tag.SetConcatenation:
int offset = readOffset();
var typeArgument = readDartType();
return new SetConcatenation(readExpressionList(),
typeArgument: typeArgument)
..fileOffset = offset;
case Tag.MapConcatenation:
int offset = readOffset();
var keyType = readDartType();
var valueType = readDartType();
return new MapConcatenation(readExpressionList(),
keyType: keyType, valueType: valueType)
..fileOffset = offset;
case Tag.InstanceCreation:
int offset = readOffset();
Reference classReference = readClassReference();
List<DartType> typeArguments = readDartTypeList();
int fieldValueCount = readUInt();
Map<Reference, Expression> fieldValues = <Reference, Expression>{};
for (int i = 0; i < fieldValueCount; i++) {
final Reference fieldRef =
readCanonicalNameReference().getReference();
final Expression value = readExpression();
fieldValues[fieldRef] = value;
}
int assertCount = readUInt();
List<AssertStatement> asserts = new List<AssertStatement>(assertCount);
for (int i = 0; i < assertCount; i++) {
asserts[i] = readStatement();
}
List<Expression> unusedArguments = readExpressionList();
return new InstanceCreation(classReference, typeArguments, fieldValues,
asserts, unusedArguments)
..fileOffset = offset;
case Tag.FileUriExpression:
Uri fileUri = readUriReference();
int offset = readOffset();
return new FileUriExpression(readExpression(), fileUri)
..fileOffset = offset;
case Tag.IsExpression:
int offset = readOffset();
return new IsExpression(readExpression(), readDartType())
..fileOffset = offset;
case Tag.AsExpression:
int offset = readOffset();
int flags = readByte();
return new AsExpression(readExpression(), readDartType())
..fileOffset = offset
..flags = flags;
case Tag.StringLiteral:
return new StringLiteral(readStringReference());
case Tag.SpecializedIntLiteral:
int biasedValue = tagByte & Tag.SpecializedPayloadMask;
return new IntLiteral(biasedValue - Tag.SpecializedIntLiteralBias);
case Tag.PositiveIntLiteral:
return new IntLiteral(readUInt());
case Tag.NegativeIntLiteral:
return new IntLiteral(-readUInt());
case Tag.BigIntLiteral:
return new IntLiteral(int.parse(readStringReference()));
case Tag.DoubleLiteral:
return new DoubleLiteral(readDouble());
case Tag.TrueLiteral:
return new BoolLiteral(true);
case Tag.FalseLiteral:
return new BoolLiteral(false);
case Tag.NullLiteral:
return new NullLiteral();
case Tag.SymbolLiteral:
return new SymbolLiteral(readStringReference());
case Tag.TypeLiteral:
return new TypeLiteral(readDartType());
case Tag.ThisExpression:
return new ThisExpression();
case Tag.Rethrow:
int offset = readOffset();
return new Rethrow()..fileOffset = offset;
case Tag.Throw:
int offset = readOffset();
return new Throw(readExpression())..fileOffset = offset;
case Tag.ListLiteral:
int offset = readOffset();
var typeArgument = readDartType();
return new ListLiteral(readExpressionList(),
typeArgument: typeArgument, isConst: false)
..fileOffset = offset;
case Tag.ConstListLiteral:
int offset = readOffset();
var typeArgument = readDartType();
return new ListLiteral(readExpressionList(),
typeArgument: typeArgument, isConst: true)
..fileOffset = offset;
case Tag.SetLiteral:
int offset = readOffset();
var typeArgument = readDartType();
return new SetLiteral(readExpressionList(),
typeArgument: typeArgument, isConst: false)
..fileOffset = offset;
case Tag.ConstSetLiteral:
int offset = readOffset();
var typeArgument = readDartType();
return new SetLiteral(readExpressionList(),
typeArgument: typeArgument, isConst: true)
..fileOffset = offset;
case Tag.MapLiteral:
int offset = readOffset();
var keyType = readDartType();
var valueType = readDartType();
return new MapLiteral(readMapEntryList(),
keyType: keyType, valueType: valueType, isConst: false)
..fileOffset = offset;
case Tag.ConstMapLiteral:
int offset = readOffset();
var keyType = readDartType();
var valueType = readDartType();
return new MapLiteral(readMapEntryList(),
keyType: keyType, valueType: valueType, isConst: true)
..fileOffset = offset;
case Tag.AwaitExpression:
return new AwaitExpression(readExpression());
case Tag.FunctionExpression:
int offset = readOffset();
return new FunctionExpression(readFunctionNode())..fileOffset = offset;
case Tag.Let:
var variable = readVariableDeclaration();
int stackHeight = variableStack.length;
pushVariableDeclaration(variable);
var body = readExpression();
variableStack.length = stackHeight;
return new Let(variable, body);
case Tag.BlockExpression:
int stackHeight = variableStack.length;
var statements = readStatementList();
var value = readExpression();
variableStack.length = stackHeight;
return new BlockExpression(new Block(statements), value);
case Tag.Instantiation:
var expression = readExpression();
var typeArguments = readDartTypeList();
return new Instantiation(expression, typeArguments);
case Tag.ConstantExpression:
int offset = readOffset();
DartType type = readDartType();
Constant constant = readConstantReference();
return new ConstantExpression(constant, type)..fileOffset = offset;
default:
throw fail('unexpected expression tag: $tag');
}
}
List<MapEntry> readMapEntryList() {
int length = readUInt();
List<MapEntry> result =
new List<MapEntry>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readMapEntry();
}
return result;
}
MapEntry readMapEntry() {
return new MapEntry(readExpression(), readExpression());
}
List<Statement> readStatementList() {
int length = readUInt();
List<Statement> result =
new List<Statement>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readStatement();
}
return result;
}
Statement readStatementOrNullIfEmpty() {
var node = readStatement();
if (node is EmptyStatement) {
return null;
} else {
return node;
}
}
Statement readStatementOption() {
return readAndCheckOptionTag() ? readStatement() : null;
}
Statement readStatement() {
int tag = readByte();
switch (tag) {
case Tag.ExpressionStatement:
return new ExpressionStatement(readExpression());
case Tag.Block:
return readBlock();
case Tag.AssertBlock:
return readAssertBlock();
case Tag.EmptyStatement:
return new EmptyStatement();
case Tag.AssertStatement:
return new AssertStatement(readExpression(),
conditionStartOffset: readOffset(),
conditionEndOffset: readOffset(),
message: readExpressionOption());
case Tag.LabeledStatement:
var label = new LabeledStatement(null);
labelStack.add(label);
label.body = readStatement()..parent = label;
labelStack.removeLast();
return label;
case Tag.BreakStatement:
int offset = readOffset();
int index = readUInt();
return new BreakStatement(labelStack[labelStackBase + index])
..fileOffset = offset;
case Tag.WhileStatement:
var offset = readOffset();
return new WhileStatement(readExpression(), readStatement())
..fileOffset = offset;
case Tag.DoStatement:
var offset = readOffset();
return new DoStatement(readStatement(), readExpression())
..fileOffset = offset;
case Tag.ForStatement:
int variableStackHeight = variableStack.length;
var offset = readOffset();
var variables = readAndPushVariableDeclarationList();
var condition = readExpressionOption();
var updates = readExpressionList();
var body = readStatement();
variableStack.length = variableStackHeight;
return new ForStatement(variables, condition, updates, body)
..fileOffset = offset;
case Tag.ForInStatement:
case Tag.AsyncForInStatement:
bool isAsync = tag == Tag.AsyncForInStatement;
int variableStackHeight = variableStack.length;
var offset = readOffset();
var bodyOffset = readOffset();
var variable = readAndPushVariableDeclaration();
var iterable = readExpression();
var body = readStatement();
variableStack.length = variableStackHeight;
return new ForInStatement(variable, iterable, body, isAsync: isAsync)
..fileOffset = offset
..bodyOffset = bodyOffset;
case Tag.SwitchStatement:
var offset = readOffset();
var expression = readExpression();
int count = readUInt();
List<SwitchCase> cases =
new List<SwitchCase>.filled(count, null, growable: true);
for (int i = 0; i < count; ++i) {
cases[i] = new SwitchCase.empty();
}
switchCaseStack.addAll(cases);
for (int i = 0; i < cases.length; ++i) {
readSwitchCaseInto(cases[i]);
}
switchCaseStack.length -= count;
return new SwitchStatement(expression, cases)..fileOffset = offset;
case Tag.ContinueSwitchStatement:
int offset = readOffset();
int index = readUInt();
return new ContinueSwitchStatement(switchCaseStack[index])
..fileOffset = offset;
case Tag.IfStatement:
int offset = readOffset();
return new IfStatement(
readExpression(), readStatement(), readStatementOrNullIfEmpty())
..fileOffset = offset;
case Tag.ReturnStatement:
int offset = readOffset();
return new ReturnStatement(readExpressionOption())..fileOffset = offset;
case Tag.TryCatch:
Statement body = readStatement();
int flags = readByte();
return new TryCatch(body, readCatchList(), isSynthetic: flags & 2 == 2);
case Tag.TryFinally:
return new TryFinally(readStatement(), readStatement());
case Tag.YieldStatement:
int offset = readOffset();
int flags = readByte();
return new YieldStatement(readExpression(),
isYieldStar: flags & YieldStatement.FlagYieldStar != 0,
isNative: flags & YieldStatement.FlagNative != 0)
..fileOffset = offset;
case Tag.VariableDeclaration:
var variable = readVariableDeclaration();
variableStack.add(variable); // Will be popped by the enclosing scope.
return variable;
case Tag.FunctionDeclaration:
int offset = readOffset();
var variable = readVariableDeclaration();
variableStack.add(variable); // Will be popped by the enclosing scope.
var function = readFunctionNode();
return new FunctionDeclaration(variable, function)..fileOffset = offset;
default:
throw fail('unexpected statement tag: $tag');
}
}
void readSwitchCaseInto(SwitchCase caseNode) {
int length = readUInt();
caseNode.expressions.length = length;
caseNode.expressionOffsets.length = length;
for (int i = 0; i < length; ++i) {
caseNode.expressionOffsets[i] = readOffset();
caseNode.expressions[i] = readExpression()..parent = caseNode;
}
caseNode.isDefault = readByte() == 1;
caseNode.body = readStatement()..parent = caseNode;
}
List<Catch> readCatchList() {
int length = readUInt();
List<Catch> result = new List<Catch>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readCatch();
}
return result;
}
Catch readCatch() {
int variableStackHeight = variableStack.length;
var offset = readOffset();
var guard = readDartType();
var exception = readAndPushVariableDeclarationOption();
var stackTrace = readAndPushVariableDeclarationOption();
var body = readStatement();
variableStack.length = variableStackHeight;
return new Catch(exception, body, guard: guard, stackTrace: stackTrace)
..fileOffset = offset;
}
Block readBlock() {
int stackHeight = variableStack.length;
var body = readStatementList();
variableStack.length = stackHeight;
return new Block(body);
}
AssertBlock readAssertBlock() {
int stackHeight = variableStack.length;
var body = readStatementList();
variableStack.length = stackHeight;
return new AssertBlock(body);
}
Supertype readSupertype() {
InterfaceType type = readDartType();
return new Supertype.byReference(type.className, type.typeArguments);
}
Supertype readSupertypeOption() {
return readAndCheckOptionTag() ? readSupertype() : null;
}
List<Supertype> readSupertypeList() {
int length = readUInt();
List<Supertype> result =
new List<Supertype>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readSupertype();
}
return result;
}
List<DartType> readDartTypeList() {
int length = readUInt();
List<DartType> result =
new List<DartType>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readDartType();
}
return result;
}
List<NamedType> readNamedTypeList() {
int length = readUInt();
List<NamedType> result =
new List<NamedType>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readNamedType();
}
return result;
}
NamedType readNamedType() {
String name = readStringReference();
DartType type = readDartType();
int flags = readByte();
return new NamedType(name, type,
isRequired: (flags & NamedType.FlagRequiredNamedType) != 0);
}
DartType readDartTypeOption() {
return readAndCheckOptionTag() ? readDartType() : null;
}
DartType readDartType() {
int tag = readByte();
switch (tag) {
case Tag.TypedefType:
int nullabilityIndex = readByte();
return new TypedefType.byReference(readTypedefReference(),
readDartTypeList(), Nullability.values[nullabilityIndex]);
case Tag.BottomType:
return const BottomType();
case Tag.InvalidType:
return const InvalidType();
case Tag.DynamicType:
return const DynamicType();
case Tag.VoidType:
return const VoidType();
case Tag.InterfaceType:
int nullabilityIndex = readByte();
return new InterfaceType.byReference(readClassReference(),
readDartTypeList(), Nullability.values[nullabilityIndex]);
case Tag.SimpleInterfaceType:
int nullabilityIndex = readByte();
return new InterfaceType.byReference(readClassReference(),
const <DartType>[], Nullability.values[nullabilityIndex]);
case Tag.FunctionType:
int typeParameterStackHeight = typeParameterStack.length;
int nullabilityIndex = readByte();
var typeParameters = readAndPushTypeParameterList();
var requiredParameterCount = readUInt();
var totalParameterCount = readUInt();
var positional = readDartTypeList();
var named = readNamedTypeList();
var typedefType = readDartTypeOption();
assert(positional.length + named.length == totalParameterCount);
var returnType = readDartType();
typeParameterStack.length = typeParameterStackHeight;
return new FunctionType(positional, returnType,
typeParameters: typeParameters,
requiredParameterCount: requiredParameterCount,
namedParameters: named,
typedefType: typedefType,
nullability: Nullability.values[nullabilityIndex]);
case Tag.SimpleFunctionType:
int nullabilityIndex = readByte();
var positional = readDartTypeList();
var returnType = readDartType();
return new FunctionType(positional, returnType,
nullability: Nullability.values[nullabilityIndex]);
case Tag.TypeParameterType:
int declaredNullabilityIndex = readByte();
int index = readUInt();
var bound = readDartTypeOption();
return new TypeParameterType(typeParameterStack[index], bound,
Nullability.values[declaredNullabilityIndex]);
default:
throw fail('unexpected dart type tag: $tag');
}
}
List<TypeParameter> readAndPushTypeParameterList(
[List<TypeParameter> list, TreeNode parent]) {
int length = readUInt();
if (length == 0) return list ?? <TypeParameter>[];
if (list == null) {
list = new List<TypeParameter>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
list[i] = new TypeParameter(null, null)..parent = parent;
}
} else if (list.length != length) {
list.length = length;
for (int i = 0; i < length; ++i) {
list[i] = new TypeParameter(null, null)..parent = parent;
}
}
typeParameterStack.addAll(list);
for (int i = 0; i < list.length; ++i) {
readTypeParameter(list[i]);
}
return list;
}
void readTypeParameter(TypeParameter node) {
node.flags = readByte();
node.annotations = readAnnotationList(node);
node.variance = readByte();
node.name = readStringOrNullIfEmpty();
node.bound = readDartType();
node.defaultType = readDartTypeOption();
}
Arguments readArguments() {
var numArguments = readUInt();
var typeArguments = readDartTypeList();
var positional = readExpressionList();
var named = readNamedExpressionList();
assert(numArguments == positional.length + named.length);
return new Arguments(positional, types: typeArguments, named: named);
}
List<NamedExpression> readNamedExpressionList() {
int length = readUInt();
List<NamedExpression> result =
new List<NamedExpression>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readNamedExpression();
}
return result;
}
NamedExpression readNamedExpression() {
return new NamedExpression(readStringReference(), readExpression());
}
List<VariableDeclaration> readAndPushVariableDeclarationList() {
int length = readUInt();
List<VariableDeclaration> result =
new List<VariableDeclaration>.filled(length, null, growable: true);
for (int i = 0; i < length; ++i) {
result[i] = readAndPushVariableDeclaration();
}
return result;
}
VariableDeclaration readAndPushVariableDeclarationOption() {
return readAndCheckOptionTag() ? readAndPushVariableDeclaration() : null;
}
VariableDeclaration readAndPushVariableDeclaration() {
var variable = readVariableDeclaration();
variableStack.add(variable);
return variable;
}
VariableDeclaration readVariableDeclaration() {
int offset = readOffset();
int fileEqualsOffset = readOffset();
// The [VariableDeclaration] instance is not created at this point yet,
// so `null` is temporarily set as the parent of the annotation nodes.
var annotations = readAnnotationList(null);
int flags = readByte();
var node = new VariableDeclaration(readStringOrNullIfEmpty(),
type: readDartType(), initializer: readExpressionOption(), flags: flags)
..fileOffset = offset
..fileEqualsOffset = fileEqualsOffset;
if (annotations.isNotEmpty) {
for (int i = 0; i < annotations.length; ++i) {
var annotation = annotations[i];
annotation.parent = node;
}
node.annotations = annotations;
}
return node;
}
int readOffset() {
// Offset is saved as unsigned,
// but actually ranges from -1 and up (thus the -1)
return readUInt() - 1;
}
}
class BinaryBuilderWithMetadata extends BinaryBuilder implements BinarySource {
/// List of metadata subsections that have corresponding [MetadataRepository]
/// and are awaiting to be parsed and attached to nodes.
List<_MetadataSubsection> _subsections;
BinaryBuilderWithMetadata(List<int> bytes,
{String filename,
bool disableLazyReading = false,
bool disableLazyClassReading = false,
bool alwaysCreateNewNamedNodes})
: super(bytes,
filename: filename,
disableLazyReading: disableLazyReading,
disableLazyClassReading: disableLazyClassReading,
alwaysCreateNewNamedNodes: alwaysCreateNewNamedNodes);
@override
void _readMetadataMappings(
Component component, int binaryOffsetForMetadataPayloads) {
// At the beginning of this function _byteOffset points right past
// metadataMappings to string table.
// Read the length of metadataMappings.
_byteOffset -= 4;
final subSectionCount = readUint32();
int endOffset = _byteOffset - 4; // End offset of the current subsection.
for (var i = 0; i < subSectionCount; i++) {
// RList<Pair<UInt32, UInt32>> nodeOffsetToMetadataOffset
_byteOffset = endOffset - 4;
final mappingLength = readUint32();
final mappingStart = (endOffset - 4) - 4 * 2 * mappingLength;
_byteOffset = mappingStart - 4;
// UInt32 tag (fixed size StringReference)
final tag = _stringTable[readUint32()];
final repository = component.metadata[tag];
if (repository != null) {
// Read nodeOffsetToMetadataOffset mapping.
final mapping = <int, int>{};
_byteOffset = mappingStart;
for (var j = 0; j < mappingLength; j++) {
final nodeOffset = readUint32();
final metadataOffset = binaryOffsetForMetadataPayloads + readUint32();
mapping[nodeOffset] = metadataOffset;
}
_subsections ??= <_MetadataSubsection>[];
_subsections.add(new _MetadataSubsection(repository, mapping));
}
// Start of the subsection and the end of the previous one.
endOffset = mappingStart - 4;
}
}
Object _readMetadata(Node node, MetadataRepository repository, int offset) {
final int savedOffset = _byteOffset;
_byteOffset = offset;
final metadata = repository.readFromBinary(node, this);
_byteOffset = savedOffset;
return metadata;
}
@override
void enterScope({List<TypeParameter> typeParameters}) {
if (typeParameters != null) {
typeParameterStack.addAll(typeParameters);
}
}
@override
void leaveScope({List<TypeParameter> typeParameters}) {
if (typeParameters != null) {
typeParameterStack.length -= typeParameters.length;
}
}
@override
Node _associateMetadata(Node node, int nodeOffset) {
if (_subsections == null) {
return node;
}
for (var subsection in _subsections) {
// First check if there is any metadata associated with this node.
final metadataOffset = subsection.mapping[nodeOffset];
if (metadataOffset != null) {
subsection.repository.mapping[node] =
_readMetadata(node, subsection.repository, metadataOffset);
}
}
return node;
}
@override
DartType readDartType() {
final nodeOffset = _byteOffset;
final result = super.readDartType();
return _associateMetadata(result, nodeOffset);
}
@override
Library readLibrary(Component component, int endOffset) {
final nodeOffset = _byteOffset;
final result = super.readLibrary(component, endOffset);
return _associateMetadata(result, nodeOffset);
}
@override
Typedef readTypedef() {
final nodeOffset = _byteOffset;
final result = super.readTypedef();
return _associateMetadata(result, nodeOffset);
}
@override
Class readClass(int endOffset) {
final nodeOffset = _byteOffset;
final result = super.readClass(endOffset);
return _associateMetadata(result, nodeOffset);
}
@override
Extension readExtension() {
final nodeOffset = _byteOffset;
final result = super.readExtension();
return _associateMetadata(result, nodeOffset);
}
@override
Field readField() {
final nodeOffset = _byteOffset;
final result = super.readField();
return _associateMetadata(result, nodeOffset);
}
@override
Constructor readConstructor() {
final nodeOffset = _byteOffset;
final result = super.readConstructor();
return _associateMetadata(result, nodeOffset);
}
@override
Procedure readProcedure(int endOffset) {
final nodeOffset = _byteOffset;
final result = super.readProcedure(endOffset);
return _associateMetadata(result, nodeOffset);
}
@override
RedirectingFactoryConstructor readRedirectingFactoryConstructor() {
final nodeOffset = _byteOffset;
final result = super.readRedirectingFactoryConstructor();
return _associateMetadata(result, nodeOffset);
}
@override
Initializer readInitializer() {
final nodeOffset = _byteOffset;
final result = super.readInitializer();
return _associateMetadata(result, nodeOffset);
}
@override
FunctionNode readFunctionNode(
{bool lazyLoadBody: false, int outerEndOffset: -1}) {
final nodeOffset = _byteOffset;
final result = super.readFunctionNode(
lazyLoadBody: lazyLoadBody, outerEndOffset: outerEndOffset);
return _associateMetadata(result, nodeOffset);
}
@override
Expression readExpression() {
final nodeOffset = _byteOffset;
final result = super.readExpression();
return _associateMetadata(result, nodeOffset);
}
@override
Arguments readArguments() {
final nodeOffset = _byteOffset;
final result = super.readArguments();
return _associateMetadata(result, nodeOffset);
}
@override
NamedExpression readNamedExpression() {
final nodeOffset = _byteOffset;
final result = super.readNamedExpression();
return _associateMetadata(result, nodeOffset);
}
@override
VariableDeclaration readVariableDeclaration() {
final nodeOffset = _byteOffset;
final result = super.readVariableDeclaration();
return _associateMetadata(result, nodeOffset);
}
@override
Statement readStatement() {
final nodeOffset = _byteOffset;
final result = super.readStatement();
return _associateMetadata(result, nodeOffset);
}
@override
Combinator readCombinator() {
final nodeOffset = _byteOffset;
final result = super.readCombinator();
return _associateMetadata(result, nodeOffset);
}
@override
LibraryDependency readLibraryDependency(Library library) {
final nodeOffset = _byteOffset;
final result = super.readLibraryDependency(library);
return _associateMetadata(result, nodeOffset);
}
@override
LibraryPart readLibraryPart(Library library) {
final nodeOffset = _byteOffset;
final result = super.readLibraryPart(library);
return _associateMetadata(result, nodeOffset);
}
@override
void readSwitchCaseInto(SwitchCase caseNode) {
_associateMetadata(caseNode, _byteOffset);
super.readSwitchCaseInto(caseNode);
}
@override
void readTypeParameter(TypeParameter param) {
_associateMetadata(param, _byteOffset);
super.readTypeParameter(param);
}
@override
Supertype readSupertype() {
final nodeOffset = _byteOffset;
InterfaceType type = super.readDartType();
return _associateMetadata(
new Supertype.byReference(type.className, type.typeArguments),
nodeOffset);
}
@override
Name readName() {
final nodeOffset = _byteOffset;
final result = super.readName();
return _associateMetadata(result, nodeOffset);
}
@override
int get currentOffset => _byteOffset;
@override
List<int> get bytes => _bytes;
}
/// Deserialized MetadataMapping corresponding to the given metadata repository.
class _MetadataSubsection {
/// [MetadataRepository] that can read this subsection.
final MetadataRepository repository;
/// Deserialized mapping from node offsets to metadata offsets.
final Map<int, int> mapping;
_MetadataSubsection(this.repository, this.mapping);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/binary/ast_to_binary.dart | // 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.
library kernel.ast_to_binary;
import 'dart:core' hide MapEntry;
import 'dart:convert' show utf8;
import 'dart:developer';
import 'dart:io' show BytesBuilder;
import 'dart:typed_data';
import '../ast.dart';
import 'tag.dart';
/// Writes to a binary file.
///
/// A [BinaryPrinter] can be used to write one file and must then be
/// discarded.
class BinaryPrinter implements Visitor<void>, BinarySink {
VariableIndexer _variableIndexer;
LabelIndexer _labelIndexer;
SwitchCaseIndexer _switchCaseIndexer;
final TypeParameterIndexer _typeParameterIndexer = new TypeParameterIndexer();
final StringIndexer stringIndexer;
ConstantIndexer _constantIndexer;
final UriIndexer _sourceUriIndexer = new UriIndexer();
bool _currentlyInNonimplementation = false;
final List<bool> _sourcesFromRealImplementation = new List<bool>();
final List<bool> _sourcesFromRealImplementationInLibrary = new List<bool>();
Map<LibraryDependency, int> _libraryDependencyIndex =
<LibraryDependency, int>{};
List<_MetadataSubsection> _metadataSubsections;
final BufferedSink _mainSink;
final BufferedSink _metadataSink;
final BytesSink _constantsBytesSink;
BufferedSink _constantsSink;
BufferedSink _sink;
bool includeSources;
bool includeOffsets;
List<int> libraryOffsets;
List<int> classOffsets;
List<int> procedureOffsets;
int _binaryOffsetForSourceTable = -1;
int _binaryOffsetForLinkTable = -1;
int _binaryOffsetForMetadataPayloads = -1;
int _binaryOffsetForMetadataMappings = -1;
int _binaryOffsetForStringTable = -1;
int _binaryOffsetForConstantTable = -1;
List<CanonicalName> _canonicalNameList;
Set<CanonicalName> _knownCanonicalNameNonRootTops = new Set<CanonicalName>();
Set<CanonicalName> _reindexedCanonicalNames = new Set<CanonicalName>();
/// Create a printer that writes to the given [sink].
///
/// The BinaryPrinter will use its own buffer, so the [sink] does not need
/// one.
BinaryPrinter(Sink<List<int>> sink,
{StringIndexer stringIndexer,
this.includeSources = true,
this.includeOffsets = true})
: _mainSink = new BufferedSink(sink),
_metadataSink = new BufferedSink(new BytesSink()),
_constantsBytesSink = new BytesSink(),
stringIndexer = stringIndexer ?? new StringIndexer() {
_constantsSink = new BufferedSink(_constantsBytesSink);
_constantIndexer = new ConstantIndexer(this.stringIndexer, this);
_sink = _mainSink;
}
void _flush() {
_sink.flushAndDestroy();
}
void writeByte(int byte) {
assert((byte & 0xFF) == byte);
_sink.addByte(byte);
}
void writeBytes(List<int> bytes) {
_sink.addBytes(bytes);
}
@pragma("vm:prefer-inline")
void writeUInt30(int value) {
assert(value >= 0 && value >> 30 == 0);
if (value < 0x80) {
_sink.addByte(value);
} else if (value < 0x4000) {
_sink.addByte2((value >> 8) | 0x80, value & 0xFF);
} else {
_sink.addByte4((value >> 24) | 0xC0, (value >> 16) & 0xFF,
(value >> 8) & 0xFF, value & 0xFF);
}
}
void writeUInt32(int value) {
_sink.addByte4((value >> 24) & 0xFF, (value >> 16) & 0xFF,
(value >> 8) & 0xFF, value & 0xFF);
}
void writeByteList(List<int> utf8Bytes) {
writeUInt30(utf8Bytes.length);
writeBytes(utf8Bytes);
}
int getBufferOffset() {
return _sink.offset;
}
void writeStringTable(StringIndexer indexer) {
_binaryOffsetForStringTable = getBufferOffset();
// Containers for the utf8 encoded strings.
final List<Uint8List> data = new List<Uint8List>();
int totalLength = 0;
const int minLength = 1 << 16;
Uint8List buffer;
int index = 0;
// Write the end offsets.
writeUInt30(indexer.index.length);
for (String key in indexer.index.keys) {
if (key.isNotEmpty) {
int requiredMinLength = key.length;
int allocateMinLength = requiredMinLength * 3;
int newIndex;
while (true) {
if (buffer == null || index + requiredMinLength >= buffer.length) {
int newLength = minLength;
if (allocateMinLength > newLength) newLength = allocateMinLength;
if (buffer != null && index > 0) {
data.add(new Uint8List.view(buffer.buffer, 0, index));
}
index = 0;
buffer = new Uint8List(newLength);
}
newIndex = NotQuiteString.writeUtf8(buffer, index, key);
if (newIndex != -1) break;
requiredMinLength = allocateMinLength;
}
if (newIndex < 0) {
// Utf8 encoding failed.
if (buffer != null && index > 0) {
data.add(new Uint8List.view(buffer.buffer, 0, index));
buffer = null;
index = 0;
}
List<int> converted = utf8.encoder.convert(key);
data.add(converted);
totalLength += converted.length;
} else {
totalLength += newIndex - index;
index = newIndex;
}
}
writeUInt30(totalLength);
}
if (buffer != null && index > 0) {
data.add(Uint8List.view(buffer.buffer, 0, index));
}
// Write the UTF-8 encoded strings.
for (int i = 0; i < data.length; ++i) {
writeBytes(data[i]);
}
}
void writeStringReference(String string) {
writeUInt30(stringIndexer.put(string));
}
void writeStringReferenceList(List<String> strings) {
writeList(strings, writeStringReference);
}
void writeConstantReference(Constant constant) {
writeUInt30(_constantIndexer.put(constant));
}
void writeConstantTable(ConstantIndexer indexer) {
_binaryOffsetForConstantTable = getBufferOffset();
writeUInt30(indexer.entries.length);
assert(identical(_sink, _mainSink));
_constantsSink.flushAndDestroy();
writeBytes(_constantsBytesSink.builder.takeBytes());
}
int writeConstantTableEntry(Constant constant) {
BufferedSink oldSink = _sink;
_sink = _constantsSink;
int initialOffset = _sink.offset;
if (constant is NullConstant) {
writeByte(ConstantTag.NullConstant);
} else if (constant is BoolConstant) {
writeByte(ConstantTag.BoolConstant);
writeByte(constant.value ? 1 : 0);
} else if (constant is IntConstant) {
writeByte(ConstantTag.IntConstant);
writeInteger(constant.value);
} else if (constant is DoubleConstant) {
writeByte(ConstantTag.DoubleConstant);
writeDouble(constant.value);
} else if (constant is StringConstant) {
writeByte(ConstantTag.StringConstant);
writeStringReference(constant.value);
} else if (constant is SymbolConstant) {
writeByte(ConstantTag.SymbolConstant);
writeNullAllowedReference(constant.libraryReference);
writeStringReference(constant.name);
} else if (constant is MapConstant) {
writeByte(ConstantTag.MapConstant);
writeDartType(constant.keyType);
writeDartType(constant.valueType);
writeUInt30(constant.entries.length);
for (final ConstantMapEntry entry in constant.entries) {
writeConstantReference(entry.key);
writeConstantReference(entry.value);
}
} else if (constant is ListConstant) {
writeByte(ConstantTag.ListConstant);
writeDartType(constant.typeArgument);
writeUInt30(constant.entries.length);
constant.entries.forEach(writeConstantReference);
} else if (constant is SetConstant) {
writeByte(ConstantTag.SetConstant);
writeDartType(constant.typeArgument);
writeUInt30(constant.entries.length);
constant.entries.forEach(writeConstantReference);
} else if (constant is InstanceConstant) {
writeByte(ConstantTag.InstanceConstant);
writeClassReference(constant.classNode);
writeUInt30(constant.typeArguments.length);
constant.typeArguments.forEach(writeDartType);
writeUInt30(constant.fieldValues.length);
constant.fieldValues.forEach((Reference fieldRef, Constant value) {
writeNonNullCanonicalNameReference(fieldRef.canonicalName);
writeConstantReference(value);
});
} else if (constant is PartialInstantiationConstant) {
writeByte(ConstantTag.PartialInstantiationConstant);
writeConstantReference(constant.tearOffConstant);
final int length = constant.types.length;
writeUInt30(length);
for (int i = 0; i < length; ++i) {
writeDartType(constant.types[i]);
}
} else if (constant is TearOffConstant) {
writeByte(ConstantTag.TearOffConstant);
writeNonNullCanonicalNameReference(constant.procedure.canonicalName);
} else if (constant is TypeLiteralConstant) {
writeByte(ConstantTag.TypeLiteralConstant);
writeDartType(constant.type);
} else if (constant is UnevaluatedConstant) {
writeByte(ConstantTag.UnevaluatedConstant);
writeNode(constant.expression);
} else {
throw new ArgumentError('Unsupported constant $constant');
}
_sink = oldSink;
return _constantsSink.offset - initialOffset;
}
void writeDartType(DartType type) {
type.accept(this);
}
// Returns the new active file uri.
void writeUriReference(Uri uri) {
final int index = _sourceUriIndexer.put(uri);
writeUInt30(index);
if (!_currentlyInNonimplementation) {
if (_sourcesFromRealImplementationInLibrary.length <= index) {
_sourcesFromRealImplementationInLibrary.length = index + 1;
}
_sourcesFromRealImplementationInLibrary[index] = true;
if (_sourcesFromRealImplementation.length <= index) {
_sourcesFromRealImplementation.length = index + 1;
}
_sourcesFromRealImplementation[index] = true;
}
}
void writeList<T>(List<T> items, void writeItem(T x)) {
writeUInt30(items.length);
for (int i = 0; i < items.length; ++i) {
writeItem(items[i]);
}
}
void writeNodeList(List<Node> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeNode(node);
}
}
void writeProcedureNodeList(List<Procedure> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeProcedureNode(node);
}
}
void writeFieldNodeList(List<Field> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeFieldNode(node);
}
}
void writeClassNodeList(List<Class> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeClassNode(node);
}
}
void writeExtensionNodeList(List<Extension> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeExtensionNode(node);
}
}
void writeConstructorNodeList(List<Constructor> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeConstructorNode(node);
}
}
void writeRedirectingFactoryConstructorNodeList(
List<RedirectingFactoryConstructor> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeRedirectingFactoryConstructorNode(node);
}
}
void writeSwitchCaseNodeList(List<SwitchCase> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeSwitchCaseNode(node);
}
}
void writeCatchNodeList(List<Catch> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeCatchNode(node);
}
}
void writeTypedefNodeList(List<Typedef> nodes) {
final len = nodes.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final node = nodes[i];
writeTypedefNode(node);
}
}
void writeNode(Node node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeFunctionNode(FunctionNode node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeArgumentsNode(Arguments node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeLibraryNode(Library node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeProcedureNode(Procedure node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeFieldNode(Field node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeClassNode(Class node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeExtensionNode(Extension node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeConstructorNode(Constructor node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeRedirectingFactoryConstructorNode(
RedirectingFactoryConstructor node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeSwitchCaseNode(SwitchCase node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeCatchNode(Catch node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeTypedefNode(Typedef node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.accept(this);
}
void writeOptionalNode(Node node) {
if (node == null) {
writeByte(Tag.Nothing);
} else {
writeByte(Tag.Something);
writeNode(node);
}
}
void writeOptionalFunctionNode(FunctionNode node) {
if (node == null) {
writeByte(Tag.Nothing);
} else {
writeByte(Tag.Something);
writeFunctionNode(node);
}
}
void writeLinkTable(Component component) {
_binaryOffsetForLinkTable = getBufferOffset();
writeList(_canonicalNameList, writeCanonicalNameEntry);
}
void indexLinkTable(Component component) {
_canonicalNameList = <CanonicalName>[];
for (int i = 0; i < component.libraries.length; ++i) {
Library library = component.libraries[i];
if (!shouldWriteLibraryCanonicalNames(library)) continue;
_indexLinkTableInternal(library.canonicalName);
_knownCanonicalNameNonRootTops.add(library.canonicalName);
}
}
void _indexLinkTableInternal(CanonicalName node) {
node.index = _canonicalNameList.length;
_canonicalNameList.add(node);
Iterable<CanonicalName> children = node.childrenOrNull;
if (children != null) {
for (CanonicalName child in children) {
_indexLinkTableInternal(child);
}
}
}
/// Compute canonical names for the whole component or parts of it.
void computeCanonicalNames(Component component) {
component.computeCanonicalNames();
}
/// Return `true` if all canonical names of the [library] should be written
/// into the link table. If some libraries of the component are skipped,
/// then all the additional names referenced by the libraries that are written
/// by [writeLibraries] are automatically added.
bool shouldWriteLibraryCanonicalNames(Library library) => true;
void writeCanonicalNameEntry(CanonicalName node) {
CanonicalName parent = node.parent;
if (parent.isRoot) {
writeUInt30(0);
} else {
writeUInt30(parent.index + 1);
}
writeStringReference(node.name);
}
void writeComponentFile(Component component) {
Timeline.timeSync("BinaryPrinter.writeComponentFile", () {
computeCanonicalNames(component);
final componentOffset = getBufferOffset();
writeUInt32(Tag.ComponentFile);
writeUInt32(Tag.BinaryFormatVersion);
writeListOfStrings(component.problemsAsJson);
indexLinkTable(component);
_collectMetadata(component);
if (_metadataSubsections != null) {
_writeNodeMetadataImpl(component, componentOffset);
}
libraryOffsets = <int>[];
CanonicalName main = getCanonicalNameOfMember(component.mainMethod);
if (main != null) {
checkCanonicalName(main);
}
writeLibraries(component);
writeUriToSource(component.uriToSource);
writeLinkTable(component);
_writeMetadataSection(component);
writeStringTable(stringIndexer);
writeConstantTable(_constantIndexer);
writeComponentIndex(component, component.libraries);
_flush();
});
}
void writeListOfStrings(List<String> strings) {
writeUInt30(strings?.length ?? 0);
if (strings != null) {
for (int i = 0; i < strings.length; i++) {
String s = strings[i];
// This is slow, but we expect there to in general be no problems. If this
// turns out to be wrong we can optimize it as we do URLs for instance.
writeByteList(utf8.encoder.convert(s));
}
}
}
/// Collect non-empty metadata repositories associated with the component.
void _collectMetadata(Component component) {
component.metadata.forEach((tag, repository) {
if (repository.mapping.isEmpty) {
return;
}
_metadataSubsections ??= <_MetadataSubsection>[];
_metadataSubsections.add(new _MetadataSubsection(repository));
});
}
/// Writes metadata associated with the given [Node].
void _writeNodeMetadata(Node node) {
_writeNodeMetadataImpl(node, getBufferOffset());
}
void _writeNodeMetadataImpl(Node node, int nodeOffset) {
for (_MetadataSubsection subsection in _metadataSubsections) {
final repository = subsection.repository;
final value = repository.mapping[node];
if (value == null) {
continue;
}
if (!MetadataRepository.isSupported(node)) {
throw new ArgumentError(
"Nodes of type ${node.runtimeType} can't have metadata.");
}
if (!identical(_sink, _mainSink)) {
throw new ArgumentError(
"Node written into metadata can't have metadata "
"(metadata: ${repository.tag}, node: ${node.runtimeType} $node)");
}
_sink = _metadataSink;
subsection.metadataMapping.add(nodeOffset);
subsection.metadataMapping.add(getBufferOffset());
repository.writeToBinary(value, node, this);
_sink = _mainSink;
}
}
@override
void enterScope(
{List<TypeParameter> typeParameters,
bool memberScope: false,
bool variableScope: false}) {
if (typeParameters != null) {
_typeParameterIndexer.enter(typeParameters);
}
if (memberScope) {
_variableIndexer = null;
}
if (variableScope) {
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
}
}
@override
void leaveScope(
{List<TypeParameter> typeParameters,
bool memberScope: false,
bool variableScope: false}) {
if (variableScope) {
_variableIndexer.popScope();
}
if (memberScope) {
_variableIndexer = null;
}
if (typeParameters != null) {
_typeParameterIndexer.exit(typeParameters);
}
}
void _writeMetadataSection(Component component) {
// Make sure metadata payloads section is 8-byte aligned,
// so certain kinds of metadata can contain aligned data.
const int metadataPayloadsAlignment = 8;
int padding = ((getBufferOffset() + metadataPayloadsAlignment - 1) &
-metadataPayloadsAlignment) -
getBufferOffset();
for (int i = 0; i < padding; ++i) {
writeByte(0);
}
_binaryOffsetForMetadataPayloads = getBufferOffset();
if (_metadataSubsections == null) {
_binaryOffsetForMetadataMappings = getBufferOffset();
writeUInt32(0); // Empty section.
return;
}
assert(identical(_sink, _mainSink));
_metadataSink.flushAndDestroy();
writeBytes((_metadataSink._sink as BytesSink).builder.takeBytes());
// RList<MetadataMapping> metadataMappings
_binaryOffsetForMetadataMappings = getBufferOffset();
for (_MetadataSubsection subsection in _metadataSubsections) {
// UInt32 tag
writeUInt32(stringIndexer.put(subsection.repository.tag));
// RList<Pair<UInt32, UInt32>> nodeOffsetToMetadataOffset
final mappingLength = subsection.metadataMapping.length;
for (int i = 0; i < mappingLength; i += 2) {
writeUInt32(subsection.metadataMapping[i]); // node offset
writeUInt32(subsection.metadataMapping[i + 1]); // metadata offset
}
writeUInt32(mappingLength ~/ 2);
}
writeUInt32(_metadataSubsections.length);
}
/// Write all of some of the libraries of the [component].
void writeLibraries(Component component) {
for (int i = 0; i < component.libraries.length; ++i) {
writeLibraryNode(component.libraries[i]);
}
}
void writeComponentIndex(Component component, List<Library> libraries) {
// It is allowed to concatenate several kernel binaries to create a
// multi-component kernel file. In order to maintain alignment of
// metadata sections within kernel binaries after concatenation,
// size of each kernel binary should be aligned.
// Component index is located at the end of a kernel binary, so padding
// is added before component index.
const int kernelFileAlignment = 8;
// Keep this in sync with number of writeUInt32 below.
int numComponentIndexEntries = 7 + libraryOffsets.length + 3;
int unalignedSize = getBufferOffset() + numComponentIndexEntries * 4;
int padding =
((unalignedSize + kernelFileAlignment - 1) & -kernelFileAlignment) -
unalignedSize;
for (int i = 0; i < padding; ++i) {
writeByte(0);
}
// Fixed-size ints at the end used as an index.
assert(_binaryOffsetForSourceTable >= 0);
writeUInt32(_binaryOffsetForSourceTable);
assert(_binaryOffsetForLinkTable >= 0);
writeUInt32(_binaryOffsetForLinkTable);
assert(_binaryOffsetForMetadataPayloads >= 0);
writeUInt32(_binaryOffsetForMetadataPayloads);
assert(_binaryOffsetForMetadataMappings >= 0);
writeUInt32(_binaryOffsetForMetadataMappings);
assert(_binaryOffsetForStringTable >= 0);
writeUInt32(_binaryOffsetForStringTable);
assert(_binaryOffsetForConstantTable >= 0);
writeUInt32(_binaryOffsetForConstantTable);
CanonicalName main = getCanonicalNameOfMember(component.mainMethod);
if (main == null) {
writeUInt32(0);
} else {
writeUInt32(main.index + 1);
}
assert(libraryOffsets.length == libraries.length);
for (int offset in libraryOffsets) {
writeUInt32(offset);
}
writeUInt32(_binaryOffsetForSourceTable); // end of last library.
writeUInt32(libraries.length);
writeUInt32(getBufferOffset() + 4); // total size.
}
void writeUriToSource(Map<Uri, Source> uriToSource) {
_binaryOffsetForSourceTable = getBufferOffset();
int length = _sourceUriIndexer.index.length;
writeUInt32(length);
List<int> index = new List<int>(length);
// Write data.
int i = 0;
Uint8List buffer = new Uint8List(1 << 16);
for (Uri uri in _sourceUriIndexer.index.keys) {
index[i] = getBufferOffset();
Source source = uriToSource[uri];
if (source == null ||
!(includeSources &&
_sourcesFromRealImplementation.length > i &&
_sourcesFromRealImplementation[i] == true)) {
source = new Source(
<int>[], const <int>[], source?.importUri, source?.fileUri);
}
String uriAsString = uri == null ? "" : "$uri";
outputStringViaBuffer(uriAsString, buffer);
writeByteList(source.source);
List<int> lineStarts = source.lineStarts;
writeUInt30(lineStarts.length);
int previousLineStart = 0;
for (int j = 0; j < lineStarts.length; ++j) {
int lineStart = lineStarts[j];
writeUInt30(lineStart - previousLineStart);
previousLineStart = lineStart;
}
String importUriAsString =
source.importUri == null ? "" : "${source.importUri}";
outputStringViaBuffer(importUriAsString, buffer);
i++;
}
// Write index for random access.
for (int i = 0; i < index.length; ++i) {
writeUInt32(index[i]);
}
}
void outputStringViaBuffer(String uriAsString, Uint8List buffer) {
if (uriAsString.length * 3 < buffer.length) {
int length = NotQuiteString.writeUtf8(buffer, 0, uriAsString);
if (length < 0) {
// Utf8 encoding failed.
writeByteList(utf8.encoder.convert(uriAsString));
} else {
writeUInt30(length);
for (int j = 0; j < length; j++) {
writeByte(buffer[j]);
}
}
} else {
// Uncommon case with very long url.
writeByteList(utf8.encoder.convert(uriAsString));
}
}
void writeLibraryDependencyReference(LibraryDependency node) {
int index = _libraryDependencyIndex[node];
if (index == null) {
throw new ArgumentError(
'Reference to library dependency $node out of scope');
}
writeUInt30(index);
}
void writeNullAllowedReference(Reference reference) {
if (reference == null) {
writeUInt30(0);
} else {
CanonicalName name = reference.canonicalName;
if (name == null) {
throw new ArgumentError('Missing canonical name for $reference');
}
checkCanonicalName(name);
writeUInt30(name.index + 1);
}
}
void writeNonNullReference(Reference reference) {
if (reference == null) {
throw new ArgumentError('Got null reference');
} else {
CanonicalName name = reference.canonicalName;
if (name == null) {
throw new ArgumentError('Missing canonical name for $reference');
}
checkCanonicalName(name);
writeUInt30(name.index + 1);
}
}
void checkCanonicalName(CanonicalName node) {
if (_knownCanonicalNameNonRootTops.contains(node.nonRootTop)) return;
if (node == null || node.isRoot) return;
if (_reindexedCanonicalNames.contains(node)) return;
checkCanonicalName(node.parent);
node.index = _canonicalNameList.length;
_canonicalNameList.add(node);
_reindexedCanonicalNames.add(node);
}
void writeNullAllowedCanonicalNameReference(CanonicalName name) {
if (name == null) {
writeUInt30(0);
} else {
checkCanonicalName(name);
writeUInt30(name.index + 1);
}
}
void writeNonNullCanonicalNameReference(CanonicalName name) {
if (name == null) {
throw new ArgumentError(
'Expected a canonical name to be valid but was `null`.');
} else {
checkCanonicalName(name);
writeUInt30(name.index + 1);
}
}
void writeLibraryReference(Library node, {bool allowNull: false}) {
if (node.canonicalName == null && !allowNull) {
throw new ArgumentError(
'Expected a library reference to be valid but was `null`.');
}
writeNullAllowedCanonicalNameReference(node.canonicalName);
}
writeOffset(int offset) {
// TODO(jensj): Delta-encoding.
// File offset ranges from -1 and up,
// but is here saved as unsigned (thus the +1)
if (!includeOffsets) {
writeUInt30(0);
} else {
writeUInt30(offset + 1);
}
}
void writeClassReference(Class class_) {
if (class_ == null) {
throw new ArgumentError(
'Expected a class reference to be valid but was `null`.');
}
writeNonNullCanonicalNameReference(getCanonicalNameOfClass(class_));
}
void writeName(Name node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
writeStringReference(node.name);
// TODO: Consider a more compressed format for private names within the
// enclosing library.
if (node.isPrivate) {
writeLibraryReference(node.library);
}
}
bool insideExternalLibrary = false;
@override
void visitLibrary(Library node) {
insideExternalLibrary = node.isExternal;
libraryOffsets.add(getBufferOffset());
writeByte(node.flags);
writeUInt30(node.languageVersionMajor);
writeUInt30(node.languageVersionMinor);
writeNonNullCanonicalNameReference(getCanonicalNameOfLibrary(node));
writeStringReference(node.name ?? '');
writeUriReference(node.fileUri);
writeListOfStrings(node.problemsAsJson);
enterScope(memberScope: true);
writeAnnotationList(node.annotations);
writeLibraryDependencies(node);
writeAdditionalExports(node.additionalExports);
writeLibraryParts(node);
leaveScope(memberScope: true);
writeTypedefNodeList(node.typedefs);
classOffsets = new List<int>();
writeClassNodeList(node.classes);
classOffsets.add(getBufferOffset());
writeExtensionNodeList(node.extensions);
writeFieldNodeList(node.fields);
procedureOffsets = new List<int>();
writeProcedureNodeList(node.procedures);
procedureOffsets.add(getBufferOffset());
// Dump all source-references used in this library; used by the VM.
int sourceReferencesOffset = getBufferOffset();
int sourceReferencesCount = 0;
// Note: We start at 1 because 0 is the null-entry and we don't want to
// include that.
for (int i = 1; i < _sourcesFromRealImplementationInLibrary.length; i++) {
if (_sourcesFromRealImplementationInLibrary[i] == true) {
sourceReferencesCount++;
}
}
writeUInt30(sourceReferencesCount);
for (int i = 1; i < _sourcesFromRealImplementationInLibrary.length; i++) {
if (_sourcesFromRealImplementationInLibrary[i] == true) {
writeUInt30(i);
_sourcesFromRealImplementationInLibrary[i] = false;
}
}
// Fixed-size ints at the end used as an index.
writeUInt32(sourceReferencesOffset);
assert(classOffsets.length > 0);
for (int i = 0; i < classOffsets.length; ++i) {
int offset = classOffsets[i];
writeUInt32(offset);
}
writeUInt32(classOffsets.length - 1);
assert(procedureOffsets.length > 0);
for (int i = 0; i < procedureOffsets.length; ++i) {
int offset = procedureOffsets[i];
writeUInt32(offset);
}
writeUInt32(procedureOffsets.length - 1);
}
void writeLibraryDependencies(Library library) {
_libraryDependencyIndex = library.dependencies.isEmpty
? const <LibraryDependency, int>{}
: <LibraryDependency, int>{};
writeUInt30(library.dependencies.length);
for (int i = 0; i < library.dependencies.length; ++i) {
LibraryDependency importNode = library.dependencies[i];
_libraryDependencyIndex[importNode] = i;
writeLibraryDependency(importNode);
}
}
void writeAdditionalExports(List<Reference> additionalExports) {
writeUInt30(additionalExports.length);
for (Reference ref in additionalExports) {
writeNonNullReference(ref);
}
}
void writeLibraryDependency(LibraryDependency node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
writeOffset(node.fileOffset);
writeByte(node.flags);
writeAnnotationList(node.annotations);
writeLibraryReference(node.targetLibrary, allowNull: true);
writeStringReference(node.name ?? '');
writeNodeList(node.combinators);
}
void visitCombinator(Combinator node) {
writeByte(node.isShow ? 1 : 0);
writeStringReferenceList(node.names);
}
void writeLibraryParts(Library library) {
writeUInt30(library.parts.length);
for (int i = 0; i < library.parts.length; ++i) {
LibraryPart partNode = library.parts[i];
writeLibraryPart(partNode);
}
}
void writeLibraryPart(LibraryPart node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
writeAnnotationList(node.annotations);
writeStringReference(node.partUri);
}
void visitTypedef(Typedef node) {
enterScope(memberScope: true);
writeNonNullCanonicalNameReference(getCanonicalNameOfTypedef(node));
writeUriReference(node.fileUri);
writeOffset(node.fileOffset);
writeStringReference(node.name);
writeAnnotationList(node.annotations);
enterScope(typeParameters: node.typeParameters, variableScope: true);
writeNodeList(node.typeParameters);
writeNode(node.type);
enterScope(typeParameters: node.typeParametersOfFunctionType);
writeNodeList(node.typeParametersOfFunctionType);
writeVariableDeclarationList(node.positionalParameters);
writeVariableDeclarationList(node.namedParameters);
leaveScope(typeParameters: node.typeParametersOfFunctionType);
leaveScope(typeParameters: node.typeParameters, variableScope: true);
leaveScope(memberScope: true);
}
void writeAnnotation(Expression annotation) {
writeNode(annotation);
}
void writeAnnotationList(List<Expression> annotations) {
final len = annotations.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final annotation = annotations[i];
writeAnnotation(annotation);
}
}
int _encodeClassFlags(int flags, ClassLevel level) {
assert((flags & Class.LevelMask) == 0);
final levelIndex = level.index - 1;
assert((levelIndex & Class.LevelMask) == levelIndex);
return flags | levelIndex;
}
@override
void visitClass(Class node) {
classOffsets.add(getBufferOffset());
if (node.isAnonymousMixin) _currentlyInNonimplementation = true;
int flags = _encodeClassFlags(node.flags, node.level);
if (node.canonicalName == null) {
throw new ArgumentError('Missing canonical name for $node');
}
writeByte(Tag.Class);
writeNonNullCanonicalNameReference(getCanonicalNameOfClass(node));
writeUriReference(node.fileUri);
writeOffset(node.startFileOffset);
writeOffset(node.fileOffset);
writeOffset(node.fileEndOffset);
writeByte(flags);
writeStringReference(node.name ?? '');
enterScope(memberScope: true);
writeAnnotationList(node.annotations);
leaveScope(memberScope: true);
enterScope(typeParameters: node.typeParameters);
writeNodeList(node.typeParameters);
writeOptionalNode(node.supertype);
writeOptionalNode(node.mixedInType);
writeNodeList(node.implementedTypes);
writeFieldNodeList(node.fields);
writeConstructorNodeList(node.constructors);
procedureOffsets = <int>[];
writeProcedureNodeList(node.procedures);
procedureOffsets.add(getBufferOffset());
writeRedirectingFactoryConstructorNodeList(
node.redirectingFactoryConstructors);
leaveScope(typeParameters: node.typeParameters);
assert(procedureOffsets.length > 0);
for (int i = 0; i < procedureOffsets.length; ++i) {
int offset = procedureOffsets[i];
writeUInt32(offset);
}
writeUInt32(procedureOffsets.length - 1);
_currentlyInNonimplementation = false;
}
static final Name _emptyName = new Name('');
@override
void visitConstructor(Constructor node) {
if (node.canonicalName == null) {
throw new ArgumentError('Missing canonical name for $node');
}
enterScope(memberScope: true);
writeByte(Tag.Constructor);
writeNonNullCanonicalNameReference(getCanonicalNameOfMember(node));
writeUriReference(node.fileUri);
writeOffset(node.startFileOffset);
writeOffset(node.fileOffset);
writeOffset(node.fileEndOffset);
writeByte(node.flags);
writeName(node.name ?? _emptyName);
writeAnnotationList(node.annotations);
assert(node.function.typeParameters.isEmpty);
writeFunctionNode(node.function);
// Parameters are in scope in the initializers.
_variableIndexer ??= new VariableIndexer();
_variableIndexer.restoreScope(node.function.positionalParameters.length +
node.function.namedParameters.length);
writeNodeList(node.initializers);
leaveScope(memberScope: true);
}
@override
void visitProcedure(Procedure node) {
procedureOffsets.add(getBufferOffset());
if (node.canonicalName == null) {
throw new ArgumentError('Missing canonical name for $node');
}
final bool currentlyInNonimplementationSaved =
_currentlyInNonimplementation;
if (node.isNoSuchMethodForwarder || node.isSyntheticForwarder) {
_currentlyInNonimplementation = true;
}
enterScope(memberScope: true);
writeByte(Tag.Procedure);
writeNonNullCanonicalNameReference(getCanonicalNameOfMember(node));
writeUriReference(node.fileUri);
writeOffset(node.startFileOffset);
writeOffset(node.fileOffset);
writeOffset(node.fileEndOffset);
writeByte(node.kind.index);
writeUInt30(node.flags);
writeName(node.name ?? _emptyName);
writeAnnotationList(node.annotations);
writeNullAllowedReference(node.forwardingStubSuperTargetReference);
writeNullAllowedReference(node.forwardingStubInterfaceTargetReference);
writeOptionalFunctionNode(node.function);
leaveScope(memberScope: true);
_currentlyInNonimplementation = currentlyInNonimplementationSaved;
assert((node.forwardingStubSuperTarget != null) ||
!(node.isForwardingStub && node.function.body != null));
}
@override
void visitField(Field node) {
if (node.canonicalName == null) {
throw new ArgumentError('Missing canonical name for $node');
}
enterScope(memberScope: true);
writeByte(Tag.Field);
writeNonNullCanonicalNameReference(getCanonicalNameOfMember(node));
writeUriReference(node.fileUri);
writeOffset(node.fileOffset);
writeOffset(node.fileEndOffset);
writeUInt30(node.flags);
writeName(node.name);
writeAnnotationList(node.annotations);
writeNode(node.type);
writeOptionalNode(node.initializer);
leaveScope(memberScope: true);
}
@override
void visitRedirectingFactoryConstructor(RedirectingFactoryConstructor node) {
if (node.canonicalName == null) {
throw new ArgumentError('Missing canonical name for $node');
}
writeByte(Tag.RedirectingFactoryConstructor);
enterScope(
typeParameters: node.typeParameters,
memberScope: true,
variableScope: true);
writeNonNullCanonicalNameReference(getCanonicalNameOfMember(node));
writeUriReference(node.fileUri);
writeOffset(node.fileOffset);
writeOffset(node.fileEndOffset);
writeByte(node.flags);
writeName(node.name);
writeAnnotationList(node.annotations);
writeNonNullReference(node.targetReference);
writeNodeList(node.typeArguments);
writeNodeList(node.typeParameters);
writeUInt30(node.positionalParameters.length + node.namedParameters.length);
writeUInt30(node.requiredParameterCount);
writeVariableDeclarationList(node.positionalParameters);
writeVariableDeclarationList(node.namedParameters);
leaveScope(
typeParameters: node.typeParameters,
memberScope: true,
variableScope: true);
}
@override
void visitInvalidInitializer(InvalidInitializer node) {
writeByte(Tag.InvalidInitializer);
writeByte(node.isSynthetic ? 1 : 0);
}
@override
void visitFieldInitializer(FieldInitializer node) {
writeByte(Tag.FieldInitializer);
writeByte(node.isSynthetic ? 1 : 0);
writeNonNullReference(node.fieldReference);
writeNode(node.value);
}
@override
void visitSuperInitializer(SuperInitializer node) {
writeByte(Tag.SuperInitializer);
writeByte(node.isSynthetic ? 1 : 0);
writeOffset(node.fileOffset);
writeNonNullReference(node.targetReference);
writeArgumentsNode(node.arguments);
}
@override
void visitRedirectingInitializer(RedirectingInitializer node) {
writeByte(Tag.RedirectingInitializer);
writeByte(node.isSynthetic ? 1 : 0);
writeOffset(node.fileOffset);
writeNonNullReference(node.targetReference);
writeArgumentsNode(node.arguments);
}
@override
void visitLocalInitializer(LocalInitializer node) {
writeByte(Tag.LocalInitializer);
writeByte(node.isSynthetic ? 1 : 0);
writeVariableDeclaration(node.variable);
}
@override
void visitAssertInitializer(AssertInitializer node) {
writeByte(Tag.AssertInitializer);
writeByte(node.isSynthetic ? 1 : 0);
writeNode(node.statement);
}
@override
void visitFunctionNode(FunctionNode node) {
writeByte(Tag.FunctionNode);
enterScope(typeParameters: node.typeParameters, variableScope: true);
LabelIndexer oldLabels = _labelIndexer;
_labelIndexer = null;
SwitchCaseIndexer oldCases = _switchCaseIndexer;
_switchCaseIndexer = null;
// Note: FunctionNode has no tag.
writeOffset(node.fileOffset);
writeOffset(node.fileEndOffset);
writeByte(node.asyncMarker.index);
writeByte(node.dartAsyncMarker.index);
writeNodeList(node.typeParameters);
writeUInt30(node.positionalParameters.length + node.namedParameters.length);
writeUInt30(node.requiredParameterCount);
writeVariableDeclarationList(node.positionalParameters);
writeVariableDeclarationList(node.namedParameters);
writeNode(node.returnType);
writeOptionalNode(node.body);
_labelIndexer = oldLabels;
_switchCaseIndexer = oldCases;
leaveScope(typeParameters: node.typeParameters, variableScope: true);
}
@override
void visitInvalidExpression(InvalidExpression node) {
writeByte(Tag.InvalidExpression);
writeOffset(node.fileOffset);
writeStringReference(node.message ?? '');
}
@override
void visitVariableGet(VariableGet node) {
_variableIndexer ??= new VariableIndexer();
int index = _variableIndexer[node.variable];
assert(index != null);
if (index & Tag.SpecializedPayloadMask == index &&
node.promotedType == null) {
writeByte(Tag.SpecializedVariableGet + index);
writeOffset(node.fileOffset);
writeUInt30(node.variable.binaryOffsetNoTag);
} else {
writeByte(Tag.VariableGet);
writeOffset(node.fileOffset);
writeUInt30(node.variable.binaryOffsetNoTag);
writeUInt30(index);
writeOptionalNode(node.promotedType);
}
}
@override
void visitVariableSet(VariableSet node) {
_variableIndexer ??= new VariableIndexer();
int index = _variableIndexer[node.variable];
assert(index != null);
if (index & Tag.SpecializedPayloadMask == index) {
writeByte(Tag.SpecializedVariableSet + index);
writeOffset(node.fileOffset);
writeUInt30(node.variable.binaryOffsetNoTag);
writeNode(node.value);
} else {
writeByte(Tag.VariableSet);
writeOffset(node.fileOffset);
writeUInt30(node.variable.binaryOffsetNoTag);
writeUInt30(index);
writeNode(node.value);
}
}
@override
void visitPropertyGet(PropertyGet node) {
writeByte(Tag.PropertyGet);
writeOffset(node.fileOffset);
writeNode(node.receiver);
writeName(node.name);
writeNullAllowedReference(node.interfaceTargetReference);
}
@override
void visitPropertySet(PropertySet node) {
writeByte(Tag.PropertySet);
writeOffset(node.fileOffset);
writeNode(node.receiver);
writeName(node.name);
writeNode(node.value);
writeNullAllowedReference(node.interfaceTargetReference);
}
@override
void visitSuperPropertyGet(SuperPropertyGet node) {
writeByte(Tag.SuperPropertyGet);
writeOffset(node.fileOffset);
writeName(node.name);
writeNullAllowedReference(node.interfaceTargetReference);
}
@override
void visitSuperPropertySet(SuperPropertySet node) {
writeByte(Tag.SuperPropertySet);
writeOffset(node.fileOffset);
writeName(node.name);
writeNode(node.value);
writeNullAllowedReference(node.interfaceTargetReference);
}
@override
void visitDirectPropertyGet(DirectPropertyGet node) {
writeByte(Tag.DirectPropertyGet);
writeOffset(node.fileOffset);
writeNode(node.receiver);
writeNonNullReference(node.targetReference);
}
@override
void visitDirectPropertySet(DirectPropertySet node) {
writeByte(Tag.DirectPropertySet);
writeOffset(node.fileOffset);
writeNode(node.receiver);
writeNonNullReference(node.targetReference);
writeNode(node.value);
}
@override
void visitStaticGet(StaticGet node) {
writeByte(Tag.StaticGet);
writeOffset(node.fileOffset);
writeNonNullReference(node.targetReference);
}
@override
void visitStaticSet(StaticSet node) {
writeByte(Tag.StaticSet);
writeOffset(node.fileOffset);
writeNonNullReference(node.targetReference);
writeNode(node.value);
}
@override
void visitMethodInvocation(MethodInvocation node) {
writeByte(Tag.MethodInvocation);
writeOffset(node.fileOffset);
writeNode(node.receiver);
writeName(node.name);
writeArgumentsNode(node.arguments);
writeNullAllowedReference(node.interfaceTargetReference);
}
@override
void visitSuperMethodInvocation(SuperMethodInvocation node) {
writeByte(Tag.SuperMethodInvocation);
writeOffset(node.fileOffset);
writeName(node.name);
writeArgumentsNode(node.arguments);
writeNullAllowedReference(node.interfaceTargetReference);
}
@override
void visitDirectMethodInvocation(DirectMethodInvocation node) {
writeByte(Tag.DirectMethodInvocation);
writeOffset(node.fileOffset);
writeNode(node.receiver);
writeNonNullReference(node.targetReference);
writeArgumentsNode(node.arguments);
}
@override
void visitStaticInvocation(StaticInvocation node) {
writeByte(node.isConst ? Tag.ConstStaticInvocation : Tag.StaticInvocation);
writeOffset(node.fileOffset);
writeNonNullReference(node.targetReference);
writeArgumentsNode(node.arguments);
}
@override
void visitConstructorInvocation(ConstructorInvocation node) {
writeByte(node.isConst
? Tag.ConstConstructorInvocation
: Tag.ConstructorInvocation);
writeOffset(node.fileOffset);
writeNonNullReference(node.targetReference);
writeArgumentsNode(node.arguments);
}
@override
void visitArguments(Arguments node) {
writeUInt30(node.positional.length + node.named.length);
writeNodeList(node.types);
writeNodeList(node.positional);
writeNodeList(node.named);
}
@override
void visitNamedExpression(NamedExpression node) {
writeStringReference(node.name);
writeNode(node.value);
}
@override
void visitNot(Not node) {
writeByte(Tag.Not);
writeNode(node.operand);
}
@override
void visitNullCheck(NullCheck node) {
writeByte(Tag.NullCheck);
writeOffset(node.fileOffset);
writeNode(node.operand);
}
int logicalOperatorIndex(String operator) {
switch (operator) {
case '&&':
return 0;
case '||':
return 1;
}
throw new ArgumentError('Not a logical operator: $operator');
}
@override
void visitLogicalExpression(LogicalExpression node) {
writeByte(Tag.LogicalExpression);
writeNode(node.left);
writeByte(logicalOperatorIndex(node.operator));
writeNode(node.right);
}
@override
void visitConditionalExpression(ConditionalExpression node) {
writeByte(Tag.ConditionalExpression);
writeNode(node.condition);
writeNode(node.then);
writeNode(node.otherwise);
writeOptionalNode(node.staticType);
}
@override
void visitStringConcatenation(StringConcatenation node) {
writeByte(Tag.StringConcatenation);
writeOffset(node.fileOffset);
writeNodeList(node.expressions);
}
@override
void visitListConcatenation(ListConcatenation node) {
writeByte(Tag.ListConcatenation);
writeOffset(node.fileOffset);
writeNode(node.typeArgument);
writeNodeList(node.lists);
}
@override
void visitSetConcatenation(SetConcatenation node) {
writeByte(Tag.SetConcatenation);
writeOffset(node.fileOffset);
writeNode(node.typeArgument);
writeNodeList(node.sets);
}
@override
void visitMapConcatenation(MapConcatenation node) {
writeByte(Tag.MapConcatenation);
writeOffset(node.fileOffset);
writeNode(node.keyType);
writeNode(node.valueType);
writeNodeList(node.maps);
}
@override
void visitInstanceCreation(InstanceCreation node) {
writeByte(Tag.InstanceCreation);
writeOffset(node.fileOffset);
writeNonNullReference(node.classReference);
writeNodeList(node.typeArguments);
writeUInt30(node.fieldValues.length);
node.fieldValues.forEach((Reference fieldRef, Expression value) {
writeNonNullReference(fieldRef);
writeNode(value);
});
writeNodeList(node.asserts);
writeNodeList(node.unusedArguments);
}
@override
void visitFileUriExpression(FileUriExpression node) {
writeByte(Tag.FileUriExpression);
writeUriReference(node.fileUri);
writeOffset(node.fileOffset);
writeNode(node.expression);
}
@override
void visitIsExpression(IsExpression node) {
writeByte(Tag.IsExpression);
writeOffset(node.fileOffset);
writeNode(node.operand);
writeNode(node.type);
}
@override
void visitAsExpression(AsExpression node) {
writeByte(Tag.AsExpression);
writeOffset(node.fileOffset);
writeByte(node.flags);
writeNode(node.operand);
writeNode(node.type);
}
@override
void visitStringLiteral(StringLiteral node) {
writeByte(Tag.StringLiteral);
writeStringReference(node.value);
}
@override
void visitIntLiteral(IntLiteral node) {
writeInteger(node.value);
}
writeInteger(int value) {
int biasedValue = value + Tag.SpecializedIntLiteralBias;
if (biasedValue >= 0 &&
biasedValue & Tag.SpecializedPayloadMask == biasedValue) {
writeByte(Tag.SpecializedIntLiteral + biasedValue);
} else if (value.abs() >> 30 == 0) {
if (value < 0) {
writeByte(Tag.NegativeIntLiteral);
writeUInt30(-value);
} else {
writeByte(Tag.PositiveIntLiteral);
writeUInt30(value);
}
} else {
// TODO: Pick a better format for big int literals.
writeByte(Tag.BigIntLiteral);
writeStringReference('$value');
}
}
@override
void visitDoubleLiteral(DoubleLiteral node) {
writeByte(Tag.DoubleLiteral);
writeDouble(node.value);
}
writeDouble(double value) {
_sink.addDouble(value);
}
@override
void visitBoolLiteral(BoolLiteral node) {
writeByte(node.value ? Tag.TrueLiteral : Tag.FalseLiteral);
}
@override
void visitNullLiteral(NullLiteral node) {
writeByte(Tag.NullLiteral);
}
@override
void visitSymbolLiteral(SymbolLiteral node) {
writeByte(Tag.SymbolLiteral);
writeStringReference(node.value);
}
@override
void visitTypeLiteral(TypeLiteral node) {
writeByte(Tag.TypeLiteral);
writeNode(node.type);
}
@override
void visitThisExpression(ThisExpression node) {
writeByte(Tag.ThisExpression);
}
@override
void visitRethrow(Rethrow node) {
writeByte(Tag.Rethrow);
writeOffset(node.fileOffset);
}
@override
void visitThrow(Throw node) {
writeByte(Tag.Throw);
writeOffset(node.fileOffset);
writeNode(node.expression);
}
@override
void visitListLiteral(ListLiteral node) {
writeByte(node.isConst ? Tag.ConstListLiteral : Tag.ListLiteral);
writeOffset(node.fileOffset);
writeNode(node.typeArgument);
writeNodeList(node.expressions);
}
@override
void visitSetLiteral(SetLiteral node) {
writeByte(node.isConst ? Tag.ConstSetLiteral : Tag.SetLiteral);
writeOffset(node.fileOffset);
writeNode(node.typeArgument);
writeNodeList(node.expressions);
}
@override
void visitMapLiteral(MapLiteral node) {
writeByte(node.isConst ? Tag.ConstMapLiteral : Tag.MapLiteral);
writeOffset(node.fileOffset);
writeNode(node.keyType);
writeNode(node.valueType);
writeNodeList(node.entries);
}
@override
void visitMapEntry(MapEntry node) {
// Note: there is no tag on MapEntry
writeNode(node.key);
writeNode(node.value);
}
@override
void visitAwaitExpression(AwaitExpression node) {
writeByte(Tag.AwaitExpression);
writeNode(node.operand);
}
@override
void visitFunctionExpression(FunctionExpression node) {
writeByte(Tag.FunctionExpression);
writeOffset(node.fileOffset);
writeFunctionNode(node.function);
}
@override
void visitLet(Let node) {
writeByte(Tag.Let);
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
writeVariableDeclaration(node.variable);
writeNode(node.body);
_variableIndexer.popScope();
}
@override
void visitBlockExpression(BlockExpression node) {
writeByte(Tag.BlockExpression);
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
writeNodeList(node.body.statements);
writeNode(node.value);
_variableIndexer.popScope();
}
@override
void visitInstantiation(Instantiation node) {
writeByte(Tag.Instantiation);
writeNode(node.expression);
writeNodeList(node.typeArguments);
}
@override
void visitLoadLibrary(LoadLibrary node) {
writeByte(Tag.LoadLibrary);
writeLibraryDependencyReference(node.import);
}
@override
void visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) {
writeByte(Tag.CheckLibraryIsLoaded);
writeLibraryDependencyReference(node.import);
}
writeStatementOrEmpty(Statement node) {
if (node == null) {
writeByte(Tag.EmptyStatement);
} else {
writeNode(node);
}
}
@override
void visitExpressionStatement(ExpressionStatement node) {
writeByte(Tag.ExpressionStatement);
writeNode(node.expression);
}
@override
void visitBlock(Block node) {
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
writeByte(Tag.Block);
writeNodeList(node.statements);
_variableIndexer.popScope();
}
@override
void visitAssertBlock(AssertBlock node) {
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
writeByte(Tag.AssertBlock);
writeNodeList(node.statements);
_variableIndexer.popScope();
}
@override
void visitEmptyStatement(EmptyStatement node) {
writeByte(Tag.EmptyStatement);
}
@override
void visitAssertStatement(AssertStatement node) {
writeByte(Tag.AssertStatement);
writeNode(node.condition);
writeOffset(node.conditionStartOffset);
writeOffset(node.conditionEndOffset);
writeOptionalNode(node.message);
}
@override
void visitLabeledStatement(LabeledStatement node) {
if (_labelIndexer == null) {
_labelIndexer = new LabelIndexer();
}
_labelIndexer.enter(node);
writeByte(Tag.LabeledStatement);
writeNode(node.body);
_labelIndexer.exit();
}
@override
void visitConstantExpression(ConstantExpression node) {
writeByte(Tag.ConstantExpression);
writeOffset(node.fileOffset);
writeDartType(node.type);
writeConstantReference(node.constant);
}
@override
void visitBreakStatement(BreakStatement node) {
writeByte(Tag.BreakStatement);
writeOffset(node.fileOffset);
writeUInt30(_labelIndexer[node.target]);
}
@override
void visitWhileStatement(WhileStatement node) {
writeByte(Tag.WhileStatement);
writeOffset(node.fileOffset);
writeNode(node.condition);
writeNode(node.body);
}
@override
void visitDoStatement(DoStatement node) {
writeByte(Tag.DoStatement);
writeOffset(node.fileOffset);
writeNode(node.body);
writeNode(node.condition);
}
@override
void visitForStatement(ForStatement node) {
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
writeByte(Tag.ForStatement);
writeOffset(node.fileOffset);
writeVariableDeclarationList(node.variables);
writeOptionalNode(node.condition);
writeNodeList(node.updates);
writeNode(node.body);
_variableIndexer.popScope();
}
@override
void visitForInStatement(ForInStatement node) {
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
writeByte(node.isAsync ? Tag.AsyncForInStatement : Tag.ForInStatement);
writeOffset(node.fileOffset);
writeOffset(node.bodyOffset);
writeVariableDeclaration(node.variable);
writeNode(node.iterable);
writeNode(node.body);
_variableIndexer.popScope();
}
@override
void visitSwitchStatement(SwitchStatement node) {
if (_switchCaseIndexer == null) {
_switchCaseIndexer = new SwitchCaseIndexer();
}
_switchCaseIndexer.enter(node);
writeByte(Tag.SwitchStatement);
writeOffset(node.fileOffset);
writeNode(node.expression);
writeSwitchCaseNodeList(node.cases);
_switchCaseIndexer.exit(node);
}
@override
void visitSwitchCase(SwitchCase node) {
// Note: there is no tag on SwitchCase.
int length = node.expressions.length;
writeUInt30(length);
for (int i = 0; i < length; ++i) {
writeOffset(node.expressionOffsets[i]);
writeNode(node.expressions[i]);
}
writeByte(node.isDefault ? 1 : 0);
writeNode(node.body);
}
@override
void visitContinueSwitchStatement(ContinueSwitchStatement node) {
writeByte(Tag.ContinueSwitchStatement);
writeOffset(node.fileOffset);
writeUInt30(_switchCaseIndexer[node.target]);
}
@override
void visitIfStatement(IfStatement node) {
writeByte(Tag.IfStatement);
writeOffset(node.fileOffset);
writeNode(node.condition);
writeNode(node.then);
writeStatementOrEmpty(node.otherwise);
}
@override
void visitReturnStatement(ReturnStatement node) {
writeByte(Tag.ReturnStatement);
writeOffset(node.fileOffset);
writeOptionalNode(node.expression);
}
int _encodeTryCatchFlags(bool needsStackTrace, bool isSynthetic) {
return (needsStackTrace ? 1 : 0) | (isSynthetic ? 2 : 0);
}
@override
void visitTryCatch(TryCatch node) {
writeByte(Tag.TryCatch);
writeNode(node.body);
bool needsStackTrace = node.catches.any((Catch c) => c.stackTrace != null);
writeByte(_encodeTryCatchFlags(needsStackTrace, node.isSynthetic));
writeCatchNodeList(node.catches);
}
@override
void visitCatch(Catch node) {
// Note: there is no tag on Catch.
_variableIndexer ??= new VariableIndexer();
_variableIndexer.pushScope();
writeOffset(node.fileOffset);
writeNode(node.guard);
writeOptionalVariableDeclaration(node.exception);
writeOptionalVariableDeclaration(node.stackTrace);
writeNode(node.body);
_variableIndexer.popScope();
}
@override
void visitTryFinally(TryFinally node) {
writeByte(Tag.TryFinally);
writeNode(node.body);
writeNode(node.finalizer);
}
@override
void visitYieldStatement(YieldStatement node) {
writeByte(Tag.YieldStatement);
writeOffset(node.fileOffset);
writeByte(node.flags);
writeNode(node.expression);
}
@override
void visitVariableDeclaration(VariableDeclaration node) {
writeByte(Tag.VariableDeclaration);
writeVariableDeclaration(node);
}
void writeVariableDeclaration(VariableDeclaration node) {
if (_metadataSubsections != null) {
_writeNodeMetadata(node);
}
node.binaryOffsetNoTag = getBufferOffset();
writeOffset(node.fileOffset);
writeOffset(node.fileEqualsOffset);
writeAnnotationList(node.annotations);
writeByte(node.flags);
writeStringReference(node.name ?? '');
writeNode(node.type);
writeOptionalNode(node.initializer);
// Declare the variable after its initializer. It is not in scope in its
// own initializer.
_variableIndexer ??= new VariableIndexer();
_variableIndexer.declare(node);
}
void writeVariableDeclarationList(List<VariableDeclaration> nodes) {
writeList(nodes, writeVariableDeclaration);
}
void writeOptionalVariableDeclaration(VariableDeclaration node) {
if (node == null) {
writeByte(Tag.Nothing);
} else {
writeByte(Tag.Something);
writeVariableDeclaration(node);
}
}
@override
void visitFunctionDeclaration(FunctionDeclaration node) {
writeByte(Tag.FunctionDeclaration);
writeOffset(node.fileOffset);
writeVariableDeclaration(node.variable);
writeFunctionNode(node.function);
}
@override
void visitBottomType(BottomType node) {
writeByte(Tag.BottomType);
}
@override
void visitInvalidType(InvalidType node) {
writeByte(Tag.InvalidType);
}
@override
void visitDynamicType(DynamicType node) {
writeByte(Tag.DynamicType);
}
@override
void visitVoidType(VoidType node) {
writeByte(Tag.VoidType);
}
@override
void visitInterfaceType(InterfaceType node) {
if (node.typeArguments.isEmpty) {
writeByte(Tag.SimpleInterfaceType);
writeByte(node.nullability.index);
writeNonNullReference(node.className);
} else {
writeByte(Tag.InterfaceType);
writeByte(node.nullability.index);
writeNonNullReference(node.className);
writeNodeList(node.typeArguments);
}
}
@override
void visitSupertype(Supertype node) {
// Writing nullability below is only necessary because
// BinaryBuilder.readSupertype reads the supertype as an InterfaceType and
// breaks it into components afterwards, and reading an InterfaceType
// requires the nullability byte.
if (node.typeArguments.isEmpty) {
writeByte(Tag.SimpleInterfaceType);
writeByte(Nullability.nonNullable.index);
writeNonNullReference(node.className);
} else {
writeByte(Tag.InterfaceType);
writeByte(Nullability.nonNullable.index);
writeNonNullReference(node.className);
writeNodeList(node.typeArguments);
}
}
@override
void visitFunctionType(FunctionType node) {
if (node.requiredParameterCount == node.positionalParameters.length &&
node.typeParameters.isEmpty &&
node.namedParameters.isEmpty &&
node.typedefType == null) {
writeByte(Tag.SimpleFunctionType);
writeByte(node.nullability.index);
writeNodeList(node.positionalParameters);
writeNode(node.returnType);
} else {
writeByte(Tag.FunctionType);
writeByte(node.nullability.index);
enterScope(typeParameters: node.typeParameters);
writeNodeList(node.typeParameters);
writeUInt30(node.requiredParameterCount);
writeUInt30(
node.positionalParameters.length + node.namedParameters.length);
writeNodeList(node.positionalParameters);
writeNodeList(node.namedParameters);
writeOptionalNode(node.typedefType);
writeNode(node.returnType);
leaveScope(typeParameters: node.typeParameters);
}
}
@override
void visitNamedType(NamedType node) {
writeStringReference(node.name);
writeNode(node.type);
int flags = (node.isRequired ? NamedType.FlagRequiredNamedType : 0);
writeByte(flags);
}
@override
void visitTypeParameterType(TypeParameterType node) {
writeByte(Tag.TypeParameterType);
writeByte(node.typeParameterTypeNullability.index);
writeUInt30(_typeParameterIndexer[node.parameter]);
writeOptionalNode(node.promotedBound);
}
@override
void visitTypedefType(TypedefType node) {
writeByte(Tag.TypedefType);
writeByte(node.nullability.index);
writeNullAllowedReference(node.typedefReference);
writeNodeList(node.typeArguments);
}
@override
void visitTypeParameter(TypeParameter node) {
writeByte(node.flags);
writeAnnotationList(node.annotations);
writeByte(node.variance);
writeStringReference(node.name ?? '');
writeNode(node.bound);
writeOptionalNode(node.defaultType);
}
@override
void visitExtension(Extension node) {
if (node.canonicalName == null) {
throw new ArgumentError('Missing canonical name for $node');
}
writeByte(Tag.Extension);
writeNonNullCanonicalNameReference(getCanonicalNameOfExtension(node));
writeStringReference(node.name ?? '');
writeUriReference(node.fileUri);
writeOffset(node.fileOffset);
enterScope(typeParameters: node.typeParameters);
writeNodeList(node.typeParameters);
writeDartType(node.onType);
leaveScope(typeParameters: node.typeParameters);
final int len = node.members.length;
writeUInt30(len);
for (int i = 0; i < len; i++) {
final ExtensionMemberDescriptor descriptor = node.members[i];
writeName(descriptor.name);
writeByte(descriptor.kind.index);
writeByte(descriptor.flags);
writeNonNullCanonicalNameReference(descriptor.member.canonicalName);
}
}
// ================================================================
// These are nodes that are never serialized directly. Reaching one
// during serialization is an error.
@override
void defaultNode(Node node) {
throw new UnsupportedError('serialization of generic Nodes');
}
@override
void defaultConstant(Constant node) {
throw new UnsupportedError('serialization of generic Constants');
}
@override
void defaultBasicLiteral(BasicLiteral node) {
throw new UnsupportedError('serialization of generic BasicLiterals');
}
@override
void defaultConstantReference(Constant node) {
throw new UnsupportedError('serialization of generic Constant references');
}
@override
void defaultDartType(DartType node) {
throw new UnsupportedError('serialization of generic DartTypes');
}
@override
void defaultExpression(Expression node) {
throw new UnsupportedError('serialization of generic Expressions');
}
@override
void defaultInitializer(Initializer node) {
throw new UnsupportedError('serialization of generic Initializers');
}
@override
void defaultMember(Member node) {
throw new UnsupportedError('serialization of generic Members');
}
@override
void defaultMemberReference(Member node) {
throw new UnsupportedError('serialization of generic Member references');
}
@override
void defaultStatement(Statement node) {
throw new UnsupportedError('serialization of generic Statements');
}
@override
void defaultTreeNode(TreeNode node) {
throw new UnsupportedError('serialization of generic TreeNodes');
}
@override
void visitBoolConstant(BoolConstant node) {
throw new UnsupportedError('serialization of BoolConstants');
}
@override
void visitBoolConstantReference(BoolConstant node) {
throw new UnsupportedError('serialization of BoolConstant references');
}
@override
void visitClassReference(Class node) {
throw new UnsupportedError('serialization of Class references');
}
@override
void visitConstructorReference(Constructor node) {
throw new UnsupportedError('serialization of Constructor references');
}
@override
void visitDoubleConstant(DoubleConstant node) {
throw new UnsupportedError('serialization of DoubleConstants');
}
@override
void visitDoubleConstantReference(DoubleConstant node) {
throw new UnsupportedError('serialization of DoubleConstant references');
}
@override
void visitFieldReference(Field node) {
throw new UnsupportedError('serialization of Field references');
}
@override
void visitInstanceConstant(InstanceConstant node) {
throw new UnsupportedError('serialization of InstanceConstants');
}
@override
void visitInstanceConstantReference(InstanceConstant node) {
throw new UnsupportedError('serialization of InstanceConstant references');
}
@override
void visitIntConstant(IntConstant node) {
throw new UnsupportedError('serialization of IntConstants');
}
@override
void visitIntConstantReference(IntConstant node) {
throw new UnsupportedError('serialization of IntConstant references');
}
@override
void visitLibraryDependency(LibraryDependency node) {
throw new UnsupportedError('serialization of LibraryDependencies');
}
@override
void visitLibraryPart(LibraryPart node) {
throw new UnsupportedError('serialization of LibraryParts');
}
@override
void visitListConstant(ListConstant node) {
throw new UnsupportedError('serialization of ListConstants');
}
@override
void visitListConstantReference(ListConstant node) {
throw new UnsupportedError('serialization of ListConstant references');
}
@override
void visitSetConstant(SetConstant node) {
throw new UnsupportedError('serialization of SetConstants');
}
@override
void visitSetConstantReference(SetConstant node) {
throw new UnsupportedError('serialization of SetConstant references');
}
@override
void visitMapConstant(MapConstant node) {
throw new UnsupportedError('serialization of MapConstants');
}
@override
void visitMapConstantReference(MapConstant node) {
throw new UnsupportedError('serialization of MapConstant references');
}
@override
void visitName(Name node) {
throw new UnsupportedError('serialization of Names');
}
@override
void visitNullConstant(NullConstant node) {
throw new UnsupportedError('serialization of NullConstants');
}
@override
void visitNullConstantReference(NullConstant node) {
throw new UnsupportedError('serialization of NullConstant references');
}
@override
void visitProcedureReference(Procedure node) {
throw new UnsupportedError('serialization of Procedure references');
}
@override
void visitComponent(Component node) {
throw new UnsupportedError('serialization of Components');
}
@override
void visitRedirectingFactoryConstructorReference(
RedirectingFactoryConstructor node) {
throw new UnsupportedError(
'serialization of RedirectingFactoryConstructor references');
}
@override
void visitStringConstant(StringConstant node) {
throw new UnsupportedError('serialization of StringConstants');
}
@override
void visitStringConstantReference(StringConstant node) {
throw new UnsupportedError('serialization of StringConstant references');
}
@override
void visitSymbolConstant(SymbolConstant node) {
throw new UnsupportedError('serialization of SymbolConstants');
}
@override
void visitSymbolConstantReference(SymbolConstant node) {
throw new UnsupportedError('serialization of SymbolConstant references');
}
@override
void visitPartialInstantiationConstant(PartialInstantiationConstant node) {
throw new UnsupportedError(
'serialization of PartialInstantiationConstants ');
}
@override
void visitPartialInstantiationConstantReference(
PartialInstantiationConstant node) {
throw new UnsupportedError(
'serialization of PartialInstantiationConstant references');
}
@override
void visitTearOffConstant(TearOffConstant node) {
throw new UnsupportedError('serialization of TearOffConstants ');
}
@override
void visitTearOffConstantReference(TearOffConstant node) {
throw new UnsupportedError('serialization of TearOffConstant references');
}
@override
void visitTypeLiteralConstant(TypeLiteralConstant node) {
throw new UnsupportedError('serialization of TypeLiteralConstants');
}
@override
void visitTypeLiteralConstantReference(TypeLiteralConstant node) {
throw new UnsupportedError(
'serialization of TypeLiteralConstant references');
}
@override
void visitTypedefReference(Typedef node) {
throw new UnsupportedError('serialization of Typedef references');
}
@override
void visitUnevaluatedConstant(UnevaluatedConstant node) {
throw new UnsupportedError('serialization of UnevaluatedConstants');
}
@override
void visitUnevaluatedConstantReference(UnevaluatedConstant node) {
throw new UnsupportedError(
'serialization of UnevaluatedConstant references');
}
}
typedef bool LibraryFilter(Library _);
class VariableIndexer {
Map<VariableDeclaration, int> index;
List<int> scopes;
int stackHeight = 0;
void declare(VariableDeclaration node) {
index ??= <VariableDeclaration, int>{};
index[node] = stackHeight++;
}
void pushScope() {
scopes ??= new List<int>();
scopes.add(stackHeight);
}
void popScope() {
stackHeight = scopes.removeLast();
}
void restoreScope(int numberOfVariables) {
stackHeight += numberOfVariables;
}
int operator [](VariableDeclaration node) {
return index == null ? null : index[node];
}
}
class LabelIndexer {
final Map<LabeledStatement, int> index = <LabeledStatement, int>{};
int stackHeight = 0;
void enter(LabeledStatement node) {
index[node] = stackHeight++;
}
void exit() {
--stackHeight;
}
int operator [](LabeledStatement node) => index[node];
}
class SwitchCaseIndexer {
final Map<SwitchCase, int> index = <SwitchCase, int>{};
int stackHeight = 0;
void enter(SwitchStatement node) {
for (SwitchCase caseNode in node.cases) {
index[caseNode] = stackHeight++;
}
}
void exit(SwitchStatement node) {
stackHeight -= node.cases.length;
}
int operator [](SwitchCase node) => index[node];
}
class ConstantIndexer extends RecursiveVisitor {
final StringIndexer stringIndexer;
final List<Constant> entries = <Constant>[];
final Map<Constant, int> offsets = <Constant, int>{};
int nextOffset = 0;
final BinaryPrinter _printer;
ConstantIndexer(this.stringIndexer, this._printer);
int put(Constant constant) {
final int oldOffset = offsets[constant];
if (oldOffset != null) return oldOffset;
// Traverse DAG in post-order to ensure children have their offsets assigned
// before the parent.
constant.visitChildren(this);
if (constant is StringConstant) {
stringIndexer.put(constant.value);
} else if (constant is SymbolConstant) {
stringIndexer.put(constant.name);
} else if (constant is DoubleConstant) {
stringIndexer.put('${constant.value}');
} else if (constant is IntConstant) {
final int value = constant.value;
if ((value.abs() >> 30) != 0) {
stringIndexer.put('$value');
}
}
final int newOffset = nextOffset;
entries.add(constant);
nextOffset += _printer.writeConstantTableEntry(constant);
return offsets[constant] = newOffset;
}
defaultConstantReference(Constant node) {
put(node);
}
int operator [](Constant node) => offsets[node];
}
class TypeParameterIndexer {
final Map<TypeParameter, int> index = <TypeParameter, int>{};
int stackHeight = 0;
void enter(List<TypeParameter> typeParameters) {
for (int i = 0; i < typeParameters.length; ++i) {
TypeParameter parameter = typeParameters[i];
index[parameter] = stackHeight;
++stackHeight;
}
}
void exit(List<TypeParameter> typeParameters) {
stackHeight -= typeParameters.length;
for (int i = 0; i < typeParameters.length; ++i) {
index.remove(typeParameters[i]);
}
}
int operator [](TypeParameter parameter) =>
index[parameter] ??
(throw new ArgumentError('Type parameter $parameter is not indexed'));
}
class StringIndexer {
// Note that the iteration order is important.
final Map<String, int> index = new Map<String, int>();
StringIndexer() {
put('');
}
int put(String string) {
int result = index[string];
if (result == null) {
result = index.length;
index[string] = result;
}
return result;
}
int operator [](String string) => index[string];
}
class UriIndexer {
// Note that the iteration order is important.
final Map<Uri, int> index = new Map<Uri, int>();
UriIndexer() {
put(null);
}
int put(Uri uri) {
int result = index[uri];
if (result == null) {
result = index.length;
index[uri] = result;
}
return result;
}
}
/// Puts a buffer in front of a [Sink<List<int>>].
class BufferedSink {
static const int SIZE = 100000;
static const int SAFE_SIZE = SIZE - 5;
static const int SMALL = 10000;
final Sink<List<int>> _sink;
Uint8List _buffer = new Uint8List(SIZE);
int length = 0;
int flushedLength = 0;
Float64List _doubleBuffer = new Float64List(1);
Uint8List _doubleBufferUint8;
int get offset => length + flushedLength;
BufferedSink(this._sink);
void addDouble(double d) {
_doubleBufferUint8 ??= _doubleBuffer.buffer.asUint8List();
_doubleBuffer[0] = d;
addByte4(_doubleBufferUint8[0], _doubleBufferUint8[1],
_doubleBufferUint8[2], _doubleBufferUint8[3]);
addByte4(_doubleBufferUint8[4], _doubleBufferUint8[5],
_doubleBufferUint8[6], _doubleBufferUint8[7]);
}
@pragma("vm:prefer-inline")
void addByte(int byte) {
_buffer[length++] = byte;
if (length == SIZE) {
_sink.add(_buffer);
_buffer = new Uint8List(SIZE);
length = 0;
flushedLength += SIZE;
}
}
@pragma("vm:prefer-inline")
void addByte2(int byte1, int byte2) {
if (length < SAFE_SIZE) {
_buffer[length++] = byte1;
_buffer[length++] = byte2;
} else {
addByte(byte1);
addByte(byte2);
}
}
@pragma("vm:prefer-inline")
void addByte4(int byte1, int byte2, int byte3, int byte4) {
if (length < SAFE_SIZE) {
_buffer[length++] = byte1;
_buffer[length++] = byte2;
_buffer[length++] = byte3;
_buffer[length++] = byte4;
} else {
addByte(byte1);
addByte(byte2);
addByte(byte3);
addByte(byte4);
}
}
void addBytes(List<int> bytes) {
// Avoid copying a large buffer into the another large buffer. Also, if
// the bytes buffer is too large to fit in our own buffer, just emit both.
if (length + bytes.length < SIZE &&
(bytes.length < SMALL || length < SMALL)) {
_buffer.setRange(length, length + bytes.length, bytes);
length += bytes.length;
} else if (bytes.length < SMALL) {
// Flush as much as we can in the current buffer.
_buffer.setRange(length, SIZE, bytes);
_sink.add(_buffer);
// Copy over the remainder into a new buffer. It is guaranteed to fit
// because the input byte array is small.
int alreadyEmitted = SIZE - length;
int remainder = bytes.length - alreadyEmitted;
_buffer = new Uint8List(SIZE);
_buffer.setRange(0, remainder, bytes, alreadyEmitted);
length = remainder;
flushedLength += SIZE;
} else {
flush();
_sink.add(bytes);
flushedLength += bytes.length;
}
}
void flush() {
_sink.add(_buffer.sublist(0, length));
_buffer = new Uint8List(SIZE);
flushedLength += length;
length = 0;
}
void flushAndDestroy() {
_sink.add(_buffer.sublist(0, length));
}
}
/// Non-empty metadata subsection.
class _MetadataSubsection {
final MetadataRepository<Object> repository;
/// List of (nodeOffset, metadataOffset) pairs.
/// Gradually filled by the writer as writing progresses, which by
/// construction guarantees that pairs are sorted by first component
/// (nodeOffset) in ascending order.
final List<int> metadataMapping = <int>[];
_MetadataSubsection(this.repository);
}
/// A [Sink] that directly writes data into a byte builder.
// TODO(dartbug.com/28316): Remove this wrapper class.
class BytesSink implements Sink<List<int>> {
final BytesBuilder builder = new BytesBuilder();
@override
void add(List<int> data) {
builder.add(data);
}
@override
void close() {
// Nothing to do.
}
}
class NotQuiteString {
/**
* Write [source] string into [target] starting at index [index].
*
* Optionally only write part of the input [source] starting at [start] and
* ending at [end].
*
* The output space needed is at most [source.length] * 3.
*
* Returns
* * Non-negative on success (the new index in [target]).
* * -1 when [target] doesn't have enough space. Note that [target] can be
* polluted starting at [index].
* * -2 on input error, i.e. an unpaired lead or tail surrogate.
*/
static int writeUtf8(List<int> target, int index, String source,
[int start = 0, int end]) {
RangeError.checkValidIndex(index, target, null, target.length);
end = RangeError.checkValidRange(start, end, source.length);
if (start == end) return index;
int i = start;
int length = target.length;
do {
int codeUnit = source.codeUnitAt(i++);
while (codeUnit < 128) {
if (index >= length) return -1;
target[index++] = codeUnit;
if (i >= end) return index;
codeUnit = source.codeUnitAt(i++);
}
if (codeUnit < 0x800) {
index += 2;
if (index > length) return -1;
target[index - 2] = 0xC0 | (codeUnit >> 6);
target[index - 1] = 0x80 | (codeUnit & 0x3f);
} else if (codeUnit & 0xF800 != 0xD800) {
// Not a surrogate.
index += 3;
if (index > length) return -1;
target[index - 3] = 0xE0 | (codeUnit >> 12);
target[index - 2] = 0x80 | ((codeUnit >> 6) & 0x3f);
target[index - 1] = 0x80 | (codeUnit & 0x3f);
} else {
if (codeUnit >= 0xDC00) return -2; // Unpaired tail surrogate.
if (i >= end) return -2; // Unpaired lead surrogate.
int nextChar = source.codeUnitAt(i++);
if (nextChar & 0xFC00 != 0xDC00) return -2; // Unpaired lead surrogate.
index += 4;
if (index > length) return -1;
codeUnit = (codeUnit & 0x3FF) + 0x40;
target[index - 4] = 0xF0 | (codeUnit >> 8);
target[index - 3] = 0x80 | ((codeUnit >> 2) & 0x3F);
target[index - 2] =
0x80 | (((codeUnit & 3) << 4) | ((nextChar & 0x3FF) >> 6));
target[index - 1] = 0x80 | (nextChar & 0x3f);
}
} while (i < end);
return index;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/binary/limited_ast_to_binary.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:kernel/ast.dart';
import 'package:kernel/binary/ast_to_binary.dart';
/// Writes libraries that satisfy the [predicate].
///
/// Only the referenced subset of canonical names is indexed and written,
/// so we don't waste time indexing all libraries of a component, when only
/// a tiny subset is used.
class LimitedBinaryPrinter extends BinaryPrinter {
final LibraryFilter predicate;
/// Excludes all uriToSource information.
///
/// By default the [predicate] above will only exclude canonical names and
/// kernel libraries, but it will still emit the sources for all libraries.
/// filtered by libraries matching [predicate].
// TODO(sigmund): provide a way to filter sources directly based on
// [predicate]. That requires special logic to handle sources from part files.
final bool excludeUriToSource;
LimitedBinaryPrinter(
Sink<List<int>> sink, this.predicate, this.excludeUriToSource,
{bool includeOffsets = true})
: super(sink,
includeSources: !excludeUriToSource,
includeOffsets: includeOffsets);
@override
void computeCanonicalNames(Component component) {
for (var library in component.libraries) {
if (predicate(library)) {
component.root
.getChildFromUri(library.importUri)
.bindTo(library.reference);
library.computeCanonicalNames();
}
}
}
@override
bool shouldWriteLibraryCanonicalNames(Library library) {
return predicate(library);
}
void writeLibraries(Component component) {
for (int i = 0; i < component.libraries.length; ++i) {
Library library = component.libraries[i];
if (predicate(library)) writeLibraryNode(library);
}
}
@override
void writeNode(Node node) {
if (node is Library && !predicate(node)) return;
super.writeNode(node);
}
@override
void writeComponentIndex(Component component, List<Library> libraries) {
var librariesToWrite = libraries.where(predicate).toList();
super.writeComponentIndex(component, librariesToWrite);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/binary/tag.dart | // 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.
library kernel.binary.tag;
class Tag {
static const int Nothing = 0;
static const int Something = 1;
static const int Class = 2;
static const int Extension = 115;
static const int FunctionNode = 3;
// Members
static const int Field = 4;
static const int Constructor = 5;
static const int Procedure = 6;
static const int RedirectingFactoryConstructor = 108;
// Initializers
static const int InvalidInitializer = 7;
static const int FieldInitializer = 8;
static const int SuperInitializer = 9;
static const int RedirectingInitializer = 10;
static const int LocalInitializer = 11;
static const int AssertInitializer = 12;
// Expressions
static const int CheckLibraryIsLoaded = 13;
static const int LoadLibrary = 14;
static const int DirectPropertyGet = 15;
static const int DirectPropertySet = 16;
static const int DirectMethodInvocation = 17;
static const int ConstStaticInvocation = 18;
static const int InvalidExpression = 19;
static const int VariableGet = 20;
static const int VariableSet = 21;
static const int PropertyGet = 22;
static const int PropertySet = 23;
static const int SuperPropertyGet = 24;
static const int SuperPropertySet = 25;
static const int StaticGet = 26;
static const int StaticSet = 27;
static const int MethodInvocation = 28;
static const int SuperMethodInvocation = 29;
static const int StaticInvocation = 30;
static const int ConstructorInvocation = 31;
static const int ConstConstructorInvocation = 32;
static const int Not = 33;
static const int NullCheck = 117;
static const int LogicalExpression = 34;
static const int ConditionalExpression = 35;
static const int StringConcatenation = 36;
static const int ListConcatenation = 111;
static const int SetConcatenation = 112;
static const int MapConcatenation = 113;
static const int InstanceCreation = 114;
static const int IsExpression = 37;
static const int AsExpression = 38;
static const int StringLiteral = 39;
static const int DoubleLiteral = 40;
static const int TrueLiteral = 41;
static const int FalseLiteral = 42;
static const int NullLiteral = 43;
static const int SymbolLiteral = 44;
static const int TypeLiteral = 45;
static const int ThisExpression = 46;
static const int Rethrow = 47;
static const int Throw = 48;
static const int ListLiteral = 49;
static const int MapLiteral = 50;
static const int AwaitExpression = 51;
static const int FunctionExpression = 52;
static const int Let = 53;
static const int BlockExpression = 82;
static const int Instantiation = 54;
static const int PositiveIntLiteral = 55;
static const int NegativeIntLiteral = 56;
static const int BigIntLiteral = 57;
static const int ConstListLiteral = 58;
static const int ConstMapLiteral = 59;
static const int SetLiteral = 109;
static const int ConstSetLiteral = 110;
static const int FileUriExpression = 116;
// Statements
static const int ExpressionStatement = 61;
static const int Block = 62;
static const int EmptyStatement = 63;
static const int AssertStatement = 64;
static const int LabeledStatement = 65;
static const int BreakStatement = 66;
static const int WhileStatement = 67;
static const int DoStatement = 68;
static const int ForStatement = 69;
static const int ForInStatement = 70;
static const int SwitchStatement = 71;
static const int ContinueSwitchStatement = 72;
static const int IfStatement = 73;
static const int ReturnStatement = 74;
static const int TryCatch = 75;
static const int TryFinally = 76;
static const int YieldStatement = 77;
static const int VariableDeclaration = 78;
static const int FunctionDeclaration = 79;
static const int AsyncForInStatement = 80;
static const int AssertBlock = 81;
// 82 is occupied by [BlockExpression] (expression).
// Types
static const int TypedefType = 87;
static const int BottomType = 89;
static const int InvalidType = 90;
static const int DynamicType = 91;
static const int VoidType = 92;
static const int InterfaceType = 93;
static const int FunctionType = 94;
static const int TypeParameterType = 95;
static const int SimpleInterfaceType = 96;
static const int SimpleFunctionType = 97;
static const int ConstantExpression = 106;
/// 108 is occupied by [RedirectingFactoryConstructor] (member).
/// 109 is occupied by [SetLiteral] (expression).
/// 110 is occupied by [ConstSetLiteral] (expression).
/// 111 is occupied by [ListConcatenation] (expression).
/// 112 is occupied by [SetConcatenation] (expression).
/// 113 is occupied by [MapConcatenation] (expression).
/// 114 is occupied by [InstanceCreation] (expression).
/// 115 is occupied by [Extension].
/// 116 is occupied by [FileUriExpression] (expression).
/// 117 is occupied by [NullCheck] (expression).
static const int SpecializedTagHighBit = 0x80; // 10000000
static const int SpecializedTagMask = 0xF8; // 11111000
static const int SpecializedPayloadMask = 0x7; // 00000111
static const int SpecializedVariableGet = 128;
static const int SpecializedVariableSet = 136;
static const int SpecializedIntLiteral = 144;
static const int SpecializedIntLiteralBias = 3;
static const int ComponentFile = 0x90ABCDEF;
/// Internal version of kernel binary format.
/// Bump it when making incompatible changes in kernel binaries.
/// Keep in sync with runtime/vm/kernel_binary.h, pkg/kernel/binary.md.
static const int BinaryFormatVersion = 34;
}
abstract class ConstantTag {
static const int NullConstant = 0;
static const int BoolConstant = 1;
static const int IntConstant = 2;
static const int DoubleConstant = 3;
static const int StringConstant = 4;
static const int SymbolConstant = 5;
static const int MapConstant = 6;
static const int ListConstant = 7;
static const int SetConstant = 13;
static const int InstanceConstant = 8;
static const int PartialInstantiationConstant = 9;
static const int TearOffConstant = 10;
static const int TypeLiteralConstant = 11;
static const int UnevaluatedConstant = 12;
// 13 is occupied by [SetConstant]
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/text/serializer_combinators.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.serializer_combinators;
import 'dart:convert' show json;
import '../ast.dart' show Node;
import '../canonical_name.dart' show CanonicalName;
import 'text_serializer.dart' show Tagger;
class DeserializationEnvironment<T extends Node> {
final DeserializationEnvironment<T> parent;
final Map<String, T> locals = <String, T>{};
final Map<String, T> binders = <String, T>{};
final Set<String> usedNames;
DeserializationEnvironment(this.parent)
: usedNames = parent?.usedNames?.toSet() ?? new Set<String>();
T lookup(String name) => locals[name] ?? parent?.lookup(name);
T addBinder(String name, T node) {
if (usedNames.contains(name)) {
throw StateError("name '$name' is already declared in this scope");
}
usedNames.add(name);
return binders[name] = node;
}
void close() {
locals.addAll(binders);
binders.clear();
}
}
class SerializationEnvironment<T extends Node> {
final SerializationEnvironment<T> parent;
final Map<T, String> locals = new Map<T, String>.identity();
final Map<T, String> binders = new Map<T, String>.identity();
int nameCount;
SerializationEnvironment(this.parent) : nameCount = parent?.nameCount ?? 0;
String lookup(T node) => locals[node] ?? parent?.lookup(node);
String addBinder(T node, String name) {
final String separator = "^";
final int codeOfZero = "0".codeUnitAt(0);
final int codeOfNine = "9".codeUnitAt(0);
int prefixLength = name.length - 1;
bool isOnlyDigits = true;
while (prefixLength >= 0 && name[prefixLength] != separator) {
int code = name.codeUnitAt(prefixLength);
isOnlyDigits = isOnlyDigits && (codeOfZero <= code && code <= codeOfNine);
--prefixLength;
}
if (prefixLength < 0 || !isOnlyDigits) {
prefixLength = name.length;
}
String prefix = name.substring(0, prefixLength);
return binders[node] = "$prefix$separator${nameCount++}";
}
void close() {
locals.addAll(binders);
binders.clear();
}
}
class DeserializationState {
final DeserializationEnvironment environment;
final CanonicalName nameRoot;
DeserializationState(this.environment, this.nameRoot);
}
class SerializationState {
final SerializationEnvironment environment;
SerializationState(this.environment);
}
abstract class TextSerializer<T> {
const TextSerializer();
T readFrom(Iterator<Object> stream, DeserializationState state);
void writeTo(StringBuffer buffer, T object, SerializationState state);
/// True if this serializer/deserializer writes/reads nothing. This is true
/// for the serializer [Nothing] and also some serializers derived from it.
bool get isEmpty => false;
}
class Nothing extends TextSerializer<void> {
const Nothing();
void readFrom(Iterator<Object> stream, DeserializationState _) {}
void writeTo(StringBuffer buffer, void ignored, SerializationState _) {}
bool get isEmpty => true;
}
class DartString extends TextSerializer<String> {
const DartString();
String readFrom(Iterator<Object> stream, DeserializationState _) {
if (stream.current is! String) {
throw StateError("expected an atom, found a list");
}
String result = json.decode(stream.current);
stream.moveNext();
return result;
}
void writeTo(StringBuffer buffer, String object, SerializationState _) {
buffer.write(json.encode(object));
}
}
class DartInt extends TextSerializer<int> {
const DartInt();
int readFrom(Iterator<Object> stream, DeserializationState _) {
if (stream.current is! String) {
throw StateError("expected an atom, found a list");
}
int result = int.parse(stream.current);
stream.moveNext();
return result;
}
void writeTo(StringBuffer buffer, int object, SerializationState _) {
buffer.write(object);
}
}
class DartDouble extends TextSerializer<double> {
const DartDouble();
double readFrom(Iterator<Object> stream, DeserializationState _) {
if (stream.current is! String) {
throw StateError("expected an atom, found a list");
}
double result = double.parse(stream.current);
stream.moveNext();
return result;
}
void writeTo(StringBuffer buffer, double object, SerializationState _) {
buffer.write(object);
}
}
class DartBool extends TextSerializer<bool> {
const DartBool();
bool readFrom(Iterator<Object> stream, DeserializationState _) {
if (stream.current is! String) {
throw StateError("expected an atom, found a list");
}
bool result;
if (stream.current == "true") {
result = true;
} else if (stream.current == "false") {
result = false;
} else {
throw StateError("expected 'true' or 'false', found '${stream.current}'");
}
stream.moveNext();
return result;
}
void writeTo(StringBuffer buffer, bool object, SerializationState _) {
buffer.write(object ? 'true' : 'false');
}
}
// == Serializers for tagged (disjoint) unions.
//
// They require a function mapping serializables to a tag string. This is
// implemented by Tagger visitors.
// A tagged union of serializer/deserializers.
class Case<T extends Node> extends TextSerializer<T> {
final Tagger<T> tagger;
final List<String> tags;
final List<TextSerializer<T>> serializers;
Case(this.tagger, this.tags, this.serializers);
Case.uninitialized(this.tagger)
: tags = [],
serializers = [];
T readFrom(Iterator<Object> stream, DeserializationState state) {
if (stream.current is! Iterator) {
throw StateError("expected list, found atom");
}
Iterator nested = stream.current;
nested.moveNext();
if (nested.current is! String) {
throw StateError("expected atom, found list");
}
String tag = nested.current;
for (int i = 0; i < tags.length; ++i) {
if (tags[i] == tag) {
nested.moveNext();
T result = serializers[i].readFrom(nested, state);
if (nested.moveNext()) {
throw StateError("extra cruft in tagged '${tag}'");
}
stream.moveNext();
return result;
}
}
throw StateError("unrecognized tag '${tag}'");
}
void writeTo(StringBuffer buffer, T object, SerializationState state) {
String tag = tagger.tag(object);
for (int i = 0; i < tags.length; ++i) {
if (tags[i] == tag) {
buffer.write("(${tag}");
if (!serializers[i].isEmpty) {
buffer.write(" ");
}
serializers[i].writeTo(buffer, object, state);
buffer.write(")");
return;
}
}
throw StateError("unrecognized tag '${tag}");
}
}
// A serializer/deserializer that unwraps/wraps nodes before serialization and
// after deserialization.
class Wrapped<S, K> extends TextSerializer<K> {
final S Function(K) unwrap;
final K Function(S) wrap;
final TextSerializer<S> contents;
Wrapped(this.unwrap, this.wrap, this.contents);
K readFrom(Iterator<Object> stream, DeserializationState state) {
return wrap(contents.readFrom(stream, state));
}
void writeTo(StringBuffer buffer, K object, SerializationState state) {
contents.writeTo(buffer, unwrap(object), state);
}
bool get isEmpty => contents.isEmpty;
}
class ScopedUse<T extends Node> extends TextSerializer<T> {
final DartString stringSerializer = const DartString();
const ScopedUse();
T readFrom(Iterator<Object> stream, DeserializationState state) {
return state.environment.lookup(stringSerializer.readFrom(stream, null));
}
void writeTo(StringBuffer buffer, T object, SerializationState state) {
stringSerializer.writeTo(buffer, state.environment.lookup(object), null);
}
}
// A serializer/deserializer for pairs.
class Tuple2Serializer<T1, T2> extends TextSerializer<Tuple2<T1, T2>> {
final TextSerializer<T1> first;
final TextSerializer<T2> second;
const Tuple2Serializer(this.first, this.second);
Tuple2<T1, T2> readFrom(Iterator<Object> stream, DeserializationState state) {
return new Tuple2(
first.readFrom(stream, state), second.readFrom(stream, state));
}
void writeTo(
StringBuffer buffer, Tuple2<T1, T2> object, SerializationState state) {
first.writeTo(buffer, object.first, state);
buffer.write(' ');
second.writeTo(buffer, object.second, state);
}
}
class Tuple2<T1, T2> {
final T1 first;
final T2 second;
const Tuple2(this.first, this.second);
}
class Tuple3Serializer<T1, T2, T3> extends TextSerializer<Tuple3<T1, T2, T3>> {
final TextSerializer<T1> first;
final TextSerializer<T2> second;
final TextSerializer<T3> third;
const Tuple3Serializer(this.first, this.second, this.third);
Tuple3<T1, T2, T3> readFrom(
Iterator<Object> stream, DeserializationState state) {
return new Tuple3(first.readFrom(stream, state),
second.readFrom(stream, state), third.readFrom(stream, state));
}
void writeTo(StringBuffer buffer, Tuple3<T1, T2, T3> object,
SerializationState state) {
first.writeTo(buffer, object.first, state);
buffer.write(' ');
second.writeTo(buffer, object.second, state);
buffer.write(' ');
third.writeTo(buffer, object.third, state);
}
}
class Tuple3<T1, T2, T3> {
final T1 first;
final T2 second;
final T3 third;
const Tuple3(this.first, this.second, this.third);
}
class Tuple4Serializer<T1, T2, T3, T4>
extends TextSerializer<Tuple4<T1, T2, T3, T4>> {
final TextSerializer<T1> first;
final TextSerializer<T2> second;
final TextSerializer<T3> third;
final TextSerializer<T4> fourth;
const Tuple4Serializer(this.first, this.second, this.third, this.fourth);
Tuple4<T1, T2, T3, T4> readFrom(
Iterator<Object> stream, DeserializationState state) {
return new Tuple4(
first.readFrom(stream, state),
second.readFrom(stream, state),
third.readFrom(stream, state),
fourth.readFrom(stream, state));
}
void writeTo(StringBuffer buffer, Tuple4<T1, T2, T3, T4> object,
SerializationState state) {
first.writeTo(buffer, object.first, state);
buffer.write(' ');
second.writeTo(buffer, object.second, state);
buffer.write(' ');
third.writeTo(buffer, object.third, state);
buffer.write(' ');
fourth.writeTo(buffer, object.fourth, state);
}
}
class Tuple4<T1, T2, T3, T4> {
final T1 first;
final T2 second;
final T3 third;
final T4 fourth;
const Tuple4(this.first, this.second, this.third, this.fourth);
}
// A serializer/deserializer for lists.
class ListSerializer<T> extends TextSerializer<List<T>> {
final TextSerializer<T> elements;
const ListSerializer(this.elements);
List<T> readFrom(Iterator<Object> stream, DeserializationState state) {
if (stream.current is! Iterator) {
throw StateError("expected a list, found an atom");
}
Iterator<Object> list = stream.current;
list.moveNext();
List<T> result = [];
while (list.current != null) {
result.add(elements.readFrom(list, state));
}
stream.moveNext();
return result;
}
void writeTo(StringBuffer buffer, List<T> object, SerializationState state) {
buffer.write('(');
for (int i = 0; i < object.length; ++i) {
if (i != 0) buffer.write(' ');
elements.writeTo(buffer, object[i], state);
}
buffer.write(')');
}
}
class Optional<T> extends TextSerializer<T> {
final TextSerializer<T> contents;
const Optional(this.contents);
T readFrom(Iterator<Object> stream, DeserializationState state) {
if (stream.current == '_') {
stream.moveNext();
return null;
}
return contents.readFrom(stream, state);
}
void writeTo(StringBuffer buffer, T object, SerializationState state) {
if (object == null) {
buffer.write('_');
} else {
contents.writeTo(buffer, object, state);
}
}
}
/// Introduces a binder to the environment.
///
/// Serializes an object and uses it as a binder for the name that is retrieved
/// from the object using [nameGetter] and (temporarily) modified using
/// [nameSetter]. The binder is added to the enclosing environment.
class Binder<T extends Node> extends TextSerializer<T> {
final TextSerializer<T> contents;
final String Function(T) nameGetter;
final void Function(T, String) nameSetter;
const Binder(this.contents, this.nameGetter, this.nameSetter);
T readFrom(Iterator<Object> stream, DeserializationState state) {
T object = contents.readFrom(stream, state);
state.environment.addBinder(nameGetter(object), object);
return object;
}
void writeTo(StringBuffer buffer, T object, SerializationState state) {
String oldName = nameGetter(object);
String newName = state.environment.addBinder(object, oldName);
nameSetter(object, newName);
contents.writeTo(buffer, object, state);
nameSetter(object, oldName);
}
}
/// Binds binders from one term in the other.
///
/// Serializes a [Tuple2] of [pattern] and [term], closing [term] over the
/// binders found in [pattern]. The binders aren't added to the enclosing
/// environment.
class Bind<P, T> extends TextSerializer<Tuple2<P, T>> {
final TextSerializer<P> pattern;
final TextSerializer<T> term;
const Bind(this.pattern, this.term);
Tuple2<P, T> readFrom(Iterator<Object> stream, DeserializationState state) {
var bindingState = new DeserializationState(
new DeserializationEnvironment(state.environment), state.nameRoot);
P first = pattern.readFrom(stream, bindingState);
bindingState.environment.close();
T second = term.readFrom(stream, bindingState);
return new Tuple2(first, second);
}
void writeTo(
StringBuffer buffer, Tuple2<P, T> tuple, SerializationState state) {
var bindingState =
new SerializationState(new SerializationEnvironment(state.environment));
pattern.writeTo(buffer, tuple.first, bindingState);
bindingState.environment.close();
buffer.write(' ');
term.writeTo(buffer, tuple.second, bindingState);
}
}
/// Binds binders from one term in the other and adds them to the environment.
///
/// Serializes a [Tuple2] of [pattern] and [term], closing [term] over the
/// binders found in [pattern]. The binders are added to the enclosing
/// environment.
class Rebind<P, T> extends TextSerializer<Tuple2<P, T>> {
final TextSerializer<P> pattern;
final TextSerializer<T> term;
const Rebind(this.pattern, this.term);
Tuple2<P, T> readFrom(Iterator<Object> stream, DeserializationState state) {
P first = pattern.readFrom(stream, state);
var closedState = new DeserializationState(
new DeserializationEnvironment(state.environment)
..binders.addAll(state.environment.binders)
..close(),
state.nameRoot);
T second = term.readFrom(stream, closedState);
return new Tuple2(first, second);
}
void writeTo(
StringBuffer buffer, Tuple2<P, T> tuple, SerializationState state) {
pattern.writeTo(buffer, tuple.first, state);
var closedState =
new SerializationState(new SerializationEnvironment(state.environment)
..binders.addAll(state.environment.binders)
..close());
buffer.write(' ');
term.writeTo(buffer, tuple.second, closedState);
}
}
class Zip<T, T1, T2> extends TextSerializer<List<T>> {
final TextSerializer<Tuple2<List<T1>, List<T2>>> lists;
final T Function(T1, T2) zip;
final Tuple2<T1, T2> Function(T) unzip;
const Zip(this.lists, this.zip, this.unzip);
List<T> readFrom(Iterator<Object> stream, DeserializationState state) {
Tuple2<List<T1>, List<T2>> toZip = lists.readFrom(stream, state);
List<T1> firsts = toZip.first;
List<T2> seconds = toZip.second;
List<T> zipped = new List<T>(toZip.first.length);
for (int i = 0; i < zipped.length; ++i) {
zipped[i] = zip(firsts[i], seconds[i]);
}
return zipped;
}
void writeTo(StringBuffer buffer, List<T> zipped, SerializationState state) {
List<T1> firsts = new List<T1>(zipped.length);
List<T2> seconds = new List<T2>(zipped.length);
for (int i = 0; i < zipped.length; ++i) {
Tuple2<T1, T2> tuple = unzip(zipped[i]);
firsts[i] = tuple.first;
seconds[i] = tuple.second;
}
lists.writeTo(buffer, new Tuple2(firsts, seconds), state);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/text/text_reader.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.text_reader;
// S-expressions
//
// An S-expression is an atom or an S-list, an atom is a string that does not
// contain the delimiters '(', ')', or ' ', and an S-list is a space delimited
// sequence of S-expressions enclosed in parentheses:
//
// <S-expression> ::= <Atom>
// | <S-list>
// <S-list> ::= '(' ')'
// | '(' <S-expression> {' ' <S-expression>}* ')'
//
// We use an iterator to read S-expressions. The iterator produces a stream
// of atoms (strings) and nested iterators (S-lists).
class TextIterator implements Iterator<Object /* String | TextIterator */ > {
static int space = ' '.codeUnitAt(0);
static int lparen = '('.codeUnitAt(0);
static int rparen = ')'.codeUnitAt(0);
static int dquote = '"'.codeUnitAt(0);
static int bslash = '\\'.codeUnitAt(0);
final String input;
int index;
TextIterator(this.input, this.index);
// Consume spaces.
void skipWhitespace() {
while (index < input.length && input.codeUnitAt(index) == space) {
++index;
}
}
// Consume the rest of a nested S-expression and the closing delimiter.
void skipToEndOfNested() {
if (current is TextIterator) {
TextIterator it = current;
while (it.moveNext());
index = it.index + 1;
}
}
void skipToEndOfAtom() {
bool isQuoted = false;
if (index < input.length && input.codeUnitAt(index) == dquote) {
++index;
isQuoted = true;
}
do {
if (index >= input.length) return;
int codeUnit = input.codeUnitAt(index);
if (isQuoted) {
// Terminator.
if (codeUnit == dquote) {
++index;
return;
}
// Escaped double quote.
if (codeUnit == bslash &&
index < input.length + 1 &&
input.codeUnitAt(index + 1) == dquote) {
index += 2;
} else {
++index;
}
} else {
// Terminator.
if (codeUnit == space || codeUnit == rparen) return;
++index;
}
} while (true);
}
@override
Object current = null;
@override
bool moveNext() {
skipToEndOfNested();
skipWhitespace();
if (index >= input.length || input.codeUnitAt(index) == rparen) {
current = null;
return false;
}
if (input.codeUnitAt(index) == lparen) {
current = new TextIterator(input, index + 1);
return true;
}
int start = index;
skipToEndOfAtom();
current = input.substring(start, index);
return true;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/text/ast_to_text.dart | // 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.
library kernel.ast_to_text;
import 'dart:core' hide MapEntry;
import 'dart:core' as core show MapEntry;
import 'dart:convert' show json;
import '../ast.dart';
import '../import_table.dart';
abstract class Namer<T> {
int index = 0;
final Map<T, String> map = <T, String>{};
String getName(T key) => map.putIfAbsent(key, () => '$prefix${++index}');
String get prefix;
}
class NormalNamer<T> extends Namer<T> {
final String prefix;
NormalNamer(this.prefix);
}
class ConstantNamer extends RecursiveVisitor<Null> with Namer<Constant> {
final String prefix;
ConstantNamer(this.prefix);
String getName(Constant constant) {
if (!map.containsKey(constant)) {
// When printing a non-fully linked kernel AST (i.e. some [Reference]s
// are not bound) to text, we need to avoid dereferencing any
// references.
//
// The normal visitor API causes references to be dereferenced in order
// to call the `visit<name>(<name>)` / `visit<name>Reference(<name>)`.
//
// We therefore handle any subclass of [Constant] which has [Reference]s
// specially here.
//
if (constant is InstanceConstant) {
// Avoid visiting `InstanceConstant.classReference`.
for (final value in constant.fieldValues.values) {
// Name everything in post-order visit of DAG.
getName(value);
}
} else if (constant is TearOffConstant) {
// We only care about naming the constants themselves. [TearOffConstant]
// has no Constant children.
// Avoid visiting `TearOffConstant.procedureReference`.
} else {
// Name everything in post-order visit of DAG.
constant.visitChildren(this);
}
}
return super.getName(constant);
}
defaultConstantReference(Constant constant) {
getName(constant);
}
defaultDartType(DartType type) {
// No need to recurse into dart types, we only care about naming the
// constants themselves.
}
}
class Disambiguator<T, U> {
final Map<T, String> namesT = <T, String>{};
final Map<U, String> namesU = <U, String>{};
final Set<String> usedNames = new Set<String>();
String disambiguate(T key1, U key2, String proposeName()) {
getNewName() {
var proposedName = proposeName();
if (usedNames.add(proposedName)) return proposedName;
int i = 2;
while (!usedNames.add('$proposedName$i')) {
++i;
}
return '$proposedName$i';
}
if (key1 != null) {
String result = namesT[key1];
if (result != null) return result;
return namesT[key1] = getNewName();
}
if (key2 != null) {
String result = namesU[key2];
if (result != null) return result;
return namesU[key2] = getNewName();
}
throw "Cannot disambiguate";
}
}
NameSystem globalDebuggingNames = new NameSystem();
String debugLibraryName(Library node) {
return node == null
? 'null'
: node.name ?? globalDebuggingNames.nameLibrary(node);
}
String debugClassName(Class node) {
return node == null
? 'null'
: node.name ?? globalDebuggingNames.nameClass(node);
}
String debugQualifiedClassName(Class node) {
return debugLibraryName(node.enclosingLibrary) + '::' + debugClassName(node);
}
String debugMemberName(Member node) {
return node.name?.name ?? globalDebuggingNames.nameMember(node);
}
String debugQualifiedMemberName(Member node) {
if (node.enclosingClass != null) {
return debugQualifiedClassName(node.enclosingClass) +
'::' +
debugMemberName(node);
} else {
return debugLibraryName(node.enclosingLibrary) +
'::' +
debugMemberName(node);
}
}
String debugTypeParameterName(TypeParameter node) {
return node.name ?? globalDebuggingNames.nameTypeParameter(node);
}
String debugQualifiedTypeParameterName(TypeParameter node) {
if (node.parent is Class) {
return debugQualifiedClassName(node.parent) +
'::' +
debugTypeParameterName(node);
}
if (node.parent is Member) {
return debugQualifiedMemberName(node.parent) +
'::' +
debugTypeParameterName(node);
}
return debugTypeParameterName(node);
}
String debugVariableDeclarationName(VariableDeclaration node) {
return node.name ?? globalDebuggingNames.nameVariable(node);
}
String debugNodeToString(Node node) {
StringBuffer buffer = new StringBuffer();
new Printer(buffer, syntheticNames: globalDebuggingNames).writeNode(node);
return '$buffer';
}
String componentToString(Component node) {
StringBuffer buffer = new StringBuffer();
new Printer(buffer, syntheticNames: new NameSystem())
.writeComponentFile(node);
return '$buffer';
}
class NameSystem {
final Namer<VariableDeclaration> variables =
new NormalNamer<VariableDeclaration>('#t');
final Namer<Member> members = new NormalNamer<Member>('#m');
final Namer<Class> classes = new NormalNamer<Class>('#class');
final Namer<Extension> extensions = new NormalNamer<Extension>('#extension');
final Namer<Library> libraries = new NormalNamer<Library>('#lib');
final Namer<TypeParameter> typeParameters =
new NormalNamer<TypeParameter>('#T');
final Namer<TreeNode> labels = new NormalNamer<TreeNode>('#L');
final Namer<Constant> constants = new ConstantNamer('#C');
final Disambiguator<Reference, CanonicalName> prefixes =
new Disambiguator<Reference, CanonicalName>();
nameVariable(VariableDeclaration node) => variables.getName(node);
nameMember(Member node) => members.getName(node);
nameClass(Class node) => classes.getName(node);
nameExtension(Extension node) => extensions.getName(node);
nameLibrary(Library node) => libraries.getName(node);
nameTypeParameter(TypeParameter node) => typeParameters.getName(node);
nameSwitchCase(SwitchCase node) => labels.getName(node);
nameLabeledStatement(LabeledStatement node) => labels.getName(node);
nameConstant(Constant node) => constants.getName(node);
final RegExp pathSeparator = new RegExp('[\\/]');
nameLibraryPrefix(Library node, {String proposedName}) {
return prefixes.disambiguate(node.reference, node.reference.canonicalName,
() {
if (proposedName != null) return proposedName;
if (node.name != null) return abbreviateName(node.name);
if (node.importUri != null) {
var path = node.importUri.hasEmptyPath
? '${node.importUri}'
: node.importUri.pathSegments.last;
if (path.endsWith('.dart')) {
path = path.substring(0, path.length - '.dart'.length);
}
return abbreviateName(path);
}
return 'L';
});
}
nameCanonicalNameAsLibraryPrefix(Reference node, CanonicalName name,
{String proposedName}) {
return prefixes.disambiguate(node, name, () {
if (proposedName != null) return proposedName;
CanonicalName canonicalName = name ?? node.canonicalName;
if (canonicalName?.name != null) {
var path = canonicalName.name;
int slash = path.lastIndexOf(pathSeparator);
if (slash >= 0) {
path = path.substring(slash + 1);
}
if (path.endsWith('.dart')) {
path = path.substring(0, path.length - '.dart'.length);
}
return abbreviateName(path);
}
return 'L';
});
}
final RegExp punctuation = new RegExp('[.:]');
String abbreviateName(String name) {
int dot = name.lastIndexOf(punctuation);
if (dot != -1) {
name = name.substring(dot + 1);
}
if (name.length > 4) {
return name.substring(0, 3);
}
return name;
}
}
abstract class Annotator {
String annotateVariable(Printer printer, VariableDeclaration node);
String annotateReturn(Printer printer, FunctionNode node);
String annotateField(Printer printer, Field node);
}
/// A quick and dirty ambiguous text printer.
class Printer extends Visitor<Null> {
final NameSystem syntheticNames;
final StringSink sink;
final Annotator annotator;
final Map<String, MetadataRepository<Object>> metadata;
ImportTable importTable;
int indentation = 0;
int column = 0;
bool showExternal;
bool showOffsets;
bool showMetadata;
static int SPACE = 0;
static int WORD = 1;
static int SYMBOL = 2;
int state = SPACE;
Printer(this.sink,
{NameSystem syntheticNames,
this.showExternal,
this.showOffsets: false,
this.showMetadata: false,
this.importTable,
this.annotator,
this.metadata})
: this.syntheticNames = syntheticNames ?? new NameSystem();
Printer createInner(ImportTable importTable,
Map<String, MetadataRepository<Object>> metadata) {
return new Printer(sink,
importTable: importTable,
metadata: metadata,
syntheticNames: syntheticNames,
annotator: annotator,
showExternal: showExternal,
showOffsets: showOffsets,
showMetadata: showMetadata);
}
bool shouldHighlight(Node node) {
return false;
}
void startHighlight(Node node) {}
void endHighlight(Node node) {}
String getLibraryName(Library node) {
return node.name ?? syntheticNames.nameLibrary(node);
}
String getLibraryReference(Library node) {
if (node == null) return '<No Library>';
if (importTable != null && importTable.getImportIndex(node) != -1) {
return syntheticNames.nameLibraryPrefix(node);
}
return getLibraryName(node);
}
String getClassName(Class node) {
return node.name ?? syntheticNames.nameClass(node);
}
String getExtensionName(Extension node) {
return node.name ?? syntheticNames.nameExtension(node);
}
String getClassReference(Class node) {
if (node == null) return '<No Class>';
String name = getClassName(node);
String library = getLibraryReference(node.enclosingLibrary);
return '$library::$name';
}
String getTypedefReference(Typedef node) {
if (node == null) return '<No Typedef>';
String library = getLibraryReference(node.enclosingLibrary);
return '$library::${node.name}';
}
static final String emptyNameString = '•';
static final Name emptyName = new Name(emptyNameString);
Name getMemberName(Member node) {
if (node.name?.name == '') return emptyName;
if (node.name != null) return node.name;
return new Name(syntheticNames.nameMember(node));
}
String getMemberReference(Member node) {
if (node == null) return '<No Member>';
String name = getMemberName(node).name;
if (node.parent is Class) {
String className = getClassReference(node.parent);
return '$className::$name';
} else {
String library = getLibraryReference(node.enclosingLibrary);
return '$library::$name';
}
}
String getVariableName(VariableDeclaration node) {
return node.name ?? syntheticNames.nameVariable(node);
}
String getVariableReference(VariableDeclaration node) {
if (node == null) return '<No VariableDeclaration>';
return getVariableName(node);
}
String getTypeParameterName(TypeParameter node) {
return node.name ?? syntheticNames.nameTypeParameter(node);
}
String getTypeParameterReference(TypeParameter node) {
if (node == null) return '<No TypeParameter>';
String name = getTypeParameterName(node);
if (node.parent is FunctionNode && node.parent.parent is Member) {
String member = getMemberReference(node.parent.parent);
return '$member::$name';
} else if (node.parent is Class) {
String className = getClassReference(node.parent);
return '$className::$name';
} else {
return name; // Bound inside a function type.
}
}
void writeComponentProblems(Component component) {
writeProblemsAsJson("Problems in component", component.problemsAsJson);
}
void writeProblemsAsJson(String header, List<String> problemsAsJson) {
if (problemsAsJson?.isEmpty == false) {
endLine("//");
write("// ");
write(header);
endLine(":");
endLine("//");
for (String s in problemsAsJson) {
Map<String, Object> decoded = json.decode(s);
List<Object> plainTextFormatted = decoded["plainTextFormatted"];
List<String> lines = plainTextFormatted.join("\n").split("\n");
for (int i = 0; i < lines.length; i++) {
write("//");
String trimmed = lines[i].trimRight();
if (trimmed.isNotEmpty) write(" ");
endLine(trimmed);
}
if (lines.isNotEmpty) endLine("//");
}
}
}
void writeLibraryFile(Library library) {
writeAnnotationList(library.annotations);
writeWord('library');
if (library.name != null) {
writeWord(library.name);
}
endLine(';');
LibraryImportTable imports = new LibraryImportTable(library);
Printer inner = createInner(imports, library.enclosingComponent?.metadata);
inner.writeStandardLibraryContent(library,
outerPrinter: this, importsToPrint: imports);
}
void printLibraryImportTable(LibraryImportTable imports) {
for (var library in imports.importedLibraries) {
var importPath = imports.getImportPath(library);
if (importPath == "") {
var prefix =
syntheticNames.nameLibraryPrefix(library, proposedName: 'self');
endLine('import self as $prefix;');
} else {
var prefix = syntheticNames.nameLibraryPrefix(library);
endLine('import "$importPath" as $prefix;');
}
}
}
void writeStandardLibraryContent(Library library,
{Printer outerPrinter, LibraryImportTable importsToPrint}) {
outerPrinter ??= this;
outerPrinter.writeProblemsAsJson(
"Problems in library", library.problemsAsJson);
if (importsToPrint != null) {
outerPrinter.printLibraryImportTable(importsToPrint);
}
writeAdditionalExports(library.additionalExports);
endLine();
library.dependencies.forEach(writeNode);
if (library.dependencies.isNotEmpty) endLine();
library.parts.forEach(writeNode);
library.typedefs.forEach(writeNode);
library.classes.forEach(writeNode);
library.extensions.forEach(writeNode);
library.fields.forEach(writeNode);
library.procedures.forEach(writeNode);
}
void writeAdditionalExports(List<Reference> additionalExports) {
if (additionalExports.isEmpty) return;
write('additionalExports = (');
bool isFirst = true;
for (Reference reference in additionalExports) {
if (isFirst) {
isFirst = false;
} else {
write(', ');
}
var node = reference.node;
if (node is Class) {
Library nodeLibrary = node.enclosingLibrary;
String prefix = syntheticNames.nameLibraryPrefix(nodeLibrary);
write(prefix + '::' + node.name);
} else if (node is Field) {
Library nodeLibrary = node.enclosingLibrary;
String prefix = syntheticNames.nameLibraryPrefix(nodeLibrary);
write(prefix + '::' + node.name.name);
} else if (node is Procedure) {
Library nodeLibrary = node.enclosingLibrary;
String prefix = syntheticNames.nameLibraryPrefix(nodeLibrary);
write(prefix + '::' + node.name.name);
} else if (node is Typedef) {
Library nodeLibrary = node.enclosingLibrary;
String prefix = syntheticNames.nameLibraryPrefix(nodeLibrary);
write(prefix + '::' + node.name);
} else if (reference.canonicalName != null) {
write(reference.canonicalName.toString());
} else {
throw new UnimplementedError('${node.runtimeType}');
}
endLine(')');
}
endLine();
}
void writeComponentFile(Component component) {
ImportTable imports = new ComponentImportTable(component);
var inner = createInner(imports, component.metadata);
writeWord('main');
writeSpaced('=');
inner.writeMemberReferenceFromReference(component.mainMethodName);
endLine(';');
if (showMetadata) {
inner.writeMetadata(component);
}
writeComponentProblems(component);
for (var library in component.libraries) {
if (library.isExternal) {
if (!showExternal) {
continue;
}
writeWord('external');
}
if (showMetadata) {
inner.writeMetadata(library);
}
writeAnnotationList(library.annotations);
writeWord('library');
if (library.name != null) {
writeWord(library.name);
}
if (library.importUri != null) {
writeSpaced('from');
writeWord('"${library.importUri}"');
}
var prefix = syntheticNames.nameLibraryPrefix(library);
writeSpaced('as');
writeWord(prefix);
endLine(' {');
++inner.indentation;
inner.writeStandardLibraryContent(library);
--inner.indentation;
endLine('}');
}
writeConstantTable(component);
}
void writeConstantTable(Component component) {
if (syntheticNames.constants.map.isEmpty) return;
ImportTable imports = new ComponentImportTable(component);
var inner = createInner(imports, component.metadata);
writeWord('constants ');
endLine(' {');
++inner.indentation;
for (final Constant constant
in syntheticNames.constants.map.keys.toList()) {
inner.writeNode(constant);
}
--inner.indentation;
endLine('}');
}
int getPrecedence(TreeNode node) {
return Precedence.of(node);
}
void write(String string) {
sink.write(string);
column += string.length;
}
void writeSpace([String string = ' ']) {
write(string);
state = SPACE;
}
void ensureSpace() {
if (state != SPACE) writeSpace();
}
void writeSymbol(String string) {
write(string);
state = SYMBOL;
}
void writeSpaced(String string) {
ensureSpace();
write(string);
writeSpace();
}
void writeComma([String string = ',']) {
write(string);
writeSpace();
}
void writeWord(String string) {
if (string.isEmpty) return;
ensureWordBoundary();
write(string);
state = WORD;
}
void ensureWordBoundary() {
if (state == WORD) {
writeSpace();
}
}
void writeIndentation() {
writeSpace(' ' * indentation);
}
void writeNode(Node node) {
if (node == null) {
writeSymbol("<Null>");
} else {
final highlight = shouldHighlight(node);
if (highlight) {
startHighlight(node);
}
if (showOffsets && node is TreeNode) {
writeWord("[${node.fileOffset}]");
}
if (showMetadata && node is TreeNode) {
writeMetadata(node);
}
node.accept(this);
if (highlight) {
endHighlight(node);
}
}
}
void writeOptionalNode(Node node) {
if (node != null) {
node.accept(this);
}
}
void writeMetadata(TreeNode node) {
if (metadata != null) {
for (var md in metadata.values) {
final nodeMetadata = md.mapping[node];
if (nodeMetadata != null) {
writeWord("[@${md.tag}=${nodeMetadata}]");
}
}
}
}
void writeAnnotatedType(DartType type, String annotation) {
writeType(type);
if (annotation != null) {
write('/');
write(annotation);
state = WORD;
}
}
void writeType(DartType type) {
if (type == null) {
write('<No DartType>');
} else {
type.accept(this);
}
}
void writeOptionalType(DartType type) {
if (type != null) {
type.accept(this);
}
}
visitSupertype(Supertype type) {
if (type == null) {
write('<No Supertype>');
} else {
writeClassReferenceFromReference(type.className);
if (type.typeArguments.isNotEmpty) {
writeSymbol('<');
writeList(type.typeArguments, writeType);
writeSymbol('>');
}
}
}
visitTypedefType(TypedefType type) {
writeTypedefReference(type.typedefNode);
if (type.typeArguments.isNotEmpty) {
writeSymbol('<');
writeList(type.typeArguments, writeType);
writeSymbol('>');
}
}
void writeModifier(bool isThere, String name) {
if (isThere) {
writeWord(name);
}
}
void writeName(Name name) {
if (name?.name == '') {
writeWord(emptyNameString);
} else {
writeWord(name?.name ?? '<anonymous>'); // TODO: write library name
}
}
void endLine([String string]) {
if (string != null) {
write(string);
}
write('\n');
state = SPACE;
column = 0;
}
void writeFunction(FunctionNode function,
{name, List<Initializer> initializers, bool terminateLine: true}) {
if (name is String) {
writeWord(name);
} else if (name is Name) {
writeName(name);
} else {
assert(name == null);
}
writeTypeParameterList(function.typeParameters);
writeParameterList(function.positionalParameters, function.namedParameters,
function.requiredParameterCount);
writeReturnType(
function.returnType, annotator?.annotateReturn(this, function));
if (initializers != null && initializers.isNotEmpty) {
endLine();
++indentation;
writeIndentation();
writeComma(':');
writeList(initializers, writeNode);
--indentation;
}
if (function.asyncMarker != AsyncMarker.Sync) {
writeSpaced(getAsyncMarkerKeyword(function.asyncMarker));
}
if (function.dartAsyncMarker != AsyncMarker.Sync &&
function.dartAsyncMarker != function.asyncMarker) {
writeSpaced("/* originally");
writeSpaced(getAsyncMarkerKeyword(function.dartAsyncMarker));
writeSpaced("*/");
}
if (function.body != null) {
writeFunctionBody(function.body, terminateLine: terminateLine);
} else if (terminateLine) {
endLine(';');
}
}
String getAsyncMarkerKeyword(AsyncMarker marker) {
switch (marker) {
case AsyncMarker.Sync:
return 'sync';
case AsyncMarker.SyncStar:
return 'sync*';
case AsyncMarker.Async:
return 'async';
case AsyncMarker.AsyncStar:
return 'async*';
case AsyncMarker.SyncYielding:
return 'yielding';
default:
return '<Invalid async marker: $marker>';
}
}
void writeFunctionBody(Statement body, {bool terminateLine: true}) {
if (body is Block && body.statements.isEmpty) {
ensureSpace();
writeSymbol('{}');
state = WORD;
if (terminateLine) {
endLine();
}
} else if (body is Block) {
ensureSpace();
endLine('{');
++indentation;
body.statements.forEach(writeNode);
--indentation;
writeIndentation();
writeSymbol('}');
state = WORD;
if (terminateLine) {
endLine();
}
} else if (body is ReturnStatement && !terminateLine) {
writeSpaced('=>');
writeExpression(body.expression);
} else {
writeBody(body);
}
}
writeFunctionType(FunctionType node,
{List<VariableDeclaration> typedefPositional,
List<VariableDeclaration> typedefNamed}) {
if (state == WORD) {
ensureSpace();
}
writeTypeParameterList(node.typeParameters);
writeSymbol('(');
List<DartType> positional = node.positionalParameters;
bool parametersAnnotated = false;
if (typedefPositional != null) {
for (VariableDeclaration formal in typedefPositional) {
parametersAnnotated =
parametersAnnotated || formal.annotations.length > 0;
}
}
if (typedefNamed != null) {
for (VariableDeclaration formal in typedefNamed) {
parametersAnnotated =
parametersAnnotated || formal.annotations.length > 0;
}
}
if (parametersAnnotated && typedefPositional != null) {
writeList(typedefPositional.take(node.requiredParameterCount),
writeVariableDeclaration);
} else {
writeList(positional.take(node.requiredParameterCount), writeType);
}
if (node.requiredParameterCount < positional.length) {
if (node.requiredParameterCount > 0) {
writeComma();
}
writeSymbol('[');
if (parametersAnnotated && typedefPositional != null) {
writeList(typedefPositional.skip(node.requiredParameterCount),
writeVariableDeclaration);
} else {
writeList(positional.skip(node.requiredParameterCount), writeType);
}
writeSymbol(']');
}
if (node.namedParameters.isNotEmpty) {
if (node.positionalParameters.isNotEmpty) {
writeComma();
}
writeSymbol('{');
if (parametersAnnotated && typedefNamed != null) {
writeList(typedefNamed, writeVariableDeclaration);
} else {
writeList(node.namedParameters, visitNamedType);
}
writeSymbol('}');
}
writeSymbol(')');
ensureSpace();
write('→');
writeNullability(node.nullability);
writeSpace();
writeType(node.returnType);
}
void writeBody(Statement body) {
if (body is Block) {
endLine(' {');
++indentation;
body.statements.forEach(writeNode);
--indentation;
writeIndentation();
endLine('}');
} else {
endLine();
++indentation;
writeNode(body);
--indentation;
}
}
void writeReturnType(DartType type, String annotation) {
if (type == null) return;
writeSpaced('→');
writeAnnotatedType(type, annotation);
}
void writeTypeParameterList(List<TypeParameter> typeParameters) {
if (typeParameters.isEmpty) return;
writeSymbol('<');
writeList(typeParameters, writeNode);
writeSymbol('>');
state = WORD; // Ensure space if not followed by another symbol.
}
void writeParameterList(List<VariableDeclaration> positional,
List<VariableDeclaration> named, int requiredParameterCount) {
writeSymbol('(');
writeList(
positional.take(requiredParameterCount), writeVariableDeclaration);
if (requiredParameterCount < positional.length) {
if (requiredParameterCount > 0) {
writeComma();
}
writeSymbol('[');
writeList(
positional.skip(requiredParameterCount), writeVariableDeclaration);
writeSymbol(']');
}
if (named.isNotEmpty) {
if (positional.isNotEmpty) {
writeComma();
}
writeSymbol('{');
writeList(named, writeVariableDeclaration);
writeSymbol('}');
}
writeSymbol(')');
}
void writeList<T>(Iterable<T> nodes, void callback(T x),
{String separator: ','}) {
bool first = true;
for (var node in nodes) {
if (first) {
first = false;
} else {
writeComma(separator);
}
callback(node);
}
}
void writeClassReferenceFromReference(Reference reference) {
writeWord(getClassReferenceFromReference(reference));
}
String getClassReferenceFromReference(Reference reference) {
if (reference == null) return '<No Class>';
if (reference.node != null) return getClassReference(reference.asClass);
if (reference.canonicalName != null)
return getCanonicalNameString(reference.canonicalName);
throw "Neither node nor canonical name found";
}
void writeMemberReferenceFromReference(Reference reference) {
writeWord(getMemberReferenceFromReference(reference));
}
String getMemberReferenceFromReference(Reference reference) {
if (reference == null) return '<No Member>';
if (reference.node != null) return getMemberReference(reference.asMember);
if (reference.canonicalName != null)
return getCanonicalNameString(reference.canonicalName);
throw "Neither node nor canonical name found";
}
String getCanonicalNameString(CanonicalName name) {
if (name.isRoot) throw 'unexpected root';
if (name.name.startsWith('@')) throw 'unexpected @';
libraryString(CanonicalName lib) {
if (lib.reference?.node != null)
return getLibraryReference(lib.reference.asLibrary);
return syntheticNames.nameCanonicalNameAsLibraryPrefix(
lib.reference, lib);
}
classString(CanonicalName cls) =>
libraryString(cls.parent) + '::' + cls.name;
if (name.parent.isRoot) return libraryString(name);
if (name.parent.parent.isRoot) return classString(name);
CanonicalName atNode = name.parent;
while (!atNode.name.startsWith('@')) atNode = atNode.parent;
String parent = "";
if (atNode.parent.parent.isRoot) {
parent = libraryString(atNode.parent);
} else {
parent = classString(atNode.parent);
}
if (name.name == '') return "$parent::$emptyNameString";
return "$parent::${name.name}";
}
void writeTypedefReference(Typedef typedefNode) {
writeWord(getTypedefReference(typedefNode));
}
void writeVariableReference(VariableDeclaration variable) {
final highlight = shouldHighlight(variable);
if (highlight) {
startHighlight(variable);
}
writeWord(getVariableReference(variable));
if (highlight) {
endHighlight(variable);
}
}
void writeTypeParameterReference(TypeParameter node) {
writeWord(getTypeParameterReference(node));
}
void writeExpression(Expression node, [int minimumPrecedence]) {
final highlight = shouldHighlight(node);
if (highlight) {
startHighlight(node);
}
if (showOffsets) writeWord("[${node.fileOffset}]");
bool needsParenteses = false;
if (minimumPrecedence != null && getPrecedence(node) < minimumPrecedence) {
needsParenteses = true;
writeSymbol('(');
}
writeNode(node);
if (needsParenteses) {
writeSymbol(')');
}
if (highlight) {
endHighlight(node);
}
}
void writeAnnotation(Expression node) {
writeSymbol('@');
if (node is ConstructorInvocation) {
writeMemberReferenceFromReference(node.targetReference);
visitArguments(node.arguments);
} else {
writeExpression(node);
}
}
void writeAnnotationList(List<Expression> nodes, {bool separateLines: true}) {
for (Expression node in nodes) {
if (separateLines) {
writeIndentation();
}
writeAnnotation(node);
if (separateLines) {
endLine();
} else {
writeSpace();
}
}
}
visitLibrary(Library node) {}
visitField(Field node) {
writeAnnotationList(node.annotations);
writeIndentation();
writeModifier(node.isLate, 'late');
writeModifier(node.isStatic, 'static');
writeModifier(node.isCovariant, 'covariant');
writeModifier(node.isGenericCovariantImpl, 'generic-covariant-impl');
writeModifier(node.isFinal, 'final');
writeModifier(node.isConst, 'const');
// Only show implicit getter/setter modifiers in cases where they are
// out of the ordinary.
if (node.isStatic) {
writeModifier(node.hasImplicitGetter, '[getter]');
writeModifier(node.hasImplicitSetter, '[setter]');
} else {
writeModifier(!node.hasImplicitGetter, '[no-getter]');
if (node.isFinal) {
writeModifier(node.hasImplicitSetter, '[setter]');
} else {
writeModifier(!node.hasImplicitSetter, '[no-setter]');
}
}
writeWord('field');
writeSpace();
writeAnnotatedType(node.type, annotator?.annotateField(this, node));
writeName(getMemberName(node));
if (node.initializer != null) {
writeSpaced('=');
writeExpression(node.initializer);
}
if ((node.enclosingClass == null &&
node.enclosingLibrary.fileUri != node.fileUri) ||
(node.enclosingClass != null &&
node.enclosingClass.fileUri != node.fileUri)) {
writeWord("/* from ${node.fileUri} */");
}
endLine(';');
}
visitProcedure(Procedure node) {
writeAnnotationList(node.annotations);
writeIndentation();
writeModifier(node.isExternal, 'external');
writeModifier(node.isStatic, 'static');
writeModifier(node.isAbstract, 'abstract');
writeModifier(node.isForwardingStub, 'forwarding-stub');
writeModifier(node.isForwardingSemiStub, 'forwarding-semi-stub');
writeModifier(node.isNoSuchMethodForwarder, 'no-such-method-forwarder');
writeWord(procedureKindToString(node.kind));
if ((node.enclosingClass == null &&
node.enclosingLibrary.fileUri != node.fileUri) ||
(node.enclosingClass != null &&
node.enclosingClass.fileUri != node.fileUri)) {
writeWord("/* from ${node.fileUri} */");
}
writeFunction(node.function, name: getMemberName(node));
}
visitConstructor(Constructor node) {
writeAnnotationList(node.annotations);
writeIndentation();
writeModifier(node.isExternal, 'external');
writeModifier(node.isConst, 'const');
writeModifier(node.isSynthetic, 'synthetic');
writeWord('constructor');
writeFunction(node.function,
name: node.name, initializers: node.initializers);
}
visitRedirectingFactoryConstructor(RedirectingFactoryConstructor node) {
writeAnnotationList(node.annotations);
writeIndentation();
writeModifier(node.isExternal, 'external');
writeModifier(node.isConst, 'const');
writeWord('redirecting_factory');
if (node.name != null) {
writeName(node.name);
}
writeTypeParameterList(node.typeParameters);
writeParameterList(node.positionalParameters, node.namedParameters,
node.requiredParameterCount);
writeSpaced('=');
writeMemberReferenceFromReference(node.targetReference);
if (node.typeArguments.isNotEmpty) {
writeSymbol('<');
writeList(node.typeArguments, writeType);
writeSymbol('>');
}
endLine(';');
}
visitClass(Class node) {
writeAnnotationList(node.annotations);
writeIndentation();
writeModifier(node.isAbstract, 'abstract');
writeWord('class');
writeWord(getClassName(node));
writeTypeParameterList(node.typeParameters);
if (node.isMixinApplication) {
writeSpaced('=');
visitSupertype(node.supertype);
writeSpaced('with');
visitSupertype(node.mixedInType);
} else if (node.supertype != null) {
writeSpaced('extends');
visitSupertype(node.supertype);
}
if (node.implementedTypes.isNotEmpty) {
writeSpaced('implements');
writeList(node.implementedTypes, visitSupertype);
}
var endLineString = ' {';
if (node.enclosingLibrary.fileUri != node.fileUri) {
endLineString += ' // from ${node.fileUri}';
}
endLine(endLineString);
++indentation;
node.fields.forEach(writeNode);
node.constructors.forEach(writeNode);
node.procedures.forEach(writeNode);
node.redirectingFactoryConstructors.forEach(writeNode);
--indentation;
writeIndentation();
endLine('}');
}
visitExtension(Extension node) {
writeIndentation();
writeWord('extension');
writeWord(getExtensionName(node));
writeTypeParameterList(node.typeParameters);
writeSpaced('on');
writeType(node.onType);
var endLineString = ' {';
if (node.enclosingLibrary.fileUri != node.fileUri) {
endLineString += ' // from ${node.fileUri}';
}
endLine(endLineString);
++indentation;
node.members.forEach((ExtensionMemberDescriptor descriptor) {
writeIndentation();
writeModifier(descriptor.isStatic, 'static');
switch (descriptor.kind) {
case ExtensionMemberKind.Method:
writeWord('method');
break;
case ExtensionMemberKind.Getter:
writeWord('get');
break;
case ExtensionMemberKind.Setter:
writeWord('set');
break;
case ExtensionMemberKind.Operator:
writeWord('operator');
break;
case ExtensionMemberKind.Field:
writeWord('field');
break;
case ExtensionMemberKind.TearOff:
writeWord('tearoff');
break;
}
writeName(descriptor.name);
writeSpaced('=');
Member member = descriptor.member.asMember;
if (member is Procedure) {
if (member.isGetter) {
writeWord('get');
} else if (member.isSetter) {
writeWord('set');
}
}
writeMemberReferenceFromReference(descriptor.member);
endLine(';');
});
--indentation;
writeIndentation();
endLine('}');
}
visitTypedef(Typedef node) {
writeAnnotationList(node.annotations);
writeIndentation();
writeWord('typedef');
writeWord(node.name);
writeTypeParameterList(node.typeParameters);
writeSpaced('=');
if (node.type is FunctionType) {
writeFunctionType(node.type,
typedefPositional: node.positionalParameters,
typedefNamed: node.namedParameters);
} else {
writeNode(node.type);
}
endLine(';');
}
visitInvalidExpression(InvalidExpression node) {
writeWord('invalid-expression');
if (node.message != null) {
writeWord('"${escapeString(node.message)}"');
}
}
visitMethodInvocation(MethodInvocation node) {
writeExpression(node.receiver, Precedence.PRIMARY);
writeSymbol('.');
writeInterfaceTarget(node.name, node.interfaceTargetReference);
writeNode(node.arguments);
}
visitDirectMethodInvocation(DirectMethodInvocation node) {
writeExpression(node.receiver, Precedence.PRIMARY);
writeSymbol('.{=');
writeMemberReferenceFromReference(node.targetReference);
writeSymbol('}');
writeNode(node.arguments);
}
visitSuperMethodInvocation(SuperMethodInvocation node) {
writeWord('super');
writeSymbol('.');
writeInterfaceTarget(node.name, node.interfaceTargetReference);
writeNode(node.arguments);
}
visitStaticInvocation(StaticInvocation node) {
writeModifier(node.isConst, 'const');
writeMemberReferenceFromReference(node.targetReference);
writeNode(node.arguments);
}
visitConstructorInvocation(ConstructorInvocation node) {
writeWord(node.isConst ? 'const' : 'new');
writeMemberReferenceFromReference(node.targetReference);
writeNode(node.arguments);
}
visitNot(Not node) {
writeSymbol('!');
writeExpression(node.operand, Precedence.PREFIX);
}
visitNullCheck(NullCheck node) {
writeExpression(node.operand, Precedence.POSTFIX);
writeSymbol('!');
}
visitLogicalExpression(LogicalExpression node) {
int precedence = Precedence.binaryPrecedence[node.operator];
writeExpression(node.left, precedence);
writeSpaced(node.operator);
writeExpression(node.right, precedence + 1);
}
visitConditionalExpression(ConditionalExpression node) {
writeExpression(node.condition, Precedence.LOGICAL_OR);
ensureSpace();
write('?');
writeStaticType(node.staticType);
writeSpace();
writeExpression(node.then);
writeSpaced(':');
writeExpression(node.otherwise);
}
String getEscapedCharacter(int codeUnit) {
switch (codeUnit) {
case 9:
return r'\t';
case 10:
return r'\n';
case 11:
return r'\v';
case 12:
return r'\f';
case 13:
return r'\r';
case 34:
return r'\"';
case 36:
return r'\$';
case 92:
return r'\\';
default:
if (codeUnit < 32 || codeUnit > 126) {
return r'\u' + '$codeUnit'.padLeft(4, '0');
} else {
return null;
}
}
}
String escapeString(String string) {
StringBuffer buffer;
for (int i = 0; i < string.length; ++i) {
String character = getEscapedCharacter(string.codeUnitAt(i));
if (character != null) {
buffer ??= new StringBuffer(string.substring(0, i));
buffer.write(character);
} else {
buffer?.write(string[i]);
}
}
return buffer == null ? string : buffer.toString();
}
visitStringConcatenation(StringConcatenation node) {
if (state == WORD) {
writeSpace();
}
write('"');
for (var part in node.expressions) {
if (part is StringLiteral) {
writeSymbol(escapeString(part.value));
} else {
writeSymbol(r'${');
writeExpression(part);
writeSymbol('}');
}
}
write('"');
state = WORD;
}
visitListConcatenation(ListConcatenation node) {
bool first = true;
for (Expression part in node.lists) {
if (!first) writeSpaced('+');
writeExpression(part);
first = false;
}
}
visitSetConcatenation(SetConcatenation node) {
bool first = true;
for (Expression part in node.sets) {
if (!first) writeSpaced('+');
writeExpression(part);
first = false;
}
}
visitMapConcatenation(MapConcatenation node) {
bool first = true;
for (Expression part in node.maps) {
if (!first) writeSpaced('+');
writeExpression(part);
first = false;
}
}
visitInstanceCreation(InstanceCreation node) {
writeClassReferenceFromReference(node.classReference);
if (node.typeArguments.isNotEmpty) {
writeSymbol('<');
writeList(node.typeArguments, writeType);
writeSymbol('>');
}
writeSymbol('{');
bool first = true;
node.fieldValues.forEach((Reference fieldRef, Expression value) {
if (!first) {
writeComma();
}
writeWord('${fieldRef.asField.name.name}');
writeSymbol(':');
writeExpression(value);
first = false;
});
for (AssertStatement assert_ in node.asserts) {
if (!first) {
writeComma();
}
write('assert(');
writeExpression(assert_.condition);
if (assert_.message != null) {
writeComma();
writeExpression(assert_.message);
}
write(')');
first = false;
}
for (Expression unusedArgument in node.unusedArguments) {
if (!first) {
writeComma();
}
writeExpression(unusedArgument);
first = false;
}
writeSymbol('}');
}
visitFileUriExpression(FileUriExpression node) {
writeExpression(node.expression);
}
visitIsExpression(IsExpression node) {
writeExpression(node.operand, Precedence.BITWISE_OR);
writeSpaced('is');
writeType(node.type);
}
visitAsExpression(AsExpression node) {
writeExpression(node.operand, Precedence.BITWISE_OR);
writeSpaced(node.isTypeError ? 'as{TypeError}' : 'as');
writeType(node.type);
}
visitSymbolLiteral(SymbolLiteral node) {
writeSymbol('#');
writeWord(node.value);
}
visitTypeLiteral(TypeLiteral node) {
writeType(node.type);
}
visitThisExpression(ThisExpression node) {
writeWord('this');
}
visitRethrow(Rethrow node) {
writeWord('rethrow');
}
visitThrow(Throw node) {
writeWord('throw');
writeSpace();
writeExpression(node.expression);
}
visitListLiteral(ListLiteral node) {
if (node.isConst) {
writeWord('const');
writeSpace();
}
if (node.typeArgument != null) {
writeSymbol('<');
writeType(node.typeArgument);
writeSymbol('>');
}
writeSymbol('[');
writeList(node.expressions, writeNode);
writeSymbol(']');
}
visitSetLiteral(SetLiteral node) {
if (node.isConst) {
writeWord('const');
writeSpace();
}
if (node.typeArgument != null) {
writeSymbol('<');
writeType(node.typeArgument);
writeSymbol('>');
}
writeSymbol('{');
writeList(node.expressions, writeNode);
writeSymbol('}');
}
visitMapLiteral(MapLiteral node) {
if (node.isConst) {
writeWord('const');
writeSpace();
}
if (node.keyType != null) {
writeSymbol('<');
writeList([node.keyType, node.valueType], writeType);
writeSymbol('>');
}
writeSymbol('{');
writeList(node.entries, writeNode);
writeSymbol('}');
}
visitMapEntry(MapEntry node) {
writeExpression(node.key);
writeComma(':');
writeExpression(node.value);
}
visitAwaitExpression(AwaitExpression node) {
writeWord('await');
writeExpression(node.operand);
}
visitFunctionExpression(FunctionExpression node) {
writeFunction(node.function, terminateLine: false);
}
visitStringLiteral(StringLiteral node) {
writeWord('"${escapeString(node.value)}"');
}
visitIntLiteral(IntLiteral node) {
writeWord('${node.value}');
}
visitDoubleLiteral(DoubleLiteral node) {
writeWord('${node.value}');
}
visitBoolLiteral(BoolLiteral node) {
writeWord('${node.value}');
}
visitNullLiteral(NullLiteral node) {
writeWord('null');
}
visitLet(Let node) {
writeWord('let');
writeVariableDeclaration(node.variable);
writeSpaced('in');
writeExpression(node.body);
}
visitBlockExpression(BlockExpression node) {
writeSpaced('block');
writeBlockBody(node.body.statements, asExpression: true);
writeSymbol(' =>');
writeExpression(node.value);
}
visitInstantiation(Instantiation node) {
writeExpression(node.expression);
writeSymbol('<');
writeList(node.typeArguments, writeType);
writeSymbol('>');
}
visitLoadLibrary(LoadLibrary node) {
writeWord('LoadLibrary');
writeSymbol('(');
writeWord(node.import.name);
writeSymbol(')');
state = WORD;
}
visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) {
writeWord('CheckLibraryIsLoaded');
writeSymbol('(');
writeWord(node.import.name);
writeSymbol(')');
state = WORD;
}
visitLibraryPart(LibraryPart node) {
writeAnnotationList(node.annotations);
writeIndentation();
writeWord('part');
writeWord(node.partUri);
endLine(";");
}
visitLibraryDependency(LibraryDependency node) {
writeIndentation();
writeWord(node.isImport ? 'import' : 'export');
var uriString;
if (node.importedLibraryReference?.node != null) {
uriString = '${node.targetLibrary.importUri}';
} else {
uriString = '${node.importedLibraryReference?.canonicalName?.name}';
}
writeWord('"$uriString"');
if (node.isDeferred) {
writeWord('deferred');
}
if (node.name != null) {
writeWord('as');
writeWord(node.name);
}
endLine(';');
}
defaultExpression(Expression node) {
writeWord('${node.runtimeType}');
}
visitVariableGet(VariableGet node) {
writeVariableReference(node.variable);
if (node.promotedType != null) {
writeSymbol('{');
writeNode(node.promotedType);
writeSymbol('}');
state = WORD;
}
}
visitVariableSet(VariableSet node) {
writeVariableReference(node.variable);
writeSpaced('=');
writeExpression(node.value);
}
void writeInterfaceTarget(Name name, Reference target) {
if (target != null) {
writeSymbol('{');
writeMemberReferenceFromReference(target);
writeSymbol('}');
} else {
writeName(name);
}
}
void writeStaticType(DartType type) {
if (type != null) {
writeSymbol('{');
writeType(type);
writeSymbol('}');
}
}
visitPropertyGet(PropertyGet node) {
writeExpression(node.receiver, Precedence.PRIMARY);
writeSymbol('.');
writeInterfaceTarget(node.name, node.interfaceTargetReference);
}
visitPropertySet(PropertySet node) {
writeExpression(node.receiver, Precedence.PRIMARY);
writeSymbol('.');
writeInterfaceTarget(node.name, node.interfaceTargetReference);
writeSpaced('=');
writeExpression(node.value);
}
visitSuperPropertyGet(SuperPropertyGet node) {
writeWord('super');
writeSymbol('.');
writeInterfaceTarget(node.name, node.interfaceTargetReference);
}
visitSuperPropertySet(SuperPropertySet node) {
writeWord('super');
writeSymbol('.');
writeInterfaceTarget(node.name, node.interfaceTargetReference);
writeSpaced('=');
writeExpression(node.value);
}
visitDirectPropertyGet(DirectPropertyGet node) {
writeExpression(node.receiver, Precedence.PRIMARY);
writeSymbol('.{=');
writeMemberReferenceFromReference(node.targetReference);
writeSymbol('}');
}
visitDirectPropertySet(DirectPropertySet node) {
writeExpression(node.receiver, Precedence.PRIMARY);
writeSymbol('.{=');
writeMemberReferenceFromReference(node.targetReference);
writeSymbol('}');
writeSpaced('=');
writeExpression(node.value);
}
visitStaticGet(StaticGet node) {
writeMemberReferenceFromReference(node.targetReference);
}
visitStaticSet(StaticSet node) {
writeMemberReferenceFromReference(node.targetReference);
writeSpaced('=');
writeExpression(node.value);
}
visitExpressionStatement(ExpressionStatement node) {
writeIndentation();
writeExpression(node.expression);
endLine(';');
}
void writeBlockBody(List<Statement> statements, {bool asExpression = false}) {
if (statements.isEmpty) {
asExpression ? writeSymbol('{}') : endLine('{}');
return;
}
endLine('{');
++indentation;
statements.forEach(writeNode);
--indentation;
writeIndentation();
asExpression ? writeSymbol('}') : endLine('}');
}
visitBlock(Block node) {
writeIndentation();
writeBlockBody(node.statements);
}
visitAssertBlock(AssertBlock node) {
writeIndentation();
writeSpaced('assert');
writeBlockBody(node.statements);
}
visitEmptyStatement(EmptyStatement node) {
writeIndentation();
endLine(';');
}
visitAssertStatement(AssertStatement node, {bool asExpression = false}) {
if (!asExpression) {
writeIndentation();
}
writeWord('assert');
writeSymbol('(');
writeExpression(node.condition);
if (node.message != null) {
writeComma();
writeExpression(node.message);
}
if (!asExpression) {
endLine(');');
} else {
writeSymbol(')');
}
}
visitLabeledStatement(LabeledStatement node) {
writeIndentation();
writeWord(syntheticNames.nameLabeledStatement(node));
endLine(':');
writeNode(node.body);
}
visitBreakStatement(BreakStatement node) {
writeIndentation();
writeWord('break');
writeWord(syntheticNames.nameLabeledStatement(node.target));
endLine(';');
}
visitWhileStatement(WhileStatement node) {
writeIndentation();
writeSpaced('while');
writeSymbol('(');
writeExpression(node.condition);
writeSymbol(')');
writeBody(node.body);
}
visitDoStatement(DoStatement node) {
writeIndentation();
writeWord('do');
writeBody(node.body);
writeIndentation();
writeSpaced('while');
writeSymbol('(');
writeExpression(node.condition);
endLine(')');
}
visitForStatement(ForStatement node) {
writeIndentation();
writeSpaced('for');
writeSymbol('(');
writeList(node.variables, writeVariableDeclaration);
writeComma(';');
if (node.condition != null) {
writeExpression(node.condition);
}
writeComma(';');
writeList(node.updates, writeExpression);
writeSymbol(')');
writeBody(node.body);
}
visitForInStatement(ForInStatement node) {
writeIndentation();
if (node.isAsync) {
writeSpaced('await');
}
writeSpaced('for');
writeSymbol('(');
writeVariableDeclaration(node.variable, useVarKeyword: true);
writeSpaced('in');
writeExpression(node.iterable);
writeSymbol(')');
writeBody(node.body);
}
visitSwitchStatement(SwitchStatement node) {
writeIndentation();
writeWord('switch');
writeSymbol('(');
writeExpression(node.expression);
endLine(') {');
++indentation;
node.cases.forEach(writeNode);
--indentation;
writeIndentation();
endLine('}');
}
visitSwitchCase(SwitchCase node) {
String label = syntheticNames.nameSwitchCase(node);
writeIndentation();
writeWord(label);
endLine(':');
for (var expression in node.expressions) {
writeIndentation();
writeWord('case');
writeExpression(expression);
endLine(':');
}
if (node.isDefault) {
writeIndentation();
writeWord('default');
endLine(':');
}
++indentation;
writeNode(node.body);
--indentation;
}
visitContinueSwitchStatement(ContinueSwitchStatement node) {
writeIndentation();
writeWord('continue');
writeWord(syntheticNames.nameSwitchCase(node.target));
endLine(';');
}
visitIfStatement(IfStatement node) {
writeIndentation();
writeWord('if');
writeSymbol('(');
writeExpression(node.condition);
writeSymbol(')');
writeBody(node.then);
if (node.otherwise != null) {
writeIndentation();
writeWord('else');
writeBody(node.otherwise);
}
}
visitReturnStatement(ReturnStatement node) {
writeIndentation();
writeWord('return');
if (node.expression != null) {
writeSpace();
writeExpression(node.expression);
}
endLine(';');
}
visitTryCatch(TryCatch node) {
writeIndentation();
writeWord('try');
writeBody(node.body);
node.catches.forEach(writeNode);
}
visitCatch(Catch node) {
writeIndentation();
if (node.guard != null) {
writeWord('on');
writeType(node.guard);
writeSpace();
}
writeWord('catch');
writeSymbol('(');
if (node.exception != null) {
writeVariableDeclaration(node.exception);
} else {
writeWord('no-exception-var');
}
if (node.stackTrace != null) {
writeComma();
writeVariableDeclaration(node.stackTrace);
}
writeSymbol(')');
writeBody(node.body);
}
visitTryFinally(TryFinally node) {
writeIndentation();
writeWord('try');
writeBody(node.body);
writeIndentation();
writeWord('finally');
writeBody(node.finalizer);
}
visitYieldStatement(YieldStatement node) {
writeIndentation();
if (node.isYieldStar) {
writeWord('yield*');
} else if (node.isNative) {
writeWord('[yield]');
} else {
writeWord('yield');
}
writeExpression(node.expression);
endLine(';');
}
visitVariableDeclaration(VariableDeclaration node) {
writeIndentation();
writeVariableDeclaration(node, useVarKeyword: true);
endLine(';');
}
visitFunctionDeclaration(FunctionDeclaration node) {
writeAnnotationList(node.variable.annotations);
writeIndentation();
writeWord('function');
if (node.function != null) {
writeFunction(node.function, name: getVariableName(node.variable));
} else {
writeWord(getVariableName(node.variable));
endLine('...;');
}
}
void writeVariableDeclaration(VariableDeclaration node,
{bool useVarKeyword: false}) {
if (showOffsets) writeWord("[${node.fileOffset}]");
if (showMetadata) writeMetadata(node);
writeAnnotationList(node.annotations, separateLines: false);
writeModifier(node.isLate, 'late');
writeModifier(node.isRequired, 'required');
writeModifier(node.isCovariant, 'covariant');
writeModifier(node.isGenericCovariantImpl, 'generic-covariant-impl');
writeModifier(node.isFinal, 'final');
writeModifier(node.isConst, 'const');
if (node.type != null) {
writeAnnotatedType(node.type, annotator?.annotateVariable(this, node));
}
if (useVarKeyword && !node.isFinal && !node.isConst && node.type == null) {
writeWord('var');
}
writeWord(getVariableName(node));
if (node.initializer != null) {
writeSpaced('=');
writeExpression(node.initializer);
}
}
visitArguments(Arguments node) {
if (node.types.isNotEmpty) {
writeSymbol('<');
writeList(node.types, writeType);
writeSymbol('>');
}
writeSymbol('(');
var allArgs =
<List<TreeNode>>[node.positional, node.named].expand((x) => x);
writeList(allArgs, writeNode);
writeSymbol(')');
}
visitNamedExpression(NamedExpression node) {
writeWord(node.name);
writeComma(':');
writeExpression(node.value);
}
defaultStatement(Statement node) {
writeIndentation();
endLine('${node.runtimeType}');
}
visitInvalidInitializer(InvalidInitializer node) {
writeWord('invalid-initializer');
}
visitFieldInitializer(FieldInitializer node) {
writeMemberReferenceFromReference(node.fieldReference);
writeSpaced('=');
writeExpression(node.value);
}
visitSuperInitializer(SuperInitializer node) {
writeWord('super');
writeMemberReferenceFromReference(node.targetReference);
writeNode(node.arguments);
}
visitRedirectingInitializer(RedirectingInitializer node) {
writeWord('this');
writeMemberReferenceFromReference(node.targetReference);
writeNode(node.arguments);
}
visitLocalInitializer(LocalInitializer node) {
writeVariableDeclaration(node.variable);
}
visitAssertInitializer(AssertInitializer node) {
visitAssertStatement(node.statement, asExpression: true);
}
defaultInitializer(Initializer node) {
writeIndentation();
endLine(': ${node.runtimeType}');
}
void writeNullability(Nullability nullability, {bool inComment = false}) {
switch (nullability) {
case Nullability.legacy:
writeSymbol('*');
if (!inComment) {
state = WORD; // Disallow a word immediately after the '*'.
}
break;
case Nullability.nullable:
writeSymbol('?');
if (!inComment) {
state = WORD; // Disallow a word immediately after the '?'.
}
break;
case Nullability.neither:
writeSymbol('%');
if (!inComment) {
state = WORD; // Disallow a word immediately after the '%'.
}
break;
case Nullability.nonNullable:
if (inComment) {
writeSymbol("!");
}
break;
}
}
void writeDartTypeNullability(DartType type, {bool inComment = false}) {
if (type is InvalidType) {
writeNullability(Nullability.neither);
} else {
writeNullability(type.nullability, inComment: inComment);
}
}
visitInvalidType(InvalidType node) {
writeWord('invalid-type');
}
visitDynamicType(DynamicType node) {
writeWord('dynamic');
}
visitVoidType(VoidType node) {
writeWord('void');
}
visitInterfaceType(InterfaceType node) {
writeClassReferenceFromReference(node.className);
if (node.typeArguments.isNotEmpty) {
writeSymbol('<');
writeList(node.typeArguments, writeType);
writeSymbol('>');
state = WORD; // Disallow a word immediately after the '>'.
}
writeNullability(node.nullability);
}
visitFunctionType(FunctionType node) {
writeFunctionType(node);
}
visitNamedType(NamedType node) {
writeModifier(node.isRequired, 'required');
writeWord(node.name);
writeSymbol(':');
writeSpace();
writeType(node.type);
}
visitTypeParameterType(TypeParameterType node) {
writeTypeParameterReference(node.parameter);
writeNullability(node.typeParameterTypeNullability);
if (node.promotedBound != null) {
writeSpaced('&');
writeType(node.promotedBound);
writeWord("/* '");
writeNullability(node.typeParameterTypeNullability, inComment: true);
writeWord("' & '");
writeDartTypeNullability(node.promotedBound, inComment: true);
writeWord("' = '");
writeNullability(node.nullability, inComment: true);
writeWord("' */");
}
}
visitTypeParameter(TypeParameter node) {
writeModifier(node.isGenericCovariantImpl, 'generic-covariant-impl');
writeAnnotationList(node.annotations, separateLines: false);
if (node.variance != Variance.covariant) {
writeWord(const <String>[
"unrelated",
"covariant",
"contravariant",
"invariant"
][node.variance]);
}
writeWord(getTypeParameterName(node));
writeSpaced('extends');
writeType(node.bound);
if (node.defaultType != null) {
writeSpaced('=');
writeType(node.defaultType);
}
}
void writeConstantReference(Constant node) {
writeWord(syntheticNames.nameConstant(node));
}
visitConstantExpression(ConstantExpression node) {
writeConstantReference(node.constant);
}
defaultConstant(Constant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
endLine('$node');
}
visitListConstant(ListConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
writeSymbol('<');
writeType(node.typeArgument);
writeSymbol('>[');
writeList(node.entries, writeConstantReference);
endLine(']');
}
visitSetConstant(SetConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
writeSymbol('<');
writeType(node.typeArgument);
writeSymbol('>{');
writeList(node.entries, writeConstantReference);
endLine('}');
}
visitMapConstant(MapConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
writeSymbol('<');
writeList([node.keyType, node.valueType], writeType);
writeSymbol('>{');
writeList(node.entries, (entry) {
writeConstantReference(entry.key);
writeSymbol(':');
writeConstantReference(entry.value);
});
endLine(')');
}
visitInstanceConstant(InstanceConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
writeClassReferenceFromReference(node.classReference);
if (!node.typeArguments.isEmpty) {
writeSymbol('<');
writeList(node.typeArguments, writeType);
writeSymbol('>');
}
writeSymbol(' {');
writeList(node.fieldValues.entries,
(core.MapEntry<Reference, Constant> entry) {
if (entry.key.node != null) {
writeWord('${entry.key.asField.name.name}');
} else {
writeWord('${entry.key.canonicalName.name}');
}
writeSymbol(':');
writeConstantReference(entry.value);
});
endLine('}');
}
visitPartialInstantiationConstant(PartialInstantiationConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
writeWord('partial-instantiation');
writeSpace();
writeMemberReferenceFromReference(node.tearOffConstant.procedureReference);
writeSpace();
writeSymbol('<');
writeList(node.types, writeType);
writeSymbol('>');
endLine();
}
visitStringConstant(StringConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
endLine('"${escapeString(node.value)}"');
}
visitTearOffConstant(TearOffConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
writeWord('tearoff');
writeSpace();
writeMemberReferenceFromReference(node.procedureReference);
endLine();
}
visitUnevaluatedConstant(UnevaluatedConstant node) {
writeIndentation();
writeConstantReference(node);
writeSpaced('=');
writeSymbol('eval');
writeSpace();
writeExpression(node.expression);
endLine();
}
defaultNode(Node node) {
write('<${node.runtimeType}>');
}
}
class Precedence extends ExpressionVisitor<int> {
static final Precedence instance = new Precedence();
static int of(Expression node) => node.accept(instance);
static const int EXPRESSION = 1;
static const int CONDITIONAL = 2;
static const int LOGICAL_NULL_AWARE = 3;
static const int LOGICAL_OR = 4;
static const int LOGICAL_AND = 5;
static const int EQUALITY = 6;
static const int RELATIONAL = 7;
static const int BITWISE_OR = 8;
static const int BITWISE_XOR = 9;
static const int BITWISE_AND = 10;
static const int SHIFT = 11;
static const int ADDITIVE = 12;
static const int MULTIPLICATIVE = 13;
static const int PREFIX = 14;
static const int POSTFIX = 15;
static const int TYPE_LITERAL = 19;
static const int PRIMARY = 20;
static const int CALLEE = 21;
static const Map<String, int> binaryPrecedence = const {
'&&': LOGICAL_AND,
'||': LOGICAL_OR,
'??': LOGICAL_NULL_AWARE,
'==': EQUALITY,
'!=': EQUALITY,
'>': RELATIONAL,
'>=': RELATIONAL,
'<': RELATIONAL,
'<=': RELATIONAL,
'|': BITWISE_OR,
'^': BITWISE_XOR,
'&': BITWISE_AND,
'>>': SHIFT,
'<<': SHIFT,
'+': ADDITIVE,
'-': ADDITIVE,
'*': MULTIPLICATIVE,
'%': MULTIPLICATIVE,
'/': MULTIPLICATIVE,
'~/': MULTIPLICATIVE,
null: EXPRESSION,
};
static bool isAssociativeBinaryOperator(int precedence) {
return precedence != EQUALITY && precedence != RELATIONAL;
}
int defaultExpression(Expression node) => EXPRESSION;
int visitInvalidExpression(InvalidExpression node) => CALLEE;
int visitMethodInvocation(MethodInvocation node) => CALLEE;
int visitSuperMethodInvocation(SuperMethodInvocation node) => CALLEE;
int visitDirectMethodInvocation(DirectMethodInvocation node) => CALLEE;
int visitStaticInvocation(StaticInvocation node) => CALLEE;
int visitConstructorInvocation(ConstructorInvocation node) => CALLEE;
int visitNot(Not node) => PREFIX;
int visitNullCheck(NullCheck node) => PRIMARY;
int visitLogicalExpression(LogicalExpression node) =>
binaryPrecedence[node.operator];
int visitConditionalExpression(ConditionalExpression node) => CONDITIONAL;
int visitStringConcatenation(StringConcatenation node) => PRIMARY;
int visitIsExpression(IsExpression node) => RELATIONAL;
int visitAsExpression(AsExpression node) => RELATIONAL;
int visitSymbolLiteral(SymbolLiteral node) => PRIMARY;
int visitTypeLiteral(TypeLiteral node) => PRIMARY;
int visitThisExpression(ThisExpression node) => CALLEE;
int visitRethrow(Rethrow node) => PRIMARY;
int visitThrow(Throw node) => EXPRESSION;
int visitListLiteral(ListLiteral node) => PRIMARY;
int visitSetLiteral(SetLiteral node) => PRIMARY;
int visitMapLiteral(MapLiteral node) => PRIMARY;
int visitAwaitExpression(AwaitExpression node) => PREFIX;
int visitFunctionExpression(FunctionExpression node) => EXPRESSION;
int visitStringLiteral(StringLiteral node) => CALLEE;
int visitIntLiteral(IntLiteral node) => CALLEE;
int visitDoubleLiteral(DoubleLiteral node) => CALLEE;
int visitBoolLiteral(BoolLiteral node) => CALLEE;
int visitNullLiteral(NullLiteral node) => CALLEE;
int visitVariableGet(VariableGet node) => PRIMARY;
int visitVariableSet(VariableSet node) => EXPRESSION;
int visitPropertyGet(PropertyGet node) => PRIMARY;
int visitPropertySet(PropertySet node) => EXPRESSION;
int visitSuperPropertyGet(SuperPropertyGet node) => PRIMARY;
int visitSuperPropertySet(SuperPropertySet node) => EXPRESSION;
int visitDirectPropertyGet(DirectPropertyGet node) => PRIMARY;
int visitDirectPropertySet(DirectPropertySet node) => EXPRESSION;
int visitStaticGet(StaticGet node) => PRIMARY;
int visitStaticSet(StaticSet node) => EXPRESSION;
int visitLet(Let node) => EXPRESSION;
}
String procedureKindToString(ProcedureKind kind) {
switch (kind) {
case ProcedureKind.Method:
return 'method';
case ProcedureKind.Getter:
return 'get';
case ProcedureKind.Setter:
return 'set';
case ProcedureKind.Operator:
return 'operator';
case ProcedureKind.Factory:
return 'factory';
}
throw 'illegal ProcedureKind: $kind';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/text/text_serialization_verifier.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import '../ast.dart';
import '../text/serializer_combinators.dart'
show DeserializationState, SerializationState, TextSerializer;
import '../text/text_reader.dart' show TextIterator;
import '../text/text_serializer.dart'
show
dartTypeSerializer,
expressionSerializer,
initializeSerializers,
statementSerializer;
import '../visitor.dart' show Visitor;
const Uri noUri = null;
const int noOffset = -1;
abstract class TextSerializationVerificationFailure {
/// [Uri] of the file containing the expression that produced an error during
/// the round trip.
final Uri uri;
/// Offset within the file with [uri] of the expression that produced an error
/// during the round trip.
final int offset;
TextSerializationVerificationFailure(this.uri, this.offset);
}
class TextSerializationFailure extends TextSerializationVerificationFailure {
final String message;
TextSerializationFailure(this.message, Uri uri, int offset)
: super(uri, offset);
}
class TextDeserializationFailure extends TextSerializationVerificationFailure {
final String message;
TextDeserializationFailure(this.message, Uri uri, int offset)
: super(uri, offset);
}
class TextRoundTripFailure extends TextSerializationVerificationFailure {
final String initial;
final String serialized;
TextRoundTripFailure(this.initial, this.serialized, Uri uri, int offset)
: super(uri, offset);
}
class TextSerializationVerifier implements Visitor<void> {
/// List of errors produced during round trips on the visited nodes.
final List<TextSerializationVerificationFailure> failures =
<TextSerializationVerificationFailure>[];
Uri lastSeenUri = noUri;
int lastSeenOffset = noOffset;
TextSerializationVerifier() {
initializeSerializers();
}
void storeLastSeenUriAndOffset(Node node) {
if (node is TreeNode) {
Location location = node.location;
if (location != null) {
lastSeenUri = location.file;
lastSeenOffset = node.fileOffset;
}
}
}
T readNode<T extends Node>(
String input, TextSerializer<T> serializer, Uri uri, int offset) {
TextIterator stream = new TextIterator(input, 0);
stream.moveNext();
T result;
try {
result = serializer.readFrom(
stream, new DeserializationState(null, new CanonicalName.root()));
} catch (exception) {
failures.add(
new TextDeserializationFailure(exception.toString(), uri, offset));
}
if (stream.moveNext()) {
failures.add(new TextDeserializationFailure(
"unexpected trailing text", uri, offset));
}
return result;
}
String writeNode<T extends Node>(
T node, TextSerializer<T> serializer, Uri uri, int offset) {
StringBuffer buffer = new StringBuffer();
try {
serializer.writeTo(buffer, node, new SerializationState(null));
} catch (exception) {
failures
.add(new TextSerializationFailure(exception.toString(), uri, offset));
}
return buffer.toString();
}
void makeExpressionRoundTrip(Expression node) {
Uri uri = noUri;
int offset = noOffset;
Location location = node.location;
if (location != null) {
uri = location.file;
offset = node.fileOffset;
}
String initial = writeNode(node, expressionSerializer, uri, offset);
// Do the round trip.
Expression deserialized =
readNode(initial, expressionSerializer, uri, offset);
String serialized =
writeNode(deserialized, expressionSerializer, uri, offset);
if (initial != serialized) {
failures.add(new TextRoundTripFailure(initial, serialized, uri, offset));
}
}
void makeDartTypeRoundTrip(DartType node) {
Uri uri = lastSeenUri;
int offset = lastSeenOffset;
String initial = writeNode(node, dartTypeSerializer, uri, offset);
// Do the round trip.
DartType deserialized = readNode(initial, dartTypeSerializer, uri, offset);
String serialized =
writeNode(deserialized, dartTypeSerializer, uri, offset);
if (initial != serialized) {
failures.add(new TextRoundTripFailure(initial, serialized, uri, offset));
}
}
void makeStatementRoundTrip(Statement node) {
Uri uri = noUri;
int offset = noOffset;
Location location = node.location;
if (location != null) {
uri = location.file;
offset = node.fileOffset;
}
String initial = writeNode(node, statementSerializer, uri, offset);
// Do the round trip.
Statement deserialized =
readNode(initial, statementSerializer, uri, offset);
String serialized =
writeNode(deserialized, expressionSerializer, uri, offset);
if (initial != serialized) {
failures.add(new TextRoundTripFailure(initial, serialized, uri, offset));
}
}
@override
void defaultExpression(Expression node) {
throw new UnsupportedError("defaultExpression");
}
@override
void defaultMemberReference(Member node) {
throw new UnsupportedError("defaultMemberReference");
}
@override
void defaultConstantReference(Constant node) {
throw new UnsupportedError("defaultConstantReference");
}
@override
void defaultConstant(Constant node) {
throw new UnsupportedError("defaultConstant");
}
@override
void defaultDartType(DartType node) {
throw new UnsupportedError("defaultDartType");
}
@override
void defaultTreeNode(TreeNode node) {
throw new UnsupportedError("defaultTreeNode");
}
@override
void defaultNode(Node node) {
throw new UnsupportedError("defaultNode");
}
@override
void defaultInitializer(Initializer node) {
throw new UnsupportedError("defaultInitializer");
}
@override
void defaultMember(Member node) {
throw new UnsupportedError("defaultMember");
}
@override
void defaultStatement(Statement node) {
throw new UnsupportedError("defaultStatement");
}
@override
void defaultBasicLiteral(BasicLiteral node) {
throw new UnsupportedError("defaultBasicLiteral");
}
@override
void visitNamedType(NamedType node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitSupertype(Supertype node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitName(Name node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitRedirectingFactoryConstructorReference(
RedirectingFactoryConstructor node) {}
@override
void visitProcedureReference(Procedure node) {}
@override
void visitConstructorReference(Constructor node) {}
@override
void visitFieldReference(Field node) {}
@override
void visitTypeLiteralConstantReference(TypeLiteralConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitTearOffConstantReference(TearOffConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitPartialInstantiationConstantReference(
PartialInstantiationConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitInstanceConstantReference(InstanceConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitListConstantReference(ListConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitSetConstantReference(SetConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitMapConstantReference(MapConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitSymbolConstantReference(SymbolConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitStringConstantReference(StringConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitDoubleConstantReference(DoubleConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitIntConstantReference(IntConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitBoolConstantReference(BoolConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitNullConstantReference(NullConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitUnevaluatedConstantReference(UnevaluatedConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitTypedefReference(Typedef node) {}
@override
void visitClassReference(Class node) {}
@override
void visitTypeLiteralConstant(TypeLiteralConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitTearOffConstant(TearOffConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitPartialInstantiationConstant(PartialInstantiationConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitInstanceConstant(InstanceConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitListConstant(ListConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitSetConstant(SetConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitMapConstant(MapConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitInstanceCreation(InstanceCreation node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitFileUriExpression(FileUriExpression node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitSymbolConstant(SymbolConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitStringConstant(StringConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitDoubleConstant(DoubleConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitIntConstant(IntConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitBoolConstant(BoolConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitNullConstant(NullConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitUnevaluatedConstant(UnevaluatedConstant node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitTypedefType(TypedefType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitTypeParameterType(TypeParameterType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitFunctionType(FunctionType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitInterfaceType(InterfaceType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitBottomType(BottomType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitVoidType(VoidType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitDynamicType(DynamicType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitInvalidType(InvalidType node) {
storeLastSeenUriAndOffset(node);
makeDartTypeRoundTrip(node);
}
@override
void visitComponent(Component node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitMapEntry(MapEntry node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitCatch(Catch node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitSwitchCase(SwitchCase node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitNamedExpression(NamedExpression node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitArguments(Arguments node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitFunctionNode(FunctionNode node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitTypeParameter(TypeParameter node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitTypedef(Typedef node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitLibraryPart(LibraryPart node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitCombinator(Combinator node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitLibraryDependency(LibraryDependency node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitLibrary(Library node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitAssertInitializer(AssertInitializer node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitLocalInitializer(LocalInitializer node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitRedirectingInitializer(RedirectingInitializer node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitSuperInitializer(SuperInitializer node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitFieldInitializer(FieldInitializer node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitInvalidInitializer(InvalidInitializer node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitClass(Class node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitExtension(Extension node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitRedirectingFactoryConstructor(RedirectingFactoryConstructor node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitField(Field node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitProcedure(Procedure node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitConstructor(Constructor node) {
storeLastSeenUriAndOffset(node);
node.visitChildren(this);
}
@override
void visitFunctionDeclaration(FunctionDeclaration node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitVariableDeclaration(VariableDeclaration node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitYieldStatement(YieldStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitTryFinally(TryFinally node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitTryCatch(TryCatch node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitReturnStatement(ReturnStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitIfStatement(IfStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitContinueSwitchStatement(ContinueSwitchStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitSwitchStatement(SwitchStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitForInStatement(ForInStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitForStatement(ForStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitDoStatement(DoStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitWhileStatement(WhileStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitBreakStatement(BreakStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitLabeledStatement(LabeledStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitAssertStatement(AssertStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitEmptyStatement(EmptyStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitAssertBlock(AssertBlock node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitBlock(Block node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitExpressionStatement(ExpressionStatement node) {
storeLastSeenUriAndOffset(node);
makeStatementRoundTrip(node);
}
@override
void visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitLoadLibrary(LoadLibrary node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitInstantiation(Instantiation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitLet(Let node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitBlockExpression(BlockExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitNullLiteral(NullLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitBoolLiteral(BoolLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitDoubleLiteral(DoubleLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitIntLiteral(IntLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitStringLiteral(StringLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitConstantExpression(ConstantExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitFunctionExpression(FunctionExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitAwaitExpression(AwaitExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitMapLiteral(MapLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitSetLiteral(SetLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitListLiteral(ListLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitThrow(Throw node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitRethrow(Rethrow node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitThisExpression(ThisExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitTypeLiteral(TypeLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitSymbolLiteral(SymbolLiteral node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitAsExpression(AsExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitIsExpression(IsExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitStringConcatenation(StringConcatenation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitListConcatenation(ListConcatenation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitSetConcatenation(SetConcatenation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitMapConcatenation(MapConcatenation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitConditionalExpression(ConditionalExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitLogicalExpression(LogicalExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitNot(Not node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitNullCheck(NullCheck node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitConstructorInvocation(ConstructorInvocation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitStaticInvocation(StaticInvocation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitSuperMethodInvocation(SuperMethodInvocation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitDirectMethodInvocation(DirectMethodInvocation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitMethodInvocation(MethodInvocation node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitStaticSet(StaticSet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitStaticGet(StaticGet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitSuperPropertySet(SuperPropertySet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitSuperPropertyGet(SuperPropertyGet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitDirectPropertySet(DirectPropertySet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitDirectPropertyGet(DirectPropertyGet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitPropertySet(PropertySet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitPropertyGet(PropertyGet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitVariableSet(VariableSet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitVariableGet(VariableGet node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
@override
void visitInvalidExpression(InvalidExpression node) {
storeLastSeenUriAndOffset(node);
makeExpressionRoundTrip(node);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/text/text_serializer.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.text_serializer;
import '../ast.dart';
import 'serializer_combinators.dart';
import '../visitor.dart' show ExpressionVisitor;
abstract class Tagger<T extends Node> {
String tag(T node);
}
class NameTagger implements Tagger<Name> {
const NameTagger();
String tag(Name name) => name.isPrivate ? "private" : "public";
}
TextSerializer<Name> publicName =
new Wrapped(unwrapPublicName, wrapPublicName, const DartString());
String unwrapPublicName(Name name) => name.name;
Name wrapPublicName(String name) => new Name(name);
TextSerializer<Name> privateName = new Wrapped(unwrapPrivateName,
wrapPrivateName, Tuple2Serializer(const DartString(), const DartString()));
Tuple2<String, String> unwrapPrivateName(Name name) {
return new Tuple2(name.library.importUri.toString(), name.name);
}
Name wrapPrivateName(Tuple2<String, String> tuple) {
// We need a map from import URI to libraries. More generally, we will need
// a way to map any 'named' node to the node's reference.
throw UnimplementedError('deserialization of private names');
}
TextSerializer<Name> nameSerializer = new Case(const NameTagger(), [
"public",
"private",
], [
publicName,
privateName
]);
class ExpressionTagger extends ExpressionVisitor<String>
implements Tagger<Expression> {
const ExpressionTagger();
String tag(Expression expression) => expression.accept(this);
String visitStringLiteral(StringLiteral _) => "string";
String visitIntLiteral(IntLiteral _) => "int";
String visitDoubleLiteral(DoubleLiteral _) => "double";
String visitBoolLiteral(BoolLiteral _) => "bool";
String visitNullLiteral(NullLiteral _) => "null";
String visitInvalidExpression(InvalidExpression _) => "invalid";
String visitNot(Not _) => "not";
String visitLogicalExpression(LogicalExpression expression) {
return expression.operator;
}
String visitStringConcatenation(StringConcatenation _) => "concat";
String visitSymbolLiteral(SymbolLiteral _) => "symbol";
String visitThisExpression(ThisExpression _) => "this";
String visitRethrow(Rethrow _) => "rethrow";
String visitThrow(Throw _) => "throw";
String visitAwaitExpression(AwaitExpression _) => "await";
String visitConditionalExpression(ConditionalExpression _) => "cond";
String visitIsExpression(IsExpression _) => "is";
String visitAsExpression(AsExpression _) => "as";
String visitTypeLiteral(TypeLiteral _) => "type";
String visitListLiteral(ListLiteral expression) {
return expression.isConst ? "const-list" : "list";
}
String visitSetLiteral(SetLiteral expression) {
return expression.isConst ? "const-set" : "set";
}
String visitMapLiteral(MapLiteral expression) {
return expression.isConst ? "const-map" : "map";
}
String visitLet(Let _) => "let";
String visitPropertyGet(PropertyGet _) => "get-prop";
String visitPropertySet(PropertySet _) => "set-prop";
String visitSuperPropertyGet(SuperPropertyGet _) => "get-super";
String visitSuperPropertySet(SuperPropertySet _) => "set-super";
String visitMethodInvocation(MethodInvocation _) => "invoke-method";
String visitSuperMethodInvocation(SuperMethodInvocation _) => "invoke-super";
String visitVariableGet(VariableGet _) => "get-var";
String visitVariableSet(VariableSet _) => "set-var";
String visitStaticGet(StaticGet _) => "get-static";
String visitStaticSet(StaticSet _) => "set-static";
String visitDirectPropertyGet(DirectPropertyGet _) => "get-direct-prop";
String visitDirectPropertySet(DirectPropertySet _) => "set-direct-prop";
String visitStaticInvocation(StaticInvocation expression) {
return expression.isConst ? "invoke-const-static" : "invoke-static";
}
String visitDirectMethodInvocation(DirectMethodInvocation _) {
return "invoke-direct-method";
}
String visitConstructorInvocation(ConstructorInvocation expression) {
return expression.isConst
? "invoke-const-constructor"
: "invoke-constructor";
}
}
TextSerializer<InvalidExpression> invalidExpressionSerializer = new Wrapped(
unwrapInvalidExpression, wrapInvalidExpression, const DartString());
String unwrapInvalidExpression(InvalidExpression expression) {
return expression.message;
}
InvalidExpression wrapInvalidExpression(String message) {
return new InvalidExpression(message);
}
TextSerializer<Not> notSerializer =
new Wrapped(unwrapNot, wrapNot, expressionSerializer);
Expression unwrapNot(Not expression) => expression.operand;
Not wrapNot(Expression operand) => new Not(operand);
TextSerializer<LogicalExpression> logicalAndSerializer = new Wrapped(
unwrapLogicalExpression,
wrapLogicalAnd,
new Tuple2Serializer(expressionSerializer, expressionSerializer));
Tuple2<Expression, Expression> unwrapLogicalExpression(
LogicalExpression expression) {
return new Tuple2(expression.left, expression.right);
}
LogicalExpression wrapLogicalAnd(Tuple2<Expression, Expression> tuple) {
return new LogicalExpression(tuple.first, '&&', tuple.second);
}
TextSerializer<LogicalExpression> logicalOrSerializer = new Wrapped(
unwrapLogicalExpression,
wrapLogicalOr,
new Tuple2Serializer(expressionSerializer, expressionSerializer));
LogicalExpression wrapLogicalOr(Tuple2<Expression, Expression> tuple) {
return new LogicalExpression(tuple.first, '||', tuple.second);
}
TextSerializer<StringConcatenation> stringConcatenationSerializer = new Wrapped(
unwrapStringConcatenation,
wrapStringConcatenation,
new ListSerializer(expressionSerializer));
List<Expression> unwrapStringConcatenation(StringConcatenation expression) {
return expression.expressions;
}
StringConcatenation wrapStringConcatenation(List<Expression> expressions) {
return new StringConcatenation(expressions);
}
TextSerializer<StringLiteral> stringLiteralSerializer =
new Wrapped(unwrapStringLiteral, wrapStringLiteral, const DartString());
String unwrapStringLiteral(StringLiteral literal) => literal.value;
StringLiteral wrapStringLiteral(String value) => new StringLiteral(value);
TextSerializer<IntLiteral> intLiteralSerializer =
new Wrapped(unwrapIntLiteral, wrapIntLiteral, const DartInt());
int unwrapIntLiteral(IntLiteral literal) => literal.value;
IntLiteral wrapIntLiteral(int value) => new IntLiteral(value);
TextSerializer<DoubleLiteral> doubleLiteralSerializer =
new Wrapped(unwrapDoubleLiteral, wrapDoubleLiteral, const DartDouble());
double unwrapDoubleLiteral(DoubleLiteral literal) => literal.value;
DoubleLiteral wrapDoubleLiteral(double value) => new DoubleLiteral(value);
TextSerializer<BoolLiteral> boolLiteralSerializer =
new Wrapped(unwrapBoolLiteral, wrapBoolLiteral, const DartBool());
bool unwrapBoolLiteral(BoolLiteral literal) => literal.value;
BoolLiteral wrapBoolLiteral(bool value) => new BoolLiteral(value);
TextSerializer<NullLiteral> nullLiteralSerializer =
new Wrapped(unwrapNullLiteral, wrapNullLiteral, const Nothing());
void unwrapNullLiteral(NullLiteral literal) {}
NullLiteral wrapNullLiteral(void ignored) => new NullLiteral();
TextSerializer<SymbolLiteral> symbolLiteralSerializer =
new Wrapped(unwrapSymbolLiteral, wrapSymbolLiteral, const DartString());
String unwrapSymbolLiteral(SymbolLiteral expression) => expression.value;
SymbolLiteral wrapSymbolLiteral(String value) => new SymbolLiteral(value);
TextSerializer<ThisExpression> thisExpressionSerializer =
new Wrapped(unwrapThisExpression, wrapThisExpression, const Nothing());
void unwrapThisExpression(ThisExpression expression) {}
ThisExpression wrapThisExpression(void ignored) => new ThisExpression();
TextSerializer<Rethrow> rethrowSerializer =
new Wrapped(unwrapRethrow, wrapRethrow, const Nothing());
void unwrapRethrow(Rethrow expression) {}
Rethrow wrapRethrow(void ignored) => new Rethrow();
TextSerializer<Throw> throwSerializer =
new Wrapped(unwrapThrow, wrapThrow, expressionSerializer);
Expression unwrapThrow(Throw expression) => expression.expression;
Throw wrapThrow(Expression expression) => new Throw(expression);
TextSerializer<AwaitExpression> awaitExpressionSerializer = new Wrapped(
unwrapAwaitExpression, wrapAwaitExpression, expressionSerializer);
Expression unwrapAwaitExpression(AwaitExpression expression) =>
expression.operand;
AwaitExpression wrapAwaitExpression(Expression operand) =>
new AwaitExpression(operand);
TextSerializer<ConditionalExpression> conditionalExpressionSerializer =
new Wrapped(
unwrapConditionalExpression,
wrapConditionalExpression,
new Tuple4Serializer(expressionSerializer, dartTypeSerializer,
expressionSerializer, expressionSerializer));
Tuple4<Expression, DartType, Expression, Expression>
unwrapConditionalExpression(ConditionalExpression expression) {
return new Tuple4(expression.condition, expression.staticType,
expression.then, expression.otherwise);
}
ConditionalExpression wrapConditionalExpression(
Tuple4<Expression, DartType, Expression, Expression> tuple) {
return new ConditionalExpression(
tuple.first, tuple.third, tuple.fourth, tuple.second);
}
TextSerializer<IsExpression> isExpressionSerializer = new Wrapped(
unwrapIsExpression,
wrapIsExpression,
new Tuple2Serializer(expressionSerializer, dartTypeSerializer));
Tuple2<Expression, DartType> unwrapIsExpression(IsExpression expression) {
return new Tuple2(expression.operand, expression.type);
}
IsExpression wrapIsExpression(Tuple2<Expression, DartType> tuple) {
return new IsExpression(tuple.first, tuple.second);
}
TextSerializer<AsExpression> asExpressionSerializer = new Wrapped(
unwrapAsExpression,
wrapAsExpression,
new Tuple2Serializer(expressionSerializer, dartTypeSerializer));
Tuple2<Expression, DartType> unwrapAsExpression(AsExpression expression) {
return new Tuple2(expression.operand, expression.type);
}
AsExpression wrapAsExpression(Tuple2<Expression, DartType> tuple) {
return new AsExpression(tuple.first, tuple.second);
}
TextSerializer<TypeLiteral> typeLiteralSerializer =
new Wrapped(unwrapTypeLiteral, wrapTypeLiteral, dartTypeSerializer);
DartType unwrapTypeLiteral(TypeLiteral expression) => expression.type;
TypeLiteral wrapTypeLiteral(DartType type) => new TypeLiteral(type);
TextSerializer<ListLiteral> listLiteralSerializer = new Wrapped(
unwrapListLiteral,
wrapListLiteral,
new Tuple2Serializer(
dartTypeSerializer, new ListSerializer(expressionSerializer)));
Tuple2<DartType, List<Expression>> unwrapListLiteral(ListLiteral expression) {
return new Tuple2(expression.typeArgument, expression.expressions);
}
ListLiteral wrapListLiteral(Tuple2<DartType, List<Expression>> tuple) {
return new ListLiteral(tuple.second,
typeArgument: tuple.first, isConst: false);
}
TextSerializer<ListLiteral> constListLiteralSerializer = new Wrapped(
unwrapListLiteral,
wrapConstListLiteral,
new Tuple2Serializer(
dartTypeSerializer, new ListSerializer(expressionSerializer)));
ListLiteral wrapConstListLiteral(Tuple2<DartType, List<Expression>> tuple) {
return new ListLiteral(tuple.second,
typeArgument: tuple.first, isConst: true);
}
TextSerializer<SetLiteral> setLiteralSerializer = new Wrapped(
unwrapSetLiteral,
wrapSetLiteral,
new Tuple2Serializer(
dartTypeSerializer, new ListSerializer(expressionSerializer)));
Tuple2<DartType, List<Expression>> unwrapSetLiteral(SetLiteral expression) {
return new Tuple2(expression.typeArgument, expression.expressions);
}
SetLiteral wrapSetLiteral(Tuple2<DartType, List<Expression>> tuple) {
return new SetLiteral(tuple.second,
typeArgument: tuple.first, isConst: false);
}
TextSerializer<SetLiteral> constSetLiteralSerializer = new Wrapped(
unwrapSetLiteral,
wrapConstSetLiteral,
new Tuple2Serializer(
dartTypeSerializer, new ListSerializer(expressionSerializer)));
SetLiteral wrapConstSetLiteral(Tuple2<DartType, List<Expression>> tuple) {
return new SetLiteral(tuple.second, typeArgument: tuple.first, isConst: true);
}
TextSerializer<MapLiteral> mapLiteralSerializer = new Wrapped(
unwrapMapLiteral,
wrapMapLiteral,
new Tuple3Serializer(dartTypeSerializer, dartTypeSerializer,
new ListSerializer(expressionSerializer)));
Tuple3<DartType, DartType, List<Expression>> unwrapMapLiteral(
MapLiteral expression) {
List<Expression> entries = new List(2 * expression.entries.length);
for (int from = 0, to = 0; from < expression.entries.length; ++from) {
MapEntry entry = expression.entries[from];
entries[to++] = entry.key;
entries[to++] = entry.value;
}
return new Tuple3(expression.keyType, expression.valueType, entries);
}
MapLiteral wrapMapLiteral(Tuple3<DartType, DartType, List<Expression>> tuple) {
List<MapEntry> entries = new List(tuple.third.length ~/ 2);
for (int from = 0, to = 0; to < entries.length; ++to) {
entries[to] = new MapEntry(tuple.third[from++], tuple.third[from++]);
}
return new MapLiteral(entries,
keyType: tuple.first, valueType: tuple.second, isConst: false);
}
TextSerializer<MapLiteral> constMapLiteralSerializer = new Wrapped(
unwrapMapLiteral,
wrapConstMapLiteral,
new Tuple3Serializer(dartTypeSerializer, dartTypeSerializer,
new ListSerializer(expressionSerializer)));
MapLiteral wrapConstMapLiteral(
Tuple3<DartType, DartType, List<Expression>> tuple) {
List<MapEntry> entries = new List(tuple.third.length ~/ 2);
for (int from = 0, to = 0; to < entries.length; ++to) {
entries[to] = new MapEntry(tuple.third[from++], tuple.third[from++]);
}
return new MapLiteral(entries,
keyType: tuple.first, valueType: tuple.second, isConst: true);
}
TextSerializer<Let> letSerializer = new Wrapped(
unwrapLet,
wrapLet,
new Bind(
new Binder(variableDeclarationSerializer, getVariableDeclarationName,
setVariableDeclarationName),
expressionSerializer));
Tuple2<VariableDeclaration, Expression> unwrapLet(Let expression) {
return new Tuple2(expression.variable, expression.body);
}
Let wrapLet(Tuple2<VariableDeclaration, Expression> tuple) {
return new Let(tuple.first, tuple.second);
}
String getVariableDeclarationName(VariableDeclaration node) => node.name;
void setVariableDeclarationName(VariableDeclaration node, String name) {
node.name = name;
}
TextSerializer<PropertyGet> propertyGetSerializer = new Wrapped(
unwrapPropertyGet,
wrapPropertyGet,
new Tuple2Serializer(expressionSerializer, nameSerializer));
Tuple2<Expression, Name> unwrapPropertyGet(PropertyGet expression) {
return new Tuple2(expression.receiver, expression.name);
}
PropertyGet wrapPropertyGet(Tuple2<Expression, Name> tuple) {
return new PropertyGet(tuple.first, tuple.second);
}
TextSerializer<PropertySet> propertySetSerializer = new Wrapped(
unwrapPropertySet,
wrapPropertySet,
new Tuple3Serializer(
expressionSerializer, nameSerializer, expressionSerializer));
Tuple3<Expression, Name, Expression> unwrapPropertySet(PropertySet expression) {
return new Tuple3(expression.receiver, expression.name, expression.value);
}
PropertySet wrapPropertySet(Tuple3<Expression, Name, Expression> tuple) {
return new PropertySet(tuple.first, tuple.second, tuple.third);
}
TextSerializer<SuperPropertyGet> superPropertyGetSerializer =
new Wrapped(unwrapSuperPropertyGet, wrapSuperPropertyGet, nameSerializer);
Name unwrapSuperPropertyGet(SuperPropertyGet expression) {
return expression.name;
}
SuperPropertyGet wrapSuperPropertyGet(Name name) {
return new SuperPropertyGet(name);
}
TextSerializer<SuperPropertySet> superPropertySetSerializer = new Wrapped(
unwrapSuperPropertySet,
wrapSuperPropertySet,
new Tuple2Serializer(nameSerializer, expressionSerializer));
Tuple2<Name, Expression> unwrapSuperPropertySet(SuperPropertySet expression) {
return new Tuple2(expression.name, expression.value);
}
SuperPropertySet wrapSuperPropertySet(Tuple2<Name, Expression> tuple) {
return new SuperPropertySet(tuple.first, tuple.second, null);
}
TextSerializer<MethodInvocation> methodInvocationSerializer = new Wrapped(
unwrapMethodInvocation,
wrapMethodInvocation,
new Tuple3Serializer(
expressionSerializer, nameSerializer, argumentsSerializer));
Tuple3<Expression, Name, Arguments> unwrapMethodInvocation(
MethodInvocation expression) {
return new Tuple3(expression.receiver, expression.name, expression.arguments);
}
MethodInvocation wrapMethodInvocation(
Tuple3<Expression, Name, Arguments> tuple) {
return new MethodInvocation(tuple.first, tuple.second, tuple.third);
}
TextSerializer<SuperMethodInvocation> superMethodInvocationSerializer =
new Wrapped(unwrapSuperMethodInvocation, wrapSuperMethodInvocation,
new Tuple2Serializer(nameSerializer, argumentsSerializer));
Tuple2<Name, Arguments> unwrapSuperMethodInvocation(
SuperMethodInvocation expression) {
return new Tuple2(expression.name, expression.arguments);
}
SuperMethodInvocation wrapSuperMethodInvocation(Tuple2<Name, Arguments> tuple) {
return new SuperMethodInvocation(tuple.first, tuple.second);
}
TextSerializer<VariableGet> variableGetSerializer = new Wrapped(
unwrapVariableGet,
wrapVariableGet,
new Tuple2Serializer(const ScopedUse<VariableDeclaration>(),
new Optional(dartTypeSerializer)));
Tuple2<VariableDeclaration, DartType> unwrapVariableGet(VariableGet node) {
return new Tuple2<VariableDeclaration, DartType>(
node.variable, node.promotedType);
}
VariableGet wrapVariableGet(Tuple2<VariableDeclaration, DartType> tuple) {
return new VariableGet(tuple.first, tuple.second);
}
TextSerializer<VariableSet> variableSetSerializer = new Wrapped(
unwrapVariableSet,
wrapVariableSet,
new Tuple2Serializer(
const ScopedUse<VariableDeclaration>(), expressionSerializer));
Tuple2<VariableDeclaration, Expression> unwrapVariableSet(VariableSet node) {
return new Tuple2<VariableDeclaration, Expression>(node.variable, node.value);
}
VariableSet wrapVariableSet(Tuple2<VariableDeclaration, Expression> tuple) {
return new VariableSet(tuple.first, tuple.second);
}
class CanonicalNameSerializer extends TextSerializer<CanonicalName> {
static const String delimiter = "::";
const CanonicalNameSerializer();
static void writeName(CanonicalName name, StringBuffer buffer) {
if (!name.isRoot) {
if (!name.parent.isRoot) {
writeName(name.parent, buffer);
buffer.write(delimiter);
}
buffer.write(name.name);
}
}
CanonicalName readFrom(Iterator<Object> stream, DeserializationState state) {
String string = const DartString().readFrom(stream, state);
CanonicalName name = state.nameRoot;
for (String s in string.split(delimiter)) {
name = name.getChild(s);
}
return name;
}
void writeTo(
StringBuffer buffer, CanonicalName name, SerializationState state) {
StringBuffer sb = new StringBuffer();
writeName(name, sb);
const DartString().writeTo(buffer, sb.toString(), state);
}
}
TextSerializer<StaticGet> staticGetSerializer =
new Wrapped(unwrapStaticGet, wrapStaticGet, new CanonicalNameSerializer());
CanonicalName unwrapStaticGet(StaticGet expression) {
return expression.targetReference.canonicalName;
}
StaticGet wrapStaticGet(CanonicalName name) {
return new StaticGet.byReference(name.getReference());
}
TextSerializer<StaticSet> staticSetSerializer = new Wrapped(
unwrapStaticSet,
wrapStaticSet,
new Tuple2Serializer(
const CanonicalNameSerializer(), expressionSerializer));
Tuple2<CanonicalName, Expression> unwrapStaticSet(StaticSet expression) {
return new Tuple2(expression.targetReference.canonicalName, expression.value);
}
StaticSet wrapStaticSet(Tuple2<CanonicalName, Expression> tuple) {
return new StaticSet.byReference(tuple.first.getReference(), tuple.second);
}
TextSerializer<DirectPropertyGet> directPropertyGetSerializer = new Wrapped(
unwrapDirectPropertyGet,
wrapDirectPropertyGet,
new Tuple2Serializer(
expressionSerializer, const CanonicalNameSerializer()));
Tuple2<Expression, CanonicalName> unwrapDirectPropertyGet(
DirectPropertyGet expression) {
return new Tuple2(
expression.receiver, expression.targetReference.canonicalName);
}
DirectPropertyGet wrapDirectPropertyGet(
Tuple2<Expression, CanonicalName> tuple) {
return new DirectPropertyGet.byReference(
tuple.first, tuple.second.getReference());
}
TextSerializer<DirectPropertySet> directPropertySetSerializer = new Wrapped(
unwrapDirectPropertySet,
wrapDirectPropertySet,
new Tuple3Serializer(expressionSerializer, const CanonicalNameSerializer(),
expressionSerializer));
Tuple3<Expression, CanonicalName, Expression> unwrapDirectPropertySet(
DirectPropertySet expression) {
return new Tuple3(expression.receiver,
expression.targetReference.canonicalName, expression.value);
}
DirectPropertySet wrapDirectPropertySet(
Tuple3<Expression, CanonicalName, Expression> tuple) {
return new DirectPropertySet.byReference(
tuple.first, tuple.second.getReference(), tuple.third);
}
TextSerializer<StaticInvocation> staticInvocationSerializer = new Wrapped(
unwrapStaticInvocation,
wrapStaticInvocation,
new Tuple2Serializer(const CanonicalNameSerializer(), argumentsSerializer));
Tuple2<CanonicalName, Arguments> unwrapStaticInvocation(
StaticInvocation expression) {
return new Tuple2(
expression.targetReference.canonicalName, expression.arguments);
}
StaticInvocation wrapStaticInvocation(Tuple2<CanonicalName, Arguments> tuple) {
return new StaticInvocation.byReference(
tuple.first.getReference(), tuple.second,
isConst: false);
}
TextSerializer<StaticInvocation> constStaticInvocationSerializer = new Wrapped(
unwrapStaticInvocation,
wrapConstStaticInvocation,
new Tuple2Serializer(const CanonicalNameSerializer(), argumentsSerializer));
StaticInvocation wrapConstStaticInvocation(
Tuple2<CanonicalName, Arguments> tuple) {
return new StaticInvocation.byReference(
tuple.first.getReference(), tuple.second,
isConst: true);
}
TextSerializer<DirectMethodInvocation> directMethodInvocationSerializer =
new Wrapped(
unwrapDirectMethodInvocation,
wrapDirectMethodInvocation,
new Tuple3Serializer(expressionSerializer,
const CanonicalNameSerializer(), argumentsSerializer));
Tuple3<Expression, CanonicalName, Arguments> unwrapDirectMethodInvocation(
DirectMethodInvocation expression) {
return new Tuple3(expression.receiver,
expression.targetReference.canonicalName, expression.arguments);
}
DirectMethodInvocation wrapDirectMethodInvocation(
Tuple3<Expression, CanonicalName, Arguments> tuple) {
return new DirectMethodInvocation.byReference(
tuple.first, tuple.second.getReference(), tuple.third);
}
TextSerializer<ConstructorInvocation> constructorInvocationSerializer =
new Wrapped(
unwrapConstructorInvocation,
wrapConstructorInvocation,
new Tuple2Serializer(
const CanonicalNameSerializer(), argumentsSerializer));
Tuple2<CanonicalName, Arguments> unwrapConstructorInvocation(
ConstructorInvocation expression) {
return new Tuple2(
expression.targetReference.canonicalName, expression.arguments);
}
ConstructorInvocation wrapConstructorInvocation(
Tuple2<CanonicalName, Arguments> tuple) {
return new ConstructorInvocation.byReference(
tuple.first.getReference(), tuple.second,
isConst: false);
}
TextSerializer<ConstructorInvocation> constConstructorInvocationSerializer =
new Wrapped(unwrapConstructorInvocation, wrapConstConstructorInvocation,
Tuple2Serializer(const CanonicalNameSerializer(), argumentsSerializer));
ConstructorInvocation wrapConstConstructorInvocation(
Tuple2<CanonicalName, Arguments> tuple) {
return new ConstructorInvocation.byReference(
tuple.first.getReference(), tuple.second,
isConst: true);
}
Case<Expression> expressionSerializer =
new Case.uninitialized(const ExpressionTagger());
TextSerializer<NamedExpression> namedExpressionSerializer = new Wrapped(
unwrapNamedExpression,
wrapNamedExpression,
new Tuple2Serializer(const DartString(), expressionSerializer));
Tuple2<String, Expression> unwrapNamedExpression(NamedExpression expression) {
return new Tuple2(expression.name, expression.value);
}
NamedExpression wrapNamedExpression(Tuple2<String, Expression> tuple) {
return new NamedExpression(tuple.first, tuple.second);
}
TextSerializer<Arguments> argumentsSerializer = new Wrapped(
unwrapArguments,
wrapArguments,
Tuple3Serializer(
new ListSerializer(dartTypeSerializer),
new ListSerializer(expressionSerializer),
new ListSerializer(namedExpressionSerializer)));
Tuple3<List<DartType>, List<Expression>, List<NamedExpression>> unwrapArguments(
Arguments arguments) {
return new Tuple3(arguments.types, arguments.positional, arguments.named);
}
Arguments wrapArguments(
Tuple3<List<DartType>, List<Expression>, List<NamedExpression>> tuple) {
return new Arguments(tuple.second, types: tuple.first, named: tuple.third);
}
class VariableDeclarationTagger implements Tagger<VariableDeclaration> {
const VariableDeclarationTagger();
String tag(VariableDeclaration decl) {
if (decl.isCovariant) throw UnimplementedError("covariant declaration");
if (decl.isFieldFormal) throw UnimplementedError("initializing formal");
if (decl.isConst) {
// It's not clear what invariants we assume about const/final. For now
// throw if we have both.
if (decl.isFinal) throw UnimplementedError("const and final");
return "const";
}
if (decl.isFinal) {
return "final";
}
return "var";
}
}
TextSerializer<VariableDeclaration> varDeclarationSerializer = new Wrapped(
unwrapVariableDeclaration,
wrapVarDeclaration,
Tuple4Serializer(
const DartString(),
dartTypeSerializer,
new Optional(expressionSerializer),
new ListSerializer(expressionSerializer)));
Tuple4<String, DartType, Expression, List<Expression>>
unwrapVariableDeclaration(VariableDeclaration declaration) {
return new Tuple4(declaration.name ?? "", declaration.type,
declaration.initializer, declaration.annotations);
}
VariableDeclaration wrapVarDeclaration(
Tuple4<String, DartType, Expression, List<Expression>> tuple) {
var result = new VariableDeclaration(tuple.first.isEmpty ? null : tuple.first,
initializer: tuple.third, type: tuple.second);
for (int i = 0; i < tuple.fourth.length; ++i) {
result.addAnnotation(tuple.fourth[i]);
}
return result;
}
TextSerializer<VariableDeclaration> finalDeclarationSerializer = new Wrapped(
unwrapVariableDeclaration,
wrapFinalDeclaration,
Tuple4Serializer(
const DartString(),
dartTypeSerializer,
new Optional(expressionSerializer),
new ListSerializer(expressionSerializer)));
VariableDeclaration wrapFinalDeclaration(
Tuple4<String, DartType, Expression, List<Expression>> tuple) {
var result = new VariableDeclaration(tuple.first.isEmpty ? null : tuple.first,
initializer: tuple.third, type: tuple.second, isFinal: true);
for (int i = 0; i < tuple.fourth.length; ++i) {
result.addAnnotation(tuple.fourth[i]);
}
return result;
}
TextSerializer<VariableDeclaration> constDeclarationSerializer = new Wrapped(
unwrapVariableDeclaration,
wrapConstDeclaration,
Tuple4Serializer(
const DartString(),
dartTypeSerializer,
new Optional(expressionSerializer),
new ListSerializer(expressionSerializer)));
VariableDeclaration wrapConstDeclaration(
Tuple4<String, DartType, Expression, List<Expression>> tuple) {
var result = new VariableDeclaration(tuple.first.isEmpty ? null : tuple.first,
initializer: tuple.third, type: tuple.second, isConst: true);
for (int i = 0; i < tuple.fourth.length; ++i) {
result.addAnnotation(tuple.fourth[i]);
}
return result;
}
TextSerializer<VariableDeclaration> variableDeclarationSerializer =
new Case(const VariableDeclarationTagger(), [
"var",
"final",
"const",
], [
varDeclarationSerializer,
finalDeclarationSerializer,
constDeclarationSerializer,
]);
TextSerializer<TypeParameter> typeParameterSerializer =
new Wrapped(unwrapTypeParameter, wrapTypeParameter, const DartString());
String unwrapTypeParameter(TypeParameter node) => node.name;
TypeParameter wrapTypeParameter(String name) => new TypeParameter(name);
TextSerializer<List<TypeParameter>> typeParametersSerializer = new Zip(
new Rebind(
new Zip(
new Rebind(
new ListSerializer(new Binder(typeParameterSerializer,
getTypeParameterName, setTypeParameterName)),
new ListSerializer(dartTypeSerializer)),
zipTypeParameterBound,
unzipTypeParameterBound),
new ListSerializer(dartTypeSerializer)),
zipTypeParameterDefaultType,
unzipTypeParameterDefaultType);
String getTypeParameterName(TypeParameter node) => node.name;
void setTypeParameterName(TypeParameter node, String name) {
node.name = name;
}
TypeParameter zipTypeParameterBound(TypeParameter node, DartType bound) {
return node..bound = bound;
}
Tuple2<TypeParameter, DartType> unzipTypeParameterBound(TypeParameter node) {
return new Tuple2(node, node.bound);
}
TypeParameter zipTypeParameterDefaultType(
TypeParameter node, DartType defaultType) {
return node..defaultType = defaultType;
}
Tuple2<TypeParameter, DartType> unzipTypeParameterDefaultType(
TypeParameter node) {
return new Tuple2(node, node.defaultType);
}
class DartTypeTagger extends DartTypeVisitor<String>
implements Tagger<DartType> {
const DartTypeTagger();
String tag(DartType type) => type.accept(this);
String visitInvalidType(InvalidType _) => "invalid";
String visitDynamicType(DynamicType _) => "dynamic";
String visitVoidType(VoidType _) => "void";
String visitBottomType(BottomType _) => "bottom";
String visitFunctionType(FunctionType _) => "->";
String visitTypeParameterType(TypeParameterType _) => "par";
}
TextSerializer<InvalidType> invalidTypeSerializer =
new Wrapped(unwrapInvalidType, wrapInvalidType, const Nothing());
void unwrapInvalidType(InvalidType type) {}
InvalidType wrapInvalidType(void ignored) => const InvalidType();
TextSerializer<DynamicType> dynamicTypeSerializer =
new Wrapped(unwrapDynamicType, wrapDynamicType, const Nothing());
void unwrapDynamicType(DynamicType type) {}
DynamicType wrapDynamicType(void ignored) => const DynamicType();
TextSerializer<VoidType> voidTypeSerializer =
new Wrapped(unwrapVoidType, wrapVoidType, const Nothing());
void unwrapVoidType(VoidType type) {}
VoidType wrapVoidType(void ignored) => const VoidType();
TextSerializer<BottomType> bottomTypeSerializer =
new Wrapped(unwrapBottomType, wrapBottomType, const Nothing());
void unwrapBottomType(BottomType type) {}
BottomType wrapBottomType(void ignored) => const BottomType();
// TODO(dmitryas): Also handle nameParameters, and typedefType.
TextSerializer<FunctionType> functionTypeSerializer = new Wrapped(
unwrapFunctionType,
wrapFunctionType,
new Bind(
typeParametersSerializer,
new Tuple4Serializer(
new ListSerializer(dartTypeSerializer),
new ListSerializer(dartTypeSerializer),
new ListSerializer(namedTypeSerializer),
dartTypeSerializer)));
Tuple2<List<TypeParameter>,
Tuple4<List<DartType>, List<DartType>, List<NamedType>, DartType>>
unwrapFunctionType(FunctionType type) {
return new Tuple2(
type.typeParameters,
new Tuple4(
type.positionalParameters.sublist(0, type.requiredParameterCount),
type.positionalParameters.sublist(type.requiredParameterCount),
type.namedParameters,
type.returnType));
}
FunctionType wrapFunctionType(
Tuple2<List<TypeParameter>,
Tuple4<List<DartType>, List<DartType>, List<NamedType>, DartType>>
tuple) {
return new FunctionType(
tuple.second.first + tuple.second.second, tuple.second.fourth,
requiredParameterCount: tuple.second.first.length,
typeParameters: tuple.first,
namedParameters: tuple.second.third);
}
TextSerializer<NamedType> namedTypeSerializer = new Wrapped(unwrapNamedType,
wrapNamedType, Tuple2Serializer(const DartString(), dartTypeSerializer));
Tuple2<String, DartType> unwrapNamedType(NamedType namedType) {
return new Tuple2(namedType.name, namedType.type);
}
NamedType wrapNamedType(Tuple2<String, DartType> tuple) {
return new NamedType(tuple.first, tuple.second);
}
TextSerializer<TypeParameterType> typeParameterTypeSerializer = new Wrapped(
unwrapTypeParameterType,
wrapTypeParameterType,
Tuple2Serializer(
new ScopedUse<TypeParameter>(), new Optional(dartTypeSerializer)));
Tuple2<TypeParameter, DartType> unwrapTypeParameterType(
TypeParameterType node) {
return new Tuple2(node.parameter, node.promotedBound);
}
TypeParameterType wrapTypeParameterType(Tuple2<TypeParameter, DartType> tuple) {
return new TypeParameterType(tuple.first, tuple.second);
}
Case<DartType> dartTypeSerializer =
new Case.uninitialized(const DartTypeTagger());
class StatementTagger extends StatementVisitor<String>
implements Tagger<Statement> {
const StatementTagger();
String tag(Statement statement) => statement.accept(this);
String visitExpressionStatement(ExpressionStatement _) => "expr";
}
TextSerializer<ExpressionStatement> expressionStatementSerializer = new Wrapped(
unwrapExpressionStatement, wrapExpressionStatement, expressionSerializer);
Expression unwrapExpressionStatement(ExpressionStatement statement) {
return statement.expression;
}
ExpressionStatement wrapExpressionStatement(Expression expression) {
return new ExpressionStatement(expression);
}
Case<Statement> statementSerializer =
new Case.uninitialized(const StatementTagger());
void initializeSerializers() {
expressionSerializer.tags.addAll([
"string",
"int",
"double",
"bool",
"null",
"invalid",
"not",
"&&",
"||",
"concat",
"symbol",
"this",
"rethrow",
"throw",
"await",
"cond",
"is",
"as",
"type",
"list",
"const-list",
"set",
"const-set",
"map",
"const-map",
"let",
"get-prop",
"set-prop",
"get-super",
"set-super",
"invoke-method",
"invoke-super",
"get-var",
"set-var",
"get-static",
"set-static",
"get-direct-prop",
"set-direct-prop",
"invoke-static",
"invoke-const-static",
"invoke-direct-method",
"invoke-constructor",
"invoke-const-constructor",
]);
expressionSerializer.serializers.addAll([
stringLiteralSerializer,
intLiteralSerializer,
doubleLiteralSerializer,
boolLiteralSerializer,
nullLiteralSerializer,
invalidExpressionSerializer,
notSerializer,
logicalAndSerializer,
logicalOrSerializer,
stringConcatenationSerializer,
symbolLiteralSerializer,
thisExpressionSerializer,
rethrowSerializer,
throwSerializer,
awaitExpressionSerializer,
conditionalExpressionSerializer,
isExpressionSerializer,
asExpressionSerializer,
typeLiteralSerializer,
listLiteralSerializer,
constListLiteralSerializer,
setLiteralSerializer,
constSetLiteralSerializer,
mapLiteralSerializer,
constMapLiteralSerializer,
letSerializer,
propertyGetSerializer,
propertySetSerializer,
superPropertyGetSerializer,
superPropertySetSerializer,
methodInvocationSerializer,
superMethodInvocationSerializer,
variableGetSerializer,
variableSetSerializer,
staticGetSerializer,
staticSetSerializer,
directPropertyGetSerializer,
directPropertySetSerializer,
staticInvocationSerializer,
constStaticInvocationSerializer,
directMethodInvocationSerializer,
constructorInvocationSerializer,
constConstructorInvocationSerializer,
]);
dartTypeSerializer.tags.addAll([
"invalid",
"dynamic",
"void",
"bottom",
"->",
"par",
]);
dartTypeSerializer.serializers.addAll([
invalidTypeSerializer,
dynamicTypeSerializer,
voidTypeSerializer,
bottomTypeSerializer,
functionTypeSerializer,
typeParameterTypeSerializer,
]);
statementSerializer.tags.addAll([
"expr",
]);
statementSerializer.serializers.addAll([
expressionStatementSerializer,
]);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/transformations/continuation.dart | // 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.
library kernel.transformations.continuation;
import 'dart:math' as math;
import '../ast.dart';
import '../core_types.dart';
import '../visitor.dart';
import 'async.dart';
class ContinuationVariables {
static const awaitJumpVar = ':await_jump_var';
static const awaitContextVar = ':await_ctx_var';
static const asyncStackTraceVar = ':async_stack_trace';
static const controllerStreamVar = ':controller_stream';
static const exceptionParam = ':exception';
static const stackTraceParam = ':stack_trace';
static String savedTryContextVar(int depth) => ':saved_try_context_var$depth';
static String exceptionVar(int depth) => ':exception$depth';
static String stackTraceVar(int depth) => ':stack_trace$depth';
}
void transformLibraries(CoreTypes coreTypes, List<Library> libraries,
{bool productMode}) {
var helper = new HelperNodes.fromCoreTypes(coreTypes, productMode);
var rewriter = new RecursiveContinuationRewriter(helper);
for (var library in libraries) {
rewriter.rewriteLibrary(library);
}
}
Component transformComponent(CoreTypes coreTypes, Component component,
{bool productMode}) {
var helper = new HelperNodes.fromCoreTypes(coreTypes, productMode);
var rewriter = new RecursiveContinuationRewriter(helper);
return rewriter.rewriteComponent(component);
}
Procedure transformProcedure(CoreTypes coreTypes, Procedure procedure,
{bool productMode}) {
var helper = new HelperNodes.fromCoreTypes(coreTypes, productMode);
var rewriter = new RecursiveContinuationRewriter(helper);
return rewriter.visitProcedure(procedure);
}
class RecursiveContinuationRewriter extends Transformer {
final HelperNodes helper;
final VariableDeclaration asyncJumpVariable = new VariableDeclaration(
ContinuationVariables.awaitJumpVar,
initializer: new IntLiteral(0));
final VariableDeclaration asyncContextVariable =
new VariableDeclaration(ContinuationVariables.awaitContextVar);
RecursiveContinuationRewriter(this.helper);
Component rewriteComponent(Component node) {
return node.accept<TreeNode>(this);
}
Library rewriteLibrary(Library node) {
return node.accept<TreeNode>(this);
}
visitProcedure(Procedure node) {
return node.isAbstract ? node : super.visitProcedure(node);
}
visitFunctionNode(FunctionNode node) {
switch (node.asyncMarker) {
case AsyncMarker.Sync:
case AsyncMarker.SyncYielding:
node.transformChildren(new RecursiveContinuationRewriter(helper));
return node;
case AsyncMarker.SyncStar:
return new SyncStarFunctionRewriter(helper, node).rewrite();
case AsyncMarker.Async:
return new AsyncFunctionRewriter(helper, node).rewrite();
case AsyncMarker.AsyncStar:
return new AsyncStarFunctionRewriter(helper, node).rewrite();
default:
return null;
}
}
}
abstract class ContinuationRewriterBase extends RecursiveContinuationRewriter {
final FunctionNode enclosingFunction;
int currentTryDepth = 0; // Nesting depth for try-blocks.
int currentCatchDepth = 0; // Nesting depth for catch-blocks.
int capturedTryDepth = 0; // Deepest yield point within a try-block.
int capturedCatchDepth = 0; // Deepest yield point within a catch-block.
ContinuationRewriterBase(HelperNodes helper, this.enclosingFunction)
: super(helper);
/// Given a container [type], which is an instantiation of the given
/// [containerClass] extract its element type.
///
/// This is used to extract element type from Future<T>, Iterable<T> and
/// Stream<T> instantiations.
///
/// If instantiation is not valid (has more than 1 type argument) then
/// this function returns [InvalidType].
static DartType elementTypeFrom(Class containerClass, DartType type) {
if (type is InterfaceType) {
if (type.classNode == containerClass) {
if (type.typeArguments.length == 0) {
return const DynamicType();
} else if (type.typeArguments.length == 1) {
return type.typeArguments[0];
} else {
return const InvalidType();
}
}
}
return const DynamicType();
}
DartType elementTypeFromReturnType(Class expected) =>
elementTypeFrom(expected, enclosingFunction.returnType);
Statement createContinuationPoint([Expression value]) {
if (value == null) value = new NullLiteral();
capturedTryDepth = math.max(capturedTryDepth, currentTryDepth);
capturedCatchDepth = math.max(capturedCatchDepth, currentCatchDepth);
return new YieldStatement(value, isNative: true);
}
TreeNode visitTryCatch(TryCatch node) {
if (node.body != null) {
++currentTryDepth;
node.body = node.body.accept<TreeNode>(this);
node.body?.parent = node;
--currentTryDepth;
}
++currentCatchDepth;
transformList(node.catches, this, node);
--currentCatchDepth;
return node;
}
TreeNode visitTryFinally(TryFinally node) {
if (node.body != null) {
++currentTryDepth;
node.body = node.body.accept<TreeNode>(this);
node.body?.parent = node;
--currentTryDepth;
}
if (node.finalizer != null) {
++currentCatchDepth;
node.finalizer = node.finalizer.accept<TreeNode>(this);
node.finalizer?.parent = node;
--currentCatchDepth;
}
return node;
}
Iterable<VariableDeclaration> createCapturedTryVariables() =>
new Iterable.generate(
capturedTryDepth,
(depth) => new VariableDeclaration(
ContinuationVariables.savedTryContextVar(depth)));
Iterable<VariableDeclaration> createCapturedCatchVariables() =>
new Iterable.generate(capturedCatchDepth).expand((depth) => [
new VariableDeclaration(ContinuationVariables.exceptionVar(depth)),
new VariableDeclaration(ContinuationVariables.stackTraceVar(depth)),
]);
List<VariableDeclaration> variableDeclarations() =>
[asyncJumpVariable, asyncContextVariable]
..addAll(createCapturedTryVariables())
..addAll(createCapturedCatchVariables());
}
class SyncStarFunctionRewriter extends ContinuationRewriterBase {
final VariableDeclaration iteratorVariable;
SyncStarFunctionRewriter(HelperNodes helper, FunctionNode enclosingFunction)
: iteratorVariable = new VariableDeclaration(':iterator')
..type = new InterfaceType(helper.syncIteratorClass, [
ContinuationRewriterBase.elementTypeFrom(
helper.iterableClass, enclosingFunction.returnType)
]),
super(helper, enclosingFunction);
FunctionNode rewrite() {
// :sync_op(:iterator) {
// modified <node.body>;
// }
// Note: SyncYielding functions have no Dart equivalent. Since they are
// synchronous, we use Sync. (Note also that the Dart VM backend uses the
// Dart async marker to decide if functions are debuggable.)
final nestedClosureVariable = new VariableDeclaration(":sync_op");
final function = new FunctionNode(buildClosureBody(),
positionalParameters: [iteratorVariable],
requiredParameterCount: 1,
asyncMarker: AsyncMarker.SyncYielding,
dartAsyncMarker: AsyncMarker.Sync)
..fileOffset = enclosingFunction.fileOffset
..fileEndOffset = enclosingFunction.fileEndOffset
..returnType = helper.coreTypes.boolLegacyRawType;
final closureFunction =
new FunctionDeclaration(nestedClosureVariable, function)
..fileOffset = enclosingFunction.parent.fileOffset;
// return new _SyncIterable<T>(:sync_body);
final arguments = new Arguments([new VariableGet(nestedClosureVariable)],
types: [elementTypeFromReturnType(helper.iterableClass)]);
final returnStatement = new ReturnStatement(
new ConstructorInvocation(helper.syncIterableConstructor, arguments));
enclosingFunction.body = new Block([]
..addAll(variableDeclarations())
..addAll([closureFunction, returnStatement]));
enclosingFunction.body.parent = enclosingFunction;
enclosingFunction.asyncMarker = AsyncMarker.Sync;
return enclosingFunction;
}
Statement buildClosureBody() {
// The body will insert calls to
// :iterator.current_=
// :iterator.isYieldEach=
// and return `true` as long as it did something and `false` when it's done.
return new Block(<Statement>[
enclosingFunction.body.accept<TreeNode>(this),
new ReturnStatement(new BoolLiteral(false))
..fileOffset = enclosingFunction.fileEndOffset
]);
}
visitYieldStatement(YieldStatement node) {
Expression transformedExpression = node.expression.accept<TreeNode>(this);
var statements = <Statement>[];
if (node.isYieldStar) {
statements.add(new ExpressionStatement(new PropertySet(
new VariableGet(iteratorVariable),
new Name("_yieldEachIterable", helper.coreLibrary),
transformedExpression,
helper.syncIteratorYieldEachIterable)));
} else {
statements.add(new ExpressionStatement(new PropertySet(
new VariableGet(iteratorVariable),
new Name("_current", helper.coreLibrary),
transformedExpression,
helper.syncIteratorCurrent)));
}
statements.add(createContinuationPoint(new BoolLiteral(true))
..fileOffset = node.fileOffset);
return new Block(statements);
}
TreeNode visitReturnStatement(ReturnStatement node) {
// sync* functions cannot return a value.
assert(node.expression == null || node.expression is NullLiteral);
node.expression = new BoolLiteral(false)..parent = node;
return node;
}
}
abstract class AsyncRewriterBase extends ContinuationRewriterBase {
final VariableDeclaration nestedClosureVariable =
new VariableDeclaration(":async_op");
final VariableDeclaration stackTraceVariable =
new VariableDeclaration(ContinuationVariables.asyncStackTraceVar);
final VariableDeclaration thenContinuationVariable =
new VariableDeclaration(":async_op_then");
final VariableDeclaration catchErrorContinuationVariable =
new VariableDeclaration(":async_op_error");
LabeledStatement labeledBody;
ExpressionLifter expressionRewriter;
AsyncRewriterBase(HelperNodes helper, FunctionNode enclosingFunction)
: super(helper, enclosingFunction) {}
void setupAsyncContinuations(List<Statement> statements) {
expressionRewriter = new ExpressionLifter(this);
// var :async_stack_trace;
statements.add(stackTraceVariable);
// var :async_op_then;
statements.add(thenContinuationVariable);
// var :async_op_error;
statements.add(catchErrorContinuationVariable);
// :async_op([:result, :exception, :stack_trace]) {
// modified <node.body>;
// }
final parameters = <VariableDeclaration>[
expressionRewriter.asyncResult,
new VariableDeclaration(ContinuationVariables.exceptionParam),
new VariableDeclaration(ContinuationVariables.stackTraceParam),
];
// Note: SyncYielding functions have no Dart equivalent. Since they are
// synchronous, we use Sync. (Note also that the Dart VM backend uses the
// Dart async marker to decide if functions are debuggable.)
final function = new FunctionNode(buildWrappedBody(),
positionalParameters: parameters,
requiredParameterCount: 0,
asyncMarker: AsyncMarker.SyncYielding,
dartAsyncMarker: AsyncMarker.Sync)
..fileOffset = enclosingFunction.fileOffset
..fileEndOffset = enclosingFunction.fileEndOffset;
// The await expression lifter might have created a number of
// [VariableDeclarations].
// TODO(kustermann): If we didn't need any variables we should not emit
// these.
statements.addAll(variableDeclarations());
statements.addAll(expressionRewriter.variables);
// Now add the closure function itself.
final closureFunction =
new FunctionDeclaration(nestedClosureVariable, function)
..fileOffset = enclosingFunction.parent.fileOffset;
statements.add(closureFunction);
// :async_stack_trace = _asyncStackTraceHelper(asyncBody);
final stackTrace = new StaticInvocation(helper.asyncStackTraceHelper,
new Arguments(<Expression>[new VariableGet(nestedClosureVariable)]));
final stackTraceAssign = new ExpressionStatement(
new VariableSet(stackTraceVariable, stackTrace));
statements.add(stackTraceAssign);
// :async_op_then = _asyncThenWrapperHelper(asyncBody);
final boundThenClosure = new StaticInvocation(helper.asyncThenWrapper,
new Arguments(<Expression>[new VariableGet(nestedClosureVariable)]));
final thenClosureVariableAssign = new ExpressionStatement(
new VariableSet(thenContinuationVariable, boundThenClosure));
statements.add(thenClosureVariableAssign);
// :async_op_error = _asyncErrorWrapperHelper(asyncBody);
final boundCatchErrorClosure = new StaticInvocation(
helper.asyncErrorWrapper,
new Arguments(<Expression>[new VariableGet(nestedClosureVariable)]));
final catchErrorClosureVariableAssign = new ExpressionStatement(
new VariableSet(
catchErrorContinuationVariable, boundCatchErrorClosure));
statements.add(catchErrorClosureVariableAssign);
}
Statement buildWrappedBody() {
++currentTryDepth;
labeledBody = new LabeledStatement(null);
labeledBody.body = visitDelimited(enclosingFunction.body)
..parent = labeledBody;
--currentTryDepth;
var exceptionVariable = new VariableDeclaration(":exception");
var stackTraceVariable = new VariableDeclaration(":stack_trace");
return new TryCatch(
buildReturn(labeledBody),
<Catch>[
new Catch(
exceptionVariable,
new Block(<Statement>[
buildCatchBody(exceptionVariable, stackTraceVariable)
]),
stackTrace: stackTraceVariable)
],
isSynthetic: true,
);
}
Statement buildCatchBody(
Statement exceptionVariable, Statement stackTraceVariable);
Statement buildReturn(Statement body);
List<Statement> statements = <Statement>[];
TreeNode visitExpressionStatement(ExpressionStatement stmt) {
stmt.expression = expressionRewriter.rewrite(stmt.expression, statements)
..parent = stmt;
statements.add(stmt);
return null;
}
TreeNode visitBlock(Block stmt) {
var saved = statements;
statements = <Statement>[];
for (var statement in stmt.statements) {
statement.accept<TreeNode>(this);
}
saved.add(new Block(statements));
statements = saved;
return null;
}
TreeNode visitEmptyStatement(EmptyStatement stmt) {
statements.add(stmt);
return null;
}
TreeNode visitAssertBlock(AssertBlock stmt) {
var saved = statements;
statements = <Statement>[];
for (var statement in stmt.statements) {
statement.accept<TreeNode>(this);
}
saved.add(new Block(statements));
statements = saved;
return null;
}
TreeNode visitAssertStatement(AssertStatement stmt) {
var condEffects = <Statement>[];
var cond = expressionRewriter.rewrite(stmt.condition, condEffects);
if (stmt.message == null) {
stmt.condition = cond..parent = stmt;
// If the translation of the condition produced a non-empty list of
// statements, ensure they are guarded by whether asserts are enabled.
statements.add(
condEffects.isEmpty ? stmt : new AssertBlock(condEffects..add(stmt)));
return null;
}
// The translation depends on the translation of the message, by cases.
Statement result;
var msgEffects = <Statement>[];
stmt.message = expressionRewriter.rewrite(stmt.message, msgEffects)
..parent = stmt;
if (condEffects.isEmpty) {
if (msgEffects.isEmpty) {
// The condition rewrote to ([], C) and the message rewrote to ([], M).
// The result is
//
// assert(C, M)
stmt.condition = cond..parent = stmt;
result = stmt;
} else {
// The condition rewrote to ([], C) and the message rewrote to (S*, M)
// where S* is non-empty. The result is
//
// assert { if (C) {} else { S*; assert(false, M); }}
stmt.condition = new BoolLiteral(false)..parent = stmt;
result = new AssertBlock([
new IfStatement(
cond, new EmptyStatement(), new Block(msgEffects..add(stmt)))
]);
}
} else {
if (msgEffects.isEmpty) {
// The condition rewrote to (S*, C) where S* is non-empty and the
// message rewrote to ([], M). The result is
//
// assert { S*; assert(C, M); }
stmt.condition = cond..parent = stmt;
condEffects.add(stmt);
} else {
// The condition rewrote to (S0*, C) and the message rewrote to (S1*, M)
// where both S0* and S1* are non-empty. The result is
//
// assert { S0*; if (C) {} else { S1*; assert(false, M); }}
stmt.condition = new BoolLiteral(false)..parent = stmt;
condEffects.add(new IfStatement(
cond, new EmptyStatement(), new Block(msgEffects..add(stmt))));
}
result = new AssertBlock(condEffects);
}
statements.add(result);
return null;
}
Statement visitDelimited(Statement stmt) {
var saved = statements;
statements = <Statement>[];
stmt.accept<TreeNode>(this);
Statement result =
statements.length == 1 ? statements.first : new Block(statements);
statements = saved;
return result;
}
Statement visitLabeledStatement(LabeledStatement stmt) {
stmt.body = visitDelimited(stmt.body)..parent = stmt;
statements.add(stmt);
return null;
}
Statement visitBreakStatement(BreakStatement stmt) {
statements.add(stmt);
return null;
}
TreeNode visitWhileStatement(WhileStatement stmt) {
Statement body = visitDelimited(stmt.body);
List<Statement> effects = <Statement>[];
Expression cond = expressionRewriter.rewrite(stmt.condition, effects);
if (effects.isEmpty) {
stmt.condition = cond..parent = stmt;
stmt.body = body..parent = stmt;
statements.add(stmt);
} else {
// The condition rewrote to a non-empty sequence of statements S* and
// value V. Rewrite the loop to:
//
// L: while (true) {
// S*
// if (V) {
// [body]
// else {
// break L;
// }
// }
LabeledStatement labeled = new LabeledStatement(stmt);
stmt.condition = new BoolLiteral(true)..parent = stmt;
effects.add(new IfStatement(cond, body, new BreakStatement(labeled)));
stmt.body = new Block(effects)..parent = stmt;
statements.add(labeled);
}
return null;
}
TreeNode visitDoStatement(DoStatement stmt) {
Statement body = visitDelimited(stmt.body);
List<Statement> effects = <Statement>[];
stmt.condition = expressionRewriter.rewrite(stmt.condition, effects)
..parent = stmt;
if (effects.isNotEmpty) {
// The condition rewrote to a non-empty sequence of statements S* and
// value V. Add the statements to the end of the loop body.
Block block = body is Block ? body : body = new Block(<Statement>[body]);
for (var effect in effects) {
block.statements.add(effect);
effect.parent = body;
}
}
stmt.body = body..parent = stmt;
statements.add(stmt);
return null;
}
TreeNode visitForStatement(ForStatement stmt) {
// Because of for-loop scoping and variable capture, it is tricky to deal
// with await in the loop's variable initializers or update expressions.
bool isSimple = true;
int length = stmt.variables.length;
List<List<Statement>> initEffects = new List<List<Statement>>(length);
for (int i = 0; i < length; ++i) {
VariableDeclaration decl = stmt.variables[i];
initEffects[i] = <Statement>[];
if (decl.initializer != null) {
decl.initializer = expressionRewriter.rewrite(
decl.initializer, initEffects[i])
..parent = decl;
}
isSimple = isSimple && initEffects[i].isEmpty;
}
length = stmt.updates.length;
List<List<Statement>> updateEffects = new List<List<Statement>>(length);
for (int i = 0; i < length; ++i) {
updateEffects[i] = <Statement>[];
stmt.updates[i] = expressionRewriter.rewrite(
stmt.updates[i], updateEffects[i])
..parent = stmt;
isSimple = isSimple && updateEffects[i].isEmpty;
}
Statement body = visitDelimited(stmt.body);
Expression cond = stmt.condition;
List<Statement> condEffects;
if (cond != null) {
condEffects = <Statement>[];
cond = expressionRewriter.rewrite(stmt.condition, condEffects);
}
if (isSimple) {
// If the condition contains await, we use a translation like the one for
// while loops, but leaving the variable declarations and the update
// expressions in place.
if (condEffects == null || condEffects.isEmpty) {
if (cond != null) stmt.condition = cond..parent = stmt;
stmt.body = body..parent = stmt;
statements.add(stmt);
} else {
LabeledStatement labeled = new LabeledStatement(stmt);
// No condition in a for loop is the same as true.
stmt.condition = null;
condEffects
.add(new IfStatement(cond, body, new BreakStatement(labeled)));
stmt.body = new Block(condEffects)..parent = stmt;
statements.add(labeled);
}
return null;
}
// If the rewrite of the initializer or update expressions produces a
// non-empty sequence of statements then the loop is desugared. If the loop
// has the form:
//
// label: for (Type x = init; cond; update) body
//
// it is translated as if it were:
//
// {
// bool first = true;
// Type temp;
// label: while (true) {
// Type x;
// if (first) {
// first = false;
// x = init;
// } else {
// x = temp;
// update;
// }
// if (cond) {
// body;
// temp = x;
// } else {
// break;
// }
// }
// }
// Place the loop variable declarations at the beginning of the body
// statements and move their initializers to a guarded list of statements.
// Add assignments to the loop variables from the previous iterations temp
// variables before the updates.
//
// temps.first is the flag 'first'.
// TODO(kmillikin) bool type for first.
List<VariableDeclaration> temps = <VariableDeclaration>[
new VariableDeclaration.forValue(new BoolLiteral(true), isFinal: false)
];
List<Statement> loopBody = <Statement>[];
List<Statement> initializers = <Statement>[
new ExpressionStatement(
new VariableSet(temps.first, new BoolLiteral(false)))
];
List<Statement> updates = <Statement>[];
List<Statement> newBody = <Statement>[body];
for (int i = 0; i < stmt.variables.length; ++i) {
VariableDeclaration decl = stmt.variables[i];
temps.add(new VariableDeclaration(null, type: decl.type));
loopBody.add(decl);
if (decl.initializer != null) {
initializers.addAll(initEffects[i]);
initializers.add(
new ExpressionStatement(new VariableSet(decl, decl.initializer)));
decl.initializer = null;
}
updates.add(new ExpressionStatement(
new VariableSet(decl, new VariableGet(temps.last))));
newBody.add(new ExpressionStatement(
new VariableSet(temps.last, new VariableGet(decl))));
}
// Add the updates to their guarded list of statements.
for (int i = 0; i < stmt.updates.length; ++i) {
updates.addAll(updateEffects[i]);
updates.add(new ExpressionStatement(stmt.updates[i]));
}
// Initializers or updates could be empty.
loopBody.add(new IfStatement(new VariableGet(temps.first),
new Block(initializers), new Block(updates)));
LabeledStatement labeled = new LabeledStatement(null);
if (cond != null) {
loopBody.addAll(condEffects);
} else {
cond = new BoolLiteral(true);
}
loopBody.add(
new IfStatement(cond, new Block(newBody), new BreakStatement(labeled)));
labeled.body =
new WhileStatement(new BoolLiteral(true), new Block(loopBody))
..parent = labeled;
statements.add(new Block(<Statement>[]
..addAll(temps)
..add(labeled)));
return null;
}
TreeNode visitForInStatement(ForInStatement stmt) {
if (stmt.isAsync) {
// Transform
//
// await for (T variable in <stream-expression>) { ... }
//
// To (in product mode):
//
// {
// :stream = <stream-expression>;
// _asyncStarListenHelper(:stream, :async_op);
// _StreamIterator<T> :for-iterator = new _StreamIterator<T>(:stream);
// try {
// while (await :for-iterator.moveNext()) {
// T <variable> = :for-iterator.current;
// ...
// }
// } finally {
// if (:for-iterator._subscription != null)
// await :for-iterator.cancel();
// }
// }
//
// Or (in non-product mode):
//
// {
// :stream = <stream-expression>;
// _asyncStarListenHelper(:stream, :async_op);
// _StreamIterator<T> :for-iterator = new _StreamIterator<T>(:stream);
// try {
// while (let _ = _asyncStarMoveNextHelper(:stream) in
// await :for-iterator.moveNext()) {
// T <variable> = :for-iterator.current;
// ...
// }
// } finally {
// if (:for-iterator._subscription != null)
// await :for-iterator.cancel();
// }
// }
var valueVariable = stmt.variable;
var streamVariable =
new VariableDeclaration(':stream', initializer: stmt.iterable);
var asyncStarListenHelper = new ExpressionStatement(new StaticInvocation(
helper.asyncStarListenHelper,
new Arguments([
new VariableGet(streamVariable),
new VariableGet(nestedClosureVariable)
])));
var iteratorVariable = new VariableDeclaration(':for-iterator',
initializer: new ConstructorInvocation(
helper.streamIteratorConstructor,
new Arguments(<Expression>[new VariableGet(streamVariable)],
types: [valueVariable.type])),
type: new InterfaceType(
helper.streamIteratorClass, [valueVariable.type]));
// await :for-iterator.moveNext()
var condition = new AwaitExpression(new MethodInvocation(
new VariableGet(iteratorVariable),
new Name('moveNext'),
new Arguments(<Expression>[]),
helper.streamIteratorMoveNext))
..fileOffset = stmt.fileOffset;
Expression whileCondition;
if (helper.productMode) {
whileCondition = condition;
} else {
// _asyncStarMoveNextHelper(:stream)
var asyncStarMoveNextCall = new StaticInvocation(
helper.asyncStarMoveNextHelper,
new Arguments([new VariableGet(streamVariable)]))
..fileOffset = stmt.fileOffset;
// let _ = asyncStarMoveNextCall in (condition)
whileCondition = new Let(
new VariableDeclaration(null, initializer: asyncStarMoveNextCall),
condition);
}
// T <variable> = :for-iterator.current;
valueVariable.initializer = new PropertyGet(
new VariableGet(iteratorVariable),
new Name('current'),
helper.streamIteratorCurrent)
..fileOffset = stmt.bodyOffset;
valueVariable.initializer.parent = valueVariable;
var whileBody = new Block(<Statement>[valueVariable, stmt.body]);
var tryBody = new WhileStatement(whileCondition, whileBody);
// if (:for-iterator._subscription != null) await :for-iterator.cancel();
var tryFinalizer = new IfStatement(
new Not(new MethodInvocation(
new PropertyGet(
new VariableGet(iteratorVariable),
new Name("_subscription", helper.asyncLibrary),
helper.coreTypes.streamIteratorSubscription),
new Name("=="),
new Arguments([new NullLiteral()]),
helper.coreTypes.objectEquals)),
new ExpressionStatement(new AwaitExpression(new MethodInvocation(
new VariableGet(iteratorVariable),
new Name('cancel'),
new Arguments(<Expression>[]),
helper.streamIteratorCancel))),
null);
var tryFinally = new TryFinally(tryBody, tryFinalizer);
var block = new Block(<Statement>[
streamVariable,
asyncStarListenHelper,
iteratorVariable,
tryFinally
]);
block.accept<TreeNode>(this);
} else {
stmt.iterable = expressionRewriter.rewrite(stmt.iterable, statements)
..parent = stmt;
stmt.body = visitDelimited(stmt.body)..parent = stmt;
statements.add(stmt);
}
return null;
}
TreeNode visitSwitchStatement(SwitchStatement stmt) {
stmt.expression = expressionRewriter.rewrite(stmt.expression, statements)
..parent = stmt;
for (var switchCase in stmt.cases) {
// Expressions in switch cases cannot contain await so they do not need to
// be translated.
switchCase.body = visitDelimited(switchCase.body)..parent = switchCase;
}
statements.add(stmt);
return null;
}
TreeNode visitContinueSwitchStatement(ContinueSwitchStatement stmt) {
statements.add(stmt);
return null;
}
TreeNode visitIfStatement(IfStatement stmt) {
stmt.condition = expressionRewriter.rewrite(stmt.condition, statements)
..parent = stmt;
stmt.then = visitDelimited(stmt.then)..parent = stmt;
if (stmt.otherwise != null) {
stmt.otherwise = visitDelimited(stmt.otherwise)..parent = stmt;
}
statements.add(stmt);
return null;
}
TreeNode visitTryCatch(TryCatch stmt) {
++currentTryDepth;
stmt.body = visitDelimited(stmt.body)..parent = stmt;
--currentTryDepth;
++currentCatchDepth;
for (var clause in stmt.catches) {
clause.body = visitDelimited(clause.body)..parent = clause;
}
--currentCatchDepth;
statements.add(stmt);
return null;
}
TreeNode visitTryFinally(TryFinally stmt) {
++currentTryDepth;
stmt.body = visitDelimited(stmt.body)..parent = stmt;
--currentTryDepth;
++currentCatchDepth;
stmt.finalizer = visitDelimited(stmt.finalizer)..parent = stmt;
--currentCatchDepth;
statements.add(stmt);
return null;
}
TreeNode visitYieldStatement(YieldStatement stmt) {
stmt.expression = expressionRewriter.rewrite(stmt.expression, statements)
..parent = stmt;
statements.add(stmt);
return null;
}
TreeNode visitVariableDeclaration(VariableDeclaration stmt) {
if (stmt.initializer != null) {
stmt.initializer = expressionRewriter.rewrite(
stmt.initializer, statements)
..parent = stmt;
}
statements.add(stmt);
return null;
}
TreeNode visitFunctionDeclaration(FunctionDeclaration stmt) {
stmt.function = stmt.function.accept<TreeNode>(this)..parent = stmt;
statements.add(stmt);
return null;
}
defaultExpression(TreeNode node) => throw 'unreachable';
}
class AsyncStarFunctionRewriter extends AsyncRewriterBase {
VariableDeclaration controllerVariable;
AsyncStarFunctionRewriter(HelperNodes helper, FunctionNode enclosingFunction)
: super(helper, enclosingFunction);
FunctionNode rewrite() {
var statements = <Statement>[];
final elementType = elementTypeFromReturnType(helper.streamClass);
// _AsyncStarStreamController<T> :controller;
controllerVariable = new VariableDeclaration(":controller",
type: new InterfaceType(
helper.asyncStarStreamControllerClass, [elementType]));
statements.add(controllerVariable);
// dynamic :controller_stream;
VariableDeclaration controllerStreamVariable =
new VariableDeclaration(ContinuationVariables.controllerStreamVar);
statements.add(controllerStreamVariable);
setupAsyncContinuations(statements);
// :controller = new _AsyncStarStreamController<T>(:async_op);
var arguments = new Arguments(
<Expression>[new VariableGet(nestedClosureVariable)],
types: [elementType]);
var buildController = new ConstructorInvocation(
helper.asyncStarStreamControllerConstructor, arguments)
..fileOffset = enclosingFunction.fileOffset;
var setController = new ExpressionStatement(
new VariableSet(controllerVariable, buildController));
statements.add(setController);
// :controller_stream = :controller.stream;
var completerGet = new VariableGet(controllerVariable);
statements.add(new ExpressionStatement(new VariableSet(
controllerStreamVariable,
new PropertyGet(completerGet, new Name('stream', helper.asyncLibrary),
helper.asyncStarStreamControllerStream))));
// return :controller_stream;
var returnStatement =
new ReturnStatement(new VariableGet(controllerStreamVariable));
statements.add(returnStatement);
enclosingFunction.body = new Block(statements);
enclosingFunction.body.parent = enclosingFunction;
enclosingFunction.asyncMarker = AsyncMarker.Sync;
return enclosingFunction;
}
Statement buildWrappedBody() {
++currentTryDepth;
Statement body = super.buildWrappedBody();
--currentTryDepth;
var finallyBody = new ExpressionStatement(new MethodInvocation(
new VariableGet(controllerVariable),
new Name("close"),
new Arguments(<Expression>[]),
helper.asyncStarStreamControllerClose));
var tryFinally = new TryFinally(body, new Block(<Statement>[finallyBody]));
return tryFinally;
}
Statement buildCatchBody(exceptionVariable, stackTraceVariable) {
return new ExpressionStatement(new MethodInvocation(
new VariableGet(controllerVariable),
new Name("addError"),
new Arguments(<Expression>[
new VariableGet(exceptionVariable),
new VariableGet(stackTraceVariable)
]),
helper.asyncStarStreamControllerAddError));
}
Statement buildReturn(Statement body) {
// Async* functions cannot return a value. The returns from the function
// have been translated into breaks from the labeled body.
return new Block(<Statement>[
body,
new ReturnStatement()..fileOffset = enclosingFunction.fileEndOffset,
]);
}
TreeNode visitYieldStatement(YieldStatement stmt) {
Expression expr = expressionRewriter.rewrite(stmt.expression, statements);
var addExpression = new MethodInvocation(
new VariableGet(controllerVariable),
new Name(stmt.isYieldStar ? 'addStream' : 'add', helper.asyncLibrary),
new Arguments(<Expression>[expr]),
stmt.isYieldStar
? helper.asyncStarStreamControllerAddStream
: helper.asyncStarStreamControllerAdd)
..fileOffset = stmt.fileOffset;
statements.add(new IfStatement(
addExpression,
new ReturnStatement(new NullLiteral()),
createContinuationPoint()..fileOffset = stmt.fileOffset));
return null;
}
TreeNode visitReturnStatement(ReturnStatement node) {
// Async* functions cannot return a value.
assert(node.expression == null || node.expression is NullLiteral);
statements
.add(new BreakStatement(labeledBody)..fileOffset = node.fileOffset);
return null;
}
}
class AsyncFunctionRewriter extends AsyncRewriterBase {
VariableDeclaration completerVariable;
VariableDeclaration returnVariable;
AsyncFunctionRewriter(HelperNodes helper, FunctionNode enclosingFunction)
: super(helper, enclosingFunction);
FunctionNode rewrite() {
var statements = <Statement>[];
// The original function return type should be Future<T> or FutureOr<T>
// because the function is async. If it was, we make a Completer<T>,
// otherwise we make a malformed type. In a "Future<T> foo() async {}"
// function the body can either return a "T" or a "Future<T>" => a
// "FutureOr<T>".
DartType valueType = elementTypeFromReturnType(helper.futureClass);
if (valueType == const DynamicType()) {
valueType = elementTypeFromReturnType(helper.futureOrClass);
}
final DartType returnType =
new InterfaceType(helper.futureOrClass, <DartType>[valueType]);
var completerTypeArguments = <DartType>[valueType];
final completerType = new InterfaceType(
helper.asyncAwaitCompleterClass, completerTypeArguments);
// final Completer<T> :async_completer = new _AsyncAwaitCompleter<T>();
completerVariable = new VariableDeclaration(":async_completer",
initializer: new ConstructorInvocation(
helper.asyncAwaitCompleterConstructor,
new Arguments([], types: completerTypeArguments))
..fileOffset = enclosingFunction.body?.fileOffset ?? -1,
isFinal: true,
type: completerType);
statements.add(completerVariable);
returnVariable = new VariableDeclaration(":return_value", type: returnType);
statements.add(returnVariable);
setupAsyncContinuations(statements);
// :async_completer.start(:async_op);
var startStatement = new ExpressionStatement(new MethodInvocation(
new VariableGet(completerVariable),
new Name('start'),
new Arguments([new VariableGet(nestedClosureVariable)]))
..fileOffset = enclosingFunction.fileOffset);
statements.add(startStatement);
// return :async_completer.future;
var completerGet = new VariableGet(completerVariable);
var returnStatement = new ReturnStatement(new PropertyGet(completerGet,
new Name('future', helper.asyncLibrary), helper.completerFuture));
statements.add(returnStatement);
enclosingFunction.body = new Block(statements);
enclosingFunction.body.parent = enclosingFunction;
enclosingFunction.asyncMarker = AsyncMarker.Sync;
return enclosingFunction;
}
Statement buildCatchBody(exceptionVariable, stackTraceVariable) {
return new ExpressionStatement(new MethodInvocation(
new VariableGet(completerVariable),
new Name("completeError"),
new Arguments([
new VariableGet(exceptionVariable),
new VariableGet(stackTraceVariable)
]),
helper.completerCompleteError));
}
Statement buildReturn(Statement body) {
// Returns from the body have all been translated into assignments to the
// return value variable followed by a break from the labeled body.
return new Block(<Statement>[
body,
new ExpressionStatement(new StaticInvocation(
helper.completeOnAsyncReturn,
new Arguments([
new VariableGet(completerVariable),
new VariableGet(returnVariable)
]))),
new ReturnStatement()..fileOffset = enclosingFunction.fileEndOffset
]);
}
visitReturnStatement(ReturnStatement node) {
var expr = node.expression == null
? new NullLiteral()
: expressionRewriter.rewrite(node.expression, statements);
statements.add(new ExpressionStatement(
new VariableSet(returnVariable, expr)..fileOffset = node.fileOffset));
statements.add(new BreakStatement(labeledBody));
return null;
}
}
class HelperNodes {
final Procedure asyncErrorWrapper;
final Library asyncLibrary;
final Procedure asyncStackTraceHelper;
final Member asyncStarStreamControllerAdd;
final Member asyncStarStreamControllerAddError;
final Member asyncStarStreamControllerAddStream;
final Class asyncStarStreamControllerClass;
final Member asyncStarStreamControllerClose;
final Constructor asyncStarStreamControllerConstructor;
final Member asyncStarStreamControllerStream;
final Member asyncStarListenHelper;
final Member asyncStarMoveNextHelper;
final Procedure asyncThenWrapper;
final Procedure awaitHelper;
final Class asyncAwaitCompleterClass;
final Member completerCompleteError;
final Member asyncAwaitCompleterConstructor;
final Member completeOnAsyncReturn;
final Member completerFuture;
final Library coreLibrary;
final CoreTypes coreTypes;
final Class futureClass;
final Class futureOrClass;
final Class iterableClass;
final Class streamClass;
final Member streamIteratorCancel;
final Class streamIteratorClass;
final Constructor streamIteratorConstructor;
final Member streamIteratorCurrent;
final Member streamIteratorMoveNext;
final Constructor syncIterableConstructor;
final Class syncIteratorClass;
final Member syncIteratorCurrent;
final Member syncIteratorYieldEachIterable;
final Class boolClass;
bool productMode;
HelperNodes._(
this.asyncErrorWrapper,
this.asyncLibrary,
this.asyncStackTraceHelper,
this.asyncStarStreamControllerAdd,
this.asyncStarStreamControllerAddError,
this.asyncStarStreamControllerAddStream,
this.asyncStarStreamControllerClass,
this.asyncStarStreamControllerClose,
this.asyncStarStreamControllerConstructor,
this.asyncStarStreamControllerStream,
this.asyncStarListenHelper,
this.asyncStarMoveNextHelper,
this.asyncThenWrapper,
this.awaitHelper,
this.asyncAwaitCompleterClass,
this.completerCompleteError,
this.asyncAwaitCompleterConstructor,
this.completeOnAsyncReturn,
this.completerFuture,
this.coreLibrary,
this.coreTypes,
this.futureClass,
this.futureOrClass,
this.iterableClass,
this.streamClass,
this.streamIteratorCancel,
this.streamIteratorClass,
this.streamIteratorConstructor,
this.streamIteratorCurrent,
this.streamIteratorMoveNext,
this.syncIterableConstructor,
this.syncIteratorClass,
this.syncIteratorCurrent,
this.syncIteratorYieldEachIterable,
this.boolClass,
this.productMode);
factory HelperNodes.fromCoreTypes(CoreTypes coreTypes, bool productMode) {
return new HelperNodes._(
coreTypes.asyncErrorWrapperHelperProcedure,
coreTypes.asyncLibrary,
coreTypes.asyncStackTraceHelperProcedure,
coreTypes.asyncStarStreamControllerAdd,
coreTypes.asyncStarStreamControllerAddError,
coreTypes.asyncStarStreamControllerAddStream,
coreTypes.asyncStarStreamControllerClass,
coreTypes.asyncStarStreamControllerClose,
coreTypes.asyncStarStreamControllerDefaultConstructor,
coreTypes.asyncStarStreamControllerStream,
coreTypes.asyncStarListenHelper,
coreTypes.asyncStarMoveNextHelper,
coreTypes.asyncThenWrapperHelperProcedure,
coreTypes.awaitHelperProcedure,
coreTypes.asyncAwaitCompleterClass,
coreTypes.completerCompleteError,
coreTypes.asyncAwaitCompleterConstructor,
coreTypes.completeOnAsyncReturn,
coreTypes.completerFuture,
coreTypes.coreLibrary,
coreTypes,
coreTypes.futureClass,
coreTypes.futureOrClass,
coreTypes.iterableClass,
coreTypes.streamClass,
coreTypes.streamIteratorCancel,
coreTypes.streamIteratorClass,
coreTypes.streamIteratorDefaultConstructor,
coreTypes.streamIteratorCurrent,
coreTypes.streamIteratorMoveNext,
coreTypes.syncIterableDefaultConstructor,
coreTypes.syncIteratorClass,
coreTypes.syncIteratorCurrent,
coreTypes.syncIteratorYieldEachIterable,
coreTypes.boolClass,
productMode);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/transformations/mixin_full_resolution.dart | // 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.
library kernel.transformations.mixin_full_resolution;
import '../ast.dart';
import '../class_hierarchy.dart';
import '../clone.dart';
import '../core_types.dart';
import '../target/targets.dart' show Target;
import '../type_algebra.dart';
void transformLibraries(Target targetInfo, CoreTypes coreTypes,
ClassHierarchy hierarchy, List<Library> libraries,
{bool doSuperResolution: true}) {
new MixinFullResolution(targetInfo, coreTypes, hierarchy,
doSuperResolution: doSuperResolution)
.transform(libraries);
}
/// Replaces all mixin applications with regular classes, cloning all fields
/// and procedures from the mixed-in class, cloning all constructors from the
/// base class.
///
/// When [doSuperResolution] constructor parameter is [true], super calls
/// (as well as super initializer invocations) are also resolved to their
/// targets in this pass.
class MixinFullResolution {
final Target targetInfo;
final CoreTypes coreTypes;
/// The [ClassHierarchy] that should be used after applying this transformer.
/// If any class was updated, in general we need to create a new
/// [ClassHierarchy] instance, with new dispatch targets; or at least let
/// the existing instance know that some of its dispatch tables are not
/// valid anymore.
ClassHierarchy hierarchy;
// This enables `super` resolution transformation, which is not compatible
// with Dart VM's requirements around incremental compilation and has been
// moved to Dart VM itself.
final bool doSuperResolution;
MixinFullResolution(this.targetInfo, this.coreTypes, this.hierarchy,
{this.doSuperResolution: true});
/// Transform the given new [libraries]. It is expected that all other
/// libraries have already been transformed.
void transform(List<Library> libraries) {
if (libraries.isEmpty) return;
var transformedClasses = new Set<Class>();
// Desugar all mixin application classes by copying in fields/methods from
// the mixin and constructors from the base class.
var processedClasses = new Set<Class>();
for (var library in libraries) {
if (library.isExternal) continue;
for (var class_ in library.classes) {
transformClass(libraries, processedClasses, transformedClasses, class_);
}
}
// We might need to update the class hierarchy.
hierarchy =
hierarchy.applyMemberChanges(transformedClasses, findDescendants: true);
if (!doSuperResolution) {
return;
}
// Resolve all super call expressions and super initializers.
for (var library in libraries) {
if (library.isExternal) continue;
for (var class_ in library.classes) {
for (var procedure in class_.procedures) {
if (procedure.containsSuperCalls) {
new SuperCallResolutionTransformer(
hierarchy, coreTypes, class_.superclass, targetInfo)
.visit(procedure);
}
}
}
}
}
transformClass(
List<Library> librariesToBeTransformed,
Set<Class> processedClasses,
Set<Class> transformedClasses,
Class class_) {
// If this class was already handled then so were all classes up to the
// [Object] class.
if (!processedClasses.add(class_)) return;
if (!librariesToBeTransformed.contains(class_.enclosingLibrary) &&
class_.enclosingLibrary.importUri?.scheme == "dart") {
// If we're not asked to transform the platform libraries then we expect
// that they will be already transformed.
return;
}
// Ensure super classes have been transformed before this class.
if (class_.superclass != null &&
class_.superclass.level.index >= ClassLevel.Mixin.index) {
transformClass(librariesToBeTransformed, processedClasses,
transformedClasses, class_.superclass);
}
// If this is not a mixin application we don't need to make forwarding
// constructors in this class.
if (!class_.isMixinApplication) return;
assert(librariesToBeTransformed.contains(class_.enclosingLibrary));
if (class_.mixedInClass.level.index < ClassLevel.Mixin.index) {
throw new Exception(
'Class "${class_.name}" mixes in "${class_.mixedInClass.name}" from'
' an external library. Did you forget --link?');
}
transformedClasses.add(class_);
// Clone fields and methods from the mixin class.
var substitution = getSubstitutionMap(class_.mixedInType);
var cloner = new CloneVisitor(typeSubstitution: substitution);
// When we copy a field from the mixed in class, we remove any
// forwarding-stub getters/setters from the superclass, but copy their
// covariance-bits onto the new field.
var nonSetters = <Name, Procedure>{};
var setters = <Name, Procedure>{};
for (var procedure in class_.procedures) {
if (procedure.isSetter) {
setters[procedure.name] = procedure;
} else {
nonSetters[procedure.name] = procedure;
}
}
for (var field in class_.mixin.fields) {
Field clone = cloner.clone(field);
Procedure setter = setters[field.name];
if (setter != null) {
setters.remove(field.name);
VariableDeclaration parameter =
setter.function.positionalParameters.first;
clone.isGenericCovariantImpl = parameter.isGenericCovariantImpl;
}
nonSetters.remove(field.name);
class_.addMember(clone);
}
class_.procedures.clear();
class_.procedures..addAll(nonSetters.values)..addAll(setters.values);
// Existing procedures in the class should only be forwarding stubs.
// Replace them with methods from the mixin class if they have the same
// name, but keep their parameter flags.
int originalLength = class_.procedures.length;
outer:
for (var procedure in class_.mixin.procedures) {
// Forwarding stubs in the mixin class are used when calling through the
// mixin class's interface, not when calling through the mixin
// application. They should not be copied.
if (procedure.isForwardingStub) continue;
// Factory constructors are not cloned.
if (procedure.isFactory) continue;
// NoSuchMethod forwarders aren't cloned.
if (procedure.isNoSuchMethodForwarder) continue;
Procedure clone = cloner.clone(procedure);
// Linear search for a forwarding stub with the same name.
for (int i = 0; i < originalLength; ++i) {
var originalProcedure = class_.procedures[i];
if (originalProcedure.name == clone.name &&
originalProcedure.kind == clone.kind) {
FunctionNode src = originalProcedure.function;
FunctionNode dst = clone.function;
if (src.positionalParameters.length !=
dst.positionalParameters.length ||
src.namedParameters.length != dst.namedParameters.length) {
// A compile time error has already occurred, but don't crash below,
// and don't add several procedures with the same name to the class.
continue outer;
}
assert(src.typeParameters.length == dst.typeParameters.length);
for (int j = 0; j < src.typeParameters.length; ++j) {
dst.typeParameters[j].flags = src.typeParameters[j].flags;
}
for (int j = 0; j < src.positionalParameters.length; ++j) {
dst.positionalParameters[j].flags =
src.positionalParameters[j].flags;
}
// TODO(kernel team): The named parameters are not sorted,
// this might not be correct.
for (int j = 0; j < src.namedParameters.length; ++j) {
dst.namedParameters[j].flags = src.namedParameters[j].flags;
}
class_.procedures[i] = clone;
continue outer;
}
}
class_.addMember(clone);
}
assert(class_.constructors.isNotEmpty);
// This class implements the mixin type. Also, backends rely on the fact
// that eliminated mixin is appended into the end of interfaces list.
class_.implementedTypes.add(class_.mixedInType);
// This class is now a normal class.
class_.mixedInType = null;
// Leave breadcrumbs for backends (e.g. for dart:mirrors implementation).
class_.isEliminatedMixin = true;
}
}
class SuperCallResolutionTransformer extends Transformer {
final ClassHierarchy hierarchy;
final CoreTypes coreTypes;
final Class lookupClass;
final Target targetInfo;
SuperCallResolutionTransformer(
this.hierarchy, this.coreTypes, this.lookupClass, this.targetInfo);
TreeNode visit(TreeNode node) => node.accept(this);
visitSuperPropertyGet(SuperPropertyGet node) {
Member target = hierarchy.getDispatchTarget(lookupClass, node.name);
if (target != null) {
return new DirectPropertyGet(new ThisExpression(), target)
..fileOffset = node.fileOffset;
} else {
return _callNoSuchMethod(node.name.name, new Arguments.empty(), node,
isGetter: true, isSuper: true);
}
}
visitSuperPropertySet(SuperPropertySet node) {
Member target =
hierarchy.getDispatchTarget(lookupClass, node.name, setter: true);
if (target != null) {
return new DirectPropertySet(
new ThisExpression(), target, visit(node.value))
..fileOffset = node.fileOffset;
} else {
// Call has to return right-hand-side.
VariableDeclaration rightHandSide =
new VariableDeclaration.forValue(visit(node.value));
Expression result = _callNoSuchMethod(
node.name.name, new Arguments([new VariableGet(rightHandSide)]), node,
isSetter: true, isSuper: true);
VariableDeclaration call = new VariableDeclaration.forValue(result);
return new Let(
rightHandSide, new Let(call, new VariableGet(rightHandSide)));
}
}
visitSuperMethodInvocation(SuperMethodInvocation node) {
Member target = hierarchy.getDispatchTarget(lookupClass, node.name);
Arguments visitedArguments = visit(node.arguments);
if (target is Procedure &&
!target.isAccessor &&
_callIsLegal(target.function, visitedArguments)) {
return new DirectMethodInvocation(
new ThisExpression(), target, visitedArguments)
..fileOffset = node.fileOffset;
} else if (target == null || (target is Procedure && !target.isAccessor)) {
// Target not found at all, or call was illegal.
return _callNoSuchMethod(node.name.name, visitedArguments, node,
isSuper: true);
} else {
return new MethodInvocation(
new DirectPropertyGet(new ThisExpression(), target),
new Name('call'),
visitedArguments)
..fileOffset = node.fileOffset;
}
}
/// Create a call to no such method.
Expression _callNoSuchMethod(
String methodName, Arguments methodArguments, TreeNode node,
{isSuper: false, isGetter: false, isSetter: false}) {
Member noSuchMethod =
hierarchy.getDispatchTarget(lookupClass, new Name("noSuchMethod"));
String methodNameUsed = (isGetter)
? "get:$methodName"
: (isSetter) ? "set:$methodName" : methodName;
if (noSuchMethod != null &&
noSuchMethod.function.positionalParameters.length == 1 &&
noSuchMethod.function.namedParameters.isEmpty) {
// We have a correct noSuchMethod method.
ConstructorInvocation invocation = _createInvocation(
methodNameUsed, methodArguments, isSuper, new ThisExpression());
return new DirectMethodInvocation(
new ThisExpression(), noSuchMethod, new Arguments([invocation]))
..fileOffset = node.fileOffset;
} else {
// Incorrect noSuchMethod method: Call noSuchMethod on Object
// with Invocation of noSuchMethod as the method that did not exist.
noSuchMethod = hierarchy.getDispatchTarget(
coreTypes.objectClass, new Name("noSuchMethod"));
ConstructorInvocation invocation = _createInvocation(
methodNameUsed, methodArguments, isSuper, new ThisExpression());
ConstructorInvocation invocationPrime = _createInvocation("noSuchMethod",
new Arguments([invocation]), false, new ThisExpression());
return new DirectMethodInvocation(
new ThisExpression(), noSuchMethod, new Arguments([invocationPrime]))
..fileOffset = node.fileOffset;
}
}
/// Creates an "new _InvocationMirror(...)" invocation.
ConstructorInvocation _createInvocation(String methodName,
Arguments callArguments, bool isSuperInvocation, Expression receiver) {
return targetInfo.instantiateInvocation(
coreTypes, receiver, methodName, callArguments, -1, isSuperInvocation);
}
/// Check that a call to the targetFunction is legal given the arguments.
///
/// I.e. check that the number of positional parameters and the names of the
/// given named parameters represents a valid call to the function.
bool _callIsLegal(FunctionNode targetFunction, Arguments arguments) {
if ((targetFunction.requiredParameterCount > arguments.positional.length) ||
(targetFunction.positionalParameters.length <
arguments.positional.length)) {
// Given too few or too many positional arguments
return false;
}
// Do we give named that we don't take?
Set<String> givenNamed = arguments.named.map((v) => v.name).toSet();
Set<String> takenNamed =
targetFunction.namedParameters.map((v) => v.name).toSet();
givenNamed.removeAll(takenNamed);
return givenNamed.isEmpty;
}
}
class SuperInitializerResolutionTransformer extends InitializerVisitor {
final Class lookupClass;
SuperInitializerResolutionTransformer(this.lookupClass);
transformInitializers(List<Initializer> initializers) {
for (var initializer in initializers) {
initializer.accept(this);
}
}
visitSuperInitializer(SuperInitializer node) {
Constructor constructor = node.target;
if (constructor.enclosingClass != lookupClass) {
// If [node] refers to a constructor target which is not directly the
// superclass but some indirect base class then this is because classes in
// the middle are mixin applications. These mixin applications will have
// received a forwarding constructor which we are required to use instead.
for (var replacement in lookupClass.constructors) {
if (constructor.name == replacement.name) {
node.target = replacement;
return null;
}
}
throw new Exception(
'Could not find a generative constructor named "${constructor.name}" '
'in lookup class "${lookupClass.name}"!');
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/transformations/method_call.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.transformations.method_call;
import 'dart:math' as math;
import '../ast.dart';
import '../class_hierarchy.dart';
import '../core_types.dart';
import '../kernel.dart';
import '../visitor.dart';
/// Problems with the method rewrite transformation:
///
/// * Cannot rewrite invocations to things called "call" because of tear-offs
/// and whatnot that when invoked turns into variableName.call(...).
///
/// * Cannot rewrite invocations to things sharing a name with a field because
/// one could have called clazz.fieldName(...).
///
/// * Rewrites will make stacktraces look weird.
///
/// * Rewrites will make noSuchMethod look weird --- e.g. calling a non-existing
/// function foo(a: 42) turns into foo%0%a(42), i.e. the method name has
/// changed ("foo" vs "foo%0%a") and the arguments has changed (named "a" vs
/// positional).
/// NOTE: At least for now this can be fixed by changing the
/// invocation_mirror_patch file. Doing this I can make all dill, language
/// and co19 tests pass!
///
/// Somewhat weird:
///
/// * Inserts methods that redirect to the correct noSuchMethod invocation
/// so that program #1 example below will work.
/// The reason it otherwise wouldn't is that b.foo(499, named1: 88) is
/// rewritten to b.foo%1%named1(499, 88) which is not legal for class B
/// (thus the method would not be create there) but IS legal for Bs parent
/// class (A), so it would be created there. The call will thus go to the
/// super (A) but shouldn't as foo was overwritten in B.
///
/// Program #1 example:
/// class A {
/// foo(required1, { named1: 499}) => print("Hello from class A");
/// }
///
/// class B extends A {
/// foo(required1) => print("Hello from class B");
/// }
///
/// main() {
/// var b = new B();
/// b.foo(499, named1: 88);
/// }
Component transformComponent(
CoreTypes coreTypes, ClassHierarchy hierarchy, Component component,
[debug = false]) {
new MethodCallTransformer(coreTypes, hierarchy, debug)
.visitComponent(component);
return component;
}
class MethodCallTransformer extends Transformer {
final CoreTypes coreTypes;
/// Keep track of "visited" procedures and constructors to not visit already
/// visited stuff, nor visit newly created stubs.
Set<Member> _visited = new Set<Member>();
/// Some things currently cannot be rewritten. Calls to methods called "call"
/// (because invoking tear-offs and closures and whatnot becomes .call)
/// as well as clashes with field names as a field can contain a function
/// and one can then do a clazz.fieldName(...).
Set<String> blacklistedSelectors = new Set<String>.from(["call"]);
/// Map from a "originally named" procedure to the "%original" procedure
/// for procedures that was moved.
Map<Procedure, Procedure> _movedBodies = {};
/// Map from a "originally named" constructor to the "%original"
/// constructor for constructors that was moved.
Map<Constructor, Constructor> _movedConstructors = {};
/// For static method transformations:
/// Maps a procedure to the mapping of argument signature to procedure stub.
Map<Procedure, Map<String, Procedure>> _staticProcedureCalls = {};
/// For constructor transformations:
/// Maps a constructor to a mapping of argument signature to constructor stub.
Map<Constructor, Map<String, Constructor>> _constructorCalls = {};
/// For non-static method transformations:
/// Maps from method name to the set of legal number of positional arguments.
Map<String, Set<int>> _methodToLegalPositionalArgumentCount = {};
/// For non-static method transformations:
/// Maps from name of method to the set of new target names seen for at least
/// one instance (i.e. rewriting has been performed from key to all values in
/// the mapped to set at least once).
Map<Name, Set<String>> _rewrittenMethods = {};
/// For non-static method transformations:
/// Maps a procedure to the mapping of argument signature to procedure stub.
Map<Procedure, Map<String, Procedure>> _superProcedureCalls = {};
/// Whether in debug mode, i.e. if we can insert extra print statements for
/// debugging purposes.
bool _debug;
/// For noSuchMethod calls.
ClassHierarchy hierarchy;
Constructor _invocationMirrorConstructor; // cached
Procedure _listFrom; // cached
MethodCallTransformer(this.coreTypes, this.hierarchy, this._debug);
@override
TreeNode visitComponent(Component node) {
// First move body of all procedures that takes optional positional or named
// parameters and record which non-static procedure names have optional
// positional arguments.
// Do the same for constructors. Then also rewrite constructor initializers
// using LocalInitializer and sort named arguments in those initializers
for (final library in node.libraries) {
for (final procedure in new List<Procedure>.from(library.procedures)) {
_moveAndTransformProcedure(procedure);
}
for (final clazz in library.classes) {
for (final field in clazz.fields) {
blacklistedSelectors.add(field.name.name);
}
for (final procedure in new List<Procedure>.from(clazz.procedures)) {
// This call creates new procedures
_moveAndTransformProcedure(procedure);
_recordNonStaticProcedureAndVariableArguments(procedure);
}
for (final constructor
in new List<Constructor>.from(clazz.constructors)) {
// This call creates new constructors
_moveAndTransformConstructor(constructor);
}
for (final constructor in clazz.constructors) {
_rewriteConstructorInitializations(constructor);
}
}
}
// Rewrite calls
node.transformChildren(this);
// Now for all method calls that was rewritten, make sure those call
// destinations actually exist, i.e. for each method with a matching name
// where the called-with-arguments is legal, create a stub
for (final library in node.libraries) {
for (final clazz in library.classes) {
for (final procedure in new List<Procedure>.from(clazz.procedures)) {
// This call creates new procedures
_createNeededNonStaticStubs(procedure);
}
}
}
return node;
}
@override
TreeNode visitProcedure(Procedure node) {
if (!_visited.contains(node)) {
_visited.add(node);
node.transformChildren(this);
}
return node;
}
@override
TreeNode visitConstructor(Constructor node) {
if (!_visited.contains(node)) {
_visited.add(node);
node.transformChildren(this);
}
return node;
}
@override
TreeNode visitStaticInvocation(StaticInvocation node) {
node.transformChildren(this);
if (!_isMethod(node.target)) return node;
if (!_hasAnyOptionalParameters(node.target.function)) return node;
if (!_callIsLegal(node.target.function, node.arguments)) return node;
// Rewrite with let if needed (without named arguments it won't do anything)
Expression rewrittenNode = _rewriteWithLetAndSort(node, node.arguments);
// Create/lookup target and set it as the new target
node.target = _getNewTargetForStaticLikeInvocation(
node.target, node.arguments, _staticProcedureCalls);
// Now turn any named parameters into positional parameters
_turnNamedArgumentsIntoPositional(node.arguments);
return rewrittenNode;
}
@override
TreeNode visitDirectMethodInvocation(DirectMethodInvocation node) {
node.transformChildren(this);
if (!_isMethod(node.target)) return node;
if (!_hasAnyOptionalParameters(node.target.function)) return node;
if (!_callIsLegal(node.target.function, node.arguments)) return node;
// Rewrite with let if needed (without named arguments it won't do anything)
Expression rewrittenNode = _rewriteWithLetAndSort(node, node.arguments);
// Create/lookup target and set it as the new target
node.target = _getNewTargetForStaticLikeInvocation(
node.target, node.arguments, _superProcedureCalls);
// Now turn any named parameters into positional parameters instead
_turnNamedArgumentsIntoPositional(node.arguments);
return rewrittenNode;
}
@override
TreeNode visitSuperMethodInvocation(SuperMethodInvocation node) {
// SuperMethodInvocation was changed since I originally wrote this,
// and now it seems to never be called anyway.
throw "visitSuperMethodInvocation is not implemented!";
}
@override
TreeNode visitMethodInvocation(MethodInvocation node) {
node.transformChildren(this);
final name = node.name.name;
// Don't renamed calls to methods that clashes in name with a field
// or is called "call".
if (blacklistedSelectors.contains(name)) return node;
// Rewrite with let if needed (without named arguments it won't do anything)
Expression rewrittenNode = _rewriteWithLetAndSort(node, node.arguments);
String argumentsSignature = _createArgumentsSignature(node.arguments);
if (node.arguments.named.isEmpty) {
// Positional: Don't rewrite if no procedure with that name can be called
// with a variable number of arguments, or where the number of arguments
// called with here isn't a legal number of arguments to any such
// procedure.
// Note for named arguments: Named arguments are always rewritten
// (except for 'call' methods) so there's no such check
final okCounts = _methodToLegalPositionalArgumentCount[name];
if (okCounts == null ||
!okCounts.contains(node.arguments.positional.length)) {
return node;
}
}
// Rewrite this call
final originalName = node.name;
node.name = _createName(node.name, argumentsSignature);
// Remember that we rewrote this call
_rewrittenMethods
.putIfAbsent(originalName, () => new Set<String>())
.add(argumentsSignature);
// Now turn any named parameters into positional parameters instead
_turnNamedArgumentsIntoPositional(node.arguments);
return rewrittenNode;
}
@override
TreeNode visitConstructorInvocation(ConstructorInvocation node) {
node.transformChildren(this);
if (!_callIsLegal(node.target.function, node.arguments)) return node;
Expression rewrittenNode;
if (node.isConst) {
// Sort named arguments by name => it's const so there's no side-effects!
// but DO NOT rewrite with let!
node.arguments.named.sort((a, b) => a.name.compareTo(b.name));
rewrittenNode = node;
} else {
rewrittenNode = _rewriteWithLetAndSort(node, node.arguments);
}
node.target = _getNewTargetForConstructor(node.target, node.arguments);
// Now turn named parameters into positional parameters instead
_turnNamedArgumentsIntoPositional(node.arguments);
return rewrittenNode;
}
@override
TreeNode visitSuperInitializer(SuperInitializer node) {
// Note that sorting was done in _rewriteConstructorInitializations
node.transformChildren(this);
if (!_callIsLegal(node.target.function, node.arguments)) return node;
node.target = _getNewTargetForConstructor(node.target, node.arguments);
// Now turn named parameters into positional parameters instead
_turnNamedArgumentsIntoPositional(node.arguments);
return node;
}
@override
TreeNode visitRedirectingInitializer(RedirectingInitializer node) {
// Note that sorting was done in _rewriteConstructorInitializations
node.transformChildren(this);
if (!_callIsLegal(node.target.function, node.arguments)) return node;
node.target = _getNewTargetForConstructor(node.target, node.arguments);
// Now turn named parameters into positional parameters instead
_turnNamedArgumentsIntoPositional(node.arguments);
return node;
}
/// Gets the new target for an invocation, using cache or creating a new one.
///
/// Assumes that any let-rewrite, named argument sorting etc has been done
/// already.
Procedure _getNewTargetForStaticLikeInvocation(Procedure target,
Arguments arguments, Map<Procedure, Map<String, Procedure>> cache) {
final createdProcedures = cache.putIfAbsent(target, () => {});
// Rewrite target
final argumentsSignature = _createArgumentsSignature(arguments);
return createdProcedures[argumentsSignature] ??
_createAndCacheInvocationProcedure(
argumentsSignature,
arguments.positional.length,
arguments.named.map((e) => e.name).toList(),
target,
_movedBodies[target],
createdProcedures,
true);
}
/// Rewrite the [Argument]s turning named arguments into positional arguments.
///
/// Note that if the [Argument]s does not take any named parameters this
/// method does nothing.
void _turnNamedArgumentsIntoPositional(Arguments arguments) {
for (final named in arguments.named) {
arguments.positional.add(named.value..parent = arguments);
}
arguments.named.clear();
}
/// Gets the new target for an invocation, using cache or creating a new one.
///
/// Assumes that any let-rewrite, named argument sorting etc has been done
/// already.
Constructor _getNewTargetForConstructor(
Constructor target, Arguments arguments) {
if (!_isNotExternal(target)) return target;
if (!_hasAnyOptionalParameters(target.function)) return target;
final argumentsSignature = _createArgumentsSignature(arguments);
final createdConstructor = _constructorCalls.putIfAbsent(target, () => {});
return createdConstructor[argumentsSignature] ??
_createAndCacheInvocationConstructor(
argumentsSignature,
arguments.positional.length,
arguments.named.map((e) => e.name).toList(),
target,
_movedConstructors[target],
createdConstructor,
true);
}
/// Create a signature for the [Arguments].
///
/// Assumes that any needed sorting etc has already been done.
///
/// Looks like x%positionalCount%named --- but it shouldn't matter if always
/// using these methods
String _createArgumentsSignature(Arguments arguments) {
String namedString = arguments.named.map((e) => e.name).join("%");
return "${arguments.positional.length}%$namedString";
}
/// Parse the argument signature.
///
/// First element will be the string representation of the number of
/// positional arguments used.
/// The rest will be the named arguments, except that with no named arguments
/// there still is a 2nd entry: the empty string...
List<String> _parseArgumentsSignature(String argumentsSignature) {
return argumentsSignature.split("%");
}
/// Rewrites an expression with let, replacing expressions in the [Arguments].
///
/// Sorts the named arguments after rewriting with let.
///
/// Note that this method does nothing if there are no named arguments, or the
/// named arguments list contain only a single named argument as any sorting
/// would have no effect. As such, the let-rewrite will also have no effect.
/// In such a case the return value is [original].
Expression _rewriteWithLetAndSort(Expression original, Arguments arguments) {
final named = arguments.named;
// Only bother if names can be unordered
if (named.length < 2) return original;
// Rewrite named with let in given order
Let let;
for (int i = named.length - 1; i >= 0; i--) {
VariableDeclaration letDeclaration =
new VariableDeclaration.forValue(named[i].value);
named[i].value = new VariableGet(letDeclaration)..parent = arguments;
let = new Let(letDeclaration, let ?? original);
}
// Sort named arguments by name
named.sort((a, b) => a.name.compareTo(b.name));
// Now also add the given positional arguments into the let
final expressions = arguments.positional;
for (int i = expressions.length - 1; i >= 0; i--) {
VariableDeclaration letDeclaration =
new VariableDeclaration.forValue(expressions[i]);
expressions[i] = new VariableGet(letDeclaration)..parent = arguments;
let = new Let(letDeclaration, let ?? original);
}
return let;
}
/// Creates all needed stubs for non static procedures.
///
/// More specifically: If calls have been made to a procedure with the same
/// name as this procedure with both 1 and 2 arguments, where both of these
/// are legal inputs to this procedure, create stubs for both of them,
/// each of which calls with whatever default parameter values are defined for
/// the non-given arguments.
void _createNeededNonStaticStubs(Procedure procedure) {
final incomingCalls = _rewrittenMethods[procedure.name];
if (incomingCalls != null &&
procedure.kind == ProcedureKind.Method &&
!procedure.isStatic) {
final createdOnSuper = _superProcedureCalls[procedure];
final names =
procedure.function.namedParameters.map((e) => e.name).toSet();
// A procedure with this name was called on at least one object with
// an argument signature like any in [incomingCalls]
nextArgumentSignature:
for (final argumentsSignature in incomingCalls) {
// Skip if it was created in a super call already
if (createdOnSuper != null &&
createdOnSuper.containsKey(argumentsSignature)) {
continue;
}
final elements = _parseArgumentsSignature(argumentsSignature);
int positional = int.parse(elements[0]);
if (positional < procedure.function.requiredParameterCount ||
positional > procedure.function.positionalParameters.length) {
// We don't take that number of positional parameters!
// Call noSuchMethod in case anyone called on object with wrong
// parameters, but where superclass does take these parameters.
_createNoSuchMethodStub(
argumentsSignature, positional, elements.sublist(1), procedure);
continue;
}
if (elements.length > 2 || elements[1] != "") {
// Named: Could the call be for this method?
for (int i = 1; i < elements.length; i++) {
String name = elements[i];
// Using a name that we don't have?
if (!names.contains(name)) {
// Call noSuchMethod in case anyone called on object with wrong
// parameters, but where superclass does take these parameters.
_createNoSuchMethodStub(argumentsSignature, positional,
elements.sublist(1), procedure);
continue nextArgumentSignature;
}
}
}
// Potential legal call => make stub
// Note the ?? here: E.g. contains on list doesn't take optionals so it
// wasn't moved, but calls were rewritten because contains on string
// takes either 1 or 2 arguments.
final destination = _movedBodies[procedure] ?? procedure;
_createAndCacheInvocationProcedure(argumentsSignature, positional,
elements.sublist(1), procedure, destination, {}, false);
}
}
}
/// Records how this procedure can be called (if it is non-static).
///
/// More specifically: Assuming that the procedure given is non-static taking
/// a variable number of positional parameters, record all number of arguments
/// that is legal, e.g. foo(int a, [int b]) is legal for 1 and 2 parameters.
/// If it takes named parameters, remember how many positional there is so
/// we also know to rewrite calls without the named arguments.
void _recordNonStaticProcedureAndVariableArguments(Procedure procedure) {
if (_isMethod(procedure) &&
!procedure.isStatic &&
_hasAnyOptionalParameters(procedure.function)) {
final name = procedure.name.name;
final okCounts = _methodToLegalPositionalArgumentCount.putIfAbsent(
name, () => new Set<int>());
for (int i = procedure.function.requiredParameterCount;
i <= procedure.function.positionalParameters.length;
i++) {
okCounts.add(i);
}
}
}
/// Move body of procedure to new procedure and call that from this procedure.
///
/// More specifically: For all procedures with optional positional parameters,
/// or named parameters, create a new procedure without optional positional
/// parameters and named parameters and move the body of the original
/// procedure into this new procedure.
/// Then make the body of the original procedure call the new procedure.
///
/// The idea is that all rewrites should call the moved procedure instead,
/// bypassing the optional/named arguments entirely.
void _moveAndTransformProcedure(Procedure procedure) {
if (_isMethod(procedure) && _hasAnyOptionalParameters(procedure.function)) {
final function = procedure.function;
// Create variable lists
final newParameterDeclarations = <VariableDeclaration>[];
final newNamedParameterDeclarations = <VariableDeclaration>[];
final newParameterVariableGets = <Expression>[];
final targetParameters = function.positionalParameters;
final targetNamedParameters = function.namedParameters;
_moveVariableInitialization(
targetParameters,
targetNamedParameters,
newParameterDeclarations,
newNamedParameterDeclarations,
newParameterVariableGets,
procedure.function);
// Create new procedure looking like the old one
// (with the old body and parameters)
FunctionNode functionNode = _createShallowFunctionCopy(function);
final newProcedure = new Procedure(
_createOriginalName(procedure), ProcedureKind.Method, functionNode,
isAbstract: procedure.isAbstract,
isStatic: procedure.isStatic,
isConst: procedure.isConst,
fileUri: procedure.fileUri);
// Add procedure to the code
_addMember(procedure, newProcedure);
// Map moved body
_movedBodies[procedure] = newProcedure;
// Transform original procedure
if (procedure.isAbstract && procedure.function.body == null) {
// do basically nothing then
procedure.function.positionalParameters = newParameterDeclarations;
procedure.function.namedParameters = newNamedParameterDeclarations;
} else if (procedure.isStatic) {
final expression = new StaticInvocation(
newProcedure, new Arguments(newParameterVariableGets));
final statement = new ReturnStatement(expression)
..parent = procedure.function;
procedure.function.body = statement;
procedure.function.positionalParameters = newParameterDeclarations;
procedure.function.namedParameters = newNamedParameterDeclarations;
} else {
final expression = new DirectMethodInvocation(new ThisExpression(),
newProcedure, new Arguments(newParameterVariableGets));
final statement = new ReturnStatement(expression)
..parent = procedure.function;
procedure.function.body = statement;
procedure.function.positionalParameters = newParameterDeclarations;
procedure.function.namedParameters = newNamedParameterDeclarations;
}
if (_debug) {
// Debug flag set: Print something to the terminal before returning to
// easily detect if rewrites are missing.
Expression debugPrint = _getPrintExpression(
"DEBUG! Procedure shouldn't have been called...", procedure);
procedure.function.body = new Block(
[new ExpressionStatement(debugPrint), procedure.function.body])
..parent = procedure.function;
}
// Mark original procedure as seen (i.e. don't transform it further)
_visited.add(procedure);
}
}
/// Rewrite constructor initializers by introducing variables and sorting.
///
/// For any* [SuperInitializer] or [RedirectingInitializer], extract the
/// parameters, put them into variables, then sorting the named parameters.
/// The idea is to sort the named parameters without changing any invocation
/// order.
///
/// * only with at least 2 named arguments, otherwise sorting would do nothing
void _rewriteConstructorInitializations(Constructor constructor) {
if (_isNotExternal(constructor)) {
// Basically copied from "super_calls.dart"
List<Initializer> initializers = constructor.initializers;
int foundIndex = -1;
Arguments arguments;
for (int i = initializers.length - 1; i >= 0; --i) {
Initializer initializer = initializers[i];
if (initializer is SuperInitializer) {
foundIndex = i;
arguments = initializer.arguments;
break;
} else if (initializer is RedirectingInitializer) {
foundIndex = i;
arguments = initializer.arguments;
break;
}
}
if (foundIndex == -1) return;
// Rewrite using variables if using named parameters (so we can sort them)
// (note that with 1 named it cannot be unsorted so we don't bother)
if (arguments.named.length < 2) return;
int argumentCount = arguments.positional.length + arguments.named.length;
// Make room for [argumentCount] [LocalInitializer]s before the
// super/redirector call.
initializers.length += argumentCount;
initializers.setRange(
foundIndex + argumentCount, // destination start (inclusive)
initializers.length, // destination end (exclusive)
initializers, // source list
foundIndex); // source start index
// Fill in the [argumentCount] reserved slots with the evaluation
// expressions of the arguments to the super/redirector constructor call
int storeIndex = foundIndex;
for (int i = 0; i < arguments.positional.length; ++i) {
var variable =
new VariableDeclaration.forValue(arguments.positional[i]);
arguments.positional[i] = new VariableGet(variable)..parent = arguments;
initializers[storeIndex++] = new LocalInitializer(variable)
..parent = constructor;
}
for (int i = 0; i < arguments.named.length; ++i) {
NamedExpression argument = arguments.named[i];
var variable = new VariableDeclaration.forValue(argument.value);
arguments.named[i].value = new VariableGet(variable)..parent = argument;
initializers[storeIndex++] = new LocalInitializer(variable)
..parent = constructor;
}
// Sort the named arguments
arguments.named.sort((a, b) => a.name.compareTo(b.name));
}
}
/// Move body of constructor to new one and call that from this one.
///
/// More specifically: For all constructors with optional positional
/// parameters, or named parameters, create a new constructor without optional
/// positional parameters and named parameters, and move the body of the
/// original constructor into this new constructor.
/// Then make the original constructor redirect to the new constructor.
///
/// The idea is that all rewrites should call the moved constructor instead,
/// bypassing the optional/named arguments entirely.
///
/// This method is very similar to _moveAndTransformProcedure
void _moveAndTransformConstructor(Constructor constructor) {
if (_isNotExternal(constructor) &&
_hasAnyOptionalParameters(constructor.function)) {
final function = constructor.function;
// Create variable lists
final newParameterDeclarations = <VariableDeclaration>[];
final newNamedParameterDeclarations = <VariableDeclaration>[];
final newParameterVariableGets = <Expression>[];
final targetParameters = function.positionalParameters;
final targetNamedParameters = function.namedParameters;
_moveVariableInitialization(
targetParameters,
targetNamedParameters,
newParameterDeclarations,
newNamedParameterDeclarations,
newParameterVariableGets,
constructor.function);
// Create new constructor looking like the old one
// (with the old body, parameters and initializers)
FunctionNode functionNode = _createShallowFunctionCopy(function);
final newConstructor = new Constructor(functionNode,
name: _createOriginalName(constructor),
isConst: constructor.isConst,
isExternal: constructor.isExternal,
initializers: constructor.initializers);
// Add constructor to the code
_addMember(constructor, newConstructor);
// Map moved body
_movedConstructors[constructor] = newConstructor;
// Transform original constructor
constructor.function.body = null;
constructor.function.positionalParameters = newParameterDeclarations;
constructor.function.namedParameters = newNamedParameterDeclarations;
constructor.initializers = [
new RedirectingInitializer(
newConstructor, new Arguments(newParameterVariableGets))
..parent = constructor
];
if (_debug) {
// Debug flag set: Print something to the terminal before returning to
// easily detect if rewrites are missing.
Expression debugPrint = _getPrintExpression(
"DEBUG! Constructor shouldn't have been called...", constructor);
var variable = new VariableDeclaration.forValue(debugPrint);
final debugInitializer = new LocalInitializer(variable)
..parent = constructor;
final redirector = constructor.initializers[0];
constructor.initializers = [debugInitializer, redirector];
}
// Mark original procedure as seen (i.e. don't transform it further)
_visited.add(constructor);
}
}
/// Creates a new [FunctionNode] based on the given one.
///
/// Parameters are taken directly (i.e. after returning the parameters will
/// have a new parent (the returned value), but still be referenced in the
/// original [FunctionNode].
/// The same goes for the body of the function.
/// The caller should take steps to remedy this after this call.
///
/// The parameters are no longer optional and named parameters have been
/// sorted and turned into regular parameters in the returned [FunctionNode].
FunctionNode _createShallowFunctionCopy(FunctionNode function) {
final newParameters =
new List<VariableDeclaration>.from(function.positionalParameters);
final named = new List<VariableDeclaration>.from(function.namedParameters);
named.sort((a, b) => a.name.compareTo(b.name));
newParameters.addAll(named);
final functionNode = new FunctionNode(function.body,
positionalParameters: newParameters,
namedParameters: [],
requiredParameterCount: newParameters.length,
returnType: function.returnType,
asyncMarker: function.asyncMarker,
dartAsyncMarker: function.dartAsyncMarker);
return functionNode;
}
/// Creates new variables, moving old initializers into them
///
/// Specifically: Given lists for output, create new variables based on
/// original parameters. Any new variable will receive the original variables
/// initializer, and the original variable will have its initializer set to
/// null.
/// Named parameters have been sorted in [newParameterVariableGets].
void _moveVariableInitialization(
List<VariableDeclaration> originalParameters,
List<VariableDeclaration> originalNamedParameters,
List<VariableDeclaration> newParameterDeclarations,
List<VariableDeclaration> newNamedParameterDeclarations,
List<Expression> newParameterVariableGets,
TreeNode newStuffParent) {
for (final orgVar in originalParameters) {
final variableDeclaration = new VariableDeclaration(orgVar.name,
initializer: orgVar.initializer,
type: orgVar.type,
isFinal: orgVar.isFinal,
isConst: orgVar.isConst)
..parent = newStuffParent;
variableDeclaration.initializer?.parent = variableDeclaration;
newParameterDeclarations.add(variableDeclaration);
orgVar.initializer = null;
newParameterVariableGets.add(new VariableGet(variableDeclaration));
}
// Named expressions in newParameterVariableGets should be sorted
final tmp = new List<_Pair<String, Expression>>();
for (final orgVar in originalNamedParameters) {
final variableDeclaration = new VariableDeclaration(orgVar.name,
initializer: orgVar.initializer,
type: orgVar.type,
isFinal: orgVar.isFinal,
isConst: orgVar.isConst)
..parent = newStuffParent;
variableDeclaration.initializer?.parent = variableDeclaration;
newNamedParameterDeclarations.add(variableDeclaration);
orgVar.initializer = null;
tmp.add(new _Pair(orgVar.name, new VariableGet(variableDeclaration)));
}
tmp.sort((a, b) => a.key.compareTo(b.key));
for (final item in tmp) {
newParameterVariableGets.add(item.value);
}
}
/// Creates a stub redirecting to noSuchMethod.
///
/// Needed because if B extends A, both have a foo method, but taking
/// different optional parameters, a call on an instance of B with parameters
/// for A should actually result in a noSuchMethod call, but if only A has
/// the rewritten method name, that method will be called...
/// TODO: We only have to create these stubs for arguments that a procedures
/// super allows, otherwise it will become a noSuchMethod automatically!
Procedure _createNoSuchMethodStub(
String argumentsSignature,
int positionalCount,
List<String> givenNamedParameters,
Procedure existing) {
// Build parameter lists
final newParameterDeclarations = <VariableDeclaration>[];
final newParameterVariableGets = <Expression>[];
for (int i = 0; i < positionalCount + givenNamedParameters.length; i++) {
final variableDeclaration = new VariableDeclaration("v%$i");
newParameterDeclarations.add(variableDeclaration);
newParameterVariableGets.add(new VariableGet(variableDeclaration));
}
var procedureName = _createName(existing.name, argumentsSignature);
// Find noSuchMethod to call
Member noSuchMethod = hierarchy.getDispatchTarget(
existing.enclosingClass, new Name("noSuchMethod"));
Arguments argumentsToNoSuchMethod;
if (noSuchMethod.function.positionalParameters.length == 1 &&
noSuchMethod.function.namedParameters.isEmpty) {
// We have a correct noSuchMethod method.
ConstructorInvocation invocation = _createInvocation(
procedureName.name, new Arguments(newParameterVariableGets));
argumentsToNoSuchMethod = new Arguments([invocation]);
} else {
// Get noSuchMethod on Object then...
noSuchMethod = hierarchy.getDispatchTarget(
coreTypes.objectClass, new Name("noSuchMethod"));
ConstructorInvocation invocation = _createInvocation(
procedureName.name, new Arguments(newParameterVariableGets));
ConstructorInvocation invocationPrime =
_createInvocation("noSuchMethod", new Arguments([invocation]));
argumentsToNoSuchMethod = new Arguments([invocationPrime]);
}
// Create return statement to call noSuchMethod
ReturnStatement statement;
final expression = new DirectMethodInvocation(
new ThisExpression(), noSuchMethod, argumentsToNoSuchMethod);
statement = new ReturnStatement(expression);
// Build procedure
final functionNode = new FunctionNode(statement,
positionalParameters: newParameterDeclarations,
namedParameters: [],
requiredParameterCount: newParameterDeclarations.length,
returnType: existing.function.returnType,
asyncMarker: existing.function.asyncMarker,
dartAsyncMarker: existing.function.dartAsyncMarker);
final procedure = new Procedure(
procedureName, ProcedureKind.Method, functionNode,
isStatic: existing.isStatic, fileUri: existing.fileUri);
// Add procedure to the code
_addMember(existing, procedure);
// Mark the new procedure as visited already (i.e. don't rewrite it again!)
_visited.add(procedure);
return procedure;
}
/// Creates an "new _InvocationMirror(...)" invocation.
ConstructorInvocation _createInvocation(
String methodName, Arguments callArguments) {
if (_invocationMirrorConstructor == null) {
Class clazz = coreTypes.invocationMirrorClass;
_invocationMirrorConstructor = clazz.constructors[0];
}
// The _InvocationMirror constructor takes the following arguments:
// * Method name (a string).
// * An arguments descriptor - a list consisting of:
// - number of arguments (including receiver).
// - number of positional arguments (including receiver).
// - pairs (2 entries in the list) of
// * named arguments name.
// * index of named argument in arguments list.
// * A list of arguments, where the first ones are the positional arguments.
// * Whether it's a super invocation or not.
int numPositionalArguments = callArguments.positional.length + 1;
int numArguments = numPositionalArguments + callArguments.named.length;
List<Expression> argumentsDescriptor = [
new IntLiteral(numArguments),
new IntLiteral(numPositionalArguments)
];
List<Expression> arguments = [];
arguments.add(new ThisExpression());
for (Expression pos in callArguments.positional) {
arguments.add(pos);
}
for (NamedExpression named in callArguments.named) {
argumentsDescriptor.add(new StringLiteral(named.name));
argumentsDescriptor.add(new IntLiteral(arguments.length));
arguments.add(named.value);
}
return new ConstructorInvocation(
_invocationMirrorConstructor,
new Arguments([
new StringLiteral(methodName),
_fixedLengthList(argumentsDescriptor),
_fixedLengthList(arguments),
new BoolLiteral(false)
]));
}
/// Create a fixed length list containing given expressions.
Expression _fixedLengthList(List<Expression> list) {
_listFrom ??= coreTypes.listFromConstructor;
return new StaticInvocation(
_listFrom,
new Arguments([new ListLiteral(list)],
named: [new NamedExpression("growable", new BoolLiteral(false))],
types: [const DynamicType()]));
}
/// Creates a new procedure taking given arguments, caching it.
///
/// Copies any non-given default values for parameters into the new procedure
/// to be able to call the [realTarget] without using optionals and named
/// parameters.
Procedure _createAndCacheInvocationProcedure(
String argumentsSignature,
int positionalCount,
List<String> givenNamedParameters,
Procedure target,
Procedure realTarget,
Map<String, Procedure> createdProcedures,
bool doSpecialCaseForAllParameters) {
// Special case: Calling with all parameters
if (doSpecialCaseForAllParameters &&
positionalCount == target.function.positionalParameters.length &&
givenNamedParameters.length == target.function.namedParameters.length) {
// We don't cache this procedure as this could make it look like
// something with name argumentsSignature actually exists
// while it doesn't (which is bad as we could then decide that we don't
// need to create a stub even though we do!)
return realTarget;
}
// Create and cache (save) constructor
// Build parameter lists
final newParameterDeclarations = <VariableDeclaration>[];
final newParameterVariableGets = <Expression>[];
_extractAndCreateParameters(positionalCount, newParameterDeclarations,
newParameterVariableGets, target, givenNamedParameters);
// Create return statement to call real target
ReturnStatement statement;
if (target.isAbstract && target.function?.body == null) {
// statement should just be null then
} else if (target.isStatic) {
final expression = new StaticInvocation(
realTarget, new Arguments(newParameterVariableGets));
statement = new ReturnStatement(expression);
} else {
final expression = new DirectMethodInvocation(new ThisExpression(),
realTarget, new Arguments(newParameterVariableGets));
statement = new ReturnStatement(expression);
}
// Build procedure
final functionNode = new FunctionNode(statement,
positionalParameters: newParameterDeclarations,
namedParameters: [],
requiredParameterCount: newParameterDeclarations.length,
returnType: target.function.returnType,
asyncMarker: target.function.asyncMarker,
dartAsyncMarker: target.function.dartAsyncMarker);
final procedure = new Procedure(
_createName(target.name, argumentsSignature),
ProcedureKind.Method,
functionNode,
isAbstract: target.isAbstract,
isStatic: target.isStatic,
isConst: target.isConst,
fileUri: target.fileUri);
// Add procedure to the code
_addMember(target, procedure);
// Cache it for future reference
createdProcedures[argumentsSignature] = procedure;
// Mark the new procedure as visited already (i.e. don't rewrite it again!)
_visited.add(procedure);
return procedure;
}
/// Creates a new constructor taking given arguments, caching it.
///
/// Copies any non-given default values for parameters into the new
/// constructor to be able to call the [realTarget] without using optionals
/// and named parameters.
Constructor _createAndCacheInvocationConstructor(
String argumentsSignature,
int positionalCount,
List<String> givenNamedParameters,
Constructor target,
Constructor realTarget,
Map<String, Constructor> createdConstructor,
bool doSpecialCaseForAllParameters) {
// Special case: Calling with all parameters
if (doSpecialCaseForAllParameters &&
positionalCount == target.function.positionalParameters.length &&
givenNamedParameters.length == target.function.namedParameters.length) {
createdConstructor[argumentsSignature] = realTarget;
return realTarget;
}
// Create and cache (save) constructor
// Build parameter lists
final newParameterDeclarations = <VariableDeclaration>[];
final newParameterVariableGets = <Expression>[];
_extractAndCreateParameters(positionalCount, newParameterDeclarations,
newParameterVariableGets, target, givenNamedParameters);
// Build constructor
final functionNode = new FunctionNode(null,
positionalParameters: newParameterDeclarations,
namedParameters: [],
requiredParameterCount: newParameterDeclarations.length,
returnType: target.function.returnType,
asyncMarker: target.function.asyncMarker,
dartAsyncMarker: target.function.dartAsyncMarker);
final constructor = new Constructor(functionNode,
name: _createName(target.name, argumentsSignature),
isConst: target.isConst,
isExternal: target.isExternal,
initializers: [
new RedirectingInitializer(
realTarget, new Arguments(newParameterVariableGets))
]);
// Add procedure to the code
_addMember(target, constructor);
// Cache it for future reference
createdConstructor[argumentsSignature] = constructor;
// Mark the new procedure as visited already (i.e. don't rewrite it again!)
_visited.add(constructor);
return constructor;
}
/// Extracts and creates parameters into the first two given lists.
///
/// What is done:
/// Step 1: Re-create the parameters given (i.e. the non-optional positional
/// ones) - i.e. create a new variable with the same name etc, put it in
/// [newParameterDeclarations]; create VariableGet for that and put it in
/// [newParameterVariableGets]
/// Step 2: Re-create the positional parameters NOT given, i.e. insert
/// defaults and add to [newParameterVariableGets] only.
/// Step 3: Re-create the named arguments (in sorted order). For actually
/// given named parameters, do as in step 1, for not-given named parameters
/// do as in step 2.
///
/// NOTE: [newParameterDeclarations] and [newParameterVariableGets] are OUTPUT
/// lists.
void _extractAndCreateParameters(
int positionalCount,
List<VariableDeclaration> newParameterDeclarations,
List<Expression> newParameterVariableGets,
Member target,
List<String> givenNamedParameters) {
// First re-create the parameters given (i.e. the non-optional positional ones)
final targetParameters = target.function.positionalParameters;
positionalCount = math.min(positionalCount, targetParameters.length);
for (int i = 0; i < positionalCount; i++) {
final orgVar = targetParameters[i];
final variableDeclaration = new VariableDeclaration(orgVar.name,
type: orgVar.type, isFinal: orgVar.isFinal, isConst: orgVar.isConst);
newParameterDeclarations.add(variableDeclaration);
newParameterVariableGets.add(new VariableGet(variableDeclaration));
}
// Default parameters for the rest of them
_fillInPositionalParameters(
positionalCount, target, newParameterVariableGets);
// Then all named parameters (given here or not)
final orgNamed =
new List<VariableDeclaration>.from(target.function.namedParameters);
orgNamed.sort((a, b) => a.name.compareTo(b.name));
final givenArgumentsIterator = givenNamedParameters.iterator;
givenArgumentsIterator.moveNext();
for (VariableDeclaration named in orgNamed) {
if (givenArgumentsIterator.current == named.name) {
// We have that one: Use it and move the iterator
final variableDeclaration = new VariableDeclaration(named.name);
newParameterDeclarations.add(variableDeclaration);
newParameterVariableGets.add(new VariableGet(variableDeclaration));
givenArgumentsIterator.moveNext();
} else {
// We don't have that one: Fill it in
_fillInSingleParameter(named, newParameterVariableGets, target);
}
}
}
/// Adds the new member the same place as the existing member
void _addMember(Member existingMember, Member newMember) {
if (existingMember.enclosingClass != null) {
existingMember.enclosingClass.addMember(newMember);
} else {
existingMember.enclosingLibrary.addMember(newMember);
}
}
/// Create expressions based on the default values from the given [Member].
///
/// More specifically: static gets and nulls will be "copied" whereas other
/// things (e.g. literals or things like "a+b") will be moved from the
/// original member as argument initializers to const fields and both the
/// original member and the expression-copy will use static gets to these.
void _fillInPositionalParameters(
int startFrom, Member copyFrom, List<Expression> fillInto) {
final targetParameters = copyFrom.function.positionalParameters;
for (int i = startFrom; i < targetParameters.length; i++) {
final parameter = targetParameters[i];
_fillInSingleParameter(parameter, fillInto, copyFrom);
}
}
/// Create expression based on the default values from the given variable.
///
/// More specifically: a static get or null will be "copied" whereas other
/// things (e.g. literals or things like "a+b") will be moved from the
/// original member as an argument initializer to a const field and both the
/// original member and the expression-copy will use a static get to it.
void _fillInSingleParameter(VariableDeclaration parameter,
List<Expression> fillInto, Member copyFrom) {
if (parameter.initializer is StaticGet) {
// Reference to const => recreate it
StaticGet staticGet = parameter.initializer;
fillInto.add(new StaticGet(staticGet.target));
} else if (parameter.initializer == null) {
// No default given => output null
fillInto.add(new NullLiteral());
} else if (parameter.initializer is IntLiteral) {
// Int literal => recreate (or else class ByteBuffer in typed_data will
// get 2 fields and the C++ code will complain!)
IntLiteral value = parameter.initializer;
fillInto.add(new IntLiteral(value.value));
} else {
// Advanced stuff => move to static const field and reference that
final initializer = parameter.initializer;
final f = new Field(
new Name('${copyFrom.name.name}%_${parameter.name}',
copyFrom.enclosingLibrary),
type: parameter.type,
initializer: initializer,
isFinal: false,
isConst: true,
isStatic: true,
fileUri: copyFrom.enclosingClass?.fileUri ??
copyFrom.enclosingLibrary.fileUri);
initializer.parent = f;
// Add field to the code
if (copyFrom.enclosingClass != null) {
copyFrom.enclosingClass.addMember(f);
} else {
copyFrom.enclosingLibrary.addMember(f);
}
// Use it at the call site
fillInto.add(new StaticGet(f));
// Now replace the initializer in the method to a StaticGet
parameter.initializer = new StaticGet(f)..parent = parameter;
}
}
/// Create an "original name" for a member.
///
/// Specifically, for a member "x" just returns "x%original";
Name _createOriginalName(Member member) {
return new Name("${member.name.name}%original", member.enclosingLibrary);
}
/// Create a [Name] based on current name and argument signature.
Name _createName(Name name, String argumentsSignature) {
String nameString = '${name.name}%$argumentsSignature';
return new Name(nameString, name.library);
}
/// Is the procedure a method?
bool _isMethod(Procedure procedure) => procedure.kind == ProcedureKind.Method;
/// Is the procedure NOT marked as external?
bool _isNotExternal(Constructor constructor) => !constructor.isExternal;
/// Does the target function have any optional arguments? (positional/named)
bool _hasAnyOptionalParameters(FunctionNode targetFunction) =>
_hasOptionalParameters(targetFunction) ||
_hasNamedParameters(targetFunction);
/// Does the target function have optional positional arguments?
bool _hasOptionalParameters(FunctionNode targetFunction) =>
targetFunction.positionalParameters.length >
targetFunction.requiredParameterCount;
/// Does the target function have named parameters?
bool _hasNamedParameters(FunctionNode targetFunction) =>
targetFunction.namedParameters.isNotEmpty;
bool _callIsLegal(FunctionNode targetFunction, Arguments arguments) {
if ((targetFunction.requiredParameterCount > arguments.positional.length) ||
(targetFunction.positionalParameters.length <
arguments.positional.length)) {
// Given too few or too many positional arguments
return false;
}
// Do we give named that we don't take?
Set<String> givenNamed = arguments.named.map((v) => v.name).toSet();
Set<String> takenNamed =
targetFunction.namedParameters.map((v) => v.name).toSet();
givenNamed.removeAll(takenNamed);
return givenNamed.isEmpty;
}
// Below methods used to add debug prints etc
Library _getDartCoreLibrary(Component component) {
if (component == null) return null;
return component.libraries.firstWhere((lib) =>
lib.importUri.scheme == 'dart' && lib.importUri.path == 'core');
}
Procedure _getProcedureInLib(Library lib, String name) {
if (lib == null) return null;
return lib.procedures
.firstWhere((procedure) => procedure.name.name == name);
}
Procedure _getProcedureInClassInLib(
Library lib, String className, String procedureName) {
if (lib == null) return null;
Class clazz = lib.classes.firstWhere((clazz) => clazz.name == className);
return clazz.procedures
.firstWhere((procedure) => procedure.name.name == procedureName);
}
Expression _getPrintExpression(String msg, TreeNode treeNode) {
TreeNode component = treeNode;
while (component is! Component) component = component.parent;
var finalMsg = msg;
if (treeNode is Member) {
finalMsg += " [ ${treeNode.name.name} ]";
if (treeNode.enclosingClass != null) {
finalMsg += " [ class ${treeNode.enclosingClass.name} ]";
}
if (treeNode.enclosingLibrary != null) {
finalMsg += " [ lib ${treeNode.enclosingLibrary.name} ]";
}
}
var stacktrace = new StaticGet(_getProcedureInClassInLib(
_getDartCoreLibrary(component), 'StackTrace', 'current'));
var printStackTrace = new StaticInvocation(
_getProcedureInLib(_getDartCoreLibrary(component), 'print'),
new Arguments([
new StringConcatenation([
new StringLiteral(finalMsg),
new StringLiteral("\n"),
stacktrace,
new StringLiteral("\n")
])
]));
return printStackTrace;
}
}
class _Pair<K, V> {
final K key;
final V value;
_Pair(this.key, this.value);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/transformations/track_widget_constructor_locations.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.transformations.track_widget_constructor_locations;
import 'package:meta/meta.dart';
import '../ast.dart';
// Parameter name used to track were widget constructor calls were made from.
//
// The parameter name contains a randomly generate hex string to avoid collision
// with user generated parameters.
const String _creationLocationParameterName =
r'$creationLocationd_0dea112b090073317d4';
/// Name of private field added to the Widget class and any other classes that
/// implement Widget.
///
/// Regardless of what library a class implementing Widget is defined in, the
/// private field will always be defined in the context of the widget_inspector
/// library ensuring no name conflicts with regular fields.
const String _locationFieldName = r'_location';
bool _hasNamedParameter(FunctionNode function, String name) {
return function.namedParameters
.any((VariableDeclaration parameter) => parameter.name == name);
}
bool _hasNamedArgument(Arguments arguments, String argumentName) {
return arguments.named
.any((NamedExpression argument) => argument.name == argumentName);
}
VariableDeclaration _getNamedParameter(
FunctionNode function,
String parameterName,
) {
for (VariableDeclaration parameter in function.namedParameters) {
if (parameter.name == parameterName) {
return parameter;
}
}
return null;
}
// TODO(jacobr): find a solution that supports optional positional parameters.
/// Add the creation location to the arguments list if possible.
///
/// Returns whether the creation location argument could be added. We cannot
/// currently add the named argument for functions with optional positional
/// parameters as the current scheme requires adding the creation location as a
/// named parameter. Fortunately that is not a significant issue in practice as
/// no Widget classes in package:flutter have optional positional parameters.
/// This code degrades gracefully for constructors with optional positional
/// parameters by skipping adding the creation location argument rather than
/// failing.
void _maybeAddCreationLocationArgument(
Arguments arguments,
FunctionNode function,
Expression creationLocation,
Class locationClass,
) {
if (_hasNamedArgument(arguments, _creationLocationParameterName)) {
return;
}
if (!_hasNamedParameter(function, _creationLocationParameterName)) {
// TODO(jakemac): We don't apply the transformation to dependencies kernel
// outlines, so instead we just assume the named parameter exists.
//
// The only case in which it shouldn't exist is if the function has optional
// positional parameters so it cannot have optional named parameters.
if (function.requiredParameterCount !=
function.positionalParameters.length) {
return;
}
}
final NamedExpression namedArgument =
new NamedExpression(_creationLocationParameterName, creationLocation);
namedArgument.parent = arguments;
arguments.named.add(namedArgument);
}
/// Adds a named parameter to a function if the function does not already have
/// a named parameter with the name or optional positional parameters.
bool _maybeAddNamedParameter(
FunctionNode function,
VariableDeclaration variable,
) {
if (_hasNamedParameter(function, _creationLocationParameterName)) {
// Gracefully handle if this method is called on a function that has already
// been transformed.
return false;
}
// Function has optional positional parameters so cannot have optional named
// parameters.
if (function.requiredParameterCount != function.positionalParameters.length) {
return false;
}
variable.parent = function;
function.namedParameters.add(variable);
return true;
}
/// Transformer that modifies all calls to Widget constructors to include
/// a [DebugLocation] parameter specifying the location where the constructor
/// call was made.
///
/// This transformer requires that all Widget constructors have already been
/// transformed to have a named parameter with the name specified by
/// `_locationParameterName`.
class _WidgetCallSiteTransformer extends Transformer {
/// The [Widget] class defined in the `package:flutter` library.
///
/// Used to perform instanceof checks to determine whether Dart constructor
/// calls are creating [Widget] objects.
Class _widgetClass;
/// The [DebugLocation] class defined in the `package:flutter` library.
Class _locationClass;
/// Current factory constructor that node being transformed is inside.
///
/// Used to flow the location passed in as an argument to the factory to the
/// actual constructor call within the factory.
Procedure _currentFactory;
WidgetCreatorTracker _tracker;
_WidgetCallSiteTransformer(
{@required Class widgetClass,
@required Class locationClass,
@required WidgetCreatorTracker tracker})
: _widgetClass = widgetClass,
_locationClass = locationClass,
_tracker = tracker;
/// Builds a call to the const constructor of the [DebugLocation]
/// object specifying the location where a constructor call was made and
/// optionally the locations for all parameters passed in.
///
/// Specifying the parameters passed in is an experimental feature. With
/// access to the source code of an application you could determine the
/// locations of the parameters passed in from the source location of the
/// constructor call but it is convenient to bundle the location and names
/// of the parameters passed in so that tools can show parameter locations
/// without re-parsing the source code.
ConstructorInvocation _constructLocation(
Location location, {
String name,
ListLiteral parameterLocations,
bool showFile: true,
}) {
final List<NamedExpression> arguments = <NamedExpression>[
new NamedExpression('line', new IntLiteral(location.line)),
new NamedExpression('column', new IntLiteral(location.column)),
];
if (showFile) {
arguments.add(new NamedExpression(
'file', new StringLiteral(location.file.toString())));
}
if (name != null) {
arguments.add(new NamedExpression('name', new StringLiteral(name)));
}
if (parameterLocations != null) {
arguments
.add(new NamedExpression('parameterLocations', parameterLocations));
}
return new ConstructorInvocation(
_locationClass.constructors.first,
new Arguments(<Expression>[], named: arguments),
isConst: true,
);
}
@override
Procedure visitProcedure(Procedure node) {
if (node.isFactory) {
_currentFactory = node;
node.transformChildren(this);
_currentFactory = null;
return node;
}
return defaultTreeNode(node);
}
bool _isSubclassOfWidget(Class clazz) {
return _tracker._isSubclassOf(clazz, _widgetClass);
}
@override
StaticInvocation visitStaticInvocation(StaticInvocation node) {
node.transformChildren(this);
final Procedure target = node.target;
if (!target.isFactory) {
return node;
}
final Class constructedClass = target.enclosingClass;
if (!_isSubclassOfWidget(constructedClass)) {
return node;
}
_addLocationArgument(node, target.function, constructedClass);
return node;
}
void _addLocationArgument(InvocationExpression node, FunctionNode function,
Class constructedClass) {
_maybeAddCreationLocationArgument(
node.arguments,
function,
_computeLocation(node, function, constructedClass),
_locationClass,
);
}
@override
ConstructorInvocation visitConstructorInvocation(ConstructorInvocation node) {
node.transformChildren(this);
final Constructor constructor = node.target;
final Class constructedClass = constructor.enclosingClass;
if (!_isSubclassOfWidget(constructedClass)) {
return node;
}
_addLocationArgument(node, constructor.function, constructedClass);
return node;
}
Expression _computeLocation(InvocationExpression node, FunctionNode function,
Class constructedClass) {
// For factory constructors we need to use the location specified as an
// argument to the factory constructor rather than the location
if (_currentFactory != null &&
_tracker._isSubclassOf(
constructedClass, _currentFactory.enclosingClass)) {
final VariableDeclaration creationLocationParameter = _getNamedParameter(
_currentFactory.function,
_creationLocationParameterName,
);
if (creationLocationParameter != null) {
return new VariableGet(creationLocationParameter);
}
}
final Arguments arguments = node.arguments;
final Location location = node.location;
final List<ConstructorInvocation> parameterLocations =
<ConstructorInvocation>[];
final List<VariableDeclaration> parameters = function.positionalParameters;
for (int i = 0; i < arguments.positional.length; ++i) {
final Expression expression = arguments.positional[i];
final VariableDeclaration parameter = parameters[i];
parameterLocations.add(_constructLocation(
expression.location,
name: parameter.name,
showFile: false,
));
}
for (NamedExpression expression in arguments.named) {
parameterLocations.add(_constructLocation(
expression.location,
name: expression.name,
showFile: false,
));
}
return _constructLocation(
location,
parameterLocations: new ListLiteral(
parameterLocations,
typeArgument: _locationClass.thisType,
isConst: true,
),
);
}
}
/// Rewrites all widget constructors and constructor invocations to add a
/// parameter specifying the location the constructor was called from.
///
/// The creation location is stored as a private field named `_location`
/// on the base widget class and flowed through the constructors using a named
/// parameter.
class WidgetCreatorTracker {
Class _widgetClass;
Class _locationClass;
/// Marker interface indicating that a private _location field is
/// available.
Class _hasCreationLocationClass;
WidgetCreatorTracker();
void _resolveFlutterClasses(Iterable<Library> libraries) {
// If the Widget or Debug location classes have been updated we need to get
// the latest version
for (Library library in libraries) {
final Uri importUri = library.importUri;
if (importUri != null && importUri.scheme == 'package') {
if (importUri.path == 'flutter/src/widgets/framework.dart' ||
importUri.path == 'flutter_web/src/widgets/framework.dart') {
for (Class class_ in library.classes) {
if (class_.name == 'Widget') {
_widgetClass = class_;
}
}
} else {
if (importUri.path == 'flutter/src/widgets/widget_inspector.dart' ||
importUri.path ==
'flutter_web/src/widgets/widget_inspector.dart') {
for (Class class_ in library.classes) {
if (class_.name == '_HasCreationLocation') {
_hasCreationLocationClass = class_;
} else if (class_.name == '_Location') {
_locationClass = class_;
}
}
}
}
}
}
}
/// Modify [clazz] to add a field named [_locationFieldName] that is the
/// first parameter of all constructors of the class.
///
/// This method should only be called for classes that implement but do not
/// extend [Widget].
void _transformClassImplementingWidget(Class clazz) {
if (clazz.fields
.any((Field field) => field.name.name == _locationFieldName)) {
// This class has already been transformed. Skip
return;
}
clazz.implementedTypes
.add(new Supertype(_hasCreationLocationClass, <DartType>[]));
// We intentionally use the library context of the _HasCreationLocation
// class for the private field even if [clazz] is in a different library
// so that all classes implementing Widget behave consistently.
final Name fieldName = new Name(
_locationFieldName,
_hasCreationLocationClass.enclosingLibrary,
);
final Field locationField = new Field(fieldName,
type: new InterfaceType(_locationClass),
isFinal: true,
reference: clazz.reference.canonicalName
?.getChildFromFieldWithName(fieldName)
?.reference);
clazz.addMember(locationField);
final Set<Constructor> _handledConstructors =
new Set<Constructor>.identity();
void handleConstructor(Constructor constructor) {
if (!_handledConstructors.add(constructor)) {
return;
}
assert(!_hasNamedParameter(
constructor.function,
_creationLocationParameterName,
));
final VariableDeclaration variable = new VariableDeclaration(
_creationLocationParameterName,
type: _locationClass.thisType,
);
if (!_maybeAddNamedParameter(constructor.function, variable)) {
return;
}
bool hasRedirectingInitializer = false;
for (Initializer initializer in constructor.initializers) {
if (initializer is RedirectingInitializer) {
if (initializer.target.enclosingClass == clazz) {
// We need to handle this constructor first or the call to
// addDebugLocationArgument bellow will fail due to the named
// parameter not yet existing on the constructor.
handleConstructor(initializer.target);
}
_maybeAddCreationLocationArgument(
initializer.arguments,
initializer.target.function,
new VariableGet(variable),
_locationClass,
);
hasRedirectingInitializer = true;
break;
}
}
if (!hasRedirectingInitializer) {
constructor.initializers.add(new FieldInitializer(
locationField,
new VariableGet(variable),
));
// TODO(jacobr): add an assert verifying the locationField is not
// null. Currently, we cannot safely add this assert because we do not
// handle Widget classes with optional positional arguments. There are
// no Widget classes in the flutter repo with optional positional
// arguments but it is possible users could add classes with optional
// positional arguments.
//
// constructor.initializers.add(new AssertInitializer(new AssertStatement(
// new IsExpression(
// new VariableGet(variable), _locationClass.thisType),
// conditionStartOffset: constructor.fileOffset,
// conditionEndOffset: constructor.fileOffset,
// )));
}
}
// Add named parameters to all constructors.
clazz.constructors.forEach(handleConstructor);
}
/// Transform the given [libraries].
void transform(Component module, List<Library> libraries) {
if (libraries.isEmpty) {
return;
}
_resolveFlutterClasses(module.libraries);
if (_widgetClass == null) {
// This application doesn't actually use the package:flutter library.
return;
}
final Set<Class> transformedClasses = new Set<Class>.identity();
final Set<Library> librariesToTransform = new Set<Library>.identity()
..addAll(libraries);
for (Library library in libraries) {
if (library.isExternal) {
continue;
}
for (Class class_ in library.classes) {
_transformWidgetConstructors(
librariesToTransform,
transformedClasses,
class_,
);
}
}
// Transform call sites to pass the location parameter.
final _WidgetCallSiteTransformer callsiteTransformer =
new _WidgetCallSiteTransformer(
widgetClass: _widgetClass,
locationClass: _locationClass,
tracker: this);
for (Library library in libraries) {
if (library.isExternal) {
continue;
}
library.transformChildren(callsiteTransformer);
}
}
bool _isSubclassOfWidget(Class clazz) => _isSubclassOf(clazz, _widgetClass);
bool _isSubclassOf(Class a, Class b) {
// TODO(askesc): Cache results.
// TODO(askesc): Test for subtype rather than subclass.
Class current = a;
while (current != null) {
if (current == b) return true;
current = current.superclass;
}
return false;
}
void _transformWidgetConstructors(Set<Library> librariesToBeTransformed,
Set<Class> transformedClasses, Class clazz) {
if (!_isSubclassOfWidget(clazz) ||
!librariesToBeTransformed.contains(clazz.enclosingLibrary) ||
!transformedClasses.add(clazz)) {
return;
}
// Ensure super classes have been transformed before this class.
if (clazz.superclass != null &&
!transformedClasses.contains(clazz.superclass)) {
_transformWidgetConstructors(
librariesToBeTransformed,
transformedClasses,
clazz.superclass,
);
}
for (Procedure procedure in clazz.procedures) {
if (procedure.isFactory) {
_maybeAddNamedParameter(
procedure.function,
new VariableDeclaration(
_creationLocationParameterName,
type: _locationClass.thisType,
),
);
}
}
// Handle the widget class and classes that implement but do not extend the
// widget class.
if (!_isSubclassOfWidget(clazz.superclass)) {
_transformClassImplementingWidget(clazz);
return;
}
final Set<Constructor> _handledConstructors =
new Set<Constructor>.identity();
void handleConstructor(Constructor constructor) {
if (!_handledConstructors.add(constructor)) {
return;
}
final VariableDeclaration variable = new VariableDeclaration(
_creationLocationParameterName,
type: _locationClass.thisType,
);
if (_hasNamedParameter(
constructor.function, _creationLocationParameterName)) {
// Constructor was already rewritten. TODO(jacobr): is this case actually hit?
return;
}
if (!_maybeAddNamedParameter(constructor.function, variable)) {
return;
}
for (Initializer initializer in constructor.initializers) {
if (initializer is RedirectingInitializer) {
if (initializer.target.enclosingClass == clazz) {
// We need to handle this constructor first or the call to
// addDebugLocationArgument could fail due to the named parameter
// not existing.
handleConstructor(initializer.target);
}
_maybeAddCreationLocationArgument(
initializer.arguments,
initializer.target.function,
new VariableGet(variable),
_locationClass,
);
} else if (initializer is SuperInitializer &&
_isSubclassOfWidget(initializer.target.enclosingClass)) {
_maybeAddCreationLocationArgument(
initializer.arguments,
initializer.target.function,
new VariableGet(variable),
_locationClass,
);
}
}
}
clazz.constructors.forEach(handleConstructor);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/transformations/flags.dart | library kernel.transformations.flags;
import '../ast.dart';
/// Flags summarizing the kinds of AST nodes contained in a given member or
/// class, for speeding up transformations that only affect certain types of
/// nodes.
///
/// These are set by the frontend and the deserializer.
class TransformerFlag {
/// The class or member contains 'super' calls, that is, one of the AST nodes
/// [SuperPropertyGet], [SuperPropertySet], [SuperMethodInvocation].
static const int superCalls = 1 << 0;
/// Temporary flag used by the verifier to indicate that the given member
/// has been seen.
static const int seenByVerifier = 1 << 1;
// TODO(asgerf): We could also add a flag for 'async' and will probably have
// one for closures as well.
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/transformations/empty.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.transformations.empty;
import '../ast.dart';
import '../kernel.dart';
import '../visitor.dart';
Component transformComponent(Component component) {
new EmptyTransformer().visitComponent(component);
return component;
}
class EmptyTransformer extends Transformer {}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/transformations/async.dart | // 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.
library kernel.transformations.async;
import '../kernel.dart';
import 'continuation.dart';
/// A transformer that introduces temporary variables for all subexpressions
/// that are alive across yield points (AwaitExpression).
///
/// The transformer is invoked by passing [rewrite] a top-level expression.
///
/// All intermediate values that are possible live across an await are named in
/// local variables.
///
/// Await expressions are translated into a call to a helper function and a
/// native yield.
class ExpressionLifter extends Transformer {
final AsyncRewriterBase continuationRewriter;
/// Have we seen an await to the right in the expression tree.
///
/// Subexpressions are visited right-to-left in the reverse of evaluation
/// order.
///
/// On entry to an expression's visit method, [seenAwait] indicates whether a
/// sibling to the right contains an await. If so the expression will be
/// named in a temporary variable because it is potentially live across an
/// await.
///
/// On exit from an expression's visit method, [seenAwait] indicates whether
/// the expression itself or a sibling to the right contains an await.
bool seenAwait = false;
/// The (reverse order) sequence of statements that have been emitted.
///
/// Transformation of an expression produces a transformed expression and a
/// sequence of statements which are assignments to local variables, calls to
/// helper functions, and yield points. Only the yield points need to be a
/// statements, and they are statements so an implementation does not have to
/// handle unnamed expression intermediate live across yield points.
///
/// The visit methods return the transformed expression and build a sequence
/// of statements by emitting statements into this list. This list is built
/// in reverse because children are visited right-to-left.
///
/// If an expression should be named it is named before visiting its children
/// so the naming assignment appears in the list before all statements
/// implementing the translation of the children.
///
/// Children that are conditionally evaluated, such as some parts of logical
/// and conditional expressions, must be delimited so that they do not emit
/// unguarded statements into [statements]. This is implemented by setting
/// [statements] to a fresh empty list before transforming those children.
List<Statement> statements = <Statement>[];
/// The number of currently live named intermediate values.
///
/// This index is used to allocate names to temporary values. Because
/// children are visited right-to-left, names are assigned in reverse order of
/// index.
///
/// When an assignment is emitted into [statements] to name an expression
/// before visiting its children, the index is not immediately reserved
/// because a child can freely use the same name as its parent. In practice,
/// this will be the rightmost named child.
///
/// After visiting the children of a named expression, [nameIndex] is set to
/// indicate one more live value (the value of the expression) than before
/// visiting the expression.
///
/// After visiting the children of an expression that is not named,
/// [nameIndex] may still account for names of subexpressions.
int nameIndex = 0;
final VariableDeclaration asyncResult = new VariableDeclaration(':result');
final List<VariableDeclaration> variables = <VariableDeclaration>[];
ExpressionLifter(this.continuationRewriter);
Block blockOf(List<Statement> statements) {
return new Block(statements.reversed.toList());
}
/// Rewrite a toplevel expression (toplevel wrt. a statement).
///
/// Rewriting an expression produces a sequence of statements and an
/// expression. The sequence of statements are added to the given list. Pass
/// an empty list if the rewritten expression should be delimited from the
/// surrounding context.
Expression rewrite(Expression expression, List<Statement> outer) {
assert(statements.isEmpty);
var saved = seenAwait;
seenAwait = false;
Expression result = expression.accept<TreeNode>(this);
outer.addAll(statements.reversed);
statements.clear();
seenAwait = seenAwait || saved;
return result;
}
// Perform an action with a given list of statements so that it cannot emit
// statements into the 'outer' list.
Expression delimit(Expression action(), List<Statement> inner) {
var index = nameIndex;
var outer = statements;
statements = inner;
Expression result = action();
nameIndex = index;
statements = outer;
return result;
}
// Name an expression by emitting an assignment to a temporary variable.
VariableGet name(Expression expr) {
VariableDeclaration temp = allocateTemporary(nameIndex);
statements.add(new ExpressionStatement(new VariableSet(temp, expr)));
return new VariableGet(temp);
}
VariableDeclaration allocateTemporary(int index) {
for (var i = variables.length; i <= index; i++) {
variables.add(new VariableDeclaration(":async_temporary_${i}"));
}
return variables[index];
}
// Simple literals. These are pure expressions so they can be evaluated after
// an await to their right.
TreeNode visitSymbolLiteral(SymbolLiteral expr) => expr;
TreeNode visitTypeLiteral(TypeLiteral expr) => expr;
TreeNode visitThisExpression(ThisExpression expr) => expr;
TreeNode visitStringLiteral(StringLiteral expr) => expr;
TreeNode visitIntLiteral(IntLiteral expr) => expr;
TreeNode visitDoubleLiteral(DoubleLiteral expr) => expr;
TreeNode visitBoolLiteral(BoolLiteral expr) => expr;
TreeNode visitNullLiteral(NullLiteral expr) => expr;
// Nullary expressions with effects.
Expression nullary(Expression expr) {
if (seenAwait) {
expr = name(expr);
++nameIndex;
}
return expr;
}
TreeNode visitInvalidExpression(InvalidExpression expr) => nullary(expr);
TreeNode visitSuperPropertyGet(SuperPropertyGet expr) => nullary(expr);
TreeNode visitStaticGet(StaticGet expr) => nullary(expr);
TreeNode visitRethrow(Rethrow expr) => nullary(expr);
// Getting a final or const variable is not an effect so it can be evaluated
// after an await to its right.
TreeNode visitVariableGet(VariableGet expr) {
if (seenAwait && !expr.variable.isFinal && !expr.variable.isConst) {
expr = name(expr);
++nameIndex;
}
return expr;
}
// Transform an expression given an action to transform the children. For
// this purposes of the await transformer the children should generally be
// translated from right to left, in the reverse of evaluation order.
Expression transform(Expression expr, void action()) {
var shouldName = seenAwait;
// 1. If there is an await in a sibling to the right, emit an assignment to
// a temporary variable before transforming the children.
var result = shouldName ? name(expr) : expr;
// 2. Remember the number of live temporaries before transforming the
// children.
var index = nameIndex;
// 3. Transform the children. Initially they do not have an await in a
// sibling to their right.
seenAwait = false;
action();
// 4. If the expression was named then the variables used for children are
// no longer live but the variable used for the expression is.
// On the other hand, a sibling to the left (yet to be processed) cannot
// reuse any of the variables used here, as the assignments in the children
// (here) would overwrite assignments in the siblings to the left,
// possibly before the use of the overwritten values.
if (shouldName) {
if (index + 1 > nameIndex) nameIndex = index + 1;
seenAwait = true;
}
return result;
}
// Unary expressions.
Expression unary(Expression expr) {
return transform(expr, () {
expr.transformChildren(this);
});
}
TreeNode visitVariableSet(VariableSet expr) => unary(expr);
TreeNode visitPropertyGet(PropertyGet expr) => unary(expr);
TreeNode visitDirectPropertyGet(DirectPropertyGet expr) => unary(expr);
TreeNode visitSuperPropertySet(SuperPropertySet expr) => unary(expr);
TreeNode visitStaticSet(StaticSet expr) => unary(expr);
TreeNode visitNot(Not expr) => unary(expr);
TreeNode visitIsExpression(IsExpression expr) => unary(expr);
TreeNode visitAsExpression(AsExpression expr) => unary(expr);
TreeNode visitThrow(Throw expr) => unary(expr);
TreeNode visitPropertySet(PropertySet expr) {
return transform(expr, () {
expr.value = expr.value.accept<TreeNode>(this)..parent = expr;
expr.receiver = expr.receiver.accept<TreeNode>(this)..parent = expr;
});
}
TreeNode visitDirectPropertySet(DirectPropertySet expr) {
return transform(expr, () {
expr.value = expr.value.accept<TreeNode>(this)..parent = expr;
expr.receiver = expr.receiver.accept<TreeNode>(this)..parent = expr;
});
}
TreeNode visitArguments(Arguments args) {
for (var named in args.named.reversed) {
named.value = named.value.accept<TreeNode>(this)..parent = named;
}
var positional = args.positional;
for (var i = positional.length - 1; i >= 0; --i) {
positional[i] = positional[i].accept<TreeNode>(this)..parent = args;
}
// Returns the arguments, which is assumed at the call sites because they do
// not replace the arguments or set parent pointers.
return args;
}
TreeNode visitMethodInvocation(MethodInvocation expr) {
return transform(expr, () {
visitArguments(expr.arguments);
expr.receiver = expr.receiver.accept<TreeNode>(this)..parent = expr;
});
}
TreeNode visitDirectMethodInvocation(DirectMethodInvocation expr) {
return transform(expr, () {
visitArguments(expr.arguments);
expr.receiver = expr.receiver.accept<TreeNode>(this)..parent = expr;
});
}
TreeNode visitSuperMethodInvocation(SuperMethodInvocation expr) {
return transform(expr, () {
visitArguments(expr.arguments);
});
}
TreeNode visitStaticInvocation(StaticInvocation expr) {
return transform(expr, () {
visitArguments(expr.arguments);
});
}
TreeNode visitConstructorInvocation(ConstructorInvocation expr) {
return transform(expr, () {
visitArguments(expr.arguments);
});
}
TreeNode visitStringConcatenation(StringConcatenation expr) {
return transform(expr, () {
var expressions = expr.expressions;
for (var i = expressions.length - 1; i >= 0; --i) {
expressions[i] = expressions[i].accept<TreeNode>(this)..parent = expr;
}
});
}
TreeNode visitListLiteral(ListLiteral expr) {
return transform(expr, () {
var expressions = expr.expressions;
for (var i = expressions.length - 1; i >= 0; --i) {
expressions[i] = expr.expressions[i].accept<TreeNode>(this)
..parent = expr;
}
});
}
TreeNode visitMapLiteral(MapLiteral expr) {
return transform(expr, () {
for (var entry in expr.entries.reversed) {
entry.value = entry.value.accept<TreeNode>(this)..parent = entry;
entry.key = entry.key.accept<TreeNode>(this)..parent = entry;
}
});
}
// Control flow.
TreeNode visitLogicalExpression(LogicalExpression expr) {
var shouldName = seenAwait;
// Right is delimited because it is conditionally evaluated.
var rightStatements = <Statement>[];
seenAwait = false;
expr.right =
delimit(() => expr.right.accept<TreeNode>(this), rightStatements)
..parent = expr;
var rightAwait = seenAwait;
if (rightStatements.isEmpty) {
// Easy case: right did not emit any statements.
seenAwait = shouldName;
return transform(expr, () {
expr.left = expr.left.accept<TreeNode>(this)..parent = expr;
seenAwait = seenAwait || rightAwait;
});
}
// If right has emitted statements we will produce a temporary t and emit
// for && (there is an analogous case for ||):
//
// t = [left] == true;
// if (t) {
// t = [right] == true;
// }
// Recall that statements are emitted in reverse order, so first emit the if
// statement, then the assignment of [left] == true, and then translate left
// so any statements it emits occur after in the accumulated list (that is,
// so they occur before in the corresponding block).
var rightBody = blockOf(rightStatements);
var result = allocateTemporary(nameIndex);
rightBody.addStatement(new ExpressionStatement(new VariableSet(
result,
new MethodInvocation(expr.right, new Name('=='),
new Arguments(<Expression>[new BoolLiteral(true)])))));
var then, otherwise;
if (expr.operator == '&&') {
then = rightBody;
otherwise = null;
} else {
then = new EmptyStatement();
otherwise = rightBody;
}
statements.add(new IfStatement(new VariableGet(result), then, otherwise));
var test = new MethodInvocation(expr.left, new Name('=='),
new Arguments(<Expression>[new BoolLiteral(true)]));
statements.add(new ExpressionStatement(new VariableSet(result, test)));
seenAwait = false;
test.receiver = test.receiver.accept<TreeNode>(this)..parent = test;
++nameIndex;
seenAwait = seenAwait || rightAwait;
return new VariableGet(result);
}
TreeNode visitConditionalExpression(ConditionalExpression expr) {
// Then and otherwise are delimited because they are conditionally
// evaluated.
var shouldName = seenAwait;
var thenStatements = <Statement>[];
seenAwait = false;
expr.then = delimit(() => expr.then.accept<TreeNode>(this), thenStatements)
..parent = expr;
var thenAwait = seenAwait;
var otherwiseStatements = <Statement>[];
seenAwait = false;
expr.otherwise = delimit(
() => expr.otherwise.accept<TreeNode>(this), otherwiseStatements)
..parent = expr;
var otherwiseAwait = seenAwait;
if (thenStatements.isEmpty && otherwiseStatements.isEmpty) {
// Easy case: neither then nor otherwise emitted any statements.
seenAwait = shouldName;
return transform(expr, () {
expr.condition = expr.condition.accept<TreeNode>(this)..parent = expr;
seenAwait = seenAwait || thenAwait || otherwiseAwait;
});
}
// If then or otherwise has emitted statements we will produce a temporary t
// and emit:
//
// if ([condition]) {
// t = [left];
// } else {
// t = [right];
// }
var result = allocateTemporary(nameIndex);
var thenBody = blockOf(thenStatements);
var otherwiseBody = blockOf(otherwiseStatements);
thenBody.addStatement(
new ExpressionStatement(new VariableSet(result, expr.then)));
otherwiseBody.addStatement(
new ExpressionStatement(new VariableSet(result, expr.otherwise)));
var branch = new IfStatement(expr.condition, thenBody, otherwiseBody);
statements.add(branch);
seenAwait = false;
branch.condition = branch.condition.accept<TreeNode>(this)..parent = branch;
++nameIndex;
seenAwait = seenAwait || thenAwait || otherwiseAwait;
return new VariableGet(result);
}
// Others.
TreeNode visitAwaitExpression(AwaitExpression expr) {
final R = continuationRewriter;
var shouldName = seenAwait;
var result = new VariableGet(asyncResult);
// The statements are in reverse order, so name the result first if
// necessary and then add the two other statements in reverse.
if (shouldName) result = name(result);
Arguments arguments = new Arguments(<Expression>[
expr.operand,
new VariableGet(R.thenContinuationVariable),
new VariableGet(R.catchErrorContinuationVariable),
new VariableGet(R.nestedClosureVariable),
]);
// We are building
//
// [yield] (let _ = _awaitHelper(...) in null)
//
// to ensure that :await_jump_var and :await_jump_ctx are updated
// before _awaitHelper is invoked (see BuildYieldStatement in
// StreamingFlowGraphBuilder for details of how [yield] is translated to
// IL). This guarantees that recursive invocation of the current function
// would continue from the correct "jump" position. Recursive invocations
// arise if future we are awaiting completes synchronously. Builtin Future
// implementation don't complete synchronously, but Flutter's
// SynchronousFuture do (see bug http://dartbug.com/32098 for more details).
statements.add(R.createContinuationPoint(new Let(
new VariableDeclaration(null,
initializer: new StaticInvocation(R.helper.awaitHelper, arguments)
..fileOffset = expr.fileOffset),
new NullLiteral()))
..fileOffset = expr.fileOffset);
seenAwait = false;
var index = nameIndex;
arguments.positional[0] = expr.operand.accept<TreeNode>(this)
..parent = arguments;
if (shouldName && index + 1 > nameIndex) nameIndex = index + 1;
seenAwait = true;
return result;
}
TreeNode visitFunctionExpression(FunctionExpression expr) {
expr.transformChildren(this);
return expr;
}
TreeNode visitLet(Let expr) {
var body = expr.body.accept<TreeNode>(this);
VariableDeclaration variable = expr.variable;
if (seenAwait) {
// There is an await in the body of `let var x = initializer in body` or
// to its right. We will produce the sequence of statements:
//
// <initializer's statements>
// var x = <initializer's value>
// <body's statements>
//
// and return the body's value.
//
// So x is in scope for all the body's statements and the body's value.
// This has the unpleasant consequence that all let-bound variables with
// await in the let's body will end up hoisted out of the expression and
// allocated to the context in the VM, even if they have no uses
// (`let _ = e0 in e1` can be used for sequencing of `e0` and `e1`).
statements.add(variable);
var index = nameIndex;
seenAwait = false;
variable.initializer = variable.initializer.accept<TreeNode>(this)
..parent = variable;
// Temporaries used in the initializer or the body are not live but the
// temporary used for the body is.
if (index + 1 > nameIndex) nameIndex = index + 1;
seenAwait = true;
return body;
} else {
// The body in `let x = initializer in body` did not contain an await. We
// can leave a let expression.
return transform(expr, () {
// The body has already been translated.
expr.body = body..parent = expr;
variable.initializer = variable.initializer.accept<TreeNode>(this)
..parent = variable;
});
}
}
visitFunctionNode(FunctionNode node) {
var nestedRewriter =
new RecursiveContinuationRewriter(continuationRewriter.helper);
return node.accept(nestedRewriter);
}
TreeNode visitBlockExpression(BlockExpression expr) {
return transform(expr, () {
expr.value = expr.value.accept<TreeNode>(this)..parent = expr;
List<Statement> body = <Statement>[];
for (Statement stmt in expr.body.statements.reversed) {
Statement translation = stmt.accept<TreeNode>(this);
if (translation != null) body.add(translation);
}
expr.body = new Block(body.reversed.toList())..parent = expr;
});
}
TreeNode defaultStatement(Statement stmt) {
// This method translates a statement nested in an expression (e.g., in a
// block expression). It produces a translated statement, a list of
// statements which are side effects necessary for any await, and a flag
// indicating whether there was an await in the statement or to its right.
// The translated statement can be null in the case where there was already
// an await to the right.
// The translation is accumulating two lists of statements, an inner list
// which is a reversed list of effects needed for the current expression and
// an outer list which represents the block containing the current
// statement. We need to preserve both of those from side effects.
List<Statement> savedInner = statements;
List<Statement> savedOuter = continuationRewriter.statements;
statements = <Statement>[];
continuationRewriter.statements = <Statement>[];
stmt.accept(continuationRewriter);
List<Statement> results = continuationRewriter.statements;
statements = savedInner;
continuationRewriter.statements = savedOuter;
if (!seenAwait && results.length == 1) return results.first;
statements.addAll(results.reversed);
return null;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/util/graph.dart | // Copyright (c) 2017, 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.md file.
library fasta.graph;
abstract class Graph<T> {
Iterable<T> get vertices;
Iterable<T> neighborsOf(T vertex);
}
/// Computes the strongly connected components of [graph].
///
/// This implementation is based on [Dijkstra's path-based strong component
/// algorithm]
/// (https://en.wikipedia.org/wiki/Path-based_strong_component_algorithm#Description).
List<List<T>> computeStrongComponents<T>(Graph<T> graph) {
List<List<T>> result = <List<T>>[];
int count = 0;
Map<T, int> preorderNumbers = <T, int>{};
List<T> unassigned = <T>[];
List<T> candidates = <T>[];
Set<T> assigned = new Set<T>();
void recursivelySearch(T vertex) {
// Step 1: Set the preorder number of [vertex] to [count], and increment
// [count].
preorderNumbers[vertex] = count++;
// Step 2: Push [vertex] onto [unassigned] and also onto [candidates].
unassigned.add(vertex);
candidates.add(vertex);
// Step 3: For each edge from [vertex] to a neighboring vertex [neighbor]:
for (T neighbor in graph.neighborsOf(vertex)) {
int neighborPreorderNumber = preorderNumbers[neighbor];
if (neighborPreorderNumber == null) {
// If the preorder number of [neighbor] has not yet been assigned,
// recursively search [neighbor];
recursivelySearch(neighbor);
} else if (!assigned.contains(neighbor)) {
// Otherwise, if [neighbor] has not yet been assigned to a strongly
// connected component:
//
// * Repeatedly pop vertices from [candidates] until the top element of
// [candidates] has a preorder number less than or equal to the
// preorder number of [neighbor].
while (preorderNumbers[candidates.last] > neighborPreorderNumber) {
candidates.removeLast();
}
}
}
// Step 4: If [vertex] is the top element of [candidates]:
if (candidates.last == vertex) {
// Pop vertices from [unassigned] until [vertex] has been popped, and
// assign the popped vertices to a new component.
List<T> component = <T>[];
while (true) {
T top = unassigned.removeLast();
component.add(top);
assigned.add(top);
if (top == vertex) break;
}
result.add(component);
// Pop [vertex] from [candidates].
candidates.removeLast();
}
}
for (T vertex in graph.vertices) {
if (preorderNumbers[vertex] == null) {
recursivelySearch(vertex);
}
}
return result;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/src/heap.dart | // Copyright (c) 2017, 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.
/// Basic implementation of a heap, with O(log n) insertion and removal.
abstract class Heap<T> {
final _items = <T>[];
bool get isEmpty => _items.isEmpty;
bool get isNotEmpty => _items.isNotEmpty;
void add(T item) {
int index = _items.length;
_items.length += 1;
while (index > 0) {
T parent = _items[_parentIndex(index)];
if (sortsBefore(parent, item)) break;
_items[index] = parent;
index = _parentIndex(index);
}
_items[index] = item;
}
T remove() {
T removed = _items[0];
T orphan = _items.removeLast();
if (_items.isNotEmpty) _reInsert(orphan);
return removed;
}
/// Client should use a derived class to specify the sort order.
bool sortsBefore(T a, T b);
int _firstChildIndex(int index) {
return (index << 1) + 1;
}
int _parentIndex(int index) {
return (index - 1) >> 1;
}
void _reInsert(T item) {
int index = 0;
while (true) {
int childIndex = _firstChildIndex(index);
if (childIndex >= _items.length) break;
T child = _items[childIndex];
if (childIndex + 1 < _items.length) {
T nextChild = _items[childIndex + 1];
if (sortsBefore(nextChild, child)) {
child = nextChild;
childIndex++;
}
}
if (sortsBefore(item, child)) break;
_items[index] = _items[childIndex];
index = childIndex;
}
_items[index] = item;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/src/bounds_checks.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import '../ast.dart'
show
BottomType,
Class,
DartType,
DynamicType,
FunctionType,
InterfaceType,
InvalidType,
NamedType,
TypeParameter,
TypeParameterType,
TypedefType,
Variance,
VoidType;
import '../type_algebra.dart' show Substitution, substitute;
import '../type_environment.dart' show SubtypeCheckMode, TypeEnvironment;
import '../util/graph.dart' show Graph, computeStrongComponents;
import '../visitor.dart' show DartTypeVisitor;
class TypeVariableGraph extends Graph<int> {
List<int> vertices;
List<TypeParameter> typeParameters;
List<DartType> bounds;
// `edges[i]` is the list of indices of type variables that reference the type
// variable with the index `i` in their bounds.
List<List<int>> edges;
TypeVariableGraph(this.typeParameters, this.bounds) {
assert(typeParameters.length == bounds.length);
vertices = new List<int>(typeParameters.length);
Map<TypeParameter, int> typeParameterIndices = <TypeParameter, int>{};
edges = new List<List<int>>(typeParameters.length);
for (int i = 0; i < vertices.length; i++) {
vertices[i] = i;
typeParameterIndices[typeParameters[i]] = i;
edges[i] = <int>[];
}
for (int i = 0; i < vertices.length; i++) {
OccurrenceCollectorVisitor collector =
new OccurrenceCollectorVisitor(typeParameters.toSet());
collector.visit(bounds[i]);
for (TypeParameter typeParameter in collector.occurred) {
edges[typeParameterIndices[typeParameter]].add(i);
}
}
}
Iterable<int> neighborsOf(int index) {
return edges[index];
}
}
class OccurrenceCollectorVisitor extends DartTypeVisitor {
final Set<TypeParameter> typeParameters;
Set<TypeParameter> occurred = new Set<TypeParameter>();
OccurrenceCollectorVisitor(this.typeParameters);
visit(DartType node) => node.accept(this);
visitNamedType(NamedType node) {
node.type.accept(this);
}
visitInvalidType(InvalidType node);
visitDynamicType(DynamicType node);
visitVoidType(VoidType node);
visitInterfaceType(InterfaceType node) {
for (DartType argument in node.typeArguments) {
argument.accept(this);
}
}
visitTypedefType(TypedefType node) {
for (DartType argument in node.typeArguments) {
argument.accept(this);
}
}
visitFunctionType(FunctionType node) {
for (TypeParameter typeParameter in node.typeParameters) {
typeParameter.bound.accept(this);
typeParameter.defaultType?.accept(this);
}
for (DartType parameter in node.positionalParameters) {
parameter.accept(this);
}
for (NamedType namedParameter in node.namedParameters) {
namedParameter.type.accept(this);
}
node.returnType.accept(this);
}
visitTypeParameterType(TypeParameterType node) {
if (typeParameters.contains(node.parameter)) {
occurred.add(node.parameter);
}
}
}
DartType instantiateToBounds(DartType type, Class objectClass) {
if (type is InterfaceType) {
for (var typeArgument in type.typeArguments) {
// If at least one of the arguments is not dynamic, we assume that the
// type is not raw and does not need instantiation of its type parameters
// to their bounds.
if (typeArgument is! DynamicType) {
return type;
}
}
return new InterfaceType.byReference(type.className,
calculateBounds(type.classNode.typeParameters, objectClass));
}
if (type is TypedefType) {
for (var typeArgument in type.typeArguments) {
if (typeArgument is! DynamicType) {
return type;
}
}
return new TypedefType.byReference(type.typedefReference,
calculateBounds(type.typedefNode.typeParameters, objectClass));
}
return type;
}
/// Calculates bounds to be provided as type arguments in place of missing type
/// arguments on raw types with the given type parameters.
///
/// See the [description]
/// (https://github.com/dart-lang/sdk/blob/master/docs/language/informal/instantiate-to-bound.md)
/// of the algorithm for details.
List<DartType> calculateBounds(
List<TypeParameter> typeParameters, Class objectClass) {
List<DartType> bounds = new List<DartType>(typeParameters.length);
for (int i = 0; i < typeParameters.length; i++) {
DartType bound = typeParameters[i].bound;
if (bound == null) {
bound = const DynamicType();
} else if (bound is InterfaceType && bound.classNode == objectClass) {
DartType defaultType = typeParameters[i].defaultType;
if (!(defaultType is InterfaceType &&
defaultType.classNode == objectClass)) {
bound = const DynamicType();
}
}
bounds[i] = bound;
}
TypeVariableGraph graph = new TypeVariableGraph(typeParameters, bounds);
List<List<int>> stronglyConnected = computeStrongComponents(graph);
for (List<int> component in stronglyConnected) {
Map<TypeParameter, DartType> upperBounds = <TypeParameter, DartType>{};
Map<TypeParameter, DartType> lowerBounds = <TypeParameter, DartType>{};
for (int typeParameterIndex in component) {
upperBounds[typeParameters[typeParameterIndex]] = const DynamicType();
lowerBounds[typeParameters[typeParameterIndex]] = const BottomType();
}
Substitution substitution =
Substitution.fromUpperAndLowerBounds(upperBounds, lowerBounds);
for (int typeParameterIndex in component) {
bounds[typeParameterIndex] =
substitution.substituteType(bounds[typeParameterIndex]);
}
}
for (int i = 0; i < typeParameters.length; i++) {
Map<TypeParameter, DartType> upperBounds = <TypeParameter, DartType>{};
Map<TypeParameter, DartType> lowerBounds = <TypeParameter, DartType>{};
upperBounds[typeParameters[i]] = bounds[i];
lowerBounds[typeParameters[i]] = const BottomType();
Substitution substitution =
Substitution.fromUpperAndLowerBounds(upperBounds, lowerBounds);
for (int j = 0; j < typeParameters.length; j++) {
bounds[j] = substitution.substituteType(bounds[j]);
}
}
return bounds;
}
class TypeArgumentIssue {
// The type argument that violated the bound.
final DartType argument;
// The type parameter with the bound that was violated.
final TypeParameter typeParameter;
// The enclosing type of the issue, that is, the one with [typeParameter].
final DartType enclosingType;
TypeArgumentIssue(this.argument, this.typeParameter, this.enclosingType);
}
// TODO(dmitryas): Remove [typedefInstantiations] when type arguments passed to
// typedefs are preserved in the Kernel output.
List<TypeArgumentIssue> findTypeArgumentIssues(
DartType type, TypeEnvironment typeEnvironment,
{bool allowSuperBounded = false}) {
List<TypeParameter> variables;
List<DartType> arguments;
List<TypeArgumentIssue> typedefRhsResult;
if (type is FunctionType && type.typedefType != null) {
// [type] is a function type that is an application of a parametrized
// typedef. We need to check both the l.h.s. and the r.h.s. of the
// definition in that case. For details, see [link]
// (https://github.com/dart-lang/sdk/blob/master/docs/language/informal/super-bounded-types.md).
FunctionType functionType = type;
FunctionType cloned = new FunctionType(
functionType.positionalParameters, functionType.returnType,
namedParameters: functionType.namedParameters,
typeParameters: functionType.typeParameters,
requiredParameterCount: functionType.requiredParameterCount,
typedefType: null);
typedefRhsResult = findTypeArgumentIssues(cloned, typeEnvironment,
allowSuperBounded: true);
type = functionType.typedefType;
}
if (type is InterfaceType) {
variables = type.classNode.typeParameters;
arguments = type.typeArguments;
} else if (type is TypedefType) {
variables = type.typedefNode.typeParameters;
arguments = type.typeArguments;
} else if (type is FunctionType) {
List<TypeArgumentIssue> result = <TypeArgumentIssue>[];
for (TypeParameter parameter in type.typeParameters) {
result.addAll(findTypeArgumentIssues(parameter.bound, typeEnvironment,
allowSuperBounded: true) ??
const <TypeArgumentIssue>[]);
}
for (DartType formal in type.positionalParameters) {
result.addAll(findTypeArgumentIssues(formal, typeEnvironment,
allowSuperBounded: true) ??
const <TypeArgumentIssue>[]);
}
for (NamedType named in type.namedParameters) {
result.addAll(findTypeArgumentIssues(named.type, typeEnvironment,
allowSuperBounded: true) ??
const <TypeArgumentIssue>[]);
}
result.addAll(findTypeArgumentIssues(type.returnType, typeEnvironment,
allowSuperBounded: true) ??
const <TypeArgumentIssue>[]);
return result.isEmpty ? null : result;
} else {
return null;
}
if (variables == null) return null;
List<TypeArgumentIssue> result;
List<TypeArgumentIssue> argumentsResult;
Map<TypeParameter, DartType> substitutionMap =
new Map<TypeParameter, DartType>.fromIterables(variables, arguments);
for (int i = 0; i < arguments.length; ++i) {
DartType argument = arguments[i];
if (argument is FunctionType && argument.typeParameters.length > 0) {
// Generic function types aren't allowed as type arguments either.
result ??= <TypeArgumentIssue>[];
result.add(new TypeArgumentIssue(argument, variables[i], type));
} else if (!typeEnvironment.isSubtypeOf(
argument,
substitute(variables[i].bound, substitutionMap),
SubtypeCheckMode.ignoringNullabilities)) {
result ??= <TypeArgumentIssue>[];
result.add(new TypeArgumentIssue(argument, variables[i], type));
}
List<TypeArgumentIssue> issues = findTypeArgumentIssues(
argument, typeEnvironment,
allowSuperBounded: true);
if (issues != null) {
argumentsResult ??= <TypeArgumentIssue>[];
argumentsResult.addAll(issues);
}
}
if (argumentsResult != null) {
result ??= <TypeArgumentIssue>[];
result.addAll(argumentsResult);
}
if (typedefRhsResult != null) {
result ??= <TypeArgumentIssue>[];
result.addAll(typedefRhsResult);
}
// [type] is regular-bounded.
if (result == null) return null;
if (!allowSuperBounded) return result;
result = null;
type = convertSuperBoundedToRegularBounded(typeEnvironment, type);
List<DartType> argumentsToReport = arguments.toList();
if (type is InterfaceType) {
variables = type.classNode.typeParameters;
arguments = type.typeArguments;
} else if (type is TypedefType) {
variables = type.typedefNode.typeParameters;
arguments = type.typeArguments;
}
substitutionMap =
new Map<TypeParameter, DartType>.fromIterables(variables, arguments);
for (int i = 0; i < arguments.length; ++i) {
DartType argument = arguments[i];
if (argument is FunctionType && argument.typeParameters.length > 0) {
// Generic function types aren't allowed as type arguments either.
result ??= <TypeArgumentIssue>[];
result
.add(new TypeArgumentIssue(argumentsToReport[i], variables[i], type));
} else if (!typeEnvironment.isSubtypeOf(
argument,
substitute(variables[i].bound, substitutionMap),
SubtypeCheckMode.ignoringNullabilities)) {
result ??= <TypeArgumentIssue>[];
result
.add(new TypeArgumentIssue(argumentsToReport[i], variables[i], type));
}
}
if (argumentsResult != null) {
result ??= <TypeArgumentIssue>[];
result.addAll(argumentsResult);
}
if (typedefRhsResult != null) {
result ??= <TypeArgumentIssue>[];
result.addAll(typedefRhsResult);
}
return result;
}
// TODO(dmitryas): Remove [typedefInstantiations] when type arguments passed to
// typedefs are preserved in the Kernel output.
List<TypeArgumentIssue> findTypeArgumentIssuesForInvocation(
List<TypeParameter> parameters,
List<DartType> arguments,
TypeEnvironment typeEnvironment,
{Map<FunctionType, List<DartType>> typedefInstantiations}) {
assert(arguments.length == parameters.length);
List<TypeArgumentIssue> result;
var substitutionMap = <TypeParameter, DartType>{};
for (int i = 0; i < arguments.length; ++i) {
substitutionMap[parameters[i]] = arguments[i];
}
for (int i = 0; i < arguments.length; ++i) {
DartType argument = arguments[i];
if (argument is TypeParameterType && argument.promotedBound != null) {
result ??= <TypeArgumentIssue>[];
result.add(new TypeArgumentIssue(argument, parameters[i], null));
} else if (argument is FunctionType && argument.typeParameters.length > 0) {
// Generic function types aren't allowed as type arguments either.
result ??= <TypeArgumentIssue>[];
result.add(new TypeArgumentIssue(argument, parameters[i], null));
} else if (!typeEnvironment.isSubtypeOf(
argument,
substitute(parameters[i].bound, substitutionMap),
SubtypeCheckMode.ignoringNullabilities)) {
result ??= <TypeArgumentIssue>[];
result.add(new TypeArgumentIssue(argument, parameters[i], null));
}
List<TypeArgumentIssue> issues = findTypeArgumentIssues(
argument, typeEnvironment,
allowSuperBounded: true);
if (issues != null) {
result ??= <TypeArgumentIssue>[];
result.addAll(issues);
}
}
return result;
}
String getGenericTypeName(DartType type) {
if (type is InterfaceType) {
return type.classNode.name;
} else if (type is TypedefType) {
return type.typedefNode.name;
}
return type.toString();
}
/// Replaces all covariant occurrences of `dynamic`, `Object`, and `void` with
/// [BottomType] and all contravariant occurrences of `Null` and [BottomType]
/// with `Object`.
DartType convertSuperBoundedToRegularBounded(
TypeEnvironment typeEnvironment, DartType type,
{bool isCovariant = true}) {
if ((type is DynamicType ||
type is VoidType ||
isObject(typeEnvironment, type)) &&
isCovariant) {
return const BottomType();
} else if ((type is BottomType || isNull(typeEnvironment, type)) &&
!isCovariant) {
return typeEnvironment.coreTypes.objectLegacyRawType;
} else if (type is InterfaceType && type.classNode.typeParameters != null) {
List<DartType> replacedTypeArguments =
new List<DartType>(type.typeArguments.length);
for (int i = 0; i < replacedTypeArguments.length; i++) {
replacedTypeArguments[i] = convertSuperBoundedToRegularBounded(
typeEnvironment, type.typeArguments[i],
isCovariant: isCovariant);
}
return new InterfaceType(type.classNode, replacedTypeArguments);
} else if (type is TypedefType && type.typedefNode.typeParameters != null) {
List<DartType> replacedTypeArguments =
new List<DartType>(type.typeArguments.length);
for (int i = 0; i < replacedTypeArguments.length; i++) {
replacedTypeArguments[i] = convertSuperBoundedToRegularBounded(
typeEnvironment, type.typeArguments[i],
isCovariant: isCovariant);
}
return new TypedefType(type.typedefNode, replacedTypeArguments);
} else if (type is FunctionType) {
var replacedReturnType = convertSuperBoundedToRegularBounded(
typeEnvironment, type.returnType,
isCovariant: isCovariant);
var replacedPositionalParameters =
new List<DartType>(type.positionalParameters.length);
for (int i = 0; i < replacedPositionalParameters.length; i++) {
replacedPositionalParameters[i] = convertSuperBoundedToRegularBounded(
typeEnvironment, type.positionalParameters[i],
isCovariant: !isCovariant);
}
var replacedNamedParameters =
new List<NamedType>(type.namedParameters.length);
for (int i = 0; i < replacedNamedParameters.length; i++) {
replacedNamedParameters[i] = new NamedType(
type.namedParameters[i].name,
convertSuperBoundedToRegularBounded(
typeEnvironment, type.namedParameters[i].type,
isCovariant: !isCovariant));
}
return new FunctionType(replacedPositionalParameters, replacedReturnType,
namedParameters: replacedNamedParameters,
typeParameters: type.typeParameters,
requiredParameterCount: type.requiredParameterCount,
typedefType: type.typedefType);
}
return type;
}
bool isObject(TypeEnvironment typeEnvironment, DartType type) {
return type is InterfaceType &&
type.classNode == typeEnvironment.coreTypes.objectClass;
}
bool isNull(TypeEnvironment typeEnvironment, DartType type) {
return type is InterfaceType &&
type.classNode == typeEnvironment.nullType.classNode;
}
int computeVariance(TypeParameter typeParameter, DartType type) {
return type.accept(new VarianceCalculator(typeParameter));
}
class VarianceCalculator implements DartTypeVisitor<int> {
final TypeParameter typeParameter;
VarianceCalculator(this.typeParameter);
@override
int defaultDartType(DartType node) => Variance.unrelated;
@override
int visitTypeParameterType(TypeParameterType node) {
if (node.parameter == typeParameter) return Variance.covariant;
return Variance.unrelated;
}
@override
int visitInterfaceType(InterfaceType node) {
int result = Variance.unrelated;
for (DartType argument in node.typeArguments) {
result = Variance.meet(result, argument.accept(this));
}
return result;
}
@override
int visitTypedefType(TypedefType node) {
int result = Variance.unrelated;
for (int i = 0; i < node.typeArguments.length; ++i) {
result = Variance.meet(
result,
Variance.combine(
node.typeArguments[i].accept(this),
node.typedefNode.type.accept(
new VarianceCalculator(node.typedefNode.typeParameters[i]))));
}
return result;
}
@override
int visitFunctionType(FunctionType node) {
int result = Variance.unrelated;
result = Variance.meet(result, node.returnType.accept(this));
for (TypeParameter functionTypeParameter in node.typeParameters) {
// If [typeParameter] is referenced in the bound at all, it makes the
// variance of [typeParameter] in the entire type invariant. The
// invocation of the visitor below is made to simply figure out if
// [typeParameter] occurs in the bound.
if (functionTypeParameter.bound.accept(this) != Variance.unrelated) {
result = Variance.invariant;
}
}
for (DartType positionalType in node.positionalParameters) {
result = Variance.meet(
result,
Variance.combine(
Variance.contravariant, positionalType.accept(this)));
}
for (NamedType namedType in node.namedParameters) {
result = Variance.meet(
result,
Variance.combine(
Variance.contravariant, namedType.type.accept(this)));
}
return result;
}
@override
int visitBottomType(BottomType node) => defaultDartType(node);
@override
int visitVoidType(VoidType node) => defaultDartType(node);
@override
int visitDynamicType(DynamicType node) => defaultDartType(node);
@override
int visitInvalidType(InvalidType node) => defaultDartType(node);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/src/hierarchy_based_type_environment.dart | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library kernel.hierarchy_based_type_environment;
import '../ast.dart' show Class, InterfaceType;
import '../class_hierarchy.dart' show ClassHierarchy;
import '../core_types.dart' show CoreTypes;
import '../type_environment.dart' show TypeEnvironment;
class HierarchyBasedTypeEnvironment extends TypeEnvironment {
final ClassHierarchy hierarchy;
HierarchyBasedTypeEnvironment(CoreTypes coreTypes, this.hierarchy)
: super.fromSubclass(coreTypes);
@override
InterfaceType getTypeAsInstanceOf(InterfaceType type, Class superclass) {
return hierarchy.getTypeAsInstanceOf(type, superclass);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/src/tool/batch_util.dart | // 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.
library kernel.batch_util;
import 'dart:async';
import 'dart:convert';
import 'dart:io';
enum CompilerOutcome {
Ok,
Fail,
}
typedef Future<CompilerOutcome> BatchCallback(List<String> arguments);
/// Runs the given [callback] in the batch mode for use by the test framework in
/// `dart-lang/sdk`.
///
/// The [callback] should behave as a main method, except it should return a
/// [CompilerOutcome] for reporting its outcome to the testing framework.
Future runBatch(BatchCallback callback) async {
int totalTests = 0;
int testsFailed = 0;
var watch = new Stopwatch()..start();
print('>>> BATCH START');
Stream input = stdin.transform(utf8.decoder).transform(new LineSplitter());
await for (String line in input) {
if (line.isEmpty) {
int time = watch.elapsedMilliseconds;
print('>>> BATCH END '
'(${totalTests - testsFailed})/$totalTests ${time}ms');
break;
}
++totalTests;
var arguments = line.split(new RegExp(r'\s+'));
try {
var outcome = await callback(arguments);
stderr.writeln('>>> EOF STDERR');
if (outcome == CompilerOutcome.Ok) {
print('>>> TEST PASS ${watch.elapsedMilliseconds}ms');
} else {
print('>>> TEST FAIL ${watch.elapsedMilliseconds}ms');
}
} catch (e, stackTrace) {
stderr.writeln(e);
stderr.writeln(stackTrace);
stderr.writeln('>>> EOF STDERR');
print('>>> TEST CRASH');
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/src/tool/command_line_util.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
import 'package:kernel/kernel.dart';
class CommandLineHelper {
static requireExactlyOneArgument(List<String> args, void Function() usage,
{bool requireFileExists: false}) {
if (args.length != 1) {
print("Expected exactly 1 argument, got ${args.length}.");
usage();
}
if (requireFileExists) CommandLineHelper.requireFileExists(args[0]);
}
static requireVariableArgumentCount(
List<int> ok, List<String> args, void Function() usage) {
if (!ok.contains(args.length)) {
print(
"Expected the argument count to be one of ${ok}, got ${args.length}.");
usage();
}
}
static requireFileExists(String file) {
if (!new File(file).existsSync()) {
print("File $file doesn't exist.");
exit(1);
}
}
static Component tryLoadDill(String file) {
try {
return loadComponentFromBinary(file);
} catch (e) {
print("$file can't be loaded.");
print(e);
exit(1);
}
return null;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/vm/constants_native_effects.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library vm.constants_native_effects;
import '../ast.dart';
import '../target/targets.dart';
import '../core_types.dart';
class VmConstantsBackend extends ConstantsBackend {
final Class immutableMapClass;
VmConstantsBackend._(this.immutableMapClass);
/// If [defines] is not `null` it will be used for handling
/// `const {bool,...}.fromEnvironment()` otherwise the current VM's values
/// will be used.
factory VmConstantsBackend(CoreTypes coreTypes) {
final Library coreLibrary = coreTypes.coreLibrary;
final Class immutableMapClass = coreLibrary.classes
.firstWhere((Class klass) => klass.name == '_ImmutableMap');
assert(immutableMapClass != null);
return new VmConstantsBackend._(immutableMapClass);
}
@override
Constant lowerMapConstant(MapConstant constant) {
// The _ImmutableMap class is implemented via one field pointing to a list
// of key/value pairs -- see runtime/lib/immutable_map.dart!
final List<Constant> kvListPairs =
new List<Constant>(2 * constant.entries.length);
for (int i = 0; i < constant.entries.length; i++) {
final ConstantMapEntry entry = constant.entries[i];
kvListPairs[2 * i] = entry.key;
kvListPairs[2 * i + 1] = entry.value;
}
// This is a bit fishy, since we merge the key and the value type by
// putting both into the same list.
final kvListConstant = new ListConstant(const DynamicType(), kvListPairs);
assert(immutableMapClass.fields.length == 1);
final Field kvPairListField = immutableMapClass.fields[0];
return new InstanceConstant(immutableMapClass.reference, <DartType>[
constant.keyType,
constant.valueType,
], <Reference, Constant>{
kvPairListField.reference: kvListConstant,
});
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/kernel/target/targets.dart | // 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.
library kernel.target.targets;
import '../ast.dart';
import '../class_hierarchy.dart';
import '../core_types.dart';
final List<String> targetNames = targets.keys.toList();
class TargetFlags {
final bool trackWidgetCreation;
TargetFlags({this.trackWidgetCreation = false});
}
typedef Target _TargetBuilder(TargetFlags flags);
final Map<String, _TargetBuilder> targets = <String, _TargetBuilder>{
'none': (TargetFlags flags) => new NoneTarget(flags),
};
Target getTarget(String name, TargetFlags flags) {
var builder = targets[name];
if (builder == null) return null;
return builder(flags);
}
abstract class DiagnosticReporter<M, C> {
void report(M message, int charOffset, int length, Uri fileUri,
{List<C> context});
}
/// The different kinds of number semantics supported by the constant evaluator.
enum NumberSemantics {
/// Dart VM number semantics.
vm,
/// JavaScript (Dart2js and DDC) number semantics.
js,
}
// Backend specific constant evaluation behavior
class ConstantsBackend {
const ConstantsBackend();
/// Lowering of a list constant to a backend-specific representation.
Constant lowerListConstant(ListConstant constant) => constant;
/// Lowering of a set constant to a backend-specific representation.
Constant lowerSetConstant(SetConstant constant) => constant;
/// Lowering of a map constant to a backend-specific representation.
Constant lowerMapConstant(MapConstant constant) => constant;
/// Number semantics to use for this backend.
NumberSemantics get numberSemantics => NumberSemantics.vm;
/// Inline control of constant variables. The given constant expression
/// is the initializer of a [Field] or [VariableDeclaration] node.
/// If this method returns `true`, the variable will be inlined at all
/// points of reference and the variable itself removed (unless overridden
/// by the `keepFields` or `keepVariables` flag to the constant transformer).
/// This method must be deterministic, i.e. it must always return the same
/// value for the same constant value and place in the AST.
bool shouldInlineConstant(ConstantExpression initializer) => true;
/// Whether this target supports unevaluated constants.
///
/// If not, then trying to perform constant evaluation without an environment
/// raises an exception.
///
/// This defaults to `false` since it requires additional work for a backend
/// to support unevaluated constants.
bool get supportsUnevaluatedConstants => false;
}
/// A target provides backend-specific options for generating kernel IR.
abstract class Target {
String get name;
/// A list of URIs of required libraries, not including dart:core.
///
/// Libraries will be loaded in order.
List<String> get extraRequiredLibraries => const <String>[];
/// A list of URIs of extra required libraries when compiling the platform.
///
/// Libraries will be loaded in order after the [extraRequiredLibraries]
/// above.
///
/// Normally not needed, but can be useful if removing libraries from the
/// [extraRequiredLibraries] list so libraries will still be available in the
/// platform if having a weird mix of current and not-quite-current as can
/// sometimes be the case.
List<String> get extraRequiredLibrariesPlatform => const <String>[];
/// A list of URIs of libraries to be indexed in the CoreTypes index, not
/// including dart:_internal, dart:async, dart:core and dart:mirrors.
List<String> get extraIndexedLibraries => const <String>[];
/// Additional declared variables implied by this target.
///
/// These can also be passed on the command-line of form `-D<name>=<value>`,
/// and those provided on the command-line take precedence over those defined
/// by the target.
Map<String, String> get extraDeclaredVariables => const <String, String>{};
/// Classes from the SDK whose interface is required for the modular
/// transformations.
Map<String, List<String>> get requiredSdkClasses => CoreTypes.requiredClasses;
/// A derived class may change this to `true` to enable forwarders to
/// user-defined `noSuchMethod` that are generated for each abstract member
/// if such `noSuchMethod` is present.
///
/// The forwarders are abstract [Procedure]s with [isNoSuchMethodForwarder]
/// bit set. The implementation of the behavior of such forwarders is up
/// for the target backend.
bool get enableNoSuchMethodForwarders => false;
/// A derived class may change this to `true` to enable Flutter specific
/// "super-mixins" semantics.
///
/// This semantics relaxes a number of constraint previously imposed on
/// mixins. Importantly it imposes the following change:
///
/// An abstract class may contain a member with a super-invocation that
/// corresponds to a member of the superclass interface, but where the
/// actual superclass does not declare or inherit a matching method.
/// Since no amount of overriding can change this property, such a class
/// cannot be extended to a class that is not abstract, it can only be
/// used to derive a mixin from.
///
/// See dartbug.com/31542 for details of the semantics.
bool get enableSuperMixins => false;
/// Perform target-specific transformations on the outlines stored in
/// [Component] when generating summaries.
///
/// This transformation is used to add metadata on outlines and to filter
/// unnecessary information before generating program summaries. This
/// transformation is not applied when compiling full kernel programs to
/// prevent affecting the internal invariants of the compiler and accidentally
/// slowing down compilation.
void performOutlineTransformations(Component component) {}
/// Perform target-specific transformations on the given libraries that must
/// run before constant evaluation.
void performPreConstantEvaluationTransformations(
Component component,
CoreTypes coreTypes,
List<Library> libraries,
DiagnosticReporter diagnosticReporter,
{void logger(String msg)}) {}
/// Perform target-specific modular transformations on the given libraries.
void performModularTransformationsOnLibraries(
Component component,
CoreTypes coreTypes,
ClassHierarchy hierarchy,
List<Library> libraries,
// TODO(askesc): Consider how to generally pass compiler options to
// transformations.
Map<String, String> environmentDefines,
DiagnosticReporter diagnosticReporter,
{void logger(String msg)});
/// Perform target-specific modular transformations on the given program.
///
/// This is used when an individual expression is compiled, e.g. for debugging
/// purposes. It is illegal to modify any of the enclosing nodes of the
/// procedure.
void performTransformationsOnProcedure(
CoreTypes coreTypes, ClassHierarchy hierarchy, Procedure procedure,
{void logger(String msg)}) {}
/// Whether a platform library may define a restricted type, such as `bool`,
/// `int`, `double`, `num`, and `String`.
///
/// By default only `dart:core` may define restricted types, but some target
/// implementations override this.
bool mayDefineRestrictedType(Uri uri) =>
uri.scheme == 'dart' && uri.path == 'core';
/// Whether a library is allowed to import a platform private library.
///
/// By default only `dart:*` libraries are allowed. May be overridden for
/// testing purposes.
bool allowPlatformPrivateLibraryAccess(Uri importer, Uri imported) =>
imported.scheme != "dart" ||
!imported.path.startsWith("_") ||
importer.scheme == "dart" ||
(importer.scheme == "package" &&
importer.path.startsWith("dart_internal/"));
/// Whether the `native` language extension is supported within [library].
///
/// The `native` language extension is not part of the language specification,
/// it means something else to each target, and it is enabled under different
/// circumstances for each target implementation. For example, the VM target
/// enables it everywhere because of existing support for "dart-ext:" native
/// extensions, but targets like dart2js only enable it on the core libraries.
bool enableNative(Uri uri) => false;
/// There are two variants of the `native` language extension. The VM expects
/// the native token to be followed by string, whereas dart2js and DDC do not.
// TODO(sigmund, ahe): ideally we should remove the `native` syntax, if not,
// we should at least unify the VM and non-VM variants.
bool get nativeExtensionExpectsString => false;
/// Whether integer literals that cannot be represented exactly on the web
/// (i.e. in Javascript) should cause an error to be issued.
/// An example of such a number is `2^53 + 1` where in Javascript - because
/// integers are represented as doubles
/// `Math.pow(2, 53) = Math.pow(2, 53) + 1`.
bool get errorOnUnexactWebIntLiterals => false;
/// Whether set literals are natively supported by this target. If set
/// literals are not supported by the target, they will be desugared into
/// explicit `Set` creation (for non-const set literals) or wrapped map
/// literals (for const set literals).
bool get supportsSetLiterals => true;
/// Builds an expression that instantiates an [Invocation] that can be passed
/// to [noSuchMethod].
Expression instantiateInvocation(CoreTypes coreTypes, Expression receiver,
String name, Arguments arguments, int offset, bool isSuper);
Expression instantiateNoSuchMethodError(CoreTypes coreTypes,
Expression receiver, String name, Arguments arguments, int offset,
{bool isMethod: false,
bool isGetter: false,
bool isSetter: false,
bool isField: false,
bool isLocalVariable: false,
bool isDynamic: false,
bool isSuper: false,
bool isStatic: false,
bool isConstructor: false,
bool isTopLevel: false});
/// Configure the given [Component] in a target specific way.
/// Returns the configured component.
Component configureComponent(Component component) => component;
String toString() => 'Target($name)';
Class concreteListLiteralClass(CoreTypes coreTypes) => null;
Class concreteConstListLiteralClass(CoreTypes coreTypes) => null;
Class concreteMapLiteralClass(CoreTypes coreTypes) => null;
Class concreteConstMapLiteralClass(CoreTypes coreTypes) => null;
Class concreteIntLiteralClass(CoreTypes coreTypes, int value) => null;
Class concreteStringLiteralClass(CoreTypes coreTypes, String value) => null;
ConstantsBackend constantsBackend(CoreTypes coreTypes);
}
class NoneConstantsBackend extends ConstantsBackend {
@override
final bool supportsUnevaluatedConstants;
const NoneConstantsBackend({this.supportsUnevaluatedConstants});
}
class NoneTarget extends Target {
final TargetFlags flags;
NoneTarget(this.flags);
String get name => 'none';
List<String> get extraRequiredLibraries => <String>[];
void performModularTransformationsOnLibraries(
Component component,
CoreTypes coreTypes,
ClassHierarchy hierarchy,
List<Library> libraries,
Map<String, String> environmentDefines,
DiagnosticReporter diagnosticReporter,
{void logger(String msg)}) {}
@override
Expression instantiateInvocation(CoreTypes coreTypes, Expression receiver,
String name, Arguments arguments, int offset, bool isSuper) {
return new InvalidExpression(null);
}
@override
Expression instantiateNoSuchMethodError(CoreTypes coreTypes,
Expression receiver, String name, Arguments arguments, int offset,
{bool isMethod: false,
bool isGetter: false,
bool isSetter: false,
bool isField: false,
bool isLocalVariable: false,
bool isDynamic: false,
bool isSuper: false,
bool isStatic: false,
bool isConstructor: false,
bool isTopLevel: false}) {
return new InvalidExpression(null);
}
@override
ConstantsBackend constantsBackend(CoreTypes coreTypes) =>
// TODO(johnniwinther): Should this vary with the use case?
const NoneConstantsBackend(supportsUnevaluatedConstants: true);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/charcode/ascii.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source is governed by a
// BSD-style license that can be found in the LICENSE file.
// ignore_for_file: constant_identifier_names
/// Declare integer constants for each ASCII character.
///
/// The constants all start with "$" to avoid conflicting with other constants.
///
/// For characters that are valid in an identifier, the character itself
/// follows the "$". For other characters, a symbolic name is used.
/// In some cases, multiple alternative symbolic names are provided.
/// Please stick to using one name per character in your code.
///
/// The symbolic names are, where applicable, the name of the symbol without
/// any "mark", "symbol" "sign" or "accent" suffix.
/// Examples: [$exclamation], [$pipe], [$dollar] and [$grave].
/// For less common symbols, a selection of common names are used.
///
/// For parenthetical markers, there is both a short name, [$lparen]/[$rparen],
/// and a long name, [$open_paren]/ [$close_paren].
///
/// For common HTML entities, the entity names are also usable as symbolic
/// names: [$apos], [$quot], [$lt], [$gt], and [$amp].
library charcode.ascii.dollar_lowercase;
// Control characters.
/// "Null character" control character.
const int $nul = 0x00;
/// "Start of Header" control character.
const int $soh = 0x01;
/// "Start of Text" control character.
const int $stx = 0x02;
/// "End of Text" control character.
const int $etx = 0x03;
/// "End of Transmission" control character.
const int $eot = 0x04;
/// "Enquiry" control character.
const int $enq = 0x05;
/// "Acknowledgment" control character.
const int $ack = 0x06;
/// "Bell" control character.
const int $bel = 0x07;
/// "Backspace" control character.
const int $bs = 0x08;
/// "Horizontal Tab" control character.
const int $ht = 0x09;
/// "Horizontal Tab" control character, common name.
const int $tab = 0x09;
/// "Line feed" control character.
const int $lf = 0x0A;
/// "Vertical Tab" control character.
const int $vt = 0x0B;
/// "Form feed" control character.
const int $ff = 0x0C;
/// "Carriage return" control character.
const int $cr = 0x0D;
/// "Shift Out" control character.
const int $so = 0x0E;
/// "Shift In" control character.
const int $si = 0x0F;
/// "Data Link Escape" control character.
const int $dle = 0x10;
/// "Device Control 1" control character (oft. XON).
const int $dc1 = 0x11;
/// "Device Control 2" control character.
const int $dc2 = 0x12;
/// "Device Control 3" control character (oft. XOFF).
const int $dc3 = 0x13;
/// "Device Control 4" control character.
const int $dc4 = 0x14;
/// "Negative Acknowledgment" control character.
const int $nak = 0x15;
/// "Synchronous idle" control character.
const int $syn = 0x16;
/// "End of Transmission Block" control character.
const int $etb = 0x17;
/// "Cancel" control character.
const int $can = 0x18;
/// "End of Medium" control character.
const int $em = 0x19;
/// "Substitute" control character.
const int $sub = 0x1A;
/// "Escape" control character.
const int $esc = 0x1B;
/// "File Separator" control character.
const int $fs = 0x1C;
/// "Group Separator" control character.
const int $gs = 0x1D;
/// "Record Separator" control character.
const int $rs = 0x1E;
/// "Unit Separator" control character.
const int $us = 0x1F;
/// "Delete" control character.
const int $del = 0x7F;
// Visible characters.
/// Space character.
const int $space = 0x20;
/// Character '!'.
const int $exclamation = 0x21;
/// Character '"', short name.
const int $quot = 0x22;
/// Character '"'.
const int $quote = 0x22;
/// Character '"'.
const int $double_quote = 0x22;
/// Character '"'.
const int $quotation = 0x22;
/// Character '#'.
const int $hash = 0x23;
/// Character '$'.
const int $$ = 0x24;
/// Character '$'.
const int $dollar = 0x24;
/// Character '%'.
const int $percent = 0x25;
/// Character '&', short name.
const int $amp = 0x26;
/// Character '&'.
const int $ampersand = 0x26;
/// Character "'".
const int $apos = 0x27;
/// Character '''.
const int $apostrophe = 0x27;
/// Character '''.
const int $single_quote = 0x27;
/// Character '('.
const int $lparen = 0x28;
/// Character '('.
const int $open_paren = 0x28;
/// Character '('.
const int $open_parenthesis = 0x28;
/// Character ')'.
const int $rparen = 0x29;
/// Character ')'.
const int $close_paren = 0x29;
/// Character ')'.
const int $close_parenthesis = 0x29;
/// Character '*'.
const int $asterisk = 0x2A;
/// Character '+'.
const int $plus = 0x2B;
/// Character ','.
const int $comma = 0x2C;
/// Character '-'.
const int $minus = 0x2D;
/// Character '-'.
const int $dash = 0x2D;
/// Character '.'.
const int $dot = 0x2E;
/// Character '.'.
const int $fullstop = 0x2E;
/// Character '/'.
const int $slash = 0x2F;
/// Character '/'.
const int $solidus = 0x2F;
/// Character '/'.
const int $division = 0x2F;
/// Character '0'.
const int $0 = 0x30;
/// Character '1'.
const int $1 = 0x31;
/// Character '2'.
const int $2 = 0x32;
/// Character '3'.
const int $3 = 0x33;
/// Character '4'.
const int $4 = 0x34;
/// Character '5'.
const int $5 = 0x35;
/// Character '6'.
const int $6 = 0x36;
/// Character '7'.
const int $7 = 0x37;
/// Character '8'.
const int $8 = 0x38;
/// Character '9'.
const int $9 = 0x39;
/// Character ':'.
const int $colon = 0x3A;
/// Character ';'.
const int $semicolon = 0x3B;
/// Character '<'.
const int $lt = 0x3C;
/// Character '<'.
const int $less_than = 0x3C;
/// Character '<'.
const int $langle = 0x3C;
/// Character '<'.
const int $open_angle = 0x3C;
/// Character '='.
const int $equal = 0x3D;
/// Character '>'.
const int $gt = 0x3E;
/// Character '>'.
const int $greater_than = 0x3E;
/// Character '>'.
const int $rangle = 0x3E;
/// Character '>'.
const int $close_angle = 0x3E;
/// Character '?'.
const int $question = 0x3F;
/// Character '@'.
const int $at = 0x40;
/// Character 'A'.
const int $A = 0x41;
/// Character 'B'.
const int $B = 0x42;
/// Character 'C'.
const int $C = 0x43;
/// Character 'D'.
const int $D = 0x44;
/// Character 'E'.
const int $E = 0x45;
/// Character 'F'.
const int $F = 0x46;
/// Character 'G'.
const int $G = 0x47;
/// Character 'H'.
const int $H = 0x48;
/// Character 'I'.
const int $I = 0x49;
/// Character 'J'.
const int $J = 0x4A;
/// Character 'K'.
const int $K = 0x4B;
/// Character 'L'.
const int $L = 0x4C;
/// Character 'M'.
const int $M = 0x4D;
/// Character 'N'.
const int $N = 0x4E;
/// Character 'O'.
const int $O = 0x4F;
/// Character 'P'.
const int $P = 0x50;
/// Character 'Q'.
const int $Q = 0x51;
/// Character 'R'.
const int $R = 0x52;
/// Character 'S'.
const int $S = 0x53;
/// Character 'T'.
const int $T = 0x54;
/// Character 'U'.
const int $U = 0x55;
/// Character 'V'.
const int $V = 0x56;
/// Character 'W'.
const int $W = 0x57;
/// Character 'X'.
const int $X = 0x58;
/// Character 'Y'.
const int $Y = 0x59;
/// Character 'Z'.
const int $Z = 0x5A;
/// Character '['.
const int $lbracket = 0x5B;
/// Character '['.
const int $open_bracket = 0x5B;
/// Character '\'.
const int $backslash = 0x5C;
/// Character ']'.
const int $rbracket = 0x5D;
/// Character ']'.
const int $close_bracket = 0x5D;
/// Character '^'.
const int $circumflex = 0x5E;
/// Character '^'.
const int $caret = 0x5E;
/// Character '^'.
const int $hat = 0x5E;
/// Character '_'.
const int $_ = 0x5F;
/// Character '_'.
const int $underscore = 0x5F;
/// Character '_'.
const int $underline = 0x5F;
/// Character '`'.
const int $backquote = 0x60;
/// Character '`'.
const int $grave = 0x60;
/// Character 'a'.
const int $a = 0x61;
/// Character 'b'.
const int $b = 0x62;
/// Character 'c'.
const int $c = 0x63;
/// Character 'd'.
const int $d = 0x64;
/// Character 'e'.
const int $e = 0x65;
/// Character 'f'.
const int $f = 0x66;
/// Character 'g'.
const int $g = 0x67;
/// Character 'h'.
const int $h = 0x68;
/// Character 'i'.
const int $i = 0x69;
/// Character 'j'.
const int $j = 0x6A;
/// Character 'k'.
const int $k = 0x6B;
/// Character 'l'.
const int $l = 0x6C;
/// Character 'm'.
const int $m = 0x6D;
/// Character 'n'.
const int $n = 0x6E;
/// Character 'o'.
const int $o = 0x6F;
/// Character 'p'.
const int $p = 0x70;
/// Character 'q'.
const int $q = 0x71;
/// Character 'r'.
const int $r = 0x72;
/// Character 's'.
const int $s = 0x73;
/// Character 't'.
const int $t = 0x74;
/// Character 'u'.
const int $u = 0x75;
/// Character 'v'.
const int $v = 0x76;
/// Character 'w'.
const int $w = 0x77;
/// Character 'x'.
const int $x = 0x78;
/// Character 'y'.
const int $y = 0x79;
/// Character 'z'.
const int $z = 0x7A;
/// Character '{'.
const int $lbrace = 0x7B;
/// Character '{'.
const int $open_brace = 0x7B;
/// Character '|'.
const int $pipe = 0x7C;
/// Character '|'.
const int $bar = 0x7C;
/// Character '}'.
const int $rbrace = 0x7D;
/// Character '}'.
const int $close_brace = 0x7D;
/// Character '~'.
const int $tilde = 0x7E;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/charcode/charcode.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Defines symbolic names for character code points.
///
/// Includes all ASCII and Latin-1 characters.
///
/// Exports the libraries `ascii.dart` and `html_entity.dart`.
///
/// Hides the characters `$minus`, `$sub` and `$tilde` from
/// `html_entities.dart`, since other characters have the same name in
/// `ascii.dart`.
library charcode;
export 'ascii.dart';
export 'html_entity.dart' hide $minus, $tilde, $sub;
| 0 |
Subsets and Splits