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/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/parser/assert.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 fasta.parser.Assert;
/// Syntactic forms of `assert`.
///
/// An assertion can legally occur as a statement. However, assertions are also
/// experimentally allowed in initializers. For improved error recovery, we
/// also attempt to parse asserts as expressions.
enum Assert {
Expression,
Initializer,
Statement,
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/parser/token_stream_rewriter.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 '../scanner/error_token.dart' show UnmatchedToken;
import '../../scanner/token.dart'
show
BeginToken,
Keyword,
SimpleToken,
SyntheticBeginToken,
SyntheticKeywordToken,
SyntheticStringToken,
SyntheticToken,
Token,
TokenType;
/// Provides the capability of inserting tokens into a token stream. This
/// implementation does this by rewriting the previous token to point to the
/// inserted token.
class TokenStreamRewriter with _TokenStreamMixin {
// TODO(brianwilkerson):
//
// When we get to the point of removing `token.previous`, the plan is to
// convert this into an interface and provide two implementations.
//
// One, used by Fasta, will connect the inserted tokens to the following token
// without modifying the previous token.
//
// The other, used by 'analyzer', will be created with the first token in the
// stream (actually with the BOF marker at the beginning of the stream). It
// will be created only when invoking 'analyzer' specific parse methods (in
// `Parser`), such as
//
// Token parseUnitWithRewrite(Token bof) {
// rewriter = AnalyzerTokenStreamRewriter(bof);
// return parseUnit(bof.next);
// }
//
/// Insert a synthetic open and close parenthesis and return the new synthetic
/// open parenthesis. If [insertIdentifier] is true, then a synthetic
/// identifier is included between the open and close parenthesis.
Token insertParens(Token token, bool includeIdentifier) {
Token next = token.next;
int offset = next.charOffset;
BeginToken leftParen =
next = new SyntheticBeginToken(TokenType.OPEN_PAREN, offset);
if (includeIdentifier) {
next = next.setNext(
new SyntheticStringToken(TokenType.IDENTIFIER, '', offset, 0));
}
next = next.setNext(new SyntheticToken(TokenType.CLOSE_PAREN, offset));
leftParen.endGroup = next;
next.setNext(token.next);
// A no-op rewriter could skip this step.
token.setNext(leftParen);
return leftParen;
}
/// Insert [newToken] after [token] and return [newToken].
Token insertToken(Token token, Token newToken) {
newToken.setNext(token.next);
// A no-op rewriter could skip this step.
token.setNext(newToken);
return newToken;
}
/// Move [endGroup] (a synthetic `)`, `]`, or `}` token) and associated
/// error token after [token] in the token stream and return [endGroup].
Token moveSynthetic(Token token, Token endGroup) {
assert(endGroup.beforeSynthetic != null);
Token errorToken;
if (endGroup.next is UnmatchedToken) {
errorToken = endGroup.next;
}
// Remove endGroup from its current location
endGroup.beforeSynthetic.setNext((errorToken ?? endGroup).next);
// Insert endGroup into its new location
Token next = token.next;
token.setNext(endGroup);
(errorToken ?? endGroup).setNext(next);
endGroup.offset = next.offset;
if (errorToken != null) {
errorToken.offset = next.offset;
}
return endGroup;
}
/// Replace the single token immediately following the [previousToken] with
/// the chain of tokens starting at the [replacementToken]. Return the
/// [replacementToken].
Token replaceTokenFollowing(Token previousToken, Token replacementToken) {
Token replacedToken = previousToken.next;
previousToken.setNext(replacementToken);
(replacementToken as SimpleToken).precedingComments =
replacedToken.precedingComments;
_lastTokenInChain(replacementToken).setNext(replacedToken.next);
return replacementToken;
}
/// Given the [firstToken] in a chain of tokens to be inserted, return the
/// last token in the chain.
///
/// As a side-effect, this method also ensures that the tokens in the chain
/// have their `previous` pointers set correctly.
Token _lastTokenInChain(Token firstToken) {
Token previous;
Token current = firstToken;
while (current.next != null && current.next.type != TokenType.EOF) {
if (previous != null) {
current.previous = previous;
}
previous = current;
current = current.next;
}
if (previous != null) {
current.previous = previous;
}
return current;
}
}
/// Provides the capability of adding tokens that lead into a token stream
/// without modifying the original token stream and not setting the any token's
/// `previous` field.
class TokenStreamGhostWriter
with _TokenStreamMixin
implements TokenStreamRewriter {
@override
Token insertParens(Token token, bool includeIdentifier) {
Token next = token.next;
int offset = next.charOffset;
BeginToken leftParen =
next = new SyntheticBeginToken(TokenType.OPEN_PAREN, offset);
if (includeIdentifier) {
Token identifier =
new SyntheticStringToken(TokenType.IDENTIFIER, '', offset, 0);
next.next = identifier;
next = identifier;
}
Token rightParen = new SyntheticToken(TokenType.CLOSE_PAREN, offset);
next.next = rightParen;
rightParen.next = token.next;
return leftParen;
}
@override
Token insertToken(Token token, Token newToken) {
newToken.next = token.next;
return newToken;
}
@override
Token moveSynthetic(Token token, Token endGroup) {
Token newEndGroup =
new SyntheticToken(endGroup.type, token.next.charOffset);
newEndGroup.next = token.next;
return newEndGroup;
}
@override
Token replaceTokenFollowing(Token previousToken, Token replacementToken) {
Token replacedToken = previousToken.next;
(replacementToken as SimpleToken).precedingComments =
replacedToken.precedingComments;
_lastTokenInChain(replacementToken).next = replacedToken.next;
return replacementToken;
}
/// Given the [firstToken] in a chain of tokens to be inserted, return the
/// last token in the chain.
Token _lastTokenInChain(Token firstToken) {
Token current = firstToken;
while (current.next != null && current.next.type != TokenType.EOF) {
current = current.next;
}
return current;
}
}
mixin _TokenStreamMixin {
/// Insert a synthetic identifier after [token] and return the new identifier.
Token insertSyntheticIdentifier(Token token, [String value]) {
return insertToken(
token,
new SyntheticStringToken(
TokenType.IDENTIFIER, value ?? '', token.next.charOffset, 0));
}
/// Insert a new synthetic [keyword] after [token] and return the new token.
Token insertSyntheticKeyword(Token token, Keyword keyword) => insertToken(
token, new SyntheticKeywordToken(keyword, token.next.charOffset));
/// Insert a new simple synthetic token of [newTokenType] after [token]
/// and return the new token.
Token insertSyntheticToken(Token token, TokenType newTokenType) {
assert(newTokenType is! Keyword, 'use insertSyntheticKeyword instead');
return insertToken(
token, new SyntheticToken(newTokenType, token.next.charOffset));
}
/// Insert [newToken] after [token] and return [newToken].
Token insertToken(Token token, Token newToken);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/parser/loop_state.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 fasta.parser.loop_state;
enum LoopState {
OutsideLoop,
InsideSwitch, // `break` statement allowed
InsideLoop, // `break` and `continue` statements allowed
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/parser/directive_context.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 '../fasta_codes.dart';
import 'parser.dart';
import '../../scanner/token.dart';
class DirectiveContext {
DirectiveState state = DirectiveState.Unknown;
void checkScriptTag(Parser parser, Token token) {
if (state == DirectiveState.Unknown) {
state = DirectiveState.Script;
return;
}
// The scanner only produces the SCRIPT_TAG
// when it is the first token in the file.
throw "Internal error: Unexpected script tag.";
}
void checkDeclaration() {
if (state != DirectiveState.PartOf) {
state = DirectiveState.Declarations;
}
}
void checkExport(Parser parser, Token token) {
if (state.index <= DirectiveState.ImportAndExport.index) {
state = DirectiveState.ImportAndExport;
return;
}
// Recovery
if (state == DirectiveState.Part) {
parser.reportRecoverableError(token, messageExportAfterPart);
} else if (state == DirectiveState.PartOf) {
parser.reportRecoverableError(token, messageNonPartOfDirectiveInPart);
} else {
parser.reportRecoverableError(token, messageDirectiveAfterDeclaration);
}
}
void checkImport(Parser parser, Token token) {
if (state.index <= DirectiveState.ImportAndExport.index) {
state = DirectiveState.ImportAndExport;
return;
}
// Recovery
if (state == DirectiveState.Part) {
parser.reportRecoverableError(token, messageImportAfterPart);
} else if (state == DirectiveState.PartOf) {
parser.reportRecoverableError(token, messageNonPartOfDirectiveInPart);
} else {
parser.reportRecoverableError(token, messageDirectiveAfterDeclaration);
}
}
void checkLibrary(Parser parser, Token token) {
if (state.index < DirectiveState.Library.index) {
state = DirectiveState.Library;
return;
}
// Recovery
if (state == DirectiveState.Library) {
parser.reportRecoverableError(token, messageMultipleLibraryDirectives);
} else if (state == DirectiveState.PartOf) {
parser.reportRecoverableError(token, messageNonPartOfDirectiveInPart);
} else {
parser.reportRecoverableError(token, messageLibraryDirectiveNotFirst);
}
}
void checkPart(Parser parser, Token token) {
if (state.index <= DirectiveState.Part.index) {
state = DirectiveState.Part;
return;
}
// Recovery
if (state == DirectiveState.PartOf) {
parser.reportRecoverableError(token, messageNonPartOfDirectiveInPart);
} else {
parser.reportRecoverableError(token, messageDirectiveAfterDeclaration);
}
}
void checkPartOf(Parser parser, Token token) {
if (state == DirectiveState.Unknown) {
state = DirectiveState.PartOf;
return;
}
// Recovery
if (state == DirectiveState.PartOf) {
parser.reportRecoverableError(token, messagePartOfTwice);
} else {
parser.reportRecoverableError(token, messageNonPartOfDirectiveInPart);
}
}
}
enum DirectiveState {
Unknown,
Script,
Library,
ImportAndExport,
Part,
PartOf,
Declarations,
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_class_builder.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 fasta.dill_class_builder;
import 'package:kernel/ast.dart'
show Class, DartType, Member, Supertype, TypeParameter;
import '../builder/class_builder.dart';
import '../problems.dart' show unimplemented;
import '../kernel/kernel_builder.dart'
show TypeBuilder, LibraryBuilder, MemberBuilder, Scope, TypeVariableBuilder;
import '../modifier.dart' show abstractMask, namedMixinApplicationMask;
import 'dill_library_builder.dart' show DillLibraryBuilder;
import 'dill_member_builder.dart' show DillMemberBuilder;
class DillClassBuilder extends ClassBuilderImpl {
final Class cls;
DillClassBuilder(Class cls, DillLibraryBuilder parent)
: cls = cls,
super(
null,
computeModifiers(cls),
cls.name,
null,
null,
null,
null,
new Scope(
local: <String, MemberBuilder>{},
setters: <String, MemberBuilder>{},
parent: parent.scope,
debugName: "class ${cls.name}",
isModifiable: false),
new Scope(
local: <String, MemberBuilder>{},
debugName: cls.name,
isModifiable: false),
parent,
cls.fileOffset);
List<TypeVariableBuilder> get typeVariables {
List<TypeVariableBuilder> typeVariables = super.typeVariables;
if (typeVariables == null && cls.typeParameters.isNotEmpty) {
typeVariables = super.typeVariables =
computeTypeVariableBuilders(library, cls.typeParameters);
}
return typeVariables;
}
Uri get fileUri => cls.fileUri;
TypeBuilder get supertype {
TypeBuilder supertype = super.supertype;
if (supertype == null) {
Supertype targetSupertype = cls.supertype;
if (targetSupertype == null) return null;
super.supertype =
supertype = computeTypeBuilder(library, targetSupertype);
}
return supertype;
}
@override
Class get actualCls => cls;
void addMember(Member member) {
DillMemberBuilder builder = new DillMemberBuilder(member, this);
String name = member.name.name;
if (builder.isConstructor || builder.isFactory) {
constructorScopeBuilder.addMember(name, builder);
} else if (builder.isSetter) {
scopeBuilder.addSetter(name, builder);
} else {
scopeBuilder.addMember(name, builder);
}
}
@override
int get typeVariablesCount => cls.typeParameters.length;
@override
List<DartType> buildTypeArguments(
LibraryBuilder library, List<TypeBuilder> arguments) {
// For performance reasons, [typeVariables] aren't restored from [target].
// So, if [arguments] is null, the default types should be retrieved from
// [cls.typeParameters].
if (arguments == null) {
List<DartType> result = new List<DartType>.filled(
cls.typeParameters.length, null,
growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = cls.typeParameters[i].defaultType;
}
return result;
}
// [arguments] != null
List<DartType> result =
new List<DartType>.filled(arguments.length, null, growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = arguments[i].build(library);
}
return result;
}
/// Returns true if this class is the result of applying a mixin to its
/// superclass.
bool get isMixinApplication => cls.isMixinApplication;
TypeBuilder get mixedInType {
return computeTypeBuilder(library, cls.mixedInType);
}
List<TypeBuilder> get interfaces {
if (cls.implementedTypes.isEmpty) return null;
if (super.interfaces == null) {
List<TypeBuilder> result =
new List<TypeBuilder>(cls.implementedTypes.length);
for (int i = 0; i < result.length; i++) {
result[i] = computeTypeBuilder(library, cls.implementedTypes[i]);
}
super.interfaces = result;
}
return super.interfaces;
}
void set mixedInType(TypeBuilder mixin) {
unimplemented("mixedInType=", -1, null);
}
}
int computeModifiers(Class cls) {
int modifiers = 0;
if (cls.isAbstract) {
modifiers |= abstractMask;
}
if (cls.isMixinApplication && cls.name != null) {
modifiers |= namedMixinApplicationMask;
}
return modifiers;
}
TypeBuilder computeTypeBuilder(
DillLibraryBuilder library, Supertype supertype) {
return supertype == null
? null
: library.loader.computeTypeBuilder(supertype.asInterfaceType);
}
List<TypeVariableBuilder> computeTypeVariableBuilders(
DillLibraryBuilder library, List<TypeParameter> typeParameters) {
if (typeParameters == null || typeParameters.length == 0) return null;
List<TypeVariableBuilder> result =
new List.filled(typeParameters.length, null);
for (int i = 0; i < result.length; i++) {
result[i] = new TypeVariableBuilder.fromKernel(typeParameters[i], library);
}
return result;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_extension_builder.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:core' hide MapEntry;
import 'package:kernel/ast.dart';
import '../builder/extension_builder.dart';
import '../builder/library_builder.dart';
import '../builder/type_builder.dart';
import '../builder/type_variable_builder.dart';
import '../kernel/kernel_builder.dart';
import '../scope.dart';
import 'dill_class_builder.dart';
import 'dill_extension_member_builder.dart';
class DillExtensionBuilder extends ExtensionBuilderImpl {
final Extension extension;
List<TypeVariableBuilder> _typeParameters;
TypeBuilder _onType;
DillExtensionBuilder(this.extension, LibraryBuilder parent)
: super(
null,
0,
extension.name,
parent,
extension.fileOffset,
new Scope(
local: <String, MemberBuilder>{},
setters: <String, MemberBuilder>{},
parent: parent.scope,
debugName: "extension ${extension.name}",
isModifiable: false),
null,
null) {
Map<Name, ExtensionMemberDescriptor> _methods = {};
Map<Name, Member> _tearOffs = {};
for (ExtensionMemberDescriptor descriptor in extension.members) {
Name name = descriptor.name;
switch (descriptor.kind) {
case ExtensionMemberKind.Method:
_methods[name] = descriptor;
break;
case ExtensionMemberKind.TearOff:
_tearOffs[name] = descriptor.member.asMember;
break;
case ExtensionMemberKind.Getter:
case ExtensionMemberKind.Operator:
case ExtensionMemberKind.Field:
Member member = descriptor.member.asMember;
scopeBuilder.addMember(name.name,
new DillExtensionMemberBuilder(member, descriptor, this));
break;
case ExtensionMemberKind.Setter:
Member member = descriptor.member.asMember;
scopeBuilder.addSetter(name.name,
new DillExtensionMemberBuilder(member, descriptor, this));
break;
}
}
_methods.forEach((Name name, ExtensionMemberDescriptor descriptor) {
Member member = descriptor.member.asMember;
scopeBuilder.addMember(
name.name,
new DillExtensionMemberBuilder(
member, descriptor, this, _tearOffs[name]));
});
}
@override
List<TypeVariableBuilder> get typeParameters {
if (_typeParameters == null && extension.typeParameters.isNotEmpty) {
_typeParameters =
computeTypeVariableBuilders(library, extension.typeParameters);
}
return _typeParameters;
}
@override
TypeBuilder get onType {
if (_onType == null) {
_onType = library.loader.computeTypeBuilder(extension.onType);
}
return _onType;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_type_alias_builder.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 fasta.dill_typedef_builder;
import 'package:kernel/ast.dart' show DartType, Typedef;
import '../kernel/kernel_builder.dart'
show
TypeAliasBuilder,
FunctionTypeBuilder,
TypeBuilder,
LibraryBuilder,
MetadataBuilder;
import '../problems.dart' show unimplemented;
import 'dill_library_builder.dart' show DillLibraryBuilder;
class DillTypeAliasBuilder extends TypeAliasBuilder {
DillTypeAliasBuilder(Typedef typedef, DillLibraryBuilder parent)
: super(null, typedef.name, null, null, parent, typedef.fileOffset,
typedef);
List<MetadataBuilder> get metadata {
return unimplemented("metadata", -1, null);
}
@override
int get typeVariablesCount => typedef.typeParameters.length;
@override
FunctionTypeBuilder get type {
return unimplemented("type", -1, null);
}
@override
DartType buildThisType(LibraryBuilder library) {
return thisType ??= typedef.type;
}
@override
List<DartType> buildTypeArguments(
LibraryBuilder library, List<TypeBuilder> arguments) {
// For performance reasons, [typeVariables] aren't restored from [target].
// So, if [arguments] is null, the default types should be retrieved from
// [cls.typeParameters].
if (arguments == null) {
List<DartType> result = new List<DartType>.filled(
typedef.typeParameters.length, null,
growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = typedef.typeParameters[i].defaultType;
}
return result;
}
// [arguments] != null
List<DartType> result =
new List<DartType>.filled(arguments.length, null, growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = arguments[i].build(library);
}
return result;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_extension_member_builder.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:core' hide MapEntry;
import 'package:kernel/ast.dart';
import '../builder/declaration.dart';
import '../problems.dart';
import 'dill_member_builder.dart';
class DillExtensionMemberBuilder extends DillMemberBuilder {
final ExtensionMemberDescriptor _descriptor;
@override
final Member extensionTearOff;
DillExtensionMemberBuilder(Member member, this._descriptor, Builder parent,
[this.extensionTearOff])
: super(member, parent);
@override
bool get isStatic => _descriptor.isStatic;
@override
bool get isExternal => member.isExternal;
@override
Procedure get procedure {
switch (_descriptor.kind) {
case ExtensionMemberKind.Method:
case ExtensionMemberKind.Getter:
case ExtensionMemberKind.Operator:
case ExtensionMemberKind.Setter:
return member;
case ExtensionMemberKind.TearOff:
case ExtensionMemberKind.Field:
}
return unsupported("procedure", charOffset, fileUri);
}
@override
ProcedureKind get kind {
switch (_descriptor.kind) {
case ExtensionMemberKind.Method:
return ProcedureKind.Method;
case ExtensionMemberKind.Getter:
return ProcedureKind.Getter;
case ExtensionMemberKind.Operator:
return ProcedureKind.Operator;
case ExtensionMemberKind.Setter:
return ProcedureKind.Setter;
case ExtensionMemberKind.TearOff:
case ExtensionMemberKind.Field:
}
return null;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_loader.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 fasta.dill_loader;
import 'dart:async' show Future;
import 'package:kernel/ast.dart' show Class, Component, DartType, Library;
import '../fasta_codes.dart'
show SummaryTemplate, Template, templateDillOutlineSummary;
import '../kernel/kernel_builder.dart'
show ClassBuilder, TypeBuilder, LibraryBuilder;
import '../kernel/type_builder_computer.dart' show TypeBuilderComputer;
import '../loader.dart' show Loader;
import '../problems.dart' show unhandled;
import '../target_implementation.dart' show TargetImplementation;
import 'dill_library_builder.dart' show DillLibraryBuilder;
import 'dill_target.dart' show DillTarget;
class DillLoader extends Loader {
DillLoader(TargetImplementation target) : super(target);
Template<SummaryTemplate> get outlineSummaryTemplate =>
templateDillOutlineSummary;
/// Append compiled libraries from the given [component]. If the [filter] is
/// provided, append only libraries whose [Uri] is accepted by the [filter].
List<DillLibraryBuilder> appendLibraries(Component component,
{bool filter(Uri uri), int byteCount: 0}) {
List<Library> componentLibraries = component.libraries;
List<Uri> requestedLibraries = <Uri>[];
DillTarget target = this.target;
for (int i = 0; i < componentLibraries.length; i++) {
Library library = componentLibraries[i];
Uri uri = library.importUri;
if (filter == null || filter(library.importUri)) {
libraries.add(library);
target.addLibrary(library);
requestedLibraries.add(uri);
}
}
List<DillLibraryBuilder> result = <DillLibraryBuilder>[];
for (int i = 0; i < requestedLibraries.length; i++) {
result.add(read(requestedLibraries[i], -1));
}
target.uriToSource.addAll(component.uriToSource);
this.byteCount += byteCount;
return result;
}
Future<Null> buildOutline(DillLibraryBuilder builder) async {
if (builder.library == null) {
unhandled("null", "builder.library", 0, builder.fileUri);
}
builder.markAsReadyToBuild();
}
Future<Null> buildBody(DillLibraryBuilder builder) {
return buildOutline(builder);
}
void finalizeExports() {
builders.forEach((Uri uri, LibraryBuilder builder) {
DillLibraryBuilder library = builder;
library.markAsReadyToFinalizeExports();
});
}
@override
ClassBuilder computeClassBuilderFromTargetClass(Class cls) {
Library kernelLibrary = cls.enclosingLibrary;
LibraryBuilder library = builders[kernelLibrary.importUri];
return library.lookupLocalMember(cls.name, required: true);
}
@override
TypeBuilder computeTypeBuilder(DartType type) {
return type.accept(new TypeBuilderComputer(this));
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_library_builder.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 fasta.dill_library_builder;
import 'dart:convert' show jsonDecode;
import 'package:kernel/ast.dart'
show
Class,
DartType,
DynamicType,
Extension,
Field,
FunctionType,
Library,
ListLiteral,
Member,
NamedNode,
Procedure,
Reference,
StaticGet,
StringLiteral,
Typedef;
import '../fasta_codes.dart'
show
Message,
noLength,
templateDuplicatedDeclaration,
templateTypeNotFound,
templateUnspecified;
import '../problems.dart' show internalProblem, unhandled, unimplemented;
import '../builder/class_builder.dart';
import '../builder/library_builder.dart';
import '../builder/member_builder.dart';
import '../builder/type_alias_builder.dart';
import '../kernel/kernel_builder.dart'
show Builder, DynamicTypeBuilder, InvalidTypeBuilder, Scope;
import '../kernel/redirecting_factory_body.dart' show RedirectingFactoryBody;
import 'dill_class_builder.dart' show DillClassBuilder;
import 'dill_extension_builder.dart';
import 'dill_member_builder.dart' show DillMemberBuilder;
import 'dill_loader.dart' show DillLoader;
import 'dill_type_alias_builder.dart' show DillTypeAliasBuilder;
class LazyLibraryScope extends Scope {
DillLibraryBuilder libraryBuilder;
LazyLibraryScope(Map<String, Builder> local, Map<String, Builder> setters,
Scope parent, String debugName, {bool isModifiable: true})
: super(
local: local,
setters: setters,
parent: parent,
debugName: debugName,
isModifiable: isModifiable);
LazyLibraryScope.top({bool isModifiable: false})
: this(<String, Builder>{}, <String, Builder>{}, null, "top",
isModifiable: isModifiable);
Map<String, Builder> get local {
if (libraryBuilder == null) throw new StateError("No library builder.");
libraryBuilder.ensureLoaded();
return super.local;
}
Map<String, Builder> get setters {
if (libraryBuilder == null) throw new StateError("No library builder.");
libraryBuilder.ensureLoaded();
return super.setters;
}
}
class DillLibraryBuilder extends LibraryBuilderImpl {
@override
final Library library;
DillLoader loader;
/// Exports that can't be serialized.
///
/// The elements of this map are documented in
/// [../kernel/kernel_library_builder.dart].
Map<String, String> unserializableExports;
// TODO(jensj): These 4 booleans could potentially be merged into a single
// state field.
bool isReadyToBuild = false;
bool isReadyToFinalizeExports = false;
bool isBuilt = false;
bool isBuiltAndMarked = false;
DillLibraryBuilder(this.library, this.loader)
: super(library.fileUri, new LazyLibraryScope.top(),
new LazyLibraryScope.top()) {
LazyLibraryScope lazyScope = scope;
lazyScope.libraryBuilder = this;
LazyLibraryScope lazyExportScope = exportScope;
lazyExportScope.libraryBuilder = this;
}
void ensureLoaded() {
if (!isReadyToBuild) throw new StateError("Not ready to build.");
if (isBuilt && !isBuiltAndMarked) {
isBuiltAndMarked = true;
finalizeExports();
return;
}
isBuiltAndMarked = true;
if (isBuilt) return;
isBuilt = true;
library.classes.forEach(addClass);
library.extensions.forEach(addExtension);
library.procedures.forEach(addMember);
library.typedefs.forEach(addTypedef);
library.fields.forEach(addMember);
if (isReadyToFinalizeExports) {
finalizeExports();
} else {
throw new StateError("Not ready to finalize exports.");
}
}
@override
bool get isSynthetic => library.isSynthetic;
@override
void setLanguageVersion(int major, int minor,
{int offset: 0, int length, bool explicit}) {}
Uri get uri => library.importUri;
Uri get fileUri => library.fileUri;
@override
String get name => library.name;
void addSyntheticDeclarationOfDynamic() {
addBuilder(
"dynamic", new DynamicTypeBuilder(const DynamicType(), this, -1), -1);
}
void addClass(Class cls) {
DillClassBuilder classBulder = new DillClassBuilder(cls, this);
addBuilder(cls.name, classBulder, cls.fileOffset);
cls.procedures.forEach(classBulder.addMember);
cls.constructors.forEach(classBulder.addMember);
for (Field field in cls.fields) {
if (field.name.name == "_redirecting#") {
ListLiteral initializer = field.initializer;
for (StaticGet get in initializer.expressions) {
RedirectingFactoryBody.restoreFromDill(get.target);
}
} else {
classBulder.addMember(field);
}
}
}
void addExtension(Extension extension) {
DillExtensionBuilder extensionBuilder =
new DillExtensionBuilder(extension, this);
addBuilder(extension.name, extensionBuilder, extension.fileOffset);
}
void addMember(Member member) {
String name = member.name.name;
if (name == "_exports#") {
Field field = member;
StringLiteral string = field.initializer;
Map<dynamic, dynamic> json = jsonDecode(string.value);
unserializableExports =
json != null ? new Map<String, String>.from(json) : null;
} else {
addBuilder(name, new DillMemberBuilder(member, this), member.fileOffset);
}
}
@override
Builder addBuilder(String name, Builder declaration, int charOffset) {
if (name == null || name.isEmpty) return null;
bool isSetter = declaration.isSetter;
if (isSetter) {
scopeBuilder.addSetter(name, declaration);
} else {
scopeBuilder.addMember(name, declaration);
}
if (!name.startsWith("_")) {
if (isSetter) {
exportScopeBuilder.addSetter(name, declaration);
} else {
exportScopeBuilder.addMember(name, declaration);
}
}
return declaration;
}
void addTypedef(Typedef typedef) {
DartType type = typedef.type;
if (type is FunctionType && type.typedefType == null) {
unhandled("null", "addTypedef", typedef.fileOffset, typedef.fileUri);
}
addBuilder(typedef.name, new DillTypeAliasBuilder(typedef, this),
typedef.fileOffset);
}
@override
void addToScope(String name, Builder member, int charOffset, bool isImport) {
unimplemented("addToScope", charOffset, fileUri);
}
@override
Builder computeAmbiguousDeclaration(
String name, Builder builder, Builder other, int charOffset,
{bool isExport: false, bool isImport: false}) {
if (builder == other) return builder;
if (builder is InvalidTypeBuilder) return builder;
if (other is InvalidTypeBuilder) return other;
// For each entry mapping key `k` to declaration `d` in `NS` an entry
// mapping `k` to `d` is added to the exported namespace of `L` unless a
// top-level declaration with the name `k` exists in `L`.
if (builder.parent == this) return builder;
Message message = templateDuplicatedDeclaration.withArguments(name);
addProblem(message, charOffset, name.length, fileUri);
return new InvalidTypeBuilder(
name, message.withLocation(fileUri, charOffset, name.length));
}
@override
String get fullNameForErrors {
return library.name ?? "<library '${library.fileUri}'>";
}
void markAsReadyToBuild() {
isReadyToBuild = true;
}
void markAsReadyToFinalizeExports() {
isReadyToFinalizeExports = true;
}
void finalizeExports() {
unserializableExports?.forEach((String name, String messageText) {
Builder declaration;
switch (name) {
case "dynamic":
case "void":
// TODO(ahe): It's likely that we shouldn't be exporting these types
// from dart:core, and this case can be removed.
declaration = loader.coreLibrary.exportScopeBuilder[name];
break;
default:
Message message = messageText == null
? templateTypeNotFound.withArguments(name)
: templateUnspecified.withArguments(messageText);
addProblem(message, -1, noLength, null);
declaration = new InvalidTypeBuilder(name, message.withoutLocation());
}
exportScopeBuilder.addMember(name, declaration);
});
for (Reference reference in library.additionalExports) {
NamedNode node = reference.node;
Uri libraryUri;
String name;
bool isSetter = false;
if (node is Class) {
libraryUri = node.enclosingLibrary.importUri;
name = node.name;
} else if (node is Procedure) {
libraryUri = node.enclosingLibrary.importUri;
name = node.name.name;
isSetter = node.isSetter;
} else if (node is Member) {
libraryUri = node.enclosingLibrary.importUri;
name = node.name.name;
} else if (node is Typedef) {
libraryUri = node.enclosingLibrary.importUri;
name = node.name;
} else {
unhandled("${node.runtimeType}", "finalizeExports", -1, fileUri);
}
DillLibraryBuilder library = loader.builders[libraryUri];
if (library == null) {
internalProblem(
templateUnspecified.withArguments("No builder for '$libraryUri'."),
-1,
fileUri);
}
Builder declaration;
if (isSetter) {
declaration = library.exportScope.setters[name];
exportScopeBuilder.addSetter(name, declaration);
} else {
declaration = library.exportScope.local[name];
exportScopeBuilder.addMember(name, declaration);
}
if (declaration == null) {
internalProblem(
templateUnspecified.withArguments(
"Exported element '$name' not found in '$libraryUri'."),
-1,
fileUri);
}
assert((declaration is ClassBuilder && node == declaration.cls) ||
(declaration is TypeAliasBuilder && node == declaration.typedef) ||
(declaration is MemberBuilder && node == declaration.member));
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_member_builder.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 fasta.dill_member_builder;
import 'package:kernel/ast.dart'
show Constructor, Field, Member, Procedure, ProcedureKind;
import '../builder/member_builder.dart';
import '../kernel/kernel_builder.dart'
show Builder, isRedirectingGenerativeConstructorImplementation;
import '../modifier.dart'
show abstractMask, constMask, externalMask, finalMask, lateMask, staticMask;
import '../problems.dart' show unhandled;
class DillMemberBuilder extends MemberBuilderImpl {
final int modifiers;
final Member member;
DillMemberBuilder(Member member, Builder parent)
: modifiers = computeModifiers(member),
member = member,
super(parent, member.fileOffset);
String get debugName => "DillMemberBuilder";
String get name => member.name.name;
bool get isConstructor => member is Constructor;
ProcedureKind get kind {
final Member member = this.member;
return member is Procedure ? member.kind : null;
}
bool get isRegularMethod => identical(ProcedureKind.Method, kind);
bool get isGetter => identical(ProcedureKind.Getter, kind);
bool get isSetter => identical(ProcedureKind.Setter, kind);
bool get isOperator => identical(ProcedureKind.Operator, kind);
bool get isFactory => identical(ProcedureKind.Factory, kind);
bool get isRedirectingGenerativeConstructor {
return isConstructor &&
isRedirectingGenerativeConstructorImplementation(member);
}
bool get isSynthetic {
final Member member = this.member;
return member is Constructor && member.isSynthetic;
}
bool get isField => member is Field;
}
int computeModifiers(Member member) {
int modifier = member.isAbstract ? abstractMask : 0;
modifier |= member.isExternal ? externalMask : 0;
if (member is Field) {
modifier |= member.isConst ? constMask : 0;
modifier |= member.isFinal ? finalMask : 0;
modifier |= member.isLate ? lateMask : 0;
modifier |= member.isStatic ? staticMask : 0;
} else if (member is Procedure) {
modifier |= member.isConst ? constMask : 0;
modifier |= member.isStatic ? staticMask : 0;
} else if (member is Constructor) {
modifier |= member.isConst ? constMask : 0;
} else {
dynamic parent = member.parent;
unhandled("${member.runtimeType}", "computeModifiers", member.fileOffset,
Uri.base.resolve(parent.fileUri));
}
return modifier;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/dill/dill_target.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 fasta.dill_target;
import 'dart:async' show Future;
import 'package:kernel/ast.dart' show Library;
import 'package:kernel/target/targets.dart' show Target;
import '../kernel/kernel_builder.dart' show ClassBuilder;
import '../problems.dart' show unsupported;
import '../target_implementation.dart' show TargetImplementation;
import '../ticker.dart' show Ticker;
import '../uri_translator.dart' show UriTranslator;
import 'dill_library_builder.dart' show DillLibraryBuilder;
import 'dill_loader.dart' show DillLoader;
class DillTarget extends TargetImplementation {
final Map<Uri, DillLibraryBuilder> libraryBuilders =
<Uri, DillLibraryBuilder>{};
bool isLoaded = false;
DillLoader loader;
DillTarget(Ticker ticker, UriTranslator uriTranslator, Target backendTarget)
: super(ticker, uriTranslator, backendTarget) {
loader = new DillLoader(this);
}
@override
void addSourceInformation(
Uri importUri, Uri fileUri, List<int> lineStarts, List<int> sourceCode) {
unsupported("addSourceInformation", -1, null);
}
@override
Future<Null> buildComponent() {
return new Future<Null>.sync(() => unsupported("buildComponent", -1, null));
}
@override
Future<Null> buildOutlines() async {
if (loader.libraries.isNotEmpty) {
await loader.buildOutlines();
loader.finalizeExports();
}
isLoaded = true;
}
@override
DillLibraryBuilder createLibraryBuilder(Uri uri, Uri fileUri, origin) {
assert(origin == null);
DillLibraryBuilder libraryBuilder = libraryBuilders.remove(uri);
assert(libraryBuilder != null, "No library found for $uri.");
return libraryBuilder;
}
@override
void breakCycle(ClassBuilder cls) {}
void addLibrary(Library library) {
libraryBuilders[library.importUri] =
new DillLibraryBuilder(library, loader);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/metadata_builder.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 fasta.metadata_builder;
import 'package:kernel/ast.dart' show Annotatable, Class, Library;
import '../kernel/body_builder.dart' show BodyBuilder;
import '../kernel/kernel_builder.dart' show ClassBuilder, MemberBuilder;
import '../scanner.dart' show Token;
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
import '../scope.dart' show Scope;
class MetadataBuilder {
final Token beginToken;
int get charOffset => beginToken.charOffset;
MetadataBuilder(this.beginToken);
static void buildAnnotations(
Annotatable parent,
List<MetadataBuilder> metadata,
SourceLibraryBuilder library,
ClassBuilder classBuilder,
MemberBuilder member) {
if (metadata == null) return;
Uri fileUri = member?.fileUri ?? classBuilder?.fileUri ?? library.fileUri;
Scope scope = parent is Library || parent is Class || classBuilder == null
? library.scope
: classBuilder.scope;
BodyBuilder bodyBuilder = library.loader
.createBodyBuilderForOutlineExpression(
library, classBuilder, member, scope, fileUri);
for (int i = 0; i < metadata.length; ++i) {
MetadataBuilder annotationBuilder = metadata[i];
parent.addAnnotation(
bodyBuilder.parseAnnotation(annotationBuilder.beginToken));
}
bodyBuilder.inferAnnotations(parent.annotations);
bodyBuilder.resolveRedirectingFactoryTargets();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/name_iterator.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 fasta.name_iterator;
import 'builder.dart' show Builder;
abstract class NameIterator implements Iterator<Builder> {
String get name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/void_type_builder.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 fasta.void_type_builder;
import 'package:kernel/ast.dart' show DartType;
import 'builder.dart' show BuiltinTypeBuilder, LibraryBuilder;
class VoidTypeBuilder extends BuiltinTypeBuilder {
VoidTypeBuilder(DartType type, LibraryBuilder compilationUnit, int charOffset)
: super("void", type, compilationUnit, charOffset);
String get debugName => "VoidTypeBuilder";
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/dynamic_type_builder.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 fasta.dynamic_type_builder;
import 'package:kernel/ast.dart' show DartType;
import 'builder.dart' show LibraryBuilder, BuiltinTypeBuilder;
class DynamicTypeBuilder extends BuiltinTypeBuilder {
DynamicTypeBuilder(
DartType type, LibraryBuilder compilationUnit, int charOffset)
: super("dynamic", type, compilationUnit, charOffset);
String get debugName => "DynamicTypeBuilder";
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/mixin_application_builder.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 fasta.mixin_application_builder;
import 'builder.dart'
show LibraryBuilder, NullabilityBuilder, TypeBuilder, TypeVariableBuilder;
import 'package:kernel/ast.dart' show InterfaceType, Supertype;
import '../fasta_codes.dart' show LocatedMessage;
import '../problems.dart' show unsupported;
class MixinApplicationBuilder extends TypeBuilder {
final TypeBuilder supertype;
final List<TypeBuilder> mixins;
Supertype builtType;
List<TypeVariableBuilder> typeVariables;
MixinApplicationBuilder(this.supertype, this.mixins);
String get name => null;
NullabilityBuilder get nullabilityBuilder {
return unsupported("nullabilityBuilder", -1, null);
}
String get debugName => "MixinApplicationBuilder";
StringBuffer printOn(StringBuffer buffer) {
buffer.write(supertype);
buffer.write(" with ");
bool first = true;
for (TypeBuilder t in mixins) {
if (!first) buffer.write(", ");
first = false;
t.printOn(buffer);
}
return buffer;
}
@override
InterfaceType build(LibraryBuilder library) {
int charOffset = -1; // TODO(ahe): Provide these.
Uri fileUri = null; // TODO(ahe): Provide these.
return unsupported("build", charOffset, fileUri);
}
@override
Supertype buildSupertype(
LibraryBuilder library, int charOffset, Uri fileUri) {
return unsupported("buildSupertype", charOffset, fileUri);
}
@override
Supertype buildMixedInType(
LibraryBuilder library, int charOffset, Uri fileUri) {
return unsupported("buildMixedInType", charOffset, fileUri);
}
@override
buildInvalidType(LocatedMessage message, {List<LocatedMessage> context}) {
return unsupported("buildInvalidType", message.charOffset, message.uri);
}
@override
MixinApplicationBuilder withNullabilityBuilder(
NullabilityBuilder nullabilityBuilder) {
return unsupported("withNullabilityBuilder", -1, null);
}
MixinApplicationBuilder clone(List<TypeBuilder> newTypes) {
int charOffset = -1; // TODO(dmitryas): Provide these.
Uri fileUri = null; // TODO(dmitryas): Provide these.
return unsupported("clone", charOffset, fileUri);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/modifier_builder.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 fasta.modifier_builder;
import '../modifier.dart'
show
abstractMask,
constMask,
covariantMask,
externalMask,
finalMask,
hasConstConstructorMask,
hasInitializerMask,
initializingFormalMask,
lateMask,
mixinDeclarationMask,
namedMixinApplicationMask,
staticMask;
import 'declaration.dart';
abstract class ModifierBuilder implements Builder {
int get modifiers;
bool get isAbstract;
bool get isCovariant;
bool get isExternal;
bool get isLate;
// TODO(johnniwinther): Add this when semantics for
// `FormalParameterBuilder.isRequired` has been updated to support required
// named parameters.
//bool get isRequired;
bool get hasInitializer;
bool get isInitializingFormal;
bool get hasConstConstructor;
bool get isMixin;
String get name;
bool get isNative;
String get debugName;
StringBuffer printOn(StringBuffer buffer);
}
abstract class ModifierBuilderImpl extends BuilderImpl
implements ModifierBuilder {
@override
Builder parent;
@override
final int charOffset;
@override
final Uri fileUri;
ModifierBuilderImpl(this.parent, this.charOffset, [Uri fileUri])
: fileUri = fileUri ?? parent?.fileUri;
@override
bool get isAbstract => (modifiers & abstractMask) != 0;
@override
bool get isConst => (modifiers & constMask) != 0;
@override
bool get isCovariant => (modifiers & covariantMask) != 0;
@override
bool get isExternal => (modifiers & externalMask) != 0;
@override
bool get isFinal => (modifiers & finalMask) != 0;
@override
bool get isStatic => (modifiers & staticMask) != 0;
@override
bool get isLate => (modifiers & lateMask) != 0;
// TODO(johnniwinther): Add this when semantics for
// `FormalParameterBuilder.isRequired` has been updated to support required
// named parameters.
//bool get isRequired => (modifiers & requiredMask) != 0;
@override
bool get isNamedMixinApplication {
return (modifiers & namedMixinApplicationMask) != 0;
}
@override
bool get hasInitializer => (modifiers & hasInitializerMask) != 0;
@override
bool get isInitializingFormal => (modifiers & initializingFormalMask) != 0;
@override
bool get hasConstConstructor => (modifiers & hasConstConstructorMask) != 0;
@override
bool get isMixin => (modifiers & mixinDeclarationMask) != 0;
@override
bool get isNative => false;
@override
StringBuffer printOn(StringBuffer buffer) {
return buffer..write(name ?? fullNameForErrors);
}
@override
String toString() =>
"${isPatch ? 'patch ' : ''}$debugName(${printOn(new StringBuffer())})";
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/formal_parameter_builder.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 fasta.formal_parameter_builder;
import '../parser.dart' show FormalParameterKind;
import '../parser/formal_parameter_kind.dart'
show
isMandatoryFormalParameterKind,
isOptionalNamedFormalParameterKind,
isOptionalPositionalFormalParameterKind;
import 'builder.dart' show LibraryBuilder, MetadataBuilder, TypeBuilder;
import 'modifier_builder.dart';
import 'package:kernel/ast.dart' show VariableDeclaration;
import '../constant_context.dart' show ConstantContext;
import '../modifier.dart' show finalMask, initializingFormalMask, requiredMask;
import '../scanner.dart' show Token;
import '../scope.dart' show Scope;
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
import '../source/source_loader.dart' show SourceLoader;
import '../kernel/body_builder.dart' show BodyBuilder;
import '../kernel/kernel_builder.dart'
show
ClassBuilder,
Builder,
ConstructorBuilder,
FieldBuilder,
LibraryBuilder,
MetadataBuilder,
TypeBuilder;
import '../kernel/kernel_shadow_ast.dart' show VariableDeclarationImpl;
/// A builder for a formal parameter, i.e. a parameter on a method or
/// constructor.
class FormalParameterBuilder extends ModifierBuilderImpl {
/// List of metadata builders for the metadata declared on this parameter.
final List<MetadataBuilder> metadata;
final int modifiers;
final TypeBuilder type;
final String name;
/// The kind of this parameter, i.e. if it's required, positional optional,
/// or named optional.
FormalParameterKind kind = FormalParameterKind.mandatory;
/// The variable declaration created for this formal parameter.
VariableDeclaration variable;
/// The first token of the default value, if any.
///
/// This is stored until outlines have been built through
/// [buildOutlineExpressions].
Token initializerToken;
FormalParameterBuilder(this.metadata, this.modifiers, this.type, this.name,
LibraryBuilder compilationUnit, int charOffset,
[Uri fileUri])
: super(compilationUnit, charOffset, fileUri);
String get debugName => "FormalParameterBuilder";
// TODO(johnniwinther): Cleanup `isRequired` semantics in face of required
// named parameters.
bool get isRequired => isMandatoryFormalParameterKind(kind);
bool get isNamedRequired => (modifiers & requiredMask) != 0;
bool get isPositional {
return isOptionalPositionalFormalParameterKind(kind) ||
isMandatoryFormalParameterKind(kind);
}
bool get isNamed => isOptionalNamedFormalParameterKind(kind);
bool get isOptional => !isRequired;
bool get isLocal => true;
@override
String get fullNameForErrors => name;
VariableDeclaration get target => variable;
VariableDeclaration build(
SourceLibraryBuilder library, int functionNestingLevel) {
if (variable == null) {
variable = new VariableDeclarationImpl(name, functionNestingLevel,
type: type?.build(library),
isFinal: isFinal,
isConst: isConst,
isFieldFormal: isInitializingFormal,
isCovariant: isCovariant,
isRequired: isNamedRequired)
..fileOffset = charOffset;
}
return variable;
}
FormalParameterBuilder clone(List<TypeBuilder> newTypes) {
// TODO(dmitryas): It's not clear how [metadata] is used currently, and
// how it should be cloned. Consider cloning it instead of reusing it.
return new FormalParameterBuilder(metadata, modifiers,
type?.clone(newTypes), name, parent, charOffset, fileUri)
..kind = kind;
}
FormalParameterBuilder forFormalParameterInitializerScope() {
assert(variable != null);
return !isInitializingFormal
? this
: (new FormalParameterBuilder(
metadata,
modifiers | finalMask | initializingFormalMask,
type,
name,
null,
charOffset,
fileUri)
..parent = parent
..variable = variable);
}
void finalizeInitializingFormal() {
Object cls = parent.parent;
if (cls is ClassBuilder) {
Builder fieldBuilder = cls.scope.lookup(name, charOffset, fileUri);
if (fieldBuilder is FieldBuilder) {
variable.type = fieldBuilder.field.type;
}
}
}
/// Builds the default value from this [initializerToken] if this is a
/// formal parameter on a const constructor or instance method.
void buildOutlineExpressions(LibraryBuilder library) {
// For modular compilation we need to include initializers for optional
// and named parameters of const constructors into the outline - to enable
// constant evaluation. Similarly we need to include initializers for
// optional and named parameters of instance methods because these might be
// needed to generated noSuchMethod forwarders.
bool isConstConstructorParameter = false;
if (parent is ConstructorBuilder) {
ConstructorBuilder constructorBuilder = parent;
isConstConstructorParameter = constructorBuilder.constructor.isConst;
}
if ((isConstConstructorParameter || parent.isClassInstanceMember) &&
initializerToken != null) {
final ClassBuilder classBuilder = parent.parent;
Scope scope = classBuilder.scope;
BodyBuilder bodyBuilder = library.loader
.createBodyBuilderForOutlineExpression(
library, classBuilder, this, scope, fileUri);
bodyBuilder.constantContext = ConstantContext.required;
variable.initializer = bodyBuilder.parseFieldInitializer(initializerToken)
..parent = variable;
bodyBuilder.typeInferrer?.inferParameterInitializer(
bodyBuilder, variable.initializer, variable.type);
if (library.loader is SourceLoader) {
SourceLoader loader = library.loader;
loader.transformPostInference(variable,
bodyBuilder.transformSetLiterals, bodyBuilder.transformCollections);
}
bodyBuilder.resolveRedirectingFactoryTargets();
}
initializerToken = null;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/type_variable_builder.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 fasta.type_variable_builder;
import 'builder.dart' show LibraryBuilder, NullabilityBuilder, TypeBuilder;
import 'package:kernel/ast.dart'
show DartType, Nullability, TypeParameter, TypeParameterType;
import '../fasta_codes.dart'
show
templateCycleInTypeVariables,
templateInternalProblemUnfinishedTypeVariable,
templateTypeArgumentsOnTypeVariable;
import '../kernel/kernel_builder.dart'
show ClassBuilder, NamedTypeBuilder, LibraryBuilder, TypeBuilder;
import '../problems.dart' show unsupported;
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
import 'declaration.dart';
import 'type_declaration_builder.dart';
class TypeVariableBuilder extends TypeDeclarationBuilderImpl {
TypeBuilder bound;
TypeBuilder defaultType;
final TypeParameter actualParameter;
TypeVariableBuilder actualOrigin;
final bool isExtensionTypeParameter;
TypeVariableBuilder(
String name, SourceLibraryBuilder compilationUnit, int charOffset,
{this.bound, this.isExtensionTypeParameter: false})
: actualParameter = new TypeParameter(name, null)
..fileOffset = charOffset,
super(null, 0, name, compilationUnit, charOffset);
TypeVariableBuilder.fromKernel(
TypeParameter parameter, LibraryBuilder compilationUnit)
: actualParameter = parameter,
// TODO(johnniwinther): Do we need to support synthesized type
// parameters from kernel?
this.isExtensionTypeParameter = false,
super(null, 0, parameter.name, compilationUnit, parameter.fileOffset);
bool get isTypeVariable => true;
String get debugName => "TypeVariableBuilder";
StringBuffer printOn(StringBuffer buffer) {
buffer.write(name);
if (bound != null) {
buffer.write(" extends ");
bound.printOn(buffer);
}
return buffer;
}
String toString() => "${printOn(new StringBuffer())}";
TypeVariableBuilder get origin => actualOrigin ?? this;
/// The [TypeParameter] built by this builder.
TypeParameter get parameter => origin.actualParameter;
// Deliberately unrelated return type to statically detect more accidental
// uses until Builder.target is fully retired.
UnrelatedTarget get target => unsupported(
"TypeVariableBuilder.target is deprecated. "
"Use TypeVariableBuilder.parameter instead.",
charOffset,
fileUri);
int get variance => parameter.variance;
void set variance(int value) {
parameter.variance = value;
}
DartType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments) {
if (arguments != null) {
int charOffset = -1; // TODO(ahe): Provide these.
Uri fileUri = null; // TODO(ahe): Provide these.
library.addProblem(
templateTypeArgumentsOnTypeVariable.withArguments(name),
charOffset,
name.length,
fileUri);
}
// If the bound is not set yet, the actual value is not important yet as it
// will be set later.
Nullability nullabilityIfOmitted = parameter.bound != null &&
library != null &&
library.isNonNullableByDefault
? TypeParameterType.computeNullabilityFromBound(parameter)
: Nullability.legacy;
DartType type = buildTypesWithBuiltArguments(
library,
nullabilityBuilder.build(library, ifOmitted: nullabilityIfOmitted),
null);
if (parameter.bound == null) {
if (library is SourceLibraryBuilder) {
library.pendingNullabilities.add(type);
} else {
library.addProblem(
templateInternalProblemUnfinishedTypeVariable.withArguments(
name, library?.uri),
parameter.fileOffset,
name.length,
fileUri);
}
}
return type;
}
DartType buildTypesWithBuiltArguments(LibraryBuilder library,
Nullability nullability, List<DartType> arguments) {
// TODO(dmitryas): Use [nullability].
if (arguments != null) {
int charOffset = -1; // TODO(ahe): Provide these.
Uri fileUri = null; // TODO(ahe): Provide these.
library.addProblem(
templateTypeArgumentsOnTypeVariable.withArguments(name),
charOffset,
name.length,
fileUri);
}
return new TypeParameterType(parameter, null, nullability);
}
TypeBuilder asTypeBuilder() {
return new NamedTypeBuilder(name, const NullabilityBuilder.omitted(), null)
..bind(this);
}
void finish(
LibraryBuilder library, ClassBuilder object, TypeBuilder dynamicType) {
if (isPatch) return;
DartType objectType =
object.buildType(library, library.nullableBuilder, null);
parameter.bound ??= bound?.build(library) ?? objectType;
// If defaultType is not set, initialize it to dynamic, unless the bound is
// explicitly specified as Object, in which case defaultType should also be
// Object. This makes sure instantiation of generic function types with an
// explicit Object bound results in Object as the instantiated type.
parameter.defaultType ??= defaultType?.build(library) ??
(bound != null && parameter.bound == objectType
? objectType
: dynamicType.build(library));
}
/// Assigns nullabilities to types in [pendingNullabilities].
///
/// It's a helper function to assign the nullabilities to type-parameter types
/// after the corresponding type parameters have their bounds set or changed.
/// The function takes into account that some of the types in the input list
/// may be bounds to some of the type parameters of other types from the input
/// list.
static void finishNullabilities(LibraryBuilder libraryBuilder,
List<TypeParameterType> pendingNullabilities) {
// The bounds of type parameters may be type-parameter types of other
// parameters from the same declaration. In this case we need to set the
// nullability for them first. To preserve the ordering, we implement a
// depth-first search over the types. We use the fact that a nullability
// of a type parameter type can't ever be 'nullable' if computed from the
// bound. It allows us to use 'nullable' nullability as the marker in the
// DFS implementation.
Nullability marker = Nullability.nullable;
List<TypeParameterType> stack =
new List<TypeParameterType>.filled(pendingNullabilities.length, null);
int stackTop = 0;
for (TypeParameterType type in pendingNullabilities) {
type.typeParameterTypeNullability = null;
}
for (TypeParameterType type in pendingNullabilities) {
if (type.typeParameterTypeNullability != null) {
// Nullability for [type] was already computed on one of the branches
// of the depth-first search. Continue to the next one.
continue;
}
if (type.parameter.bound is TypeParameterType) {
TypeParameterType current = type;
TypeParameterType next = current.parameter.bound;
while (next != null && next.typeParameterTypeNullability == null) {
stack[stackTop++] = current;
current.typeParameterTypeNullability = marker;
current = next;
if (current.parameter.bound is TypeParameterType) {
next = current.parameter.bound;
if (next.typeParameterTypeNullability == marker) {
next.typeParameterTypeNullability = Nullability.neither;
libraryBuilder.addProblem(
templateCycleInTypeVariables.withArguments(
next.parameter.name, current.parameter.name),
next.parameter.fileOffset,
next.parameter.name.length,
next.parameter.location.file);
next = null;
}
} else {
next = null;
}
}
current.typeParameterTypeNullability =
TypeParameterType.computeNullabilityFromBound(current.parameter);
while (stackTop != 0) {
--stackTop;
current = stack[stackTop];
current.typeParameterTypeNullability =
TypeParameterType.computeNullabilityFromBound(current.parameter);
}
} else {
type.typeParameterTypeNullability =
TypeParameterType.computeNullabilityFromBound(type.parameter);
}
}
}
void applyPatch(covariant TypeVariableBuilder patch) {
patch.actualOrigin = this;
}
TypeVariableBuilder clone(List<TypeBuilder> newTypes) {
// TODO(dmitryas): Figure out if using [charOffset] here is a good idea.
// An alternative is to use the offset of the node the cloned type variable
// is declared on.
return new TypeVariableBuilder(name, parent, charOffset,
bound: bound.clone(newTypes));
}
@override
bool operator ==(Object other) {
return other is TypeVariableBuilder && parameter == other.parameter;
}
@override
int get hashCode => parameter.hashCode;
static List<TypeParameter> typeParametersFromBuilders(
List<TypeVariableBuilder> builders) {
if (builders == null) return null;
List<TypeParameter> result =
new List<TypeParameter>.filled(builders.length, null, growable: true);
for (int i = 0; i < builders.length; i++) {
result[i] = builders[i].parameter;
}
return result;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/declaration_builder.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:core' hide MapEntry;
import 'package:kernel/ast.dart';
import '../messages.dart';
import '../scope.dart';
import 'builder.dart';
import 'library_builder.dart';
import 'metadata_builder.dart';
import 'type_declaration_builder.dart';
abstract class DeclarationBuilder implements TypeDeclarationBuilder {
Scope get scope;
ScopeBuilder get scopeBuilder;
LibraryBuilder get library;
/// Lookup a member accessed statically through this declaration.
Builder findStaticBuilder(
String name, int charOffset, Uri fileUri, LibraryBuilder accessingLibrary,
{bool isSetter: false});
void addProblem(Message message, int charOffset, int length,
{bool wasHandled: false, List<LocatedMessage> context});
/// Returns the type of `this` in an instance of this declaration.
///
/// This is non-null for class and mixin declarations and `null` for
/// extension declarations.
InterfaceType get thisType;
/// Lookups the member [name] declared in this declaration.
///
/// If [setter] is `true` the sought member is a setter or assignable field.
/// If [required] is `true` and no member is found an internal problem is
/// reported.
Builder lookupLocalMember(String name,
{bool setter: false, bool required: false});
}
abstract class DeclarationBuilderImpl extends TypeDeclarationBuilderImpl
implements DeclarationBuilder {
@override
final Scope scope;
@override
final ScopeBuilder scopeBuilder;
DeclarationBuilderImpl(List<MetadataBuilder> metadata, int modifiers,
String name, LibraryBuilder parent, int charOffset, this.scope)
: scopeBuilder = new ScopeBuilder(scope),
super(metadata, modifiers, name, parent, charOffset);
@override
LibraryBuilder get library {
LibraryBuilder library = parent;
return library.partOfLibrary ?? library;
}
@override
void addProblem(Message message, int charOffset, int length,
{bool wasHandled: false, List<LocatedMessage> context}) {
library.addProblem(message, charOffset, length, fileUri,
wasHandled: wasHandled, context: context);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/enum_builder.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 fasta.enum_builder;
import 'builder.dart' show ClassBuilder, MetadataBuilder, NullabilityBuilder;
import 'package:kernel/ast.dart'
show
Arguments,
Class,
Constructor,
ConstructorInvocation,
DirectPropertyGet,
Expression,
Field,
FieldInitializer,
IntLiteral,
InterfaceType,
ListLiteral,
ProcedureKind,
ReturnStatement,
StaticGet,
StringLiteral,
SuperInitializer,
ThisExpression,
VariableGet;
import '../fasta_codes.dart'
show
LocatedMessage,
messageNoUnnamedConstructorInObject,
templateDuplicatedDeclaration,
templateDuplicatedDeclarationCause,
templateDuplicatedDeclarationSyntheticCause,
templateEnumConstantSameNameAsEnclosing;
import '../modifier.dart'
show
constMask,
finalMask,
hasInitializerMask,
initializingFormalMask,
staticMask;
import '../source/source_class_builder.dart' show SourceClassBuilder;
import '../kernel/kernel_builder.dart'
show
Builder,
FormalParameterBuilder,
ClassBuilder,
ConstructorBuilder,
FieldBuilder,
NamedTypeBuilder,
ProcedureBuilder,
TypeBuilder,
LibraryBuilder,
MemberBuilder,
MetadataBuilder,
Scope;
import '../kernel/metadata_collector.dart';
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
class EnumBuilder extends SourceClassBuilder {
final List<EnumConstantInfo> enumConstantInfos;
final NamedTypeBuilder intType;
final NamedTypeBuilder stringType;
final NamedTypeBuilder objectType;
final NamedTypeBuilder listType;
EnumBuilder.internal(
List<MetadataBuilder> metadata,
String name,
Scope scope,
Scope constructors,
Class cls,
this.enumConstantInfos,
this.intType,
this.listType,
this.objectType,
this.stringType,
LibraryBuilder parent,
int startCharOffset,
int charOffset,
int charEndOffset)
: super(metadata, 0, name, null, null, null, null, scope, constructors,
parent, null, startCharOffset, charOffset, charEndOffset,
cls: cls);
factory EnumBuilder(
MetadataCollector metadataCollector,
List<MetadataBuilder> metadata,
String name,
List<EnumConstantInfo> enumConstantInfos,
SourceLibraryBuilder parent,
int startCharOffset,
int charOffset,
int charEndOffset) {
assert(enumConstantInfos == null || enumConstantInfos.isNotEmpty);
// TODO(ahe): These types shouldn't be looked up in scope, they come
// directly from dart:core.
TypeBuilder intType =
new NamedTypeBuilder("int", const NullabilityBuilder.omitted(), null);
TypeBuilder stringType = new NamedTypeBuilder(
"String", const NullabilityBuilder.omitted(), null);
NamedTypeBuilder objectType = new NamedTypeBuilder(
"Object", const NullabilityBuilder.omitted(), null);
Class cls = new Class(name: name);
Map<String, MemberBuilder> members = <String, MemberBuilder>{};
Map<String, MemberBuilder> constructors = <String, MemberBuilder>{};
NamedTypeBuilder selfType =
new NamedTypeBuilder(name, const NullabilityBuilder.omitted(), null);
TypeBuilder listType = new NamedTypeBuilder(
"List", const NullabilityBuilder.omitted(), <TypeBuilder>[selfType]);
/// metadata class E {
/// final int index;
/// final String _name;
/// const E(this.index, this._name);
/// static const E id0 = const E(0, 'E.id0');
/// ...
/// static const E idn-1 = const E(n - 1, 'E.idn-1');
/// static const List<E> values = const <E>[id0, ..., idn-1];
/// String toString() => _name;
/// }
members["index"] = new FieldBuilder(null, intType, "index",
finalMask | hasInitializerMask, parent, charOffset, charOffset);
members["_name"] = new FieldBuilder(null, stringType, "_name",
finalMask | hasInitializerMask, parent, charOffset, charOffset);
ConstructorBuilder constructorBuilder = new ConstructorBuilder(
null,
constMask,
null,
"",
null,
<FormalParameterBuilder>[
new FormalParameterBuilder(null, initializingFormalMask, intType,
"index", parent, charOffset),
new FormalParameterBuilder(null, initializingFormalMask, stringType,
"_name", parent, charOffset)
],
parent,
charOffset,
charOffset,
charOffset,
charEndOffset);
constructors[""] = constructorBuilder;
FieldBuilder valuesBuilder = new FieldBuilder(
null,
listType,
"values",
constMask | staticMask | hasInitializerMask,
parent,
charOffset,
charOffset);
members["values"] = valuesBuilder;
ProcedureBuilder toStringBuilder = new ProcedureBuilder(
null,
0,
stringType,
"toString",
null,
null,
ProcedureKind.Method,
parent,
charOffset,
charOffset,
charOffset,
charEndOffset);
members["toString"] = toStringBuilder;
String className = name;
if (enumConstantInfos != null) {
for (int i = 0; i < enumConstantInfos.length; i++) {
EnumConstantInfo enumConstantInfo = enumConstantInfos[i];
List<MetadataBuilder> metadata = enumConstantInfo.metadata;
String name = enumConstantInfo.name;
String documentationComment = enumConstantInfo.documentationComment;
MemberBuilder existing = members[name];
if (existing != null) {
// The existing declaration is synthetic if it has the same
// charOffset as the enclosing enum.
bool isSynthetic = existing.charOffset == charOffset;
List<LocatedMessage> context = isSynthetic
? <LocatedMessage>[
templateDuplicatedDeclarationSyntheticCause
.withArguments(name)
.withLocation(
parent.fileUri, charOffset, className.length)
]
: <LocatedMessage>[
templateDuplicatedDeclarationCause
.withArguments(name)
.withLocation(
parent.fileUri, existing.charOffset, name.length)
];
parent.addProblem(templateDuplicatedDeclaration.withArguments(name),
enumConstantInfo.charOffset, name.length, parent.fileUri,
context: context);
enumConstantInfos[i] = null;
} else if (name == className) {
parent.addProblem(
templateEnumConstantSameNameAsEnclosing.withArguments(name),
enumConstantInfo.charOffset,
name.length,
parent.fileUri);
}
FieldBuilder fieldBuilder = new FieldBuilder(
metadata,
selfType,
name,
constMask | staticMask | hasInitializerMask,
parent,
enumConstantInfo.charOffset,
enumConstantInfo.charOffset);
metadataCollector?.setDocumentationComment(
fieldBuilder.field, documentationComment);
members[name] = fieldBuilder..next = existing;
}
}
final int startCharOffsetComputed =
metadata == null ? startCharOffset : metadata.first.charOffset;
EnumBuilder enumBuilder = new EnumBuilder.internal(
metadata,
name,
new Scope(
local: members,
parent: parent.scope,
debugName: "enum $name",
isModifiable: false),
new Scope(local: constructors, debugName: name, isModifiable: false),
cls,
enumConstantInfos,
intType,
listType,
objectType,
stringType,
parent,
startCharOffsetComputed,
charOffset,
charEndOffset);
void setParent(String name, MemberBuilder builder) {
do {
builder.parent = enumBuilder;
builder = builder.next;
} while (builder != null);
}
members.forEach(setParent);
constructors.forEach(setParent);
selfType.bind(enumBuilder);
return enumBuilder;
}
TypeBuilder get mixedInType => null;
InterfaceType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments) {
return rawType(nullabilityBuilder.build(library));
}
@override
Class build(SourceLibraryBuilder libraryBuilder, LibraryBuilder coreLibrary) {
cls.isEnum = true;
intType.resolveIn(coreLibrary.scope, charOffset, fileUri, libraryBuilder);
stringType.resolveIn(
coreLibrary.scope, charOffset, fileUri, libraryBuilder);
objectType.resolveIn(
coreLibrary.scope, charOffset, fileUri, libraryBuilder);
listType.resolveIn(coreLibrary.scope, charOffset, fileUri, libraryBuilder);
FieldBuilder indexFieldBuilder = firstMemberNamed("index");
Field indexField = indexFieldBuilder.build(libraryBuilder);
FieldBuilder nameFieldBuilder = firstMemberNamed("_name");
Field nameField = nameFieldBuilder.build(libraryBuilder);
ProcedureBuilder toStringBuilder = firstMemberNamed("toString");
toStringBuilder.body = new ReturnStatement(
new DirectPropertyGet(new ThisExpression(), nameField));
List<Expression> values = <Expression>[];
if (enumConstantInfos != null) {
for (EnumConstantInfo enumConstantInfo in enumConstantInfos) {
if (enumConstantInfo != null) {
Builder declaration = firstMemberNamed(enumConstantInfo.name);
if (declaration.isField) {
FieldBuilder field = declaration;
values.add(new StaticGet(field.build(libraryBuilder)));
}
}
}
}
FieldBuilder valuesBuilder = firstMemberNamed("values");
valuesBuilder.build(libraryBuilder);
valuesBuilder.initializer = new ListLiteral(values,
typeArgument: rawType(library.nonNullable), isConst: true);
ConstructorBuilder constructorBuilder = constructorScopeBuilder[""];
Constructor constructor = constructorBuilder.build(libraryBuilder);
constructor.initializers.insert(
0,
new FieldInitializer(indexField,
new VariableGet(constructor.function.positionalParameters[0]))
..parent = constructor);
constructor.initializers.insert(
1,
new FieldInitializer(nameField,
new VariableGet(constructor.function.positionalParameters[1]))
..parent = constructor);
ClassBuilder objectClass = objectType.declaration;
MemberBuilder superConstructor = objectClass.findConstructorOrFactory(
"", charOffset, fileUri, libraryBuilder);
if (superConstructor == null || !superConstructor.isConstructor) {
// TODO(ahe): Ideally, we would also want to check that [Object]'s
// unnamed constructor requires no arguments. But that information isn't
// always available at this point, and it's not really a situation that
// can happen unless you start modifying the SDK sources.
library.addProblem(messageNoUnnamedConstructorInObject,
objectClass.charOffset, objectClass.name.length, objectClass.fileUri);
} else {
constructor.initializers.add(
new SuperInitializer(superConstructor.member, new Arguments.empty())
..parent = constructor);
}
int index = 0;
if (enumConstantInfos != null) {
for (EnumConstantInfo enumConstantInfo in enumConstantInfos) {
if (enumConstantInfo != null) {
String constant = enumConstantInfo.name;
Builder declaration = firstMemberNamed(constant);
FieldBuilder field;
if (declaration.isField) {
field = declaration;
} else {
continue;
}
Arguments arguments = new Arguments(<Expression>[
new IntLiteral(index++),
new StringLiteral("$name.$constant")
]);
field.initializer =
new ConstructorInvocation(constructor, arguments, isConst: true);
}
}
}
return super.build(libraryBuilder, coreLibrary);
}
@override
Builder findConstructorOrFactory(
String name, int charOffset, Uri uri, LibraryBuilder library) {
return null;
}
}
class EnumConstantInfo {
final List<MetadataBuilder> metadata;
final String name;
final int charOffset;
final String documentationComment;
const EnumConstantInfo(
this.metadata, this.name, this.charOffset, this.documentationComment);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/declaration.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 fasta.declaration;
import '../problems.dart' show unsupported;
/// Dummy class to help deprecate [Builder.target].
abstract class UnrelatedTarget {}
abstract class Builder {
/// Used when multiple things with the same name are declared within the same
/// parent. Only used for top-level and class-member declarations, not for
/// block scopes.
Builder next;
Builder get parent;
Uri get fileUri;
int get charOffset;
get target;
Builder get origin;
String get fullNameForErrors;
bool get hasProblem;
bool get isConst;
bool get isConstructor;
bool get isFactory;
bool get isField;
bool get isFinal;
bool get isGetter;
/// Returns `true` if this builder is an extension declaration.
///
/// For instance `B` in:
///
/// class A {}
/// extension B on A {}
///
bool get isExtension;
/// Returns `true` if this builder is a member of a class, mixin, or extension
/// declaration.
///
/// For instance `A.constructor`, `method1a`, `method1b`, `method2a`,
/// `method2b`, `method3a`, and `method3b` in:
///
/// class A {
/// A.constructor();
/// method1a() {}
/// static method1b() {}
/// }
/// mixin B {
/// method2a() {}
/// static method2b() {}
/// }
/// extends C on A {
/// method3a() {}
/// static method3b() {}
/// }
///
bool get isDeclarationMember;
/// Returns `true` if this builder is a member of a class or mixin
/// declaration.
///
/// For instance `A.constructor`, `method1a`, `method1b`, `method2a` and
/// `method2b` in:
///
/// class A {
/// A.constructor();
/// method1a() {}
/// static method1b() {}
/// }
/// mixin B {
/// method2a() {}
/// static method2b() {}
/// }
/// extends C on A {
/// method3a() {} // Not a class member.
/// static method3b() {} // Not a class member.
/// }
///
bool get isClassMember;
/// Returns `true` if this builder is a member of an extension declaration.
///
/// For instance `method3a` and `method3b` in:
///
/// class A {
/// A.constructor(); // Not an extension member.
/// method1a() {} // Not an extension member.
/// static method1b() {} // Not an extension member.
/// }
/// mixin B {
/// method2a() {} // Not an extension member.
/// static method2b() {} // Not an extension member.
/// }
/// extends C on A {
/// method3a() {}
/// static method3b() {}
/// }
///
bool get isExtensionMember;
/// Returns `true` if this builder is an instance member of a class, mixin, or
/// extension declaration.
///
/// For instance `method1a`, `method2a`, and `method3a` in:
///
/// class A {
/// A.constructor(); // Not a declaration instance member.
/// method1a() {}
/// static method1b() {} // Not a declaration instance member.
/// }
/// mixin B {
/// method2a() {}
/// static method2b() {} // Not a declaration instance member.
/// }
/// extends C on A {
/// method3a() {}
/// static method3b() {} // Not a declaration instance member.
/// }
///
bool get isDeclarationInstanceMember;
/// Returns `true` if this builder is an instance member of a class or mixin
/// extension declaration.
///
/// For instance `method1a` and `method2a` in:
///
/// class A {
/// A.constructor(); // Not a class instance member.
/// method1a() {}
/// static method1b() {} // Not a class instance member.
/// }
/// mixin B {
/// method2a() {}
/// static method2b() {} // Not a class instance member.
/// }
/// extends C on A {
/// method3a() {} // Not a class instance member.
/// static method3b() {} // Not a class instance member.
/// }
///
bool get isClassInstanceMember;
/// Returns `true` if this builder is an instance member of an extension
/// declaration.
///
/// For instance `method3a` in:
///
/// class A {
/// A.constructor(); // Not an extension instance member.
/// method1a() {} // Not an extension instance member.
/// static method1b() {} // Not an extension instance member.
/// }
/// mixin B {
/// method2a() {} // Not an extension instance member.
/// static method2b() {} // Not an extension instance member.
/// }
/// extends C on A {
/// method3a() {}
/// static method3b() {} // Not an extension instance member.
/// }
///
bool get isExtensionInstanceMember;
bool get isLocal;
bool get isPatch;
bool get isRegularMethod;
bool get isSetter;
bool get isStatic;
bool get isSynthetic;
bool get isTopLevel;
bool get isTypeDeclaration;
bool get isTypeVariable;
bool get isMixinApplication;
bool get isNamedMixinApplication;
bool get isAnonymousMixinApplication;
/// Applies [patch] to this declaration.
void applyPatch(Builder patch);
/// Returns the number of patches that was finished.
int finishPatch();
/// Resolve constructors (lookup names in scope) recorded in this builder and
/// return the number of constructors resolved.
int resolveConstructors(covariant Builder parent);
/// Return `true` if this builder is a duplicate of another with the same
/// name. This is `false` for the builder first declared amongst duplicates.
bool get isDuplicate;
}
abstract class BuilderImpl implements Builder {
@override
Builder next;
BuilderImpl();
@override
get target => unsupported("${runtimeType}.target", charOffset, fileUri);
@override
Builder get origin => this;
bool get hasProblem => false;
@override
bool get isConst => false;
@override
bool get isConstructor => false;
@override
bool get isFactory => false;
@override
bool get isField => false;
@override
bool get isFinal => false;
@override
bool get isGetter => false;
@override
bool get isExtension => false;
@override
bool get isDeclarationMember => false;
@override
bool get isClassMember => false;
@override
bool get isExtensionMember => false;
@override
bool get isDeclarationInstanceMember => false;
@override
bool get isClassInstanceMember => false;
@override
bool get isExtensionInstanceMember => false;
@override
bool get isLocal => false;
@override
bool get isPatch => this != origin;
@override
bool get isRegularMethod => false;
@override
bool get isSetter => false;
@override
bool get isStatic => false;
@override
bool get isSynthetic => false;
@override
bool get isTopLevel => false;
@override
bool get isTypeDeclaration => false;
@override
bool get isTypeVariable => false;
@override
bool get isMixinApplication => false;
@override
bool get isNamedMixinApplication => false;
@override
bool get isAnonymousMixinApplication {
return isMixinApplication && !isNamedMixinApplication;
}
@override
void applyPatch(Builder patch) {
unsupported("${runtimeType}.applyPatch", charOffset, fileUri);
}
@override
int finishPatch() {
if (!isPatch) return 0;
unsupported("${runtimeType}.finishPatch", charOffset, fileUri);
return 0;
}
@override
int resolveConstructors(covariant Builder parent) => 0;
@override
bool get isDuplicate => next != null;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/type_declaration_builder.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 fasta.type_declaration_builder;
import 'package:kernel/ast.dart' show DartType, Nullability;
import 'builder.dart'
show
Builder,
LibraryBuilder,
MetadataBuilder,
NullabilityBuilder,
TypeBuilder;
import 'modifier_builder.dart';
abstract class TypeDeclarationBuilder implements ModifierBuilder {
void set parent(Builder value);
List<MetadataBuilder> get metadata;
int get typeVariablesCount => 0;
DartType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments);
/// [arguments] have already been built.
DartType buildTypesWithBuiltArguments(LibraryBuilder library,
Nullability nullability, List<DartType> arguments);
}
abstract class TypeDeclarationBuilderImpl extends ModifierBuilderImpl
implements TypeDeclarationBuilder {
@override
final List<MetadataBuilder> metadata;
@override
final int modifiers;
@override
final String name;
TypeDeclarationBuilderImpl(
this.metadata, this.modifiers, this.name, Builder parent, int charOffset,
[Uri fileUri])
: assert(modifiers != null),
super(parent, charOffset, fileUri);
@override
bool get isTypeDeclaration => true;
@override
String get fullNameForErrors => name;
@override
int get typeVariablesCount => 0;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/type_alias_builder.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 fasta.function_type_alias_builder;
import 'package:kernel/ast.dart'
show
DartType,
DynamicType,
FunctionType,
InvalidType,
Nullability,
TypeParameter,
Typedef,
VariableDeclaration;
import 'package:kernel/type_algebra.dart'
show FreshTypeParameters, getFreshTypeParameters, substitute;
import '../fasta_codes.dart'
show noLength, templateCyclicTypedef, templateTypeArgumentMismatch;
import '../kernel/kernel_builder.dart'
show
FunctionTypeBuilder,
FormalParameterBuilder,
LibraryBuilder,
MetadataBuilder,
TypeBuilder,
TypeVariableBuilder;
import '../problems.dart' show unhandled, unsupported;
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
import 'builder.dart'
show
LibraryBuilder,
MetadataBuilder,
NullabilityBuilder,
TypeBuilder,
TypeVariableBuilder;
import 'declaration.dart';
import 'type_declaration_builder.dart';
class TypeAliasBuilder extends TypeDeclarationBuilderImpl {
final TypeBuilder type;
final List<TypeVariableBuilder> typeVariables;
/// The [Typedef] built by this builder.
final Typedef typedef;
DartType thisType;
TypeAliasBuilder(List<MetadataBuilder> metadata, String name,
this.typeVariables, this.type, LibraryBuilder parent, int charOffset,
[Typedef typedef])
: typedef = typedef ??
(new Typedef(name, null,
typeParameters: TypeVariableBuilder.typeParametersFromBuilders(
typeVariables),
fileUri: parent.library.fileUri)
..fileOffset = charOffset),
super(metadata, 0, name, parent, charOffset);
// Deliberately unrelated return type to statically detect more accidental
// use until Builder.target is fully retired.
UnrelatedTarget get target => unsupported(
"TypeAliasBuilder.target is deprecated. "
"Use TypeAliasBuilder.typedef instead.",
charOffset,
fileUri);
String get debugName => "TypeAliasBuilder";
LibraryBuilder get parent => super.parent;
Typedef build(SourceLibraryBuilder libraryBuilder) {
typedef..type ??= buildThisType(libraryBuilder);
TypeBuilder type = this.type;
if (type is FunctionTypeBuilder) {
List<TypeParameter> typeParameters =
new List<TypeParameter>(type.typeVariables?.length ?? 0);
for (int i = 0; i < typeParameters.length; ++i) {
TypeVariableBuilder typeVariable = type.typeVariables[i];
typeParameters[i] = typeVariable.parameter;
}
FreshTypeParameters freshTypeParameters =
getFreshTypeParameters(typeParameters);
typedef.typeParametersOfFunctionType
.addAll(freshTypeParameters.freshTypeParameters);
if (type.formals != null) {
for (FormalParameterBuilder formal in type.formals) {
VariableDeclaration parameter = formal.build(libraryBuilder, 0);
parameter.type = freshTypeParameters.substitute(parameter.type);
if (formal.isNamed) {
typedef.namedParameters.add(parameter);
} else {
typedef.positionalParameters.add(parameter);
}
}
}
} else if (type != null) {
unhandled("${type.fullNameForErrors}", "build", charOffset, fileUri);
}
return typedef;
}
DartType buildThisType(LibraryBuilder library) {
if (thisType != null) {
if (identical(thisType, cyclicTypeAliasMarker)) {
library.addProblem(templateCyclicTypedef.withArguments(name),
charOffset, noLength, fileUri);
return const InvalidType();
}
return thisType;
}
// It is a compile-time error for an alias (typedef) to refer to itself. We
// detect cycles by detecting recursive calls to this method using an
// instance of InvalidType that isn't identical to `const InvalidType()`.
thisType = cyclicTypeAliasMarker;
TypeBuilder type = this.type;
if (type is FunctionTypeBuilder) {
FunctionType builtType = type?.build(library, typedef.thisType);
if (builtType != null) {
if (typeVariables != null) {
for (TypeVariableBuilder tv in typeVariables) {
// Follow bound in order to find all cycles
tv.bound?.build(library);
}
}
return thisType = builtType;
} else {
return thisType = const InvalidType();
}
} else if (type == null) {
return thisType = const InvalidType();
} else {
return unhandled(
"${type.fullNameForErrors}", "buildThisType", charOffset, fileUri);
}
}
/// [arguments] have already been built.
DartType buildTypesWithBuiltArguments(LibraryBuilder library,
Nullability nullability, List<DartType> arguments) {
DartType thisType = buildThisType(library);
if (const DynamicType() == thisType) return thisType;
FunctionType result = thisType.withNullability(nullability);
if (typedef.typeParameters.isEmpty && arguments == null) return result;
Map<TypeParameter, DartType> substitution = <TypeParameter, DartType>{};
for (int i = 0; i < typedef.typeParameters.length; i++) {
substitution[typedef.typeParameters[i]] = arguments[i];
}
return substitute(result, substitution);
}
List<DartType> buildTypeArguments(
LibraryBuilder library, List<TypeBuilder> arguments) {
if (arguments == null && typeVariables == null) {
return <DartType>[];
}
if (arguments == null && typeVariables != null) {
List<DartType> result =
new List<DartType>.filled(typeVariables.length, null, growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = typeVariables[i].defaultType.build(library);
}
if (library is SourceLibraryBuilder) {
library.inferredTypes.addAll(result);
}
return result;
}
if (arguments != null && arguments.length != (typeVariables?.length ?? 0)) {
// That should be caught and reported as a compile-time error earlier.
return unhandled(
templateTypeArgumentMismatch
.withArguments(typeVariables.length)
.message,
"buildTypeArguments",
-1,
null);
}
// arguments.length == typeVariables.length
List<DartType> result =
new List<DartType>.filled(arguments.length, null, growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = arguments[i].build(library);
}
return result;
}
/// If [arguments] are null, the default types for the variables are used.
@override
int get typeVariablesCount => typeVariables?.length ?? 0;
@override
DartType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments) {
DartType thisType = buildThisType(library);
if (thisType is InvalidType) return thisType;
if (typedef.typeParameters.isEmpty && arguments == null) {
return thisType.withNullability(nullabilityBuilder.build(library));
}
// Otherwise, substitute.
return buildTypesWithBuiltArguments(
library,
nullabilityBuilder.build(library),
buildTypeArguments(library, arguments));
}
}
final InvalidType cyclicTypeAliasMarker = new InvalidType();
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/invalid_type_builder.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 fasta.invalid_type_builder;
import 'package:kernel/ast.dart' show DartType, InvalidType, Nullability;
import '../fasta_codes.dart' show LocatedMessage;
import 'builder.dart' show NullabilityBuilder;
import '../kernel/kernel_builder.dart' show TypeBuilder, LibraryBuilder;
import 'type_declaration_builder.dart';
class InvalidTypeBuilder extends TypeDeclarationBuilderImpl {
String get debugName => "InvalidTypeBuilder";
final LocatedMessage message;
final List<LocatedMessage> context;
final bool suppressMessage;
InvalidTypeBuilder(String name, this.message,
{this.context, this.suppressMessage: true})
: super(null, 0, name, null, message.charOffset, message.uri);
@override
InvalidType get target => const InvalidType();
DartType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments) {
return buildTypesWithBuiltArguments(library, null, null);
}
/// [Arguments] have already been built.
DartType buildTypesWithBuiltArguments(LibraryBuilder library,
Nullability nullability, List<DartType> arguments) {
if (!suppressMessage) {
library.addProblem(message.messageObject, message.charOffset,
message.length, message.uri,
context: context);
}
return const InvalidType();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/unresolved_type.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 fasta.unresolved_type;
import 'builder.dart' show LibraryBuilder, Scope, TypeBuilder;
/// A wrapper around a type that is yet to be resolved.
class UnresolvedType {
final TypeBuilder builder;
final int charOffset;
final Uri fileUri;
UnresolvedType(this.builder, this.charOffset, this.fileUri);
void resolveIn(Scope scope, LibraryBuilder library) =>
builder.resolveIn(scope, charOffset, fileUri, library);
/// Performs checks on the type after it's resolved.
void checkType(LibraryBuilder library) {
return builder.check(library, charOffset, fileUri);
}
/// Normalizes the type arguments in accordance with Dart 1 semantics.
void normalizeType() => builder.normalize(charOffset, fileUri);
String toString() => "UnresolvedType(@$charOffset, $builder)";
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/field_builder.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 fasta.field_builder;
import 'package:kernel/ast.dart' show DartType, Expression;
import 'builder.dart' show LibraryBuilder;
import 'member_builder.dart';
import 'package:kernel/ast.dart'
show
Class,
DartType,
Expression,
Field,
InvalidType,
Member,
Name,
NullLiteral;
import '../constant_context.dart' show ConstantContext;
import '../fasta_codes.dart'
show
messageInternalProblemAlreadyInitialized,
templateCantInferTypeDueToCircularity;
import '../kernel/body_builder.dart' show BodyBuilder;
import '../kernel/kernel_builder.dart'
show
ClassBuilder,
Builder,
ImplicitFieldType,
TypeBuilder,
LibraryBuilder,
MetadataBuilder;
import '../problems.dart' show internalProblem;
import '../scanner.dart' show Token;
import '../scope.dart' show Scope;
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
import '../source/source_loader.dart' show SourceLoader;
import '../type_inference/type_inference_engine.dart'
show IncludesTypeParametersNonCovariantly, Variance;
import '../type_inference/type_inferrer.dart'
show ExpressionInferenceResult, TypeInferrerImpl;
import '../type_inference/type_schema.dart' show UnknownType;
import 'extension_builder.dart';
class FieldBuilder extends MemberBuilderImpl {
final String name;
final int modifiers;
final Field field;
final List<MetadataBuilder> metadata;
final TypeBuilder type;
Token constInitializerToken;
bool hadTypesInferred = false;
FieldBuilder(this.metadata, this.type, this.name, this.modifiers,
Builder compilationUnit, int charOffset, int charEndOffset)
: field = new Field(null, fileUri: compilationUnit?.fileUri)
..fileOffset = charOffset
..fileEndOffset = charEndOffset,
super(compilationUnit, charOffset);
Member get member => field;
String get debugName => "FieldBuilder";
bool get isField => true;
void set initializer(Expression value) {
if (!hasInitializer && value is! NullLiteral && !isConst && !isFinal) {
internalProblem(
messageInternalProblemAlreadyInitialized, charOffset, fileUri);
}
field.initializer = value..parent = field;
}
bool get isEligibleForInference {
return type == null && (hasInitializer || isClassInstanceMember);
}
Field build(SourceLibraryBuilder libraryBuilder) {
field
..isCovariant = isCovariant
..isFinal = isFinal
..isConst = isConst
..isLate = isLate;
if (isExtensionMember) {
ExtensionBuilder extension = parent;
field.name = new Name('${extension.name}|$name', libraryBuilder.library);
field
..hasImplicitGetter = false
..hasImplicitSetter = false
..isStatic = true
..isExtensionMember = true;
} else {
// TODO(johnniwinther): How can the name already have been computed.
field.name ??= new Name(name, libraryBuilder.library);
bool isInstanceMember = !isStatic && !isTopLevel;
field
..hasImplicitGetter = isInstanceMember
..hasImplicitSetter = isInstanceMember && !isConst && !isFinal
..isStatic = !isInstanceMember
..isExtensionMember = false;
}
if (type != null) {
field.type = type.build(libraryBuilder);
if (!isFinal && !isConst) {
IncludesTypeParametersNonCovariantly needsCheckVisitor;
if (parent is ClassBuilder) {
ClassBuilder enclosingClassBuilder = parent;
Class enclosingClass = enclosingClassBuilder.cls;
if (enclosingClass.typeParameters.isNotEmpty) {
needsCheckVisitor = new IncludesTypeParametersNonCovariantly(
enclosingClass.typeParameters,
// We are checking the field type as if it is the type of the
// parameter of the implicit setter and this is a contravariant
// position.
initialVariance: Variance.contravariant);
}
}
if (needsCheckVisitor != null) {
if (field.type.accept(needsCheckVisitor)) {
field.isGenericCovariantImpl = true;
}
}
}
}
return field;
}
@override
void buildOutlineExpressions(LibraryBuilder library) {
ClassBuilder classBuilder = isClassMember ? parent : null;
MetadataBuilder.buildAnnotations(
field, metadata, library, classBuilder, this);
// For modular compilation we need to include initializers of all const
// fields and all non-static final fields in classes with const constructors
// into the outline.
if ((isConst ||
(isFinal &&
!isStatic &&
isClassMember &&
classBuilder.hasConstConstructor)) &&
constInitializerToken != null) {
Scope scope = classBuilder?.scope ?? library.scope;
BodyBuilder bodyBuilder = library.loader
.createBodyBuilderForOutlineExpression(
library, classBuilder, this, scope, fileUri);
bodyBuilder.constantContext =
isConst ? ConstantContext.inferred : ConstantContext.required;
initializer = bodyBuilder.parseFieldInitializer(constInitializerToken)
..parent = field;
bodyBuilder.typeInferrer
?.inferFieldInitializer(bodyBuilder, field.type, field.initializer);
if (library.loader is SourceLoader) {
SourceLoader loader = library.loader;
loader.transformPostInference(field, bodyBuilder.transformSetLiterals,
bodyBuilder.transformCollections);
}
bodyBuilder.resolveRedirectingFactoryTargets();
}
constInitializerToken = null;
}
@override
void inferType() {
SourceLibraryBuilder library = this.library;
if (field.type is! ImplicitFieldType) {
// We have already inferred a type.
return;
}
ImplicitFieldType type = field.type;
if (type.member != this) {
// The implicit type was inherited.
FieldBuilder other = type.member;
other.inferCopiedType(field);
return;
}
if (type.isStarted) {
library.addProblem(
templateCantInferTypeDueToCircularity.withArguments(name),
charOffset,
name.length,
fileUri);
field.type = const InvalidType();
return;
}
type.isStarted = true;
TypeInferrerImpl typeInferrer = library.loader.typeInferenceEngine
.createTopLevelTypeInferrer(
fileUri, field.enclosingClass?.thisType, library);
BodyBuilder bodyBuilder =
library.loader.createBodyBuilderForField(this, typeInferrer);
bodyBuilder.constantContext =
isConst ? ConstantContext.inferred : ConstantContext.none;
initializer = bodyBuilder.parseFieldInitializer(type.initializerToken);
type.initializerToken = null;
ExpressionInferenceResult result = typeInferrer.inferExpression(
field.initializer, const UnknownType(), true,
isVoidAllowed: true);
DartType inferredType =
typeInferrer.inferDeclarationType(result.inferredType);
if (field.type is ImplicitFieldType) {
// `field.type` may have changed if a circularity was detected when
// [inferredType] was computed.
field.type = inferredType;
IncludesTypeParametersNonCovariantly needsCheckVisitor;
if (parent is ClassBuilder) {
ClassBuilder enclosingClassBuilder = parent;
Class enclosingClass = enclosingClassBuilder.cls;
if (enclosingClass.typeParameters.isNotEmpty) {
needsCheckVisitor = new IncludesTypeParametersNonCovariantly(
enclosingClass.typeParameters,
// We are checking the field type as if it is the type of the
// parameter of the implicit setter and this is a contravariant
// position.
initialVariance: Variance.contravariant);
}
}
if (needsCheckVisitor != null) {
if (field.type.accept(needsCheckVisitor)) {
field.isGenericCovariantImpl = true;
}
}
}
// The following is a hack. The outline should contain the compiled
// initializers, however, as top-level inference is subtly different from
// we need to compile the field initializer again when everything else is
// compiled.
field.initializer = null;
}
void inferCopiedType(Field other) {
inferType();
other.type = field.type;
other.initializer = null;
}
DartType get builtType => field.type;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/procedure_builder.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 fasta.procedure_builder;
import 'dart:core' hide MapEntry;
import 'package:front_end/src/fasta/kernel/kernel_api.dart';
import 'package:kernel/ast.dart' hide Variance;
import 'package:kernel/type_algebra.dart';
import '../../base/common.dart';
import 'builder.dart'
show
Builder,
FormalParameterBuilder,
LibraryBuilder,
MetadataBuilder,
Scope,
TypeBuilder,
TypeVariableBuilder;
import 'member_builder.dart';
import 'extension_builder.dart';
import 'type_variable_builder.dart';
import '../../scanner/token.dart' show Token;
import '../constant_context.dart' show ConstantContext;
import '../kernel/body_builder.dart' show BodyBuilder;
import '../kernel/expression_generator_helper.dart'
show ExpressionGeneratorHelper;
import '../kernel/kernel_builder.dart'
show
ClassBuilder,
ConstructorReferenceBuilder,
Builder,
FormalParameterBuilder,
LibraryBuilder,
MetadataBuilder,
TypeBuilder,
TypeVariableBuilder,
isRedirectingGenerativeConstructorImplementation;
import '../kernel/kernel_shadow_ast.dart' show VariableDeclarationImpl;
import '../kernel/redirecting_factory_body.dart' show RedirectingFactoryBody;
import '../loader.dart' show Loader;
import '../messages.dart'
show
Message,
messageConstFactoryRedirectionToNonConst,
messageMoreThanOneSuperOrThisInitializer,
messageNonInstanceTypeVariableUse,
messagePatchDeclarationMismatch,
messagePatchDeclarationOrigin,
messagePatchNonExternal,
messageSuperInitializerNotLast,
messageThisInitializerNotAlone,
noLength;
import '../problems.dart' show unexpected;
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
import '../type_inference/type_inference_engine.dart'
show IncludesTypeParametersNonCovariantly, Variance;
/// Common base class for constructor and procedure builders.
abstract class FunctionBuilder extends MemberBuilderImpl {
final List<MetadataBuilder> metadata;
final int modifiers;
final TypeBuilder returnType;
final String name;
final List<TypeVariableBuilder> typeVariables;
final List<FormalParameterBuilder> formals;
/// If this procedure is an extension instance member, [_extensionThis] holds
/// the synthetically added `this` parameter.
VariableDeclaration _extensionThis;
/// If this procedure is an extension instance member,
/// [_extensionTypeParameters] holds the type parameters copied from the
/// extension declaration.
List<TypeParameter> _extensionTypeParameters;
FunctionBuilder(
this.metadata,
this.modifiers,
this.returnType,
this.name,
this.typeVariables,
this.formals,
LibraryBuilder compilationUnit,
int charOffset,
this.nativeMethodName)
: super(compilationUnit, charOffset) {
if (formals != null) {
for (int i = 0; i < formals.length; i++) {
formals[i].parent = this;
}
}
}
String get debugName => "FunctionBuilder";
AsyncMarker get asyncModifier;
ProcedureKind get kind;
bool get isConstructor => false;
bool get isRegularMethod => identical(ProcedureKind.Method, kind);
bool get isGetter => identical(ProcedureKind.Getter, kind);
bool get isSetter => identical(ProcedureKind.Setter, kind);
bool get isOperator => identical(ProcedureKind.Operator, kind);
bool get isFactory => identical(ProcedureKind.Factory, kind);
/// This is the formal parameter scope as specified in the Dart Programming
/// Language Specification, 4th ed, section 9.2.
Scope computeFormalParameterScope(Scope parent) {
if (formals == null) return parent;
Map<String, Builder> local = <String, Builder>{};
for (FormalParameterBuilder formal in formals) {
if (!isConstructor || !formal.isInitializingFormal) {
local[formal.name] = formal;
}
}
return new Scope(
local: local,
parent: parent,
debugName: "formal parameter",
isModifiable: false);
}
Scope computeFormalParameterInitializerScope(Scope parent) {
// From
// [dartLangSpec.tex](../../../../../../docs/language/dartLangSpec.tex) at
// revision 94b23d3b125e9d246e07a2b43b61740759a0dace:
//
// When the formal parameter list of a non-redirecting generative
// constructor contains any initializing formals, a new scope is
// introduced, the _formal parameter initializer scope_, which is the
// current scope of the initializer list of the constructor, and which is
// enclosed in the scope where the constructor is declared. Each
// initializing formal in the formal parameter list introduces a final
// local variable into the formal parameter initializer scope, but not into
// the formal parameter scope; every other formal parameter introduces a
// local variable into both the formal parameter scope and the formal
// parameter initializer scope.
if (formals == null) return parent;
Map<String, Builder> local = <String, Builder>{};
for (FormalParameterBuilder formal in formals) {
local[formal.name] = formal.forFormalParameterInitializerScope();
}
return new Scope(
local: local,
parent: parent,
debugName: "formal parameter initializer",
isModifiable: false);
}
/// This scope doesn't correspond to any scope specified in the Dart
/// Programming Language Specification, 4th ed. It's an unspecified extension
/// to support generic methods.
Scope computeTypeParameterScope(Scope parent) {
if (typeVariables == null) return parent;
Map<String, Builder> local = <String, Builder>{};
for (TypeVariableBuilder variable in typeVariables) {
local[variable.name] = variable;
}
return new Scope(
local: local,
parent: parent,
debugName: "type parameter",
isModifiable: false);
}
FormalParameterBuilder getFormal(String name) {
if (formals != null) {
for (FormalParameterBuilder formal in formals) {
if (formal.name == name) return formal;
}
}
return null;
}
final String nativeMethodName;
FunctionNode function;
Statement _body;
FunctionBuilder get actualOrigin;
void set body(Statement newBody) {
// if (newBody != null) {
// if (isAbstract) {
// // TODO(danrubel): Is this check needed?
// return internalProblem(messageInternalProblemBodyOnAbstractMethod,
// newBody.fileOffset, fileUri);
// }
// }
_body = newBody;
if (function != null) {
// A forwarding semi-stub is a method that is abstract in the source code,
// but which needs to have a forwarding stub body in order to ensure that
// covariance checks occur. We don't want to replace the forwarding stub
// body with null.
TreeNode parent = function.parent;
if (!(newBody == null &&
parent is Procedure &&
parent.isForwardingSemiStub)) {
function.body = newBody;
newBody?.parent = function;
}
}
}
void setRedirectingFactoryBody(Member target, List<DartType> typeArguments) {
if (_body != null) {
unexpected("null", "${_body.runtimeType}", charOffset, fileUri);
}
_body = new RedirectingFactoryBody(target, typeArguments);
function.body = _body;
_body?.parent = function;
if (isPatch) {
actualOrigin.setRedirectingFactoryBody(target, typeArguments);
}
}
Statement get body => _body ??= new EmptyStatement();
bool get isNative => nativeMethodName != null;
FunctionNode buildFunction(LibraryBuilder library) {
assert(function == null);
FunctionNode result = new FunctionNode(body, asyncMarker: asyncModifier);
IncludesTypeParametersNonCovariantly needsCheckVisitor;
if (!isConstructor && !isFactory && parent is ClassBuilder) {
ClassBuilder enclosingClassBuilder = parent;
Class enclosingClass = enclosingClassBuilder.cls;
if (enclosingClass.typeParameters.isNotEmpty) {
needsCheckVisitor = new IncludesTypeParametersNonCovariantly(
enclosingClass.typeParameters,
// We are checking the parameter types which are in a
// contravariant position.
initialVariance: Variance.contravariant);
}
}
if (typeVariables != null) {
for (TypeVariableBuilder t in typeVariables) {
TypeParameter parameter = t.parameter;
result.typeParameters.add(parameter);
if (needsCheckVisitor != null) {
if (parameter.bound.accept(needsCheckVisitor)) {
parameter.isGenericCovariantImpl = true;
}
}
}
setParents(result.typeParameters, result);
}
if (formals != null) {
for (FormalParameterBuilder formal in formals) {
VariableDeclaration parameter = formal.build(library, 0);
if (needsCheckVisitor != null) {
if (parameter.type.accept(needsCheckVisitor)) {
parameter.isGenericCovariantImpl = true;
}
}
if (formal.isNamed) {
result.namedParameters.add(parameter);
} else {
result.positionalParameters.add(parameter);
}
parameter.parent = result;
if (formal.isRequired) {
result.requiredParameterCount++;
}
}
}
if (!isExtensionInstanceMember &&
isSetter &&
(formals?.length != 1 || formals[0].isOptional)) {
// Replace illegal parameters by single dummy parameter.
// Do this after building the parameters, since the diet listener
// assumes that parameters are built, even if illegal in number.
VariableDeclaration parameter =
new VariableDeclarationImpl("#synthetic", 0);
result.positionalParameters.clear();
result.positionalParameters.add(parameter);
parameter.parent = result;
result.namedParameters.clear();
result.requiredParameterCount = 1;
}
if (returnType != null) {
result.returnType = returnType.build(library);
}
if (!isConstructor &&
!isDeclarationInstanceMember &&
parent is ClassBuilder) {
ClassBuilder enclosingClassBuilder = parent;
List<TypeParameter> typeParameters =
enclosingClassBuilder.cls.typeParameters;
if (typeParameters.isNotEmpty) {
Map<TypeParameter, DartType> substitution;
DartType removeTypeVariables(DartType type) {
if (substitution == null) {
substitution = <TypeParameter, DartType>{};
for (TypeParameter parameter in typeParameters) {
substitution[parameter] = const DynamicType();
}
}
library.addProblem(
messageNonInstanceTypeVariableUse, charOffset, noLength, fileUri);
return substitute(type, substitution);
}
Set<TypeParameter> set = typeParameters.toSet();
for (VariableDeclaration parameter in result.positionalParameters) {
if (containsTypeVariable(parameter.type, set)) {
parameter.type = removeTypeVariables(parameter.type);
}
}
for (VariableDeclaration parameter in result.namedParameters) {
if (containsTypeVariable(parameter.type, set)) {
parameter.type = removeTypeVariables(parameter.type);
}
}
if (containsTypeVariable(result.returnType, set)) {
result.returnType = removeTypeVariables(result.returnType);
}
}
}
if (isExtensionInstanceMember) {
ExtensionBuilder extensionBuilder = parent;
_extensionThis = result.positionalParameters.first;
if (extensionBuilder.typeParameters != null) {
int count = extensionBuilder.typeParameters.length;
_extensionTypeParameters = new List<TypeParameter>(count);
for (int index = 0; index < count; index++) {
_extensionTypeParameters[index] = result.typeParameters[index];
}
}
}
return function = result;
}
/// Returns the [index]th parameter of this function.
///
/// The index is the syntactical index, including both positional and named
/// parameter in the order they are declared, and excluding the synthesized
/// this parameter on extension instance members.
VariableDeclaration getFormalParameter(int index) {
if (isExtensionInstanceMember) {
return formals[index + 1].variable;
} else {
return formals[index].variable;
}
}
/// If this is an extension instance method, the tear off closure parameter
/// corresponding to the [index]th parameter on the instance method is
/// returned.
///
/// This is used to update the default value for the closure parameter when
/// it has been computed for the original parameter.
VariableDeclaration getExtensionTearOffParameter(int index) => null;
/// Returns the parameter for 'this' synthetically added to extension
/// instance members.
VariableDeclaration get extensionThis {
assert(_extensionThis != null || !isExtensionInstanceMember,
"ProcedureBuilder.extensionThis has not been set.");
return _extensionThis;
}
/// Returns a list of synthetic type parameters added to extension instance
/// members.
List<TypeParameter> get extensionTypeParameters {
// Use [_extensionThis] as marker for whether extension type parameters have
// been computed.
assert(_extensionThis != null || !isExtensionInstanceMember,
"ProcedureBuilder.extensionTypeParameters has not been set.");
return _extensionTypeParameters;
}
Member build(SourceLibraryBuilder library);
@override
void buildOutlineExpressions(LibraryBuilder library) {
MetadataBuilder.buildAnnotations(
member, metadata, library, isClassMember ? parent : null, this);
if (formals != null) {
// For const constructors we need to include default parameter values
// into the outline. For all other formals we need to call
// buildOutlineExpressions to clear initializerToken to prevent
// consuming too much memory.
for (FormalParameterBuilder formal in formals) {
formal.buildOutlineExpressions(library);
}
}
}
void becomeNative(Loader loader) {
MemberBuilder constructor = loader.getNativeAnnotation();
Arguments arguments =
new Arguments(<Expression>[new StringLiteral(nativeMethodName)]);
Expression annotation;
if (constructor.isConstructor) {
annotation = new ConstructorInvocation(constructor.member, arguments)
..isConst = true;
} else {
annotation = new StaticInvocation(constructor.member, arguments)
..isConst = true;
}
member.addAnnotation(annotation);
}
bool checkPatch(FunctionBuilder patch) {
if (!isExternal) {
patch.library.addProblem(
messagePatchNonExternal, patch.charOffset, noLength, patch.fileUri,
context: [
messagePatchDeclarationOrigin.withLocation(
fileUri, charOffset, noLength)
]);
return false;
}
return true;
}
void reportPatchMismatch(Builder patch) {
library.addProblem(messagePatchDeclarationMismatch, patch.charOffset,
noLength, patch.fileUri, context: [
messagePatchDeclarationOrigin.withLocation(fileUri, charOffset, noLength)
]);
}
}
class ProcedureBuilder extends FunctionBuilder {
final Procedure _procedure;
final int charOpenParenOffset;
final ProcedureKind kind;
ProcedureBuilder patchForTesting;
AsyncMarker actualAsyncModifier = AsyncMarker.Sync;
@override
ProcedureBuilder actualOrigin;
Procedure get actualProcedure => _procedure;
bool hadTypesInferred = false;
/// If this is an extension instance method then [_extensionTearOff] holds
/// the synthetically created tear off function.
Procedure _extensionTearOff;
/// If this is an extension instance method then
/// [_extensionTearOffParameterMap] holds a map from the parameters of
/// the methods to the parameter of the closure returned in the tear-off.
///
/// This map is used to set the default values on the closure parameters when
/// these have been built.
Map<VariableDeclaration, VariableDeclaration> _extensionTearOffParameterMap;
ProcedureBuilder(
List<MetadataBuilder> metadata,
int modifiers,
TypeBuilder returnType,
String name,
List<TypeVariableBuilder> typeVariables,
List<FormalParameterBuilder> formals,
this.kind,
SourceLibraryBuilder compilationUnit,
int startCharOffset,
int charOffset,
this.charOpenParenOffset,
int charEndOffset,
[String nativeMethodName])
: _procedure =
new Procedure(null, kind, null, fileUri: compilationUnit?.fileUri)
..startFileOffset = startCharOffset
..fileOffset = charOffset
..fileEndOffset = charEndOffset,
super(metadata, modifiers, returnType, name, typeVariables, formals,
compilationUnit, charOffset, nativeMethodName);
@override
ProcedureBuilder get origin => actualOrigin ?? this;
AsyncMarker get asyncModifier => actualAsyncModifier;
Statement get body {
if (_body == null && !isAbstract && !isExternal) {
_body = new EmptyStatement();
}
return _body;
}
void set asyncModifier(AsyncMarker newModifier) {
actualAsyncModifier = newModifier;
if (function != null) {
// No parent, it's an enum.
function.asyncMarker = actualAsyncModifier;
function.dartAsyncMarker = actualAsyncModifier;
}
}
bool get isEligibleForTopLevelInference {
if (isDeclarationInstanceMember) {
if (returnType == null) return true;
if (formals != null) {
for (FormalParameterBuilder formal in formals) {
if (formal.type == null) return true;
}
}
}
return false;
}
/// Returns `true` if this procedure is declared in an extension declaration.
bool get isExtensionMethod {
return parent is ExtensionBuilder;
}
Procedure build(SourceLibraryBuilder libraryBuilder) {
// TODO(ahe): I think we may call this twice on parts. Investigate.
if (_procedure.name == null) {
_procedure.function = buildFunction(libraryBuilder);
_procedure.function.parent = _procedure;
_procedure.function.fileOffset = charOpenParenOffset;
_procedure.function.fileEndOffset = _procedure.fileEndOffset;
_procedure.isAbstract = isAbstract;
_procedure.isExternal = isExternal;
_procedure.isConst = isConst;
if (isExtensionMethod) {
ExtensionBuilder extensionBuilder = parent;
_procedure.isExtensionMember = true;
_procedure.isStatic = true;
String kindInfix = '';
if (isExtensionInstanceMember) {
// Instance getter and setter are converted to methods so we use an
// infix to make their names unique.
switch (kind) {
case ProcedureKind.Getter:
kindInfix = 'get#';
break;
case ProcedureKind.Setter:
kindInfix = 'set#';
break;
case ProcedureKind.Method:
case ProcedureKind.Operator:
kindInfix = '';
break;
case ProcedureKind.Factory:
throw new UnsupportedError(
'Unexpected extension method kind ${kind}');
}
_procedure.kind = ProcedureKind.Method;
}
_procedure.name = new Name(
'${extensionBuilder.name}|${kindInfix}${name}',
libraryBuilder.library);
} else {
_procedure.isStatic = isStatic;
_procedure.name = new Name(name, libraryBuilder.library);
}
if (extensionTearOff != null) {
_buildExtensionTearOff(libraryBuilder, parent);
}
}
return _procedure;
}
/// Creates a top level function that creates a tear off of an extension
/// instance method.
///
/// For this declaration
///
/// extension E<T> on A<T> {
/// X method<S>(S s, Y y) {}
/// }
///
/// we create the top level function
///
/// X E|method<T, S>(A<T> #this, S s, Y y) {}
///
/// and the tear off function
///
/// X Function<S>(S, Y) E|get#method<T>(A<T> #this) {
/// return (S s, Y y) => E|method<T, S>(#this, s, y);
/// }
///
void _buildExtensionTearOff(
SourceLibraryBuilder libraryBuilder, ExtensionBuilder extensionBuilder) {
assert(
_extensionTearOff != null, "No extension tear off created for $this.");
if (_extensionTearOff.name != null) return;
_extensionTearOffParameterMap = {};
int fileOffset = _procedure.fileOffset;
int extensionTypeParameterCount =
extensionBuilder.typeParameters?.length ?? 0;
List<TypeParameter> typeParameters = <TypeParameter>[];
Map<TypeParameter, DartType> substitutionMap = {};
List<DartType> typeArguments = <DartType>[];
for (TypeParameter typeParameter in function.typeParameters) {
TypeParameter newTypeParameter = new TypeParameter(typeParameter.name);
typeParameters.add(newTypeParameter);
typeArguments.add(substitutionMap[typeParameter] =
new TypeParameterType(newTypeParameter));
}
List<TypeParameter> tearOffTypeParameters = <TypeParameter>[];
List<TypeParameter> closureTypeParameters = <TypeParameter>[];
Substitution substitution = Substitution.fromMap(substitutionMap);
for (int index = 0; index < typeParameters.length; index++) {
TypeParameter newTypeParameter = typeParameters[index];
newTypeParameter.bound =
substitution.substituteType(function.typeParameters[index].bound);
newTypeParameter.defaultType = function.typeParameters[index].defaultType;
if (index < extensionTypeParameterCount) {
tearOffTypeParameters.add(newTypeParameter);
} else {
closureTypeParameters.add(newTypeParameter);
}
}
VariableDeclaration copyParameter(
VariableDeclaration parameter, DartType type,
{bool isOptional}) {
VariableDeclaration newParameter = new VariableDeclaration(parameter.name,
type: type, isFinal: parameter.isFinal)
..fileOffset = parameter.fileOffset;
_extensionTearOffParameterMap[parameter] = newParameter;
return newParameter;
}
VariableDeclaration extensionThis = copyParameter(
function.positionalParameters.first,
substitution.substituteType(function.positionalParameters.first.type),
isOptional: false);
DartType closureReturnType =
substitution.substituteType(function.returnType);
List<VariableDeclaration> closurePositionalParameters = [];
List<Expression> closurePositionalArguments = [];
for (int position = 0;
position < function.positionalParameters.length;
position++) {
VariableDeclaration parameter = function.positionalParameters[position];
if (position == 0) {
/// Pass `this` as a captured variable.
closurePositionalArguments
.add(new VariableGet(extensionThis)..fileOffset = fileOffset);
} else {
DartType type = substitution.substituteType(parameter.type);
VariableDeclaration newParameter = copyParameter(parameter, type,
isOptional: position >= function.requiredParameterCount);
closurePositionalParameters.add(newParameter);
closurePositionalArguments
.add(new VariableGet(newParameter)..fileOffset = fileOffset);
}
}
List<VariableDeclaration> closureNamedParameters = [];
List<NamedExpression> closureNamedArguments = [];
for (VariableDeclaration parameter in function.namedParameters) {
DartType type = substitution.substituteType(parameter.type);
VariableDeclaration newParameter =
copyParameter(parameter, type, isOptional: true);
closureNamedParameters.add(newParameter);
closureNamedArguments.add(new NamedExpression(parameter.name,
new VariableGet(newParameter)..fileOffset = fileOffset));
}
Statement closureBody = new ReturnStatement(
new StaticInvocation(
_procedure,
new Arguments(closurePositionalArguments,
types: typeArguments, named: closureNamedArguments))
..fileOffset = fileOffset)
..fileOffset = fileOffset;
FunctionExpression closure = new FunctionExpression(new FunctionNode(
closureBody,
typeParameters: closureTypeParameters,
positionalParameters: closurePositionalParameters,
namedParameters: closureNamedParameters,
requiredParameterCount: _procedure.function.requiredParameterCount - 1,
returnType: closureReturnType,
asyncMarker: _procedure.function.asyncMarker,
dartAsyncMarker: _procedure.function.dartAsyncMarker))
..fileOffset = fileOffset;
_extensionTearOff
..name = new Name(
'${extensionBuilder.name}|get#${name}', libraryBuilder.library)
..function = new FunctionNode(
new ReturnStatement(closure)..fileOffset = fileOffset,
typeParameters: tearOffTypeParameters,
positionalParameters: [extensionThis],
requiredParameterCount: 1,
returnType: closure.function.functionType)
..fileUri = fileUri
..fileOffset = fileOffset;
_extensionTearOff.function.parent = _extensionTearOff;
}
@override
VariableDeclaration getExtensionTearOffParameter(int index) {
if (_extensionTearOffParameterMap != null) {
return _extensionTearOffParameterMap[getFormalParameter(index)];
}
return null;
}
/// The [Procedure] built by this builder.
Procedure get procedure => isPatch ? origin.procedure : _procedure;
/// If this is an extension instance method then [_extensionTearOff] holds
/// the synthetically created tear off function.
Procedure get extensionTearOff {
if (isExtensionInstanceMember && kind == ProcedureKind.Method) {
_extensionTearOff ??= new Procedure(null, ProcedureKind.Method, null,
isStatic: true, isExtensionMember: true);
}
return _extensionTearOff;
}
Member get member => procedure;
@override
int finishPatch() {
if (!isPatch) return 0;
// TODO(ahe): restore file-offset once we track both origin and patch file
// URIs. See https://github.com/dart-lang/sdk/issues/31579
origin.procedure.fileUri = fileUri;
origin.procedure.startFileOffset = _procedure.startFileOffset;
origin.procedure.fileOffset = _procedure.fileOffset;
origin.procedure.fileEndOffset = _procedure.fileEndOffset;
origin.procedure.annotations
.forEach((m) => m.fileOffset = _procedure.fileOffset);
origin.procedure.isAbstract = _procedure.isAbstract;
origin.procedure.isExternal = _procedure.isExternal;
origin.procedure.function = _procedure.function;
origin.procedure.function.parent = origin.procedure;
return 1;
}
@override
void becomeNative(Loader loader) {
_procedure.isExternal = true;
super.becomeNative(loader);
}
@override
void applyPatch(Builder patch) {
if (patch is ProcedureBuilder) {
if (checkPatch(patch)) {
patch.actualOrigin = this;
if (retainDataForTesting) {
patchForTesting = patch;
}
}
} else {
reportPatchMismatch(patch);
}
}
}
// TODO(ahe): Move this to own file?
class ConstructorBuilder extends FunctionBuilder {
final Constructor _constructor;
final int charOpenParenOffset;
bool hasMovedSuperInitializer = false;
SuperInitializer superInitializer;
RedirectingInitializer redirectingInitializer;
Token beginInitializers;
@override
ConstructorBuilder actualOrigin;
ConstructorBuilder patchForTesting;
Constructor get actualConstructor => _constructor;
ConstructorBuilder(
List<MetadataBuilder> metadata,
int modifiers,
TypeBuilder returnType,
String name,
List<TypeVariableBuilder> typeVariables,
List<FormalParameterBuilder> formals,
SourceLibraryBuilder compilationUnit,
int startCharOffset,
int charOffset,
this.charOpenParenOffset,
int charEndOffset,
[String nativeMethodName])
: _constructor = new Constructor(null, fileUri: compilationUnit?.fileUri)
..startFileOffset = startCharOffset
..fileOffset = charOffset
..fileEndOffset = charEndOffset,
super(metadata, modifiers, returnType, name, typeVariables, formals,
compilationUnit, charOffset, nativeMethodName);
@override
ConstructorBuilder get origin => actualOrigin ?? this;
@override
bool get isDeclarationInstanceMember => false;
@override
bool get isClassInstanceMember => false;
bool get isConstructor => true;
AsyncMarker get asyncModifier => AsyncMarker.Sync;
ProcedureKind get kind => null;
bool get isRedirectingGenerativeConstructor {
return isRedirectingGenerativeConstructorImplementation(_constructor);
}
bool get isEligibleForTopLevelInference {
if (formals != null) {
for (FormalParameterBuilder formal in formals) {
if (formal.type == null && formal.isInitializingFormal) return true;
}
}
return false;
}
Member build(SourceLibraryBuilder libraryBuilder) {
if (_constructor.name == null) {
_constructor.function = buildFunction(libraryBuilder);
_constructor.function.parent = _constructor;
_constructor.function.fileOffset = charOpenParenOffset;
_constructor.function.fileEndOffset = _constructor.fileEndOffset;
_constructor.function.typeParameters = const <TypeParameter>[];
_constructor.isConst = isConst;
_constructor.isExternal = isExternal;
_constructor.name = new Name(name, libraryBuilder.library);
}
if (isEligibleForTopLevelInference) {
for (FormalParameterBuilder formal in formals) {
if (formal.type == null && formal.isInitializingFormal) {
formal.variable.type = null;
}
}
libraryBuilder.loader.typeInferenceEngine.toBeInferred[_constructor] =
libraryBuilder;
}
return _constructor;
}
@override
void buildOutlineExpressions(LibraryBuilder library) {
super.buildOutlineExpressions(library);
// For modular compilation purposes we need to include initializers
// for const constructors into the outline.
if (isConst && beginInitializers != null) {
ClassBuilder classBuilder = parent;
BodyBuilder bodyBuilder = library.loader
.createBodyBuilderForOutlineExpression(
library, classBuilder, this, classBuilder.scope, fileUri);
bodyBuilder.constantContext = ConstantContext.required;
bodyBuilder.parseInitializers(beginInitializers);
bodyBuilder.resolveRedirectingFactoryTargets();
}
beginInitializers = null;
}
FunctionNode buildFunction(LibraryBuilder library) {
// According to the specification §9.3 the return type of a constructor
// function is its enclosing class.
FunctionNode functionNode = super.buildFunction(library);
ClassBuilder enclosingClassBuilder = parent;
Class enclosingClass = enclosingClassBuilder.cls;
List<DartType> typeParameterTypes = new List<DartType>();
for (int i = 0; i < enclosingClass.typeParameters.length; i++) {
TypeParameter typeParameter = enclosingClass.typeParameters[i];
typeParameterTypes.add(new TypeParameterType(typeParameter));
}
functionNode.returnType =
new InterfaceType(enclosingClass, typeParameterTypes);
return functionNode;
}
/// The [Constructor] built by this builder.
Constructor get constructor => isPatch ? origin.constructor : _constructor;
Member get member => constructor;
void injectInvalidInitializer(
Message message, int charOffset, ExpressionGeneratorHelper helper) {
List<Initializer> initializers = _constructor.initializers;
Initializer lastInitializer = initializers.removeLast();
assert(lastInitializer == superInitializer ||
lastInitializer == redirectingInitializer);
Initializer error = helper.buildInvalidInitializer(
helper.buildProblem(message, charOffset, noLength));
initializers.add(error..parent = _constructor);
initializers.add(lastInitializer);
}
void addInitializer(
Initializer initializer, ExpressionGeneratorHelper helper) {
List<Initializer> initializers = _constructor.initializers;
if (initializer is SuperInitializer) {
if (superInitializer != null || redirectingInitializer != null) {
injectInvalidInitializer(messageMoreThanOneSuperOrThisInitializer,
initializer.fileOffset, helper);
} else {
initializers.add(initializer..parent = _constructor);
superInitializer = initializer;
}
} else if (initializer is RedirectingInitializer) {
if (superInitializer != null || redirectingInitializer != null) {
injectInvalidInitializer(messageMoreThanOneSuperOrThisInitializer,
initializer.fileOffset, helper);
} else if (_constructor.initializers.isNotEmpty) {
Initializer first = _constructor.initializers.first;
Initializer error = helper.buildInvalidInitializer(helper.buildProblem(
messageThisInitializerNotAlone, first.fileOffset, noLength));
initializers.add(error..parent = _constructor);
} else {
initializers.add(initializer..parent = _constructor);
redirectingInitializer = initializer;
}
} else if (redirectingInitializer != null) {
injectInvalidInitializer(
messageThisInitializerNotAlone, initializer.fileOffset, helper);
} else if (superInitializer != null) {
injectInvalidInitializer(
messageSuperInitializerNotLast, superInitializer.fileOffset, helper);
} else {
initializers.add(initializer..parent = _constructor);
}
}
@override
int finishPatch() {
if (!isPatch) return 0;
// TODO(ahe): restore file-offset once we track both origin and patch file
// URIs. See https://github.com/dart-lang/sdk/issues/31579
origin.constructor.fileUri = fileUri;
origin.constructor.startFileOffset = _constructor.startFileOffset;
origin.constructor.fileOffset = _constructor.fileOffset;
origin.constructor.fileEndOffset = _constructor.fileEndOffset;
origin.constructor.annotations
.forEach((m) => m.fileOffset = _constructor.fileOffset);
origin.constructor.isExternal = _constructor.isExternal;
origin.constructor.function = _constructor.function;
origin.constructor.function.parent = origin.constructor;
origin.constructor.initializers = _constructor.initializers;
setParents(origin.constructor.initializers, origin.constructor);
return 1;
}
@override
void becomeNative(Loader loader) {
_constructor.isExternal = true;
super.becomeNative(loader);
}
@override
void applyPatch(Builder patch) {
if (patch is ConstructorBuilder) {
if (checkPatch(patch)) {
patch.actualOrigin = this;
if (retainDataForTesting) {
patchForTesting = patch;
}
}
} else {
reportPatchMismatch(patch);
}
}
void prepareInitializers() {
// For const constructors we parse initializers already at the outlining
// stage, there is no easy way to make body building stage skip initializer
// parsing, so we simply clear parsed initializers and rebuild them
// again.
// Note: this method clears both initializers from the target Kernel node
// and internal state associated with parsing initializers.
if (constructor.isConst) {
constructor.initializers.length = 0;
redirectingInitializer = null;
superInitializer = null;
hasMovedSuperInitializer = false;
}
}
}
class RedirectingFactoryBuilder extends ProcedureBuilder {
final ConstructorReferenceBuilder redirectionTarget;
List<DartType> typeArguments;
RedirectingFactoryBuilder(
List<MetadataBuilder> metadata,
int modifiers,
TypeBuilder returnType,
String name,
List<TypeVariableBuilder> typeVariables,
List<FormalParameterBuilder> formals,
SourceLibraryBuilder compilationUnit,
int startCharOffset,
int charOffset,
int charOpenParenOffset,
int charEndOffset,
[String nativeMethodName,
this.redirectionTarget])
: super(
metadata,
modifiers,
returnType,
name,
typeVariables,
formals,
ProcedureKind.Factory,
compilationUnit,
startCharOffset,
charOffset,
charOpenParenOffset,
charEndOffset,
nativeMethodName);
@override
Statement get body => _body;
@override
void setRedirectingFactoryBody(Member target, List<DartType> typeArguments) {
if (_body != null) {
unexpected("null", "${_body.runtimeType}", charOffset, fileUri);
}
// Ensure that constant factories only have constant targets/bodies.
if (isConst && !target.isConst) {
library.addProblem(messageConstFactoryRedirectionToNonConst, charOffset,
noLength, fileUri);
}
_body = new RedirectingFactoryBody(target, typeArguments);
function.body = _body;
_body?.parent = function;
if (isPatch) {
if (function.typeParameters != null) {
Map<TypeParameter, DartType> substitution = <TypeParameter, DartType>{};
for (int i = 0; i < function.typeParameters.length; i++) {
substitution[function.typeParameters[i]] =
new TypeParameterType(actualOrigin.function.typeParameters[i]);
}
List<DartType> newTypeArguments =
new List<DartType>(typeArguments.length);
for (int i = 0; i < newTypeArguments.length; i++) {
newTypeArguments[i] = substitute(typeArguments[i], substitution);
}
typeArguments = newTypeArguments;
}
actualOrigin.setRedirectingFactoryBody(target, typeArguments);
}
}
@override
Procedure build(SourceLibraryBuilder library) {
Procedure result = super.build(library);
result.isRedirectingFactoryConstructor = true;
if (redirectionTarget.typeArguments != null) {
typeArguments =
new List<DartType>(redirectionTarget.typeArguments.length);
for (int i = 0; i < typeArguments.length; i++) {
typeArguments[i] = redirectionTarget.typeArguments[i].build(library);
}
}
return result;
}
@override
int finishPatch() {
if (!isPatch) return 0;
super.finishPatch();
if (origin is RedirectingFactoryBuilder) {
RedirectingFactoryBuilder redirectingOrigin = origin;
redirectingOrigin.typeArguments = typeArguments;
}
return 1;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/library_builder.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 fasta.library_builder;
import 'package:kernel/ast.dart' show Library, Nullability;
import '../combinator.dart' show Combinator;
import '../problems.dart' show internalProblem, unsupported;
import '../export.dart' show Export;
import '../loader.dart' show Loader;
import '../messages.dart'
show
FormattedMessage,
LocatedMessage,
Message,
templateInternalProblemConstructorNotFound,
templateInternalProblemNotFoundIn,
templateInternalProblemPrivateConstructorAccess;
import '../severity.dart' show Severity;
import 'builder.dart'
show
ClassBuilder,
Builder,
FieldBuilder,
MemberBuilder,
ModifierBuilder,
NameIterator,
NullabilityBuilder,
PrefixBuilder,
Scope,
ScopeBuilder,
TypeBuilder;
import 'declaration.dart';
import 'modifier_builder.dart';
abstract class LibraryBuilder implements ModifierBuilder {
Scope get scope;
Scope get exportScope;
ScopeBuilder get scopeBuilder;
ScopeBuilder get exportScopeBuilder;
List<Export> get exporters;
LibraryBuilder partOfLibrary;
bool mayImplementRestrictedTypes;
// Deliberately unrelated return type to statically detect more accidental
// use until Builder.target is fully retired.
@override
UnrelatedTarget get target;
/// Set the langauge version to a specific non-null major and minor version.
///
/// If the language version has previously been explicitly set set (i.e. with
/// [explicit] set to true), any subsequent call (explicit or not) should be
/// ignored.
/// Multiple calls with [explicit] set to false should be allowed though.
///
/// The main idea is that the .packages file specifies a default language
/// version, but that the library can have source code that specifies another
/// one which should be supported, but specifying several in code should not
/// change anything.
///
/// [offset] and [length] refers to the offset and length of the source code
/// specifying the language version.
void setLanguageVersion(int major, int minor,
{int offset: 0, int length, bool explicit});
bool get isPart;
Loader get loader;
/// Returns the [Library] built by this builder.
Library get library;
/// Returns the import uri for the library.
///
/// This is the canonical uri for the library, for instance 'dart:core'.
Uri get uri;
Iterator<Builder> get iterator;
NameIterator get nameIterator;
Builder addBuilder(String name, Builder declaration, int charOffset);
void addExporter(
LibraryBuilder exporter, List<Combinator> combinators, int charOffset);
/// Add a problem with a severity determined by the severity of the message.
///
/// If [fileUri] is null, it defaults to `this.fileUri`.
///
/// See `Loader.addMessage` for an explanation of the
/// arguments passed to this method.
FormattedMessage addProblem(
Message message, int charOffset, int length, Uri fileUri,
{bool wasHandled: false,
List<LocatedMessage> context,
Severity severity,
bool problemOnLibrary: false});
/// Returns true if the export scope was modified.
bool addToExportScope(String name, Builder member, [int charOffset = -1]);
void addToScope(String name, Builder member, int charOffset, bool isImport);
Builder computeAmbiguousDeclaration(
String name, Builder declaration, Builder other, int charOffset,
{bool isExport: false, bool isImport: false});
int finishDeferredLoadTearoffs();
int finishForwarders();
int finishNativeMethods();
int finishPatchMethods();
/// Looks up [constructorName] in the class named [className].
///
/// The class is looked up in this library's export scope unless
/// [bypassLibraryPrivacy] is true, in which case it is looked up in the
/// library scope of this library.
///
/// It is an error if no such class is found, or if the class doesn't have a
/// matching constructor (or factory).
///
/// If [constructorName] is null or the empty string, it's assumed to be an
/// unnamed constructor. it's an error if [constructorName] starts with
/// `"_"`, and [bypassLibraryPrivacy] is false.
MemberBuilder getConstructor(String className,
{String constructorName, bool bypassLibraryPrivacy: false});
int finishTypeVariables(ClassBuilder object, TypeBuilder dynamicType);
/// This method instantiates type parameters to their bounds in some cases
/// where they were omitted by the programmer and not provided by the type
/// inference. The method returns the number of distinct type variables
/// that were instantiated in this library.
int computeDefaultTypes(TypeBuilder dynamicType, TypeBuilder bottomType,
ClassBuilder objectClass);
void becomeCoreLibrary();
void addSyntheticDeclarationOfDynamic();
/// Lookups the member [name] declared in this library.
///
/// If [required] is `true` and no member is found an internal problem is
/// reported.
Builder lookupLocalMember(String name, {bool required: false});
Builder lookup(String name, int charOffset, Uri fileUri);
/// If this is a patch library, apply its patches to [origin].
void applyPatches();
void recordAccess(int charOffset, int length, Uri fileUri);
void buildOutlineExpressions();
List<FieldBuilder> takeImplicitlyTypedFields();
bool get isNonNullableByDefault;
Nullability get nullable;
Nullability get nonNullable;
Nullability nullableIfTrue(bool isNullable);
NullabilityBuilder get nullableBuilder;
NullabilityBuilder get nonNullableBuilder;
NullabilityBuilder nullableBuilderIfTrue(bool isNullable);
}
abstract class LibraryBuilderImpl extends ModifierBuilderImpl
implements LibraryBuilder {
@override
final Scope scope;
@override
final Scope exportScope;
@override
final ScopeBuilder scopeBuilder;
@override
final ScopeBuilder exportScopeBuilder;
@override
final List<Export> exporters = <Export>[];
@override
LibraryBuilder partOfLibrary;
@override
bool mayImplementRestrictedTypes = false;
LibraryBuilderImpl(Uri fileUri, this.scope, this.exportScope)
: scopeBuilder = new ScopeBuilder(scope),
exportScopeBuilder = new ScopeBuilder(exportScope),
super(null, -1, fileUri);
@override
bool get isSynthetic => false;
// Deliberately unrelated return type to statically detect more accidental
// use until Builder.target is fully retired.
@override
UnrelatedTarget get target => unsupported(
"LibraryBuilder.target is deprecated. "
"Use LibraryBuilder.library instead.",
charOffset,
fileUri);
/// Set the langauge version to a specific non-null major and minor version.
///
/// If the language version has previously been explicitly set set (i.e. with
/// [explicit] set to true), any subsequent call (explicit or not) should be
/// ignored.
/// Multiple calls with [explicit] set to false should be allowed though.
///
/// The main idea is that the .packages file specifies a default language
/// version, but that the library can have source code that specifies another
/// one which should be supported, but specifying several in code should not
/// change anything.
///
/// [offset] and [length] refers to the offset and length of the source code
/// specifying the language version.
@override
void setLanguageVersion(int major, int minor,
{int offset: 0, int length, bool explicit});
@override
Builder get parent => null;
@override
bool get isPart => false;
@override
String get debugName => "LibraryBuilder";
@override
Loader get loader;
@override
int get modifiers => 0;
@override
Uri get uri;
@override
Iterator<Builder> get iterator {
return new LibraryLocalDeclarationIterator(this);
}
@override
NameIterator get nameIterator {
return new LibraryLocalDeclarationNameIterator(this);
}
@override
void addExporter(
LibraryBuilder exporter, List<Combinator> combinators, int charOffset) {
exporters.add(new Export(exporter, this, combinators, charOffset));
}
@override
FormattedMessage addProblem(
Message message, int charOffset, int length, Uri fileUri,
{bool wasHandled: false,
List<LocatedMessage> context,
Severity severity,
bool problemOnLibrary: false}) {
fileUri ??= this.fileUri;
return loader.addProblem(message, charOffset, length, fileUri,
wasHandled: wasHandled,
context: context,
severity: severity,
problemOnLibrary: true);
}
@override
bool addToExportScope(String name, Builder member, [int charOffset = -1]) {
if (name.startsWith("_")) return false;
if (member is PrefixBuilder) return false;
Map<String, Builder> map =
member.isSetter ? exportScope.setters : exportScope.local;
Builder existing = map[name];
if (existing == member) return false;
if (existing != null) {
Builder result = computeAmbiguousDeclaration(
name, existing, member, charOffset,
isExport: true);
map[name] = result;
return result != existing;
} else {
map[name] = member;
}
return true;
}
@override
int finishDeferredLoadTearoffs() => 0;
@override
int finishForwarders() => 0;
@override
int finishNativeMethods() => 0;
@override
int finishPatchMethods() => 0;
@override
MemberBuilder getConstructor(String className,
{String constructorName, bool bypassLibraryPrivacy: false}) {
constructorName ??= "";
if (constructorName.startsWith("_") && !bypassLibraryPrivacy) {
return internalProblem(
templateInternalProblemPrivateConstructorAccess
.withArguments(constructorName),
-1,
null);
}
Builder cls = (bypassLibraryPrivacy ? scope : exportScope)
.lookup(className, -1, null);
if (cls is ClassBuilder) {
// TODO(ahe): This code is similar to code in `endNewExpression` in
// `body_builder.dart`, try to share it.
MemberBuilder constructor =
cls.findConstructorOrFactory(constructorName, -1, null, this);
if (constructor == null) {
// Fall-through to internal error below.
} else if (constructor.isConstructor) {
if (!cls.isAbstract) {
return constructor;
}
} else if (constructor.isFactory) {
return constructor;
}
}
throw internalProblem(
templateInternalProblemConstructorNotFound.withArguments(
"$className.$constructorName", uri),
-1,
null);
}
@override
int finishTypeVariables(ClassBuilder object, TypeBuilder dynamicType) => 0;
@override
int computeDefaultTypes(TypeBuilder dynamicType, TypeBuilder bottomType,
ClassBuilder objectClass) {
return 0;
}
@override
void becomeCoreLibrary() {
if (scope.local["dynamic"] == null) {
addSyntheticDeclarationOfDynamic();
}
}
@override
Builder lookupLocalMember(String name, {bool required: false}) {
Builder builder = scope.local[name];
if (required && builder == null) {
internalProblem(
templateInternalProblemNotFoundIn.withArguments(
name, fullNameForErrors),
-1,
null);
}
return builder;
}
@override
Builder lookup(String name, int charOffset, Uri fileUri) {
return scope.lookup(name, charOffset, fileUri);
}
@override
void applyPatches() {
if (!isPatch) return;
unsupported("${runtimeType}.applyPatches", -1, fileUri);
}
@override
void recordAccess(int charOffset, int length, Uri fileUri) {}
@override
void buildOutlineExpressions() {}
@override
List<FieldBuilder> takeImplicitlyTypedFields() => null;
// TODO(38287): Compute the predicate using the library version instead.
@override
bool get isNonNullableByDefault => loader.target.enableNonNullable;
@override
Nullability get nullable {
return isNonNullableByDefault ? Nullability.nullable : Nullability.legacy;
}
@override
Nullability get nonNullable {
return isNonNullableByDefault
? Nullability.nonNullable
: Nullability.legacy;
}
@override
Nullability nullableIfTrue(bool isNullable) {
if (isNonNullableByDefault) {
return isNullable ? Nullability.nullable : Nullability.nonNullable;
}
return Nullability.legacy;
}
@override
NullabilityBuilder get nullableBuilder {
return isNonNullableByDefault
? const NullabilityBuilder.nullable()
: const NullabilityBuilder.omitted();
}
@override
NullabilityBuilder get nonNullableBuilder {
return const NullabilityBuilder.omitted();
}
@override
NullabilityBuilder nullableBuilderIfTrue(bool isNullable) {
return isNullable
? const NullabilityBuilder.nullable()
: const NullabilityBuilder.omitted();
}
}
class LibraryLocalDeclarationIterator implements Iterator<Builder> {
final LibraryBuilder library;
final Iterator<Builder> iterator;
LibraryLocalDeclarationIterator(this.library)
: iterator = library.scope.iterator;
Builder get current => iterator.current;
bool moveNext() {
while (iterator.moveNext()) {
if (current.parent == library) return true;
}
return false;
}
}
class LibraryLocalDeclarationNameIterator implements NameIterator {
final LibraryBuilder library;
final NameIterator iterator;
LibraryLocalDeclarationNameIterator(this.library)
: iterator = library.scope.nameIterator;
Builder get current => iterator.current;
String get name => iterator.name;
bool moveNext() {
while (iterator.moveNext()) {
if (current.parent == library) return true;
}
return false;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/constructor_reference_builder.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 fasta.constructor_reference_builder;
import '../messages.dart' show noLength, templateConstructorNotFound;
import 'builder.dart'
show
ClassBuilder,
Builder,
LibraryBuilder,
PrefixBuilder,
QualifiedName,
Scope,
TypeBuilder,
flattenName;
class ConstructorReferenceBuilder {
final int charOffset;
final Uri fileUri;
final Object name;
final List<TypeBuilder> typeArguments;
/// This is the name of a named constructor. As `bar` in `new Foo<T>.bar()`.
final String suffix;
Builder target;
ConstructorReferenceBuilder(this.name, this.typeArguments, this.suffix,
Builder parent, this.charOffset)
: fileUri = parent.fileUri;
String get fullNameForErrors {
return "${flattenName(name, charOffset, fileUri)}"
"${suffix == null ? '' : '.$suffix'}";
}
void resolveIn(Scope scope, LibraryBuilder accessingLibrary) {
final Object name = this.name;
Builder declaration;
if (name is QualifiedName) {
String prefix = name.qualifier;
String middle = name.name;
declaration = scope.lookup(prefix, charOffset, fileUri);
if (declaration is PrefixBuilder) {
PrefixBuilder prefix = declaration;
declaration = prefix.lookup(middle, name.charOffset, fileUri);
} else if (declaration is ClassBuilder) {
ClassBuilder cls = declaration;
declaration = cls.findConstructorOrFactory(
middle, name.charOffset, fileUri, accessingLibrary);
if (suffix == null) {
target = declaration;
return;
}
}
} else {
declaration = scope.lookup(name, charOffset, fileUri);
}
if (declaration is ClassBuilder) {
target = declaration.findConstructorOrFactory(
suffix ?? "", charOffset, fileUri, accessingLibrary);
}
if (target == null) {
accessingLibrary.addProblem(
templateConstructorNotFound.withArguments(fullNameForErrors),
charOffset,
noLength,
fileUri);
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/class_builder.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 fasta.class_builder;
import 'package:kernel/ast.dart'
show
Arguments,
AsExpression,
Class,
Constructor,
DartType,
DynamicType,
Expression,
Field,
FunctionNode,
InterfaceType,
InvalidType,
ListLiteral,
Member,
MethodInvocation,
Name,
Nullability,
Procedure,
ProcedureKind,
RedirectingFactoryConstructor,
ReturnStatement,
StaticGet,
Supertype,
ThisExpression,
TypeParameter,
TypeParameterType,
VariableDeclaration,
VoidType;
import 'package:kernel/ast.dart' show FunctionType, TypeParameterType;
import 'package:kernel/class_hierarchy.dart' show ClassHierarchy;
import 'package:kernel/clone.dart' show CloneWithoutBody;
import 'package:kernel/core_types.dart' show CoreTypes;
import 'package:kernel/src/bounds_checks.dart'
show TypeArgumentIssue, findTypeArgumentIssues, getGenericTypeName;
import 'package:kernel/text/text_serialization_verifier.dart';
import 'package:kernel/type_algebra.dart' show Substitution, substitute;
import 'package:kernel/type_algebra.dart' as type_algebra
show getSubstitutionMap;
import 'package:kernel/type_environment.dart'
show SubtypeCheckMode, TypeEnvironment;
import '../../base/common.dart';
import '../dill/dill_member_builder.dart' show DillMemberBuilder;
import 'builder.dart'
show
ConstructorReferenceBuilder,
Builder,
LibraryBuilder,
MemberBuilder,
MetadataBuilder,
NullabilityBuilder,
Scope,
ScopeBuilder,
TypeBuilder,
TypeVariableBuilder;
import 'declaration.dart';
import 'declaration_builder.dart';
import '../fasta_codes.dart'
show
LocatedMessage,
Message,
messageGenericFunctionTypeUsedAsActualTypeArgument,
messageImplementsFutureOr,
messagePatchClassOrigin,
messagePatchClassTypeVariablesMismatch,
messagePatchDeclarationMismatch,
messagePatchDeclarationOrigin,
noLength,
templateDuplicatedDeclarationUse,
templateGenericFunctionTypeInferredAsActualTypeArgument,
templateImplementsRepeated,
templateImplementsSuperClass,
templateImplicitMixinOverride,
templateIncompatibleRedirecteeFunctionType,
templateIncorrectTypeArgument,
templateIncorrectTypeArgumentInSupertype,
templateIncorrectTypeArgumentInSupertypeInferred,
templateInterfaceCheck,
templateInternalProblemNotFoundIn,
templateMixinApplicationIncompatibleSupertype,
templateNamedMixinOverride,
templateOverriddenMethodCause,
templateOverrideFewerNamedArguments,
templateOverrideFewerPositionalArguments,
templateOverrideMismatchNamedParameter,
templateOverrideMoreRequiredArguments,
templateOverrideTypeMismatchParameter,
templateOverrideTypeMismatchReturnType,
templateOverrideTypeMismatchSetter,
templateOverrideTypeVariablesMismatch,
templateRedirectingFactoryIncompatibleTypeArgument,
templateRedirectionTargetNotFound,
templateTypeArgumentMismatch;
import '../kernel/kernel_builder.dart'
show
ConstructorReferenceBuilder,
Builder,
FunctionBuilder,
NamedTypeBuilder,
LibraryBuilder,
MemberBuilder,
MetadataBuilder,
ProcedureBuilder,
RedirectingFactoryBuilder,
Scope,
TypeBuilder,
TypeVariableBuilder;
import '../kernel/redirecting_factory_body.dart'
show getRedirectingFactoryBody, RedirectingFactoryBody;
import '../kernel/kernel_target.dart' show KernelTarget;
import '../kernel/types.dart' show Types;
import '../names.dart' show noSuchMethodName;
import '../problems.dart'
show internalProblem, unexpected, unhandled, unimplemented, unsupported;
import '../scope.dart' show AmbiguousBuilder;
import '../source/source_library_builder.dart' show SourceLibraryBuilder;
import '../type_inference/type_schema.dart' show UnknownType;
abstract class ClassBuilder implements DeclarationBuilder {
/// The type variables declared on a class, extension or mixin declaration.
List<TypeVariableBuilder> typeVariables;
/// The type in the `extends` clause of a class declaration.
///
/// Currently this also holds the synthesized super class for a mixin
/// declaration.
TypeBuilder supertype;
/// The type in the `implements` clause of a class or mixin declaration.
List<TypeBuilder> interfaces;
/// The types in the `on` clause of an extension or mixin declaration.
List<TypeBuilder> onTypes;
Scope get constructors;
ScopeBuilder get constructorScopeBuilder;
Map<String, ConstructorRedirection> redirectingConstructors;
ClassBuilder actualOrigin;
ClassBuilder patchForTesting;
TypeBuilder get mixedInType;
void set mixedInType(TypeBuilder mixin);
List<ConstructorReferenceBuilder> get constructorReferences;
void buildOutlineExpressions(LibraryBuilder library);
/// Registers a constructor redirection for this class and returns true if
/// this redirection gives rise to a cycle that has not been reported before.
bool checkConstructorCyclic(String source, String target);
Builder findConstructorOrFactory(
String name, int charOffset, Uri uri, LibraryBuilder accessingLibrary);
void forEach(void f(String name, Builder builder));
@override
Builder lookupLocalMember(String name,
{bool setter: false, bool required: false});
/// Find the first member of this class with [name]. This method isn't
/// suitable for scope lookups as it will throw an error if the name isn't
/// declared. The [scope] should be used for that. This method is used to
/// find a member that is known to exist and it will pick the first
/// declaration if the name is ambiguous.
///
/// For example, this method is convenient for use when building synthetic
/// members, such as those of an enum.
MemberBuilder firstMemberNamed(String name);
/// The [Class] built by this builder.
///
/// For a patch class the origin class is returned.
Class get cls;
// Deliberately unrelated return type to statically detect more accidental
// use until Builder.target is fully retired.
UnrelatedTarget get target;
@override
ClassBuilder get origin;
Class get actualCls;
InterfaceType get legacyRawType;
InterfaceType get nullableRawType;
InterfaceType get nonNullableRawType;
InterfaceType rawType(Nullability nullability);
List<DartType> buildTypeArguments(
LibraryBuilder library, List<TypeBuilder> arguments);
Supertype buildSupertype(LibraryBuilder library, List<TypeBuilder> arguments);
Supertype buildMixedInType(
LibraryBuilder library, List<TypeBuilder> arguments);
void checkSupertypes(CoreTypes coreTypes);
void checkBoundsInSupertype(
Supertype supertype, TypeEnvironment typeEnvironment);
void checkBoundsInOutline(TypeEnvironment typeEnvironment);
void addRedirectingConstructor(
ProcedureBuilder constructorBuilder, SourceLibraryBuilder library);
void handleSeenCovariant(
Types types,
Member declaredMember,
Member interfaceMember,
bool isSetter,
callback(Member declaredMember, Member interfaceMember, bool isSetter));
void checkOverride(
Types types,
Member declaredMember,
Member interfaceMember,
bool isSetter,
callback(Member declaredMember, Member interfaceMember, bool isSetter),
{bool isInterfaceCheck = false});
void checkOverrides(
ClassHierarchy hierarchy, TypeEnvironment typeEnvironment);
void checkAbstractMembers(CoreTypes coreTypes, ClassHierarchy hierarchy,
TypeEnvironment typeEnvironment);
bool hasUserDefinedNoSuchMethod(
Class klass, ClassHierarchy hierarchy, Class objectClass);
void transformProcedureToNoSuchMethodForwarder(
Member noSuchMethodInterface, KernelTarget target, Procedure procedure);
void addNoSuchMethodForwarderForProcedure(Member noSuchMethod,
KernelTarget target, Procedure procedure, ClassHierarchy hierarchy);
void addNoSuchMethodForwarderGetterForField(Member noSuchMethod,
KernelTarget target, Field field, ClassHierarchy hierarchy);
void addNoSuchMethodForwarderSetterForField(Member noSuchMethod,
KernelTarget target, Field field, ClassHierarchy hierarchy);
/// Adds noSuchMethod forwarding stubs to this class. Returns `true` if the
/// class was modified.
bool addNoSuchMethodForwarders(KernelTarget target, ClassHierarchy hierarchy);
/// Returns whether a covariant parameter was seen and more methods thus have
/// to be checked.
bool checkMethodOverride(Types types, Procedure declaredMember,
Procedure interfaceMember, bool isInterfaceCheck);
void checkGetterOverride(Types types, Member declaredMember,
Member interfaceMember, bool isInterfaceCheck);
/// Returns whether a covariant parameter was seen and more methods thus have
/// to be checked.
bool checkSetterOverride(Types types, Member declaredMember,
Member interfaceMember, bool isInterfaceCheck);
// When the overriding member is inherited, report the class containing
// the conflict as the main error.
void reportInvalidOverride(bool isInterfaceCheck, Member declaredMember,
Message message, int fileOffset, int length,
{List<LocatedMessage> context});
void checkMixinApplication(ClassHierarchy hierarchy);
// Computes the function type of a given redirection target. Returns [null] if
// the type of the target could not be computed.
FunctionType computeRedirecteeType(
RedirectingFactoryBuilder factory, TypeEnvironment typeEnvironment);
String computeRedirecteeName(ConstructorReferenceBuilder redirectionTarget);
void checkRedirectingFactory(
RedirectingFactoryBuilder factory, TypeEnvironment typeEnvironment);
void checkRedirectingFactories(TypeEnvironment typeEnvironment);
/// Returns a map which maps the type variables of [superclass] to their
/// respective values as defined by the superclass clause of this class (and
/// its superclasses).
///
/// It's assumed that [superclass] is a superclass of this class.
///
/// For example, given:
///
/// class Box<T> {}
/// class BeatBox extends Box<Beat> {}
/// class Beat {}
///
/// We have:
///
/// [[BeatBox]].getSubstitutionMap([[Box]]) -> {[[Box::T]]: Beat]]}.
///
/// It's an error if [superclass] isn't a superclass.
Map<TypeParameter, DartType> getSubstitutionMap(Class superclass);
/// Looks up the member by [name] on the class built by this class builder.
///
/// If [isSetter] is `false`, only fields, methods, and getters with that name
/// will be found. If [isSetter] is `true`, only non-final fields and setters
/// will be found.
///
/// If [isSuper] is `false`, the member is found among the interface members
/// the class built by this class builder. If [isSuper] is `true`, the member
/// is found among the class members of the superclass.
///
/// If this class builder is a patch, interface members declared in this
/// patch are searched before searching the interface members in the origin
/// class.
Member lookupInstanceMember(ClassHierarchy hierarchy, Name name,
{bool isSetter: false, bool isSuper: false});
/// Looks up the constructor by [name] on the the class built by this class
/// builder.
///
/// If [isSuper] is `true`, constructors in the superclass are searched.
Constructor lookupConstructor(Name name, {bool isSuper: false});
}
abstract class ClassBuilderImpl extends DeclarationBuilderImpl
implements ClassBuilder {
@override
List<TypeVariableBuilder> typeVariables;
@override
TypeBuilder supertype;
@override
List<TypeBuilder> interfaces;
@override
List<TypeBuilder> onTypes;
@override
final Scope constructors;
@override
final ScopeBuilder constructorScopeBuilder;
@override
Map<String, ConstructorRedirection> redirectingConstructors;
@override
ClassBuilder actualOrigin;
@override
ClassBuilder patchForTesting;
ClassBuilderImpl(
List<MetadataBuilder> metadata,
int modifiers,
String name,
this.typeVariables,
this.supertype,
this.interfaces,
this.onTypes,
Scope scope,
this.constructors,
LibraryBuilder parent,
int charOffset)
: constructorScopeBuilder = new ScopeBuilder(constructors),
super(metadata, modifiers, name, parent, charOffset, scope);
@override
String get debugName => "ClassBuilder";
@override
bool get isMixinApplication => mixedInType != null;
@override
bool get isNamedMixinApplication {
return isMixinApplication && super.isNamedMixinApplication;
}
@override
List<ConstructorReferenceBuilder> get constructorReferences => null;
@override
void buildOutlineExpressions(LibraryBuilder library) {
void build(String ignore, Builder declaration) {
MemberBuilder member = declaration;
member.buildOutlineExpressions(library);
}
MetadataBuilder.buildAnnotations(
isPatch ? origin.cls : cls, metadata, library, this, null);
constructors.forEach(build);
scope.forEach(build);
}
/// Registers a constructor redirection for this class and returns true if
/// this redirection gives rise to a cycle that has not been reported before.
bool checkConstructorCyclic(String source, String target) {
ConstructorRedirection redirect = new ConstructorRedirection(target);
redirectingConstructors ??= <String, ConstructorRedirection>{};
redirectingConstructors[source] = redirect;
while (redirect != null) {
if (redirect.cycleReported) return false;
if (redirect.target == source) {
redirect.cycleReported = true;
return true;
}
redirect = redirectingConstructors[redirect.target];
}
return false;
}
@override
int resolveConstructors(LibraryBuilder library) {
if (constructorReferences == null) return 0;
for (ConstructorReferenceBuilder ref in constructorReferences) {
ref.resolveIn(scope, library);
}
int count = constructorReferences.length;
if (count != 0) {
Map<String, MemberBuilder> constructors = this.constructors.local;
// Copy keys to avoid concurrent modification error.
List<String> names = constructors.keys.toList();
for (String name in names) {
Builder declaration = constructors[name];
do {
if (declaration.parent != this) {
unexpected("$fileUri", "${declaration.parent.fileUri}", charOffset,
fileUri);
}
if (declaration is RedirectingFactoryBuilder) {
// Compute the immediate redirection target, not the effective.
ConstructorReferenceBuilder redirectionTarget =
declaration.redirectionTarget;
if (redirectionTarget != null) {
Builder targetBuilder = redirectionTarget.target;
if (declaration.next == null) {
// Only the first one (that is, the last on in the linked list)
// is actually in the kernel tree. This call creates a StaticGet
// to [declaration.target] in a field `_redirecting#` which is
// only legal to do to things in the kernel tree.
addRedirectingConstructor(declaration, library);
}
if (targetBuilder is FunctionBuilder) {
List<DartType> typeArguments = declaration.typeArguments;
if (typeArguments == null) {
// TODO(32049) If type arguments aren't specified, they should
// be inferred. Currently, the inference is not performed.
// The code below is a workaround.
typeArguments = new List<DartType>.filled(
targetBuilder.member.enclosingClass.typeParameters.length,
const DynamicType(),
growable: true);
}
declaration.setRedirectingFactoryBody(
targetBuilder.member, typeArguments);
} else if (targetBuilder is DillMemberBuilder) {
List<DartType> typeArguments = declaration.typeArguments;
if (typeArguments == null) {
// TODO(32049) If type arguments aren't specified, they should
// be inferred. Currently, the inference is not performed.
// The code below is a workaround.
typeArguments = new List<DartType>.filled(
targetBuilder.member.enclosingClass.typeParameters.length,
const DynamicType(),
growable: true);
}
declaration.setRedirectingFactoryBody(
targetBuilder.member, typeArguments);
} else if (targetBuilder is AmbiguousBuilder) {
Message message = templateDuplicatedDeclarationUse
.withArguments(redirectionTarget.fullNameForErrors);
if (declaration.isConst) {
addProblem(message, declaration.charOffset, noLength);
} else {
addProblem(message, declaration.charOffset, noLength);
}
// CoreTypes aren't computed yet, and this is the outline
// phase. So we can't and shouldn't create a method body.
declaration.body = new RedirectingFactoryBody.unresolved(
redirectionTarget.fullNameForErrors);
} else {
Message message = templateRedirectionTargetNotFound
.withArguments(redirectionTarget.fullNameForErrors);
if (declaration.isConst) {
addProblem(message, declaration.charOffset, noLength);
} else {
addProblem(message, declaration.charOffset, noLength);
}
// CoreTypes aren't computed yet, and this is the outline
// phase. So we can't and shouldn't create a method body.
declaration.body = new RedirectingFactoryBody.unresolved(
redirectionTarget.fullNameForErrors);
}
}
}
declaration = declaration.next;
} while (declaration != null);
}
}
return count;
}
@override
Builder findStaticBuilder(
String name, int charOffset, Uri fileUri, LibraryBuilder accessingLibrary,
{bool isSetter: false}) {
if (accessingLibrary.origin != library.origin && name.startsWith("_")) {
return null;
}
Builder declaration = isSetter
? scope.lookupSetter(name, charOffset, fileUri, isInstanceScope: false)
: scope.lookup(name, charOffset, fileUri, isInstanceScope: false);
if (declaration == null && isPatch) {
return origin.findStaticBuilder(
name, charOffset, fileUri, accessingLibrary,
isSetter: isSetter);
}
return declaration;
}
@override
Builder findConstructorOrFactory(
String name, int charOffset, Uri uri, LibraryBuilder accessingLibrary) {
if (accessingLibrary.origin != library.origin && name.startsWith("_")) {
return null;
}
Builder declaration = constructors.lookup(name, charOffset, uri);
if (declaration == null && isPatch) {
return origin.findConstructorOrFactory(
name, charOffset, uri, accessingLibrary);
}
return declaration;
}
@override
void forEach(void f(String name, Builder builder)) {
scope.forEach(f);
}
@override
Builder lookupLocalMember(String name,
{bool setter: false, bool required: false}) {
Builder builder = setter ? scope.setters[name] : scope.local[name];
if (builder == null && isPatch) {
builder = setter ? origin.scope.setters[name] : origin.scope.local[name];
}
if (required && builder == null) {
internalProblem(
templateInternalProblemNotFoundIn.withArguments(
name, fullNameForErrors),
-1,
null);
}
return builder;
}
@override
MemberBuilder firstMemberNamed(String name) {
Builder declaration = lookupLocalMember(name, required: true);
while (declaration.next != null) {
declaration = declaration.next;
}
return declaration;
}
InterfaceType _legacyRawType;
InterfaceType _nullableRawType;
InterfaceType _nonNullableRawType;
// Deliberately unrelated return type to statically detect more accidental
// use until Builder.target is fully retired.
@override
UnrelatedTarget get target => unsupported(
"ClassBuilder.target is deprecated. "
"Use ClassBuilder.cls instead.",
charOffset,
fileUri);
@override
ClassBuilder get origin => actualOrigin ?? this;
@override
InterfaceType get thisType => cls.thisType;
@override
InterfaceType get legacyRawType {
// TODO(dmitryas): Use computeBound instead of DynamicType here?
return _legacyRawType ??= new InterfaceType(
cls,
new List<DartType>.filled(typeVariablesCount, const DynamicType()),
Nullability.legacy);
}
@override
InterfaceType get nullableRawType {
// TODO(dmitryas): Use computeBound instead of DynamicType here?
return _nullableRawType ??= new InterfaceType(
cls,
new List<DartType>.filled(typeVariablesCount, const DynamicType()),
Nullability.nullable);
}
@override
InterfaceType get nonNullableRawType {
// TODO(dmitryas): Use computeBound instead of DynamicType here?
return _nonNullableRawType ??= new InterfaceType(
cls,
new List<DartType>.filled(typeVariablesCount, const DynamicType()),
Nullability.nonNullable);
}
@override
InterfaceType rawType(Nullability nullability) {
switch (nullability) {
case Nullability.legacy:
return legacyRawType;
case Nullability.nullable:
return nullableRawType;
case Nullability.nonNullable:
return nonNullableRawType;
case Nullability.neither:
default:
return unhandled("$nullability", "rawType", noOffset, noUri);
}
}
@override
InterfaceType buildTypesWithBuiltArguments(LibraryBuilder library,
Nullability nullability, List<DartType> arguments) {
assert(arguments == null || cls.typeParameters.length == arguments.length);
return arguments == null
? rawType(nullability)
: new InterfaceType(cls, arguments, nullability);
}
@override
int get typeVariablesCount => typeVariables?.length ?? 0;
@override
List<DartType> buildTypeArguments(
LibraryBuilder library, List<TypeBuilder> arguments) {
if (arguments == null && typeVariables == null) {
return <DartType>[];
}
if (arguments == null && typeVariables != null) {
List<DartType> result =
new List<DartType>.filled(typeVariables.length, null, growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = typeVariables[i].defaultType.build(library);
}
if (library is SourceLibraryBuilder) {
library.inferredTypes.addAll(result);
}
return result;
}
if (arguments != null && arguments.length != typeVariablesCount) {
// That should be caught and reported as a compile-time error earlier.
return unhandled(
templateTypeArgumentMismatch
.withArguments(typeVariablesCount)
.message,
"buildTypeArguments",
-1,
null);
}
// arguments.length == typeVariables.length
List<DartType> result =
new List<DartType>.filled(arguments.length, null, growable: true);
for (int i = 0; i < result.length; ++i) {
result[i] = arguments[i].build(library);
}
return result;
}
@override
InterfaceType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments) {
return buildTypesWithBuiltArguments(
library,
nullabilityBuilder.build(library),
buildTypeArguments(library, arguments));
}
@override
Supertype buildSupertype(
LibraryBuilder library, List<TypeBuilder> arguments) {
Class cls = isPatch ? origin.cls : this.cls;
return new Supertype(cls, buildTypeArguments(library, arguments));
}
@override
Supertype buildMixedInType(
LibraryBuilder library, List<TypeBuilder> arguments) {
Class cls = isPatch ? origin.cls : this.cls;
if (arguments != null) {
return new Supertype(cls, buildTypeArguments(library, arguments));
} else {
return new Supertype(
cls,
new List<DartType>.filled(
cls.typeParameters.length, const UnknownType(),
growable: true));
}
}
@override
void checkSupertypes(CoreTypes coreTypes) {
// This method determines whether the class (that's being built) its super
// class appears both in 'extends' and 'implements' clauses and whether any
// interface appears multiple times in the 'implements' clause.
if (interfaces == null) return;
// Extract super class (if it exists).
ClassBuilder superClass;
TypeBuilder superClassType = supertype;
if (superClassType is NamedTypeBuilder) {
Builder decl = superClassType.declaration;
if (decl is ClassBuilder) {
superClass = decl;
}
}
// Validate interfaces.
Map<ClassBuilder, int> problems;
Map<ClassBuilder, int> problemsOffsets;
Set<ClassBuilder> implemented = new Set<ClassBuilder>();
for (TypeBuilder type in interfaces) {
if (type is NamedTypeBuilder) {
int charOffset = -1; // TODO(ahe): Get offset from type.
Builder decl = type.declaration;
if (decl is ClassBuilder) {
ClassBuilder interface = decl;
if (superClass == interface) {
addProblem(
templateImplementsSuperClass.withArguments(interface.name),
charOffset,
noLength);
} else if (implemented.contains(interface)) {
// Aggregate repetitions.
problems ??= new Map<ClassBuilder, int>();
problems[interface] ??= 0;
problems[interface] += 1;
problemsOffsets ??= new Map<ClassBuilder, int>();
problemsOffsets[interface] ??= charOffset;
} else if (interface.cls == coreTypes.futureOrClass) {
addProblem(messageImplementsFutureOr, charOffset,
interface.cls.name.length);
} else {
implemented.add(interface);
}
}
}
}
if (problems != null) {
problems.forEach((ClassBuilder interface, int repetitions) {
addProblem(
templateImplementsRepeated.withArguments(
interface.name, repetitions),
problemsOffsets[interface],
noLength);
});
}
}
@override
void checkBoundsInSupertype(
Supertype supertype, TypeEnvironment typeEnvironment) {
SourceLibraryBuilder library = this.library;
List<TypeArgumentIssue> issues = findTypeArgumentIssues(
new InterfaceType(supertype.classNode, supertype.typeArguments),
typeEnvironment,
allowSuperBounded: false);
if (issues != null) {
for (TypeArgumentIssue issue in issues) {
Message message;
DartType argument = issue.argument;
TypeParameter typeParameter = issue.typeParameter;
bool inferred = library.inferredTypes.contains(argument);
if (argument is FunctionType && argument.typeParameters.length > 0) {
if (inferred) {
message = templateGenericFunctionTypeInferredAsActualTypeArgument
.withArguments(argument);
} else {
message = messageGenericFunctionTypeUsedAsActualTypeArgument;
}
typeParameter = null;
} else {
if (inferred) {
message =
templateIncorrectTypeArgumentInSupertypeInferred.withArguments(
argument,
typeParameter.bound,
typeParameter.name,
getGenericTypeName(issue.enclosingType),
supertype.classNode.name,
name);
} else {
message = templateIncorrectTypeArgumentInSupertype.withArguments(
argument,
typeParameter.bound,
typeParameter.name,
getGenericTypeName(issue.enclosingType),
supertype.classNode.name,
name);
}
}
library.reportTypeArgumentIssue(
message, fileUri, charOffset, typeParameter);
}
}
}
@override
void checkBoundsInOutline(TypeEnvironment typeEnvironment) {
SourceLibraryBuilder library = this.library;
// Check in bounds of own type variables.
for (TypeParameter parameter in cls.typeParameters) {
List<TypeArgumentIssue> issues = findTypeArgumentIssues(
parameter.bound, typeEnvironment,
allowSuperBounded: true);
if (issues != null) {
for (TypeArgumentIssue issue in issues) {
DartType argument = issue.argument;
TypeParameter typeParameter = issue.typeParameter;
if (library.inferredTypes.contains(argument)) {
// Inference in type expressions in the supertypes boils down to
// instantiate-to-bound which shouldn't produce anything that breaks
// the bounds after the non-simplicity checks are done. So, any
// violation here is the result of non-simple bounds, and the error
// is reported elsewhere.
continue;
}
Message message;
if (argument is FunctionType && argument.typeParameters.length > 0) {
message = messageGenericFunctionTypeUsedAsActualTypeArgument;
typeParameter = null;
} else {
message = templateIncorrectTypeArgument.withArguments(
argument,
typeParameter.bound,
typeParameter.name,
getGenericTypeName(issue.enclosingType));
}
library.reportTypeArgumentIssue(
message, fileUri, parameter.fileOffset, typeParameter);
}
}
}
// Check in supers.
if (cls.supertype != null) {
checkBoundsInSupertype(cls.supertype, typeEnvironment);
}
if (cls.mixedInType != null) {
checkBoundsInSupertype(cls.mixedInType, typeEnvironment);
}
if (cls.implementedTypes != null) {
for (Supertype supertype in cls.implementedTypes) {
checkBoundsInSupertype(supertype, typeEnvironment);
}
}
// Check in members.
for (Field field in cls.fields) {
library.checkBoundsInField(field, typeEnvironment);
}
for (Procedure procedure in cls.procedures) {
library.checkBoundsInFunctionNode(
procedure.function, typeEnvironment, fileUri);
}
for (Constructor constructor in cls.constructors) {
library.checkBoundsInFunctionNode(
constructor.function, typeEnvironment, fileUri);
}
for (RedirectingFactoryConstructor redirecting
in cls.redirectingFactoryConstructors) {
library.checkBoundsInFunctionNodeParts(
typeEnvironment, fileUri, redirecting.fileOffset,
typeParameters: redirecting.typeParameters,
positionalParameters: redirecting.positionalParameters,
namedParameters: redirecting.namedParameters);
}
}
@override
void addRedirectingConstructor(
ProcedureBuilder constructorBuilder, SourceLibraryBuilder library) {
// Add a new synthetic field to this class for representing factory
// constructors. This is used to support resolving such constructors in
// source code.
//
// The synthetic field looks like this:
//
// final _redirecting# = [c1, ..., cn];
//
// Where each c1 ... cn are an instance of [StaticGet] whose target is
// [constructor.target].
//
// TODO(ahe): Add a kernel node to represent redirecting factory bodies.
DillMemberBuilder constructorsField =
origin.scope.local.putIfAbsent("_redirecting#", () {
ListLiteral literal = new ListLiteral(<Expression>[]);
Name name = new Name("_redirecting#", library.library);
Field field = new Field(name,
isStatic: true, initializer: literal, fileUri: cls.fileUri)
..fileOffset = cls.fileOffset;
cls.addMember(field);
return new DillMemberBuilder(field, this);
});
Field field = constructorsField.member;
ListLiteral literal = field.initializer;
literal.expressions
.add(new StaticGet(constructorBuilder.procedure)..parent = literal);
}
@override
void handleSeenCovariant(
Types types,
Member declaredMember,
Member interfaceMember,
bool isSetter,
callback(Member declaredMember, Member interfaceMember, bool isSetter)) {
// When a parameter is covariant we have to check that we also
// override the same member in all parents.
for (Supertype supertype in interfaceMember.enclosingClass.supers) {
Member m = types.hierarchy.getInterfaceMemberKernel(
supertype.classNode, interfaceMember.name, isSetter);
if (m != null) {
callback(declaredMember, m, isSetter);
}
}
}
@override
void checkOverride(
Types types,
Member declaredMember,
Member interfaceMember,
bool isSetter,
callback(Member declaredMember, Member interfaceMember, bool isSetter),
{bool isInterfaceCheck = false}) {
if (declaredMember == interfaceMember) {
return;
}
if (declaredMember is Constructor || interfaceMember is Constructor) {
unimplemented(
"Constructor in override check.", declaredMember.fileOffset, fileUri);
}
if (declaredMember is Procedure && interfaceMember is Procedure) {
if (declaredMember.kind == ProcedureKind.Method &&
interfaceMember.kind == ProcedureKind.Method) {
bool seenCovariant = checkMethodOverride(
types, declaredMember, interfaceMember, isInterfaceCheck);
if (seenCovariant) {
handleSeenCovariant(
types, declaredMember, interfaceMember, isSetter, callback);
}
}
if (declaredMember.kind == ProcedureKind.Getter &&
interfaceMember.kind == ProcedureKind.Getter) {
checkGetterOverride(
types, declaredMember, interfaceMember, isInterfaceCheck);
}
if (declaredMember.kind == ProcedureKind.Setter &&
interfaceMember.kind == ProcedureKind.Setter) {
bool seenCovariant = checkSetterOverride(
types, declaredMember, interfaceMember, isInterfaceCheck);
if (seenCovariant) {
handleSeenCovariant(
types, declaredMember, interfaceMember, isSetter, callback);
}
}
} else {
bool declaredMemberHasGetter = declaredMember is Field ||
declaredMember is Procedure && declaredMember.isGetter;
bool interfaceMemberHasGetter = interfaceMember is Field ||
interfaceMember is Procedure && interfaceMember.isGetter;
bool declaredMemberHasSetter = (declaredMember is Field &&
!declaredMember.isFinal &&
!declaredMember.isConst) ||
declaredMember is Procedure && declaredMember.isSetter;
bool interfaceMemberHasSetter = (interfaceMember is Field &&
!interfaceMember.isFinal &&
!interfaceMember.isConst) ||
interfaceMember is Procedure && interfaceMember.isSetter;
if (declaredMemberHasGetter && interfaceMemberHasGetter) {
checkGetterOverride(
types, declaredMember, interfaceMember, isInterfaceCheck);
}
if (declaredMemberHasSetter && interfaceMemberHasSetter) {
bool seenCovariant = checkSetterOverride(
types, declaredMember, interfaceMember, isInterfaceCheck);
if (seenCovariant) {
handleSeenCovariant(
types, declaredMember, interfaceMember, isSetter, callback);
}
}
}
// TODO(ahe): Handle other cases: accessors, operators, and fields.
}
@override
void checkOverrides(
ClassHierarchy hierarchy, TypeEnvironment typeEnvironment) {}
@override
void checkAbstractMembers(CoreTypes coreTypes, ClassHierarchy hierarchy,
TypeEnvironment typeEnvironment) {}
@override
bool hasUserDefinedNoSuchMethod(
Class klass, ClassHierarchy hierarchy, Class objectClass) {
Member noSuchMethod = hierarchy.getDispatchTarget(klass, noSuchMethodName);
return noSuchMethod != null && noSuchMethod.enclosingClass != objectClass;
}
@override
void transformProcedureToNoSuchMethodForwarder(
Member noSuchMethodInterface, KernelTarget target, Procedure procedure) {
String prefix =
procedure.isGetter ? 'get:' : procedure.isSetter ? 'set:' : '';
Expression invocation = target.backendTarget.instantiateInvocation(
target.loader.coreTypes,
new ThisExpression(),
prefix + procedure.name.name,
new Arguments.forwarded(procedure.function),
procedure.fileOffset,
/*isSuper=*/ false);
Expression result = new MethodInvocation(new ThisExpression(),
noSuchMethodName, new Arguments([invocation]), noSuchMethodInterface)
..fileOffset = procedure.fileOffset;
if (procedure.function.returnType is! VoidType) {
result = new AsExpression(result, procedure.function.returnType)
..isTypeError = true
..fileOffset = procedure.fileOffset;
}
procedure.function.body = new ReturnStatement(result)
..fileOffset = procedure.fileOffset;
procedure.function.body.parent = procedure.function;
procedure.isAbstract = false;
procedure.isNoSuchMethodForwarder = true;
procedure.isForwardingStub = false;
procedure.isForwardingSemiStub = false;
}
@override
void addNoSuchMethodForwarderForProcedure(Member noSuchMethod,
KernelTarget target, Procedure procedure, ClassHierarchy hierarchy) {
CloneWithoutBody cloner = new CloneWithoutBody(
typeSubstitution: type_algebra.getSubstitutionMap(
hierarchy.getClassAsInstanceOf(cls, procedure.enclosingClass)),
cloneAnnotations: false);
Procedure cloned = cloner.clone(procedure)..isExternal = false;
transformProcedureToNoSuchMethodForwarder(noSuchMethod, target, cloned);
cls.procedures.add(cloned);
cloned.parent = cls;
SourceLibraryBuilder library = this.library;
library.forwardersOrigins.add(cloned);
library.forwardersOrigins.add(procedure);
}
@override
void addNoSuchMethodForwarderGetterForField(Member noSuchMethod,
KernelTarget target, Field field, ClassHierarchy hierarchy) {
Substitution substitution = Substitution.fromSupertype(
hierarchy.getClassAsInstanceOf(cls, field.enclosingClass));
Procedure getter = new Procedure(
field.name,
ProcedureKind.Getter,
new FunctionNode(null,
typeParameters: <TypeParameter>[],
positionalParameters: <VariableDeclaration>[],
namedParameters: <VariableDeclaration>[],
requiredParameterCount: 0,
returnType: substitution.substituteType(field.type)),
fileUri: field.fileUri)
..fileOffset = field.fileOffset;
transformProcedureToNoSuchMethodForwarder(noSuchMethod, target, getter);
cls.procedures.add(getter);
getter.parent = cls;
}
@override
void addNoSuchMethodForwarderSetterForField(Member noSuchMethod,
KernelTarget target, Field field, ClassHierarchy hierarchy) {
Substitution substitution = Substitution.fromSupertype(
hierarchy.getClassAsInstanceOf(cls, field.enclosingClass));
Procedure setter = new Procedure(
field.name,
ProcedureKind.Setter,
new FunctionNode(null,
typeParameters: <TypeParameter>[],
positionalParameters: <VariableDeclaration>[
new VariableDeclaration("value",
type: substitution.substituteType(field.type))
],
namedParameters: <VariableDeclaration>[],
requiredParameterCount: 1,
returnType: const VoidType()),
fileUri: field.fileUri)
..fileOffset = field.fileOffset;
transformProcedureToNoSuchMethodForwarder(noSuchMethod, target, setter);
cls.procedures.add(setter);
setter.parent = cls;
}
@override
bool addNoSuchMethodForwarders(
KernelTarget target, ClassHierarchy hierarchy) {
if (cls.isAbstract) return false;
Set<Name> existingForwardersNames = new Set<Name>();
Set<Name> existingSetterForwardersNames = new Set<Name>();
Class leastConcreteSuperclass = cls.superclass;
while (
leastConcreteSuperclass != null && leastConcreteSuperclass.isAbstract) {
leastConcreteSuperclass = leastConcreteSuperclass.superclass;
}
if (leastConcreteSuperclass != null) {
bool superHasUserDefinedNoSuchMethod = hasUserDefinedNoSuchMethod(
leastConcreteSuperclass, hierarchy, target.objectClass);
List<Member> concrete =
hierarchy.getDispatchTargets(leastConcreteSuperclass);
for (Member member
in hierarchy.getInterfaceMembers(leastConcreteSuperclass)) {
if ((superHasUserDefinedNoSuchMethod ||
leastConcreteSuperclass.enclosingLibrary.compareTo(
member.enclosingClass.enclosingLibrary) !=
0 &&
member.name.isPrivate) &&
ClassHierarchy.findMemberByName(concrete, member.name) == null) {
existingForwardersNames.add(member.name);
}
}
List<Member> concreteSetters =
hierarchy.getDispatchTargets(leastConcreteSuperclass, setters: true);
for (Member member in hierarchy
.getInterfaceMembers(leastConcreteSuperclass, setters: true)) {
if (ClassHierarchy.findMemberByName(concreteSetters, member.name) ==
null) {
existingSetterForwardersNames.add(member.name);
}
}
}
Member noSuchMethod = ClassHierarchy.findMemberByName(
hierarchy.getInterfaceMembers(cls), noSuchMethodName);
List<Member> concrete = hierarchy.getDispatchTargets(cls);
List<Member> declared = hierarchy.getDeclaredMembers(cls);
bool clsHasUserDefinedNoSuchMethod =
hasUserDefinedNoSuchMethod(cls, hierarchy, target.objectClass);
bool changed = false;
for (Member member in hierarchy.getInterfaceMembers(cls)) {
// We generate a noSuchMethod forwarder for [member] in [cls] if the
// following three conditions are satisfied simultaneously:
// 1) There is a user-defined noSuchMethod in [cls] or [member] is private
// and the enclosing library of [member] is different from that of
// [cls].
// 2) There is no implementation of [member] in [cls].
// 3) The superclass of [cls] has no forwarder for [member].
if (member is Procedure &&
(clsHasUserDefinedNoSuchMethod ||
cls.enclosingLibrary
.compareTo(member.enclosingClass.enclosingLibrary) !=
0 &&
member.name.isPrivate) &&
ClassHierarchy.findMemberByName(concrete, member.name) == null &&
!existingForwardersNames.contains(member.name)) {
if (ClassHierarchy.findMemberByName(declared, member.name) != null) {
transformProcedureToNoSuchMethodForwarder(
noSuchMethod, target, member);
} else {
addNoSuchMethodForwarderForProcedure(
noSuchMethod, target, member, hierarchy);
}
existingForwardersNames.add(member.name);
changed = true;
continue;
}
if (member is Field &&
ClassHierarchy.findMemberByName(concrete, member.name) == null &&
!existingForwardersNames.contains(member.name)) {
addNoSuchMethodForwarderGetterForField(
noSuchMethod, target, member, hierarchy);
existingForwardersNames.add(member.name);
changed = true;
}
}
List<Member> concreteSetters =
hierarchy.getDispatchTargets(cls, setters: true);
List<Member> declaredSetters =
hierarchy.getDeclaredMembers(cls, setters: true);
for (Member member in hierarchy.getInterfaceMembers(cls, setters: true)) {
if (member is Procedure &&
ClassHierarchy.findMemberByName(concreteSetters, member.name) ==
null &&
!existingSetterForwardersNames.contains(member.name)) {
if (ClassHierarchy.findMemberByName(declaredSetters, member.name) !=
null) {
transformProcedureToNoSuchMethodForwarder(
noSuchMethod, target, member);
} else {
addNoSuchMethodForwarderForProcedure(
noSuchMethod, target, member, hierarchy);
}
existingSetterForwardersNames.add(member.name);
changed = true;
}
if (member is Field &&
ClassHierarchy.findMemberByName(concreteSetters, member.name) ==
null &&
!existingSetterForwardersNames.contains(member.name)) {
addNoSuchMethodForwarderSetterForField(
noSuchMethod, target, member, hierarchy);
existingSetterForwardersNames.add(member.name);
changed = true;
}
}
return changed;
}
Uri _getMemberUri(Member member) {
if (member is Field) return member.fileUri;
if (member is Procedure) return member.fileUri;
// Other member types won't be seen because constructors don't participate
// in override relationships
return unhandled('${member.runtimeType}', '_getMemberUri', -1, null);
}
Substitution _computeInterfaceSubstitution(
Types types,
Member declaredMember,
Member interfaceMember,
FunctionNode declaredFunction,
FunctionNode interfaceFunction,
bool isInterfaceCheck) {
Substitution interfaceSubstitution = Substitution.empty;
if (interfaceMember.enclosingClass.typeParameters.isNotEmpty) {
interfaceSubstitution = Substitution.fromInterfaceType(types.hierarchy
.getKernelTypeAsInstanceOf(
cls.thisType, interfaceMember.enclosingClass));
}
if (declaredFunction?.typeParameters?.length !=
interfaceFunction?.typeParameters?.length) {
reportInvalidOverride(
isInterfaceCheck,
declaredMember,
templateOverrideTypeVariablesMismatch.withArguments(
"${declaredMember.enclosingClass.name}."
"${declaredMember.name.name}",
"${interfaceMember.enclosingClass.name}."
"${interfaceMember.name.name}"),
declaredMember.fileOffset,
noLength,
context: [
templateOverriddenMethodCause
.withArguments(interfaceMember.name.name)
.withLocation(_getMemberUri(interfaceMember),
interfaceMember.fileOffset, noLength)
]);
} else if (declaredFunction?.typeParameters != null) {
Map<TypeParameter, DartType> substitutionMap =
<TypeParameter, DartType>{};
for (int i = 0; i < declaredFunction.typeParameters.length; ++i) {
substitutionMap[interfaceFunction.typeParameters[i]] =
new TypeParameterType(declaredFunction.typeParameters[i]);
}
Substitution substitution = Substitution.fromMap(substitutionMap);
for (int i = 0; i < declaredFunction.typeParameters.length; ++i) {
TypeParameter declaredParameter = declaredFunction.typeParameters[i];
TypeParameter interfaceParameter = interfaceFunction.typeParameters[i];
if (!interfaceParameter.isGenericCovariantImpl) {
DartType declaredBound = declaredParameter.bound;
DartType interfaceBound = interfaceParameter.bound;
if (interfaceSubstitution != null) {
declaredBound = interfaceSubstitution.substituteType(declaredBound);
interfaceBound =
interfaceSubstitution.substituteType(interfaceBound);
}
if (declaredBound != substitution.substituteType(interfaceBound)) {
reportInvalidOverride(
isInterfaceCheck,
declaredMember,
templateOverrideTypeVariablesMismatch.withArguments(
"${declaredMember.enclosingClass.name}."
"${declaredMember.name.name}",
"${interfaceMember.enclosingClass.name}."
"${interfaceMember.name.name}"),
declaredMember.fileOffset,
noLength,
context: [
templateOverriddenMethodCause
.withArguments(interfaceMember.name.name)
.withLocation(_getMemberUri(interfaceMember),
interfaceMember.fileOffset, noLength)
]);
}
}
}
interfaceSubstitution =
Substitution.combine(interfaceSubstitution, substitution);
}
return interfaceSubstitution;
}
Substitution _computeDeclaredSubstitution(
Types types, Member declaredMember) {
Substitution declaredSubstitution = Substitution.empty;
if (declaredMember.enclosingClass.typeParameters.isNotEmpty) {
declaredSubstitution = Substitution.fromInterfaceType(types.hierarchy
.getKernelTypeAsInstanceOf(
cls.thisType, declaredMember.enclosingClass));
}
return declaredSubstitution;
}
void _checkTypes(
Types types,
Substitution interfaceSubstitution,
Substitution declaredSubstitution,
Member declaredMember,
Member interfaceMember,
DartType declaredType,
DartType interfaceType,
bool isCovariant,
VariableDeclaration declaredParameter,
bool isInterfaceCheck,
{bool asIfDeclaredParameter = false}) {
if (interfaceSubstitution != null) {
interfaceType = interfaceSubstitution.substituteType(interfaceType);
}
if (declaredSubstitution != null) {
declaredType = declaredSubstitution.substituteType(declaredType);
}
bool inParameter = declaredParameter != null || asIfDeclaredParameter;
DartType subtype = inParameter ? interfaceType : declaredType;
DartType supertype = inParameter ? declaredType : interfaceType;
if (types.isSubtypeOfKernel(
subtype, supertype, SubtypeCheckMode.ignoringNullabilities)) {
// No problem--the proper subtyping relation is satisfied.
} else if (isCovariant &&
types.isSubtypeOfKernel(
supertype, subtype, SubtypeCheckMode.ignoringNullabilities)) {
// No problem--the overriding parameter is marked "covariant" and has
// a type which is a subtype of the parameter it overrides.
} else if (subtype is InvalidType || supertype is InvalidType) {
// Don't report a problem as something else is wrong that has already
// been reported.
} else {
// Report an error.
String declaredMemberName =
'${declaredMember.enclosingClass.name}.${declaredMember.name.name}';
String interfaceMemberName =
'${interfaceMember.enclosingClass.name}.${interfaceMember.name.name}';
Message message;
int fileOffset;
if (declaredParameter == null) {
if (asIfDeclaredParameter) {
// Setter overridden by field
message = templateOverrideTypeMismatchSetter.withArguments(
declaredMemberName,
declaredType,
interfaceType,
interfaceMemberName);
} else {
message = templateOverrideTypeMismatchReturnType.withArguments(
declaredMemberName,
declaredType,
interfaceType,
interfaceMemberName);
}
fileOffset = declaredMember.fileOffset;
} else {
message = templateOverrideTypeMismatchParameter.withArguments(
declaredParameter.name,
declaredMemberName,
declaredType,
interfaceType,
interfaceMemberName);
fileOffset = declaredParameter.fileOffset;
}
reportInvalidOverride(
isInterfaceCheck, declaredMember, message, fileOffset, noLength,
context: [
templateOverriddenMethodCause
.withArguments(interfaceMember.name.name)
.withLocation(_getMemberUri(interfaceMember),
interfaceMember.fileOffset, noLength)
]);
}
}
@override
bool checkMethodOverride(Types types, Procedure declaredMember,
Procedure interfaceMember, bool isInterfaceCheck) {
assert(declaredMember.kind == ProcedureKind.Method);
assert(interfaceMember.kind == ProcedureKind.Method);
bool seenCovariant = false;
FunctionNode declaredFunction = declaredMember.function;
FunctionNode interfaceFunction = interfaceMember.function;
Substitution interfaceSubstitution = _computeInterfaceSubstitution(
types,
declaredMember,
interfaceMember,
declaredFunction,
interfaceFunction,
isInterfaceCheck);
Substitution declaredSubstitution =
_computeDeclaredSubstitution(types, declaredMember);
_checkTypes(
types,
interfaceSubstitution,
declaredSubstitution,
declaredMember,
interfaceMember,
declaredFunction.returnType,
interfaceFunction.returnType,
false,
null,
isInterfaceCheck);
if (declaredFunction.positionalParameters.length <
interfaceFunction.positionalParameters.length) {
reportInvalidOverride(
isInterfaceCheck,
declaredMember,
templateOverrideFewerPositionalArguments.withArguments(
"${declaredMember.enclosingClass.name}."
"${declaredMember.name.name}",
"${interfaceMember.enclosingClass.name}."
"${interfaceMember.name.name}"),
declaredMember.fileOffset,
noLength,
context: [
templateOverriddenMethodCause
.withArguments(interfaceMember.name.name)
.withLocation(interfaceMember.fileUri,
interfaceMember.fileOffset, noLength)
]);
}
if (interfaceFunction.requiredParameterCount <
declaredFunction.requiredParameterCount) {
reportInvalidOverride(
isInterfaceCheck,
declaredMember,
templateOverrideMoreRequiredArguments.withArguments(
"${declaredMember.enclosingClass.name}."
"${declaredMember.name.name}",
"${interfaceMember.enclosingClass.name}."
"${interfaceMember.name.name}"),
declaredMember.fileOffset,
noLength,
context: [
templateOverriddenMethodCause
.withArguments(interfaceMember.name.name)
.withLocation(interfaceMember.fileUri,
interfaceMember.fileOffset, noLength)
]);
}
for (int i = 0;
i < declaredFunction.positionalParameters.length &&
i < interfaceFunction.positionalParameters.length;
i++) {
VariableDeclaration declaredParameter =
declaredFunction.positionalParameters[i];
VariableDeclaration interfaceParameter =
interfaceFunction.positionalParameters[i];
_checkTypes(
types,
interfaceSubstitution,
declaredSubstitution,
declaredMember,
interfaceMember,
declaredParameter.type,
interfaceFunction.positionalParameters[i].type,
declaredParameter.isCovariant || interfaceParameter.isCovariant,
declaredParameter,
isInterfaceCheck);
if (declaredParameter.isCovariant) seenCovariant = true;
}
if (declaredFunction.namedParameters.isEmpty &&
interfaceFunction.namedParameters.isEmpty) {
return seenCovariant;
}
if (declaredFunction.namedParameters.length <
interfaceFunction.namedParameters.length) {
reportInvalidOverride(
isInterfaceCheck,
declaredMember,
templateOverrideFewerNamedArguments.withArguments(
"${declaredMember.enclosingClass.name}."
"${declaredMember.name.name}",
"${interfaceMember.enclosingClass.name}."
"${interfaceMember.name.name}"),
declaredMember.fileOffset,
noLength,
context: [
templateOverriddenMethodCause
.withArguments(interfaceMember.name.name)
.withLocation(interfaceMember.fileUri,
interfaceMember.fileOffset, noLength)
]);
}
int compareNamedParameters(VariableDeclaration p0, VariableDeclaration p1) {
return p0.name.compareTo(p1.name);
}
List<VariableDeclaration> sortedFromDeclared =
new List.from(declaredFunction.namedParameters)
..sort(compareNamedParameters);
List<VariableDeclaration> sortedFromInterface =
new List.from(interfaceFunction.namedParameters)
..sort(compareNamedParameters);
Iterator<VariableDeclaration> declaredNamedParameters =
sortedFromDeclared.iterator;
Iterator<VariableDeclaration> interfaceNamedParameters =
sortedFromInterface.iterator;
outer:
while (declaredNamedParameters.moveNext() &&
interfaceNamedParameters.moveNext()) {
while (declaredNamedParameters.current.name !=
interfaceNamedParameters.current.name) {
if (!declaredNamedParameters.moveNext()) {
reportInvalidOverride(
isInterfaceCheck,
declaredMember,
templateOverrideMismatchNamedParameter.withArguments(
"${declaredMember.enclosingClass.name}."
"${declaredMember.name.name}",
interfaceNamedParameters.current.name,
"${interfaceMember.enclosingClass.name}."
"${interfaceMember.name.name}"),
declaredMember.fileOffset,
noLength,
context: [
templateOverriddenMethodCause
.withArguments(interfaceMember.name.name)
.withLocation(interfaceMember.fileUri,
interfaceMember.fileOffset, noLength)
]);
break outer;
}
}
VariableDeclaration declaredParameter = declaredNamedParameters.current;
_checkTypes(
types,
interfaceSubstitution,
declaredSubstitution,
declaredMember,
interfaceMember,
declaredParameter.type,
interfaceNamedParameters.current.type,
declaredParameter.isCovariant,
declaredParameter,
isInterfaceCheck);
if (declaredParameter.isCovariant) seenCovariant = true;
}
return seenCovariant;
}
void checkGetterOverride(Types types, Member declaredMember,
Member interfaceMember, bool isInterfaceCheck) {
Substitution interfaceSubstitution = _computeInterfaceSubstitution(
types, declaredMember, interfaceMember, null, null, isInterfaceCheck);
Substitution declaredSubstitution =
_computeDeclaredSubstitution(types, declaredMember);
DartType declaredType = declaredMember.getterType;
DartType interfaceType = interfaceMember.getterType;
_checkTypes(
types,
interfaceSubstitution,
declaredSubstitution,
declaredMember,
interfaceMember,
declaredType,
interfaceType,
false,
null,
isInterfaceCheck);
}
@override
bool checkSetterOverride(Types types, Member declaredMember,
Member interfaceMember, bool isInterfaceCheck) {
Substitution interfaceSubstitution = _computeInterfaceSubstitution(
types, declaredMember, interfaceMember, null, null, isInterfaceCheck);
Substitution declaredSubstitution =
_computeDeclaredSubstitution(types, declaredMember);
DartType declaredType = declaredMember.setterType;
DartType interfaceType = interfaceMember.setterType;
VariableDeclaration declaredParameter =
declaredMember.function?.positionalParameters?.elementAt(0);
bool isCovariant = declaredParameter?.isCovariant ?? false;
if (!isCovariant && declaredMember is Field) {
isCovariant = declaredMember.isCovariant;
}
if (!isCovariant && interfaceMember is Field) {
isCovariant = interfaceMember.isCovariant;
}
_checkTypes(
types,
interfaceSubstitution,
declaredSubstitution,
declaredMember,
interfaceMember,
declaredType,
interfaceType,
isCovariant,
declaredParameter,
isInterfaceCheck,
asIfDeclaredParameter: true);
return isCovariant;
}
@override
void reportInvalidOverride(bool isInterfaceCheck, Member declaredMember,
Message message, int fileOffset, int length,
{List<LocatedMessage> context}) {
if (declaredMember.enclosingClass == cls) {
// Ordinary override
library.addProblem(message, fileOffset, length, declaredMember.fileUri,
context: context);
} else {
context = [
message.withLocation(declaredMember.fileUri, fileOffset, length),
...?context
];
if (isInterfaceCheck) {
// Interface check
library.addProblem(
templateInterfaceCheck.withArguments(
declaredMember.name.name, cls.name),
cls.fileOffset,
cls.name.length,
cls.fileUri,
context: context);
} else {
if (cls.isAnonymousMixin) {
// Implicit mixin application class
String baseName = cls.superclass.demangledName;
String mixinName = cls.mixedInClass.name;
int classNameLength = cls.nameAsMixinApplicationSubclass.length;
library.addProblem(
templateImplicitMixinOverride.withArguments(
mixinName, baseName, declaredMember.name.name),
cls.fileOffset,
classNameLength,
cls.fileUri,
context: context);
} else {
// Named mixin application class
library.addProblem(
templateNamedMixinOverride.withArguments(
cls.name, declaredMember.name.name),
cls.fileOffset,
cls.name.length,
cls.fileUri,
context: context);
}
}
}
}
@override
String get fullNameForErrors {
return isMixinApplication && !isNamedMixinApplication
? "${supertype.fullNameForErrors} with ${mixedInType.fullNameForErrors}"
: name;
}
@override
void checkMixinApplication(ClassHierarchy hierarchy) {
// A mixin declaration can only be applied to a class that implements all
// the declaration's superclass constraints.
InterfaceType supertype = cls.supertype.asInterfaceType;
Substitution substitution = Substitution.fromSupertype(cls.mixedInType);
for (Supertype constraint in cls.mixedInClass.superclassConstraints()) {
InterfaceType interface =
substitution.substituteSupertype(constraint).asInterfaceType;
if (hierarchy.getTypeAsInstanceOf(supertype, interface.classNode) !=
interface) {
library.addProblem(
templateMixinApplicationIncompatibleSupertype.withArguments(
supertype, interface, cls.mixedInType.asInterfaceType),
cls.fileOffset,
noLength,
cls.fileUri);
}
}
}
@override
void applyPatch(Builder patch) {
if (patch is ClassBuilder) {
patch.actualOrigin = this;
if (retainDataForTesting) {
patchForTesting = patch;
}
// TODO(ahe): Complain if `patch.supertype` isn't null.
scope.local.forEach((String name, Builder member) {
Builder memberPatch = patch.scope.local[name];
if (memberPatch != null) {
member.applyPatch(memberPatch);
}
});
scope.setters.forEach((String name, Builder member) {
Builder memberPatch = patch.scope.setters[name];
if (memberPatch != null) {
member.applyPatch(memberPatch);
}
});
constructors.local.forEach((String name, Builder member) {
Builder memberPatch = patch.constructors.local[name];
if (memberPatch != null) {
member.applyPatch(memberPatch);
}
});
int originLength = typeVariables?.length ?? 0;
int patchLength = patch.typeVariables?.length ?? 0;
if (originLength != patchLength) {
patch.addProblem(messagePatchClassTypeVariablesMismatch,
patch.charOffset, noLength, context: [
messagePatchClassOrigin.withLocation(fileUri, charOffset, noLength)
]);
} else if (typeVariables != null) {
int count = 0;
for (TypeVariableBuilder t in patch.typeVariables) {
typeVariables[count++].applyPatch(t);
}
}
} else {
library.addProblem(messagePatchDeclarationMismatch, patch.charOffset,
noLength, patch.fileUri, context: [
messagePatchDeclarationOrigin.withLocation(
fileUri, charOffset, noLength)
]);
}
}
@override
FunctionType computeRedirecteeType(
RedirectingFactoryBuilder factory, TypeEnvironment typeEnvironment) {
ConstructorReferenceBuilder redirectionTarget = factory.redirectionTarget;
FunctionNode target;
if (redirectionTarget.target == null) return null;
if (redirectionTarget.target is FunctionBuilder) {
FunctionBuilder targetBuilder = redirectionTarget.target;
target = targetBuilder.function;
} else if (redirectionTarget.target is DillMemberBuilder &&
(redirectionTarget.target.isConstructor ||
redirectionTarget.target.isFactory)) {
DillMemberBuilder targetBuilder = redirectionTarget.target;
// It seems that the [redirectionTarget.target] is an instance of
// [DillMemberBuilder] whenever the redirectee is an implicit constructor,
// e.g.
//
// class A {
// factory A() = B;
// }
// class B implements A {}
//
target = targetBuilder.member.function;
} else if (redirectionTarget.target is AmbiguousBuilder) {
// Multiple definitions with the same name: An error has already been
// issued.
// TODO(http://dartbug.com/35294): Unfortunate error; see also
// https://dart-review.googlesource.com/c/sdk/+/85390/.
return null;
} else {
unhandled("${redirectionTarget.target}", "computeRedirecteeType",
charOffset, fileUri);
}
List<DartType> typeArguments =
getRedirectingFactoryBody(factory.procedure).typeArguments;
FunctionType targetFunctionType = target.functionType;
if (typeArguments != null &&
targetFunctionType.typeParameters.length != typeArguments.length) {
addProblem(
templateTypeArgumentMismatch
.withArguments(targetFunctionType.typeParameters.length),
redirectionTarget.charOffset,
noLength);
return null;
}
// Compute the substitution of the target class type parameters if
// [redirectionTarget] has any type arguments.
Substitution substitution;
bool hasProblem = false;
if (typeArguments != null && typeArguments.length > 0) {
substitution = Substitution.fromPairs(
targetFunctionType.typeParameters, typeArguments);
for (int i = 0; i < targetFunctionType.typeParameters.length; i++) {
TypeParameter typeParameter = targetFunctionType.typeParameters[i];
DartType typeParameterBound =
substitution.substituteType(typeParameter.bound);
DartType typeArgument = typeArguments[i];
// Check whether the [typeArgument] respects the bounds of
// [typeParameter].
if (!typeEnvironment.isSubtypeOf(typeArgument, typeParameterBound,
SubtypeCheckMode.ignoringNullabilities)) {
addProblem(
templateRedirectingFactoryIncompatibleTypeArgument.withArguments(
typeArgument, typeParameterBound),
redirectionTarget.charOffset,
noLength);
hasProblem = true;
}
}
} else if (typeArguments == null &&
targetFunctionType.typeParameters.length > 0) {
// TODO(hillerstrom): In this case, we need to perform type inference on
// the redirectee to obtain actual type arguments which would allow the
// following program to type check:
//
// class A<T> {
// factory A() = B;
// }
// class B<T> implements A<T> {
// B();
// }
//
return null;
}
// Substitute if necessary.
targetFunctionType = substitution == null
? targetFunctionType
: (substitution.substituteType(targetFunctionType.withoutTypeParameters)
as FunctionType);
return hasProblem ? null : targetFunctionType;
}
@override
String computeRedirecteeName(ConstructorReferenceBuilder redirectionTarget) {
String targetName = redirectionTarget.fullNameForErrors;
if (targetName == "") {
return redirectionTarget.target.parent.fullNameForErrors;
} else {
return targetName;
}
}
@override
void checkRedirectingFactory(
RedirectingFactoryBuilder factory, TypeEnvironment typeEnvironment) {
// The factory type cannot contain any type parameters other than those of
// its enclosing class, because constructors cannot specify type parameters
// of their own.
FunctionType factoryType =
factory.procedure.function.thisFunctionType.withoutTypeParameters;
FunctionType redirecteeType =
computeRedirecteeType(factory, typeEnvironment);
// TODO(hillerstrom): It would be preferable to know whether a failure
// happened during [_computeRedirecteeType].
if (redirecteeType == null) return;
// Check whether [redirecteeType] <: [factoryType].
if (!typeEnvironment.isSubtypeOf(
redirecteeType, factoryType, SubtypeCheckMode.ignoringNullabilities)) {
addProblem(
templateIncompatibleRedirecteeFunctionType.withArguments(
redirecteeType, factoryType),
factory.redirectionTarget.charOffset,
noLength);
}
}
@override
void checkRedirectingFactories(TypeEnvironment typeEnvironment) {
Map<String, MemberBuilder> constructors = this.constructors.local;
Iterable<String> names = constructors.keys;
for (String name in names) {
Builder constructor = constructors[name];
do {
if (constructor is RedirectingFactoryBuilder) {
checkRedirectingFactory(constructor, typeEnvironment);
}
constructor = constructor.next;
} while (constructor != null);
}
}
@override
Map<TypeParameter, DartType> getSubstitutionMap(Class superclass) {
Supertype supertype = cls.supertype;
Map<TypeParameter, DartType> substitutionMap = <TypeParameter, DartType>{};
List<DartType> arguments;
List<TypeParameter> variables;
Class classNode;
while (classNode != superclass) {
classNode = supertype.classNode;
arguments = supertype.typeArguments;
variables = classNode.typeParameters;
supertype = classNode.supertype;
if (variables.isNotEmpty) {
Map<TypeParameter, DartType> directSubstitutionMap =
<TypeParameter, DartType>{};
for (int i = 0; i < variables.length; i++) {
DartType argument =
i < arguments.length ? arguments[i] : const DynamicType();
if (substitutionMap != null) {
// TODO(ahe): Investigate if requiring the caller to use
// `substituteDeep` from `package:kernel/type_algebra.dart` instead
// of `substitute` is faster. If so, we can simply this code.
argument = substitute(argument, substitutionMap);
}
directSubstitutionMap[variables[i]] = argument;
}
substitutionMap = directSubstitutionMap;
}
}
return substitutionMap;
}
@override
Member lookupInstanceMember(ClassHierarchy hierarchy, Name name,
{bool isSetter: false, bool isSuper: false}) {
Class instanceClass = cls;
if (isPatch) {
assert(identical(instanceClass, origin.cls),
"Found ${origin.cls} expected $instanceClass");
if (isSuper) {
// The super class is only correctly found through the origin class.
instanceClass = origin.cls;
} else {
Member member =
hierarchy.getInterfaceMember(instanceClass, name, setter: isSetter);
if (member?.parent == instanceClass) {
// Only if the member is found in the patch can we use it.
return member;
} else {
// Otherwise, we need to keep searching in the origin class.
instanceClass = origin.cls;
}
}
}
if (isSuper) {
instanceClass = instanceClass.superclass;
if (instanceClass == null) return null;
}
Member target = isSuper
? hierarchy.getDispatchTarget(instanceClass, name, setter: isSetter)
: hierarchy.getInterfaceMember(instanceClass, name, setter: isSetter);
if (isSuper && target == null) {
if (cls.isMixinDeclaration ||
(library.loader.target.backendTarget.enableSuperMixins &&
this.isAbstract)) {
target =
hierarchy.getInterfaceMember(instanceClass, name, setter: isSetter);
}
}
return target;
}
@override
Constructor lookupConstructor(Name name, {bool isSuper: false}) {
Class instanceClass = cls;
if (isSuper) {
instanceClass = instanceClass.superclass;
}
if (instanceClass != null) {
for (Constructor constructor in instanceClass.constructors) {
if (constructor.name == name) return constructor;
}
}
/// Performs a similar lookup to [lookupConstructor], but using a slower
/// implementation.
Constructor lookupConstructorWithPatches(Name name, bool isSuper) {
ClassBuilder builder = this.origin;
ClassBuilder getSuperclass(ClassBuilder builder) {
// This way of computing the superclass is slower than using the kernel
// objects directly.
Object supertype = builder.supertype;
if (supertype is NamedTypeBuilder) {
Object builder = supertype.declaration;
if (builder is ClassBuilder) return builder;
}
return null;
}
if (isSuper) {
builder = getSuperclass(builder)?.origin;
}
if (builder != null) {
Class cls = builder.cls;
for (Constructor constructor in cls.constructors) {
if (constructor.name == name) return constructor;
}
}
return null;
}
return lookupConstructorWithPatches(name, isSuper);
}
}
class ConstructorRedirection {
String target;
bool cycleReported;
ConstructorRedirection(this.target) : cycleReported = false;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/builtin_type_builder.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 fasta.builtin_type_builder;
import 'package:kernel/ast.dart' show DartType, Nullability;
import 'builder.dart' show LibraryBuilder, NullabilityBuilder, TypeBuilder;
import 'type_declaration_builder.dart';
abstract class BuiltinTypeBuilder extends TypeDeclarationBuilderImpl {
final DartType type;
BuiltinTypeBuilder(
String name, this.type, LibraryBuilder compilationUnit, int charOffset)
: super(null, 0, name, compilationUnit, charOffset);
DartType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments) {
// TODO(dmitryas): Use [nullabilityBuilder].
return type;
}
DartType buildTypesWithBuiltArguments(LibraryBuilder library,
Nullability nullability, List<DartType> arguments) {
// TODO(dmitryas): Use [nullability].
return type;
}
String get debugName => "BuiltinTypeBuilder";
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/member_builder.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 fasta.member_builder;
import 'dart:core' hide MapEntry;
import 'package:kernel/ast.dart';
import '../problems.dart' show unsupported;
import 'builder.dart' show ClassBuilder, Builder, LibraryBuilder;
import 'declaration.dart';
import 'declaration_builder.dart';
import 'extension_builder.dart';
import 'modifier_builder.dart';
import '../kernel/class_hierarchy_builder.dart';
abstract class MemberBuilder implements ModifierBuilder, ClassMember {
bool get isRedirectingGenerativeConstructor;
void set parent(Builder value);
LibraryBuilder get library;
/// The [Member] built by this builder;
Member get member;
// TODO(johnniwinther): Deprecate this.
Member get target;
// TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
Member get extensionTearOff;
// TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
Procedure get procedure;
// TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
ProcedureKind get kind;
void buildOutlineExpressions(LibraryBuilder library);
void inferType();
void inferCopiedType(covariant Object other);
}
abstract class MemberBuilderImpl extends ModifierBuilderImpl
implements MemberBuilder {
/// For top-level members, the parent is set correctly during
/// construction. However, for class members, the parent is initially the
/// library and updated later.
@override
Builder parent;
@override
String get name;
MemberBuilderImpl(this.parent, int charOffset) : super(parent, charOffset);
@override
bool get isDeclarationInstanceMember => isDeclarationMember && !isStatic;
@override
bool get isClassInstanceMember => isClassMember && !isStatic;
@override
bool get isExtensionInstanceMember => isExtensionMember && !isStatic;
@override
bool get isDeclarationMember => parent is DeclarationBuilder;
@override
bool get isClassMember => parent is ClassBuilder;
@override
bool get isExtensionMember => parent is ExtensionBuilder;
@override
bool get isTopLevel => !isDeclarationMember;
@override
bool get isNative => false;
@override
bool get isRedirectingGenerativeConstructor => false;
@override
LibraryBuilder get library {
if (parent is LibraryBuilder) {
LibraryBuilder library = parent;
return library.partOfLibrary ?? library;
} else if (parent is ExtensionBuilder) {
ExtensionBuilder extension = parent;
return extension.library;
} else {
ClassBuilder cls = parent;
return cls.library;
}
}
// TODO(johnniwinther): Deprecate this.
@override
Member get target => member;
// TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
@override
Member get extensionTearOff =>
unsupported("extensionTearOff", charOffset, fileUri);
// TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
@override
Procedure get procedure => unsupported("procedure", charOffset, fileUri);
// TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
@override
ProcedureKind get kind => unsupported("kind", charOffset, fileUri);
@override
void buildOutlineExpressions(LibraryBuilder library) {}
@override
String get fullNameForErrors => name;
@override
void inferType() => unsupported("inferType", charOffset, fileUri);
@override
void inferCopiedType(covariant Object other) {
unsupported("inferType", charOffset, fileUri);
}
@override
ClassBuilder get classBuilder => parent is ClassBuilder ? parent : null;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/nullability_builder.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:core' hide MapEntry;
import 'package:kernel/ast.dart';
import '../kernel/body_builder.dart';
import '../builder/builder.dart';
import '../problems.dart';
/// Represents the nullability modifiers encountered while parsing the types.
///
/// The syntactic nullability needs to be interpreted, that is, built, into the
/// semantic nullability used on [DartType]s of Kernel.
enum SyntacticNullability {
/// Used when the type is declared with '?' suffix after it.
nullable,
/// Used when the type is declared in an opted-out library.
legacy,
/// Used when the type is declared without any nullability suffixes.
omitted,
}
class NullabilityBuilder {
final SyntacticNullability _syntacticNullability;
const NullabilityBuilder.nullable()
: _syntacticNullability = SyntacticNullability.nullable;
const NullabilityBuilder.omitted()
: _syntacticNullability = SyntacticNullability.omitted;
factory NullabilityBuilder.fromNullability(Nullability nullability) {
switch (nullability) {
case Nullability.nullable:
return const NullabilityBuilder.nullable();
case Nullability.legacy:
case Nullability.nonNullable:
case Nullability.neither:
default:
return const NullabilityBuilder.omitted();
}
}
Nullability build(LibraryBuilder libraryBuilder, {Nullability ifOmitted}) {
// TODO(dmitryas): Ensure that either ifOmitted is set or libraryBuilder is
// provided;
//assert(libraryBuilder != null || ifOmitted != null);
ifOmitted ??= (libraryBuilder == null ? Nullability.legacy : null);
ifOmitted ??= libraryBuilder.isNonNullableByDefault
? Nullability.nonNullable
: Nullability.legacy;
switch (_syntacticNullability) {
case SyntacticNullability.legacy:
return Nullability.legacy;
case SyntacticNullability.nullable:
return Nullability.nullable;
case SyntacticNullability.omitted:
return ifOmitted;
}
return unhandled(
"$_syntacticNullability", "buildNullability", noLocation, null);
}
void writeNullabilityOn(StringBuffer sb) {
switch (_syntacticNullability) {
case SyntacticNullability.legacy:
sb.write("*");
return;
case SyntacticNullability.nullable:
sb.write("?");
return;
case SyntacticNullability.omitted:
// Do nothing.
return;
}
unhandled("$_syntacticNullability", "writeNullabilityOn", noLocation, null);
}
String toString() {
StringBuffer buffer = new StringBuffer();
writeNullabilityOn(buffer);
return "$buffer";
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/extension_builder.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:core' hide MapEntry;
import 'package:kernel/ast.dart';
import '../fasta_codes.dart' show templateInternalProblemNotFoundIn;
import '../scope.dart';
import '../problems.dart';
import 'builder.dart';
import 'declaration.dart';
import 'declaration_builder.dart';
import 'library_builder.dart';
import 'metadata_builder.dart';
import 'type_builder.dart';
import 'type_variable_builder.dart';
abstract class ExtensionBuilder implements DeclarationBuilder {
List<TypeVariableBuilder> get typeParameters;
TypeBuilder get onType;
/// Return the [Extension] built by this builder.
Extension get extension;
// Deliberately unrelated return type to statically detect more accidental
// use until Builder.target is fully retired.
@override
UnrelatedTarget get target;
void buildOutlineExpressions(LibraryBuilder library);
}
abstract class ExtensionBuilderImpl extends DeclarationBuilderImpl
implements ExtensionBuilder {
@override
final List<TypeVariableBuilder> typeParameters;
@override
final TypeBuilder onType;
ExtensionBuilderImpl(
List<MetadataBuilder> metadata,
int modifiers,
String name,
LibraryBuilder parent,
int charOffset,
Scope scope,
this.typeParameters,
this.onType)
: super(metadata, modifiers, name, parent, charOffset, scope);
/// Lookup a static member of this declaration.
@override
Builder findStaticBuilder(
String name, int charOffset, Uri fileUri, LibraryBuilder accessingLibrary,
{bool isSetter: false}) {
if (accessingLibrary.origin != library.origin && name.startsWith("_")) {
return null;
}
Builder declaration = isSetter
? scope.lookupSetter(name, charOffset, fileUri, isInstanceScope: false)
: scope.lookup(name, charOffset, fileUri, isInstanceScope: false);
// TODO(johnniwinther): Handle patched extensions.
return declaration;
}
// Deliberately unrelated return type to statically detect more accidental
// use until Builder.target is fully retired.
@override
UnrelatedTarget get target => unsupported(
"ExtensionBuilder.target is deprecated. "
"Use ExtensionBuilder.extension instead.",
charOffset,
fileUri);
@override
DartType buildType(LibraryBuilder library,
NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments) {
throw new UnsupportedError("ExtensionBuilder.buildType is not supported.");
}
@override
DartType buildTypesWithBuiltArguments(LibraryBuilder library,
Nullability nullability, List<DartType> arguments) {
throw new UnsupportedError("ExtensionBuilder.buildTypesWithBuiltArguments "
"is not supported.");
}
@override
bool get isExtension => true;
@override
InterfaceType get thisType => null;
@override
Builder lookupLocalMember(String name,
{bool setter: false, bool required: false}) {
// TODO(johnniwinther): Support patching on extensions.
Builder builder = setter ? scope.setters[name] : scope.local[name];
if (required && builder == null) {
internalProblem(
templateInternalProblemNotFoundIn.withArguments(
name, fullNameForErrors),
-1,
null);
}
return builder;
}
@override
String get debugName => "ExtensionBuilder";
@override
void buildOutlineExpressions(LibraryBuilder library) {
void build(String ignore, Builder declaration) {
MemberBuilder member = declaration;
member.buildOutlineExpressions(library);
}
// TODO(johnniwinther): Handle annotations on the extension declaration.
//MetadataBuilder.buildAnnotations(
// isPatch ? origin.extension : extension,
// metadata, library, this, null);
scope.forEach(build);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/named_type_builder.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 fasta.named_type_builder;
import 'package:kernel/ast.dart' show DartType, Supertype;
import '../fasta_codes.dart'
show
Message,
Template,
noLength,
templateMissingExplicitTypeArguments,
messageNotATypeContext,
LocatedMessage,
templateNotAType,
templateTypeArgumentMismatch,
templateTypeArgumentsOnTypeVariable,
templateTypeNotFound;
import '../messages.dart'
show noLength, templateSupertypeIsIllegal, templateSupertypeIsTypeVariable;
import '../problems.dart' show unhandled;
import '../severity.dart' show Severity;
import 'builder.dart'
show
Builder,
Identifier,
LibraryBuilder,
NullabilityBuilder,
PrefixBuilder,
QualifiedName,
Scope,
TypeBuilder,
TypeDeclarationBuilder,
TypeVariableBuilder,
flattenName;
import '../kernel/kernel_builder.dart'
show
ClassBuilder,
InvalidTypeBuilder,
LibraryBuilder,
TypeBuilder,
TypeDeclarationBuilder,
TypeVariableBuilder,
flattenName;
class NamedTypeBuilder extends TypeBuilder {
final Object name;
List<TypeBuilder> arguments;
final NullabilityBuilder nullabilityBuilder;
@override
TypeDeclarationBuilder declaration;
NamedTypeBuilder(this.name, this.nullabilityBuilder, this.arguments);
NamedTypeBuilder.fromTypeDeclarationBuilder(
this.declaration, this.nullabilityBuilder,
[this.arguments])
: this.name = declaration.name;
@override
void bind(TypeDeclarationBuilder declaration) {
this.declaration = declaration?.origin;
}
@override
void resolveIn(
Scope scope, int charOffset, Uri fileUri, LibraryBuilder library) {
if (declaration != null) return;
final Object name = this.name;
Builder member;
if (name is QualifiedName) {
Object qualifier = name.qualifier;
String prefixName = flattenName(qualifier, charOffset, fileUri);
Builder prefix = scope.lookup(prefixName, charOffset, fileUri);
if (prefix is PrefixBuilder) {
member = prefix.lookup(name.name, name.charOffset, fileUri);
}
} else if (name is String) {
member = scope.lookup(name, charOffset, fileUri);
} else {
unhandled("${name.runtimeType}", "resolveIn", charOffset, fileUri);
}
if (member is TypeVariableBuilder) {
declaration = member.origin;
if (arguments != null) {
String typeName;
int typeNameOffset;
if (name is Identifier) {
typeName = name.name;
typeNameOffset = name.charOffset;
} else {
typeName = name;
typeNameOffset = charOffset;
}
Message message =
templateTypeArgumentsOnTypeVariable.withArguments(typeName);
library.addProblem(message, typeNameOffset, typeName.length, fileUri);
declaration = buildInvalidType(
message.withLocation(fileUri, typeNameOffset, typeName.length));
}
return;
} else if (member is TypeDeclarationBuilder) {
declaration = member.origin;
if (!declaration.isExtension) {
if (arguments == null && declaration.typeVariablesCount != 0) {
String typeName;
int typeNameOffset;
if (name is Identifier) {
typeName = name.name;
typeNameOffset = name.charOffset;
} else {
typeName = name;
typeNameOffset = charOffset;
}
library.addProblem(
templateMissingExplicitTypeArguments
.withArguments(declaration.typeVariablesCount),
typeNameOffset,
typeName.length,
fileUri);
}
return;
}
}
Template<Message Function(String name)> template =
member == null ? templateTypeNotFound : templateNotAType;
String flatName = flattenName(name, charOffset, fileUri);
List<LocatedMessage> context;
if (member != null) {
context = <LocatedMessage>[
messageNotATypeContext.withLocation(member.fileUri, member.charOffset,
name is Identifier ? name.name.length : "$name".length)
];
}
int length =
name is Identifier ? name.endCharOffset - charOffset : flatName.length;
Message message = template.withArguments(flatName);
library.addProblem(message, charOffset, length, fileUri, context: context);
declaration = buildInvalidType(
message.withLocation(fileUri, charOffset, length),
context: context);
}
@override
void check(LibraryBuilder library, int charOffset, Uri fileUri) {
if (arguments != null &&
arguments.length != declaration.typeVariablesCount) {
Message message = templateTypeArgumentMismatch
.withArguments(declaration.typeVariablesCount);
library.addProblem(message, charOffset, noLength, fileUri);
declaration =
buildInvalidType(message.withLocation(fileUri, charOffset, noLength));
}
}
@override
void normalize(int charOffset, Uri fileUri) {
if (arguments != null &&
arguments.length != declaration.typeVariablesCount) {
// [arguments] will be normalized later if they are null.
arguments = null;
}
}
String get debugName => "NamedTypeBuilder";
StringBuffer printOn(StringBuffer buffer) {
buffer.write(name);
if (arguments?.isEmpty ?? true) return buffer;
buffer.write("<");
bool first = true;
for (TypeBuilder t in arguments) {
if (!first) buffer.write(", ");
first = false;
t.printOn(buffer);
}
buffer.write(">");
nullabilityBuilder.writeNullabilityOn(buffer);
return buffer;
}
InvalidTypeBuilder buildInvalidType(LocatedMessage message,
{List<LocatedMessage> context}) {
// TODO(ahe): Consider if it makes sense to pass a QualifiedName to
// InvalidTypeBuilder?
return new InvalidTypeBuilder(
flattenName(name, message.charOffset, message.uri), message,
context: context);
}
Supertype handleInvalidSupertype(
LibraryBuilder library, int charOffset, Uri fileUri) {
Template<Message Function(String name)> template =
declaration.isTypeVariable
? templateSupertypeIsTypeVariable
: templateSupertypeIsIllegal;
library.addProblem(
template.withArguments(flattenName(name, charOffset, fileUri)),
charOffset,
noLength,
fileUri);
return null;
}
DartType build(LibraryBuilder library) {
assert(declaration != null, "Declaration has not been resolved on $this.");
return declaration.buildType(library, nullabilityBuilder, arguments);
}
Supertype buildSupertype(
LibraryBuilder library, int charOffset, Uri fileUri) {
TypeDeclarationBuilder declaration = this.declaration;
if (declaration is ClassBuilder) {
return declaration.buildSupertype(library, arguments);
} else if (declaration is InvalidTypeBuilder) {
library.addProblem(
declaration.message.messageObject,
declaration.message.charOffset,
declaration.message.length,
declaration.message.uri,
severity: Severity.error);
return null;
} else {
return handleInvalidSupertype(library, charOffset, fileUri);
}
}
Supertype buildMixedInType(
LibraryBuilder library, int charOffset, Uri fileUri) {
TypeDeclarationBuilder declaration = this.declaration;
if (declaration is ClassBuilder) {
return declaration.buildMixedInType(library, arguments);
} else if (declaration is InvalidTypeBuilder) {
library.addProblem(
declaration.message.messageObject,
declaration.message.charOffset,
declaration.message.length,
declaration.message.uri,
severity: Severity.error);
return null;
} else {
return handleInvalidSupertype(library, charOffset, fileUri);
}
}
TypeBuilder subst(Map<TypeVariableBuilder, TypeBuilder> substitution) {
TypeBuilder result = substitution[declaration];
if (result != null) {
assert(declaration is TypeVariableBuilder);
return result;
} else if (arguments != null) {
List<TypeBuilder> arguments;
int i = 0;
for (TypeBuilder argument in this.arguments) {
TypeBuilder type = argument.subst(substitution);
if (type != argument) {
arguments ??= this.arguments.toList();
arguments[i] = type;
}
i++;
}
if (arguments != null) {
NamedTypeBuilder result =
new NamedTypeBuilder(name, nullabilityBuilder, arguments);
if (declaration != null) {
result.bind(declaration);
} else {
throw new UnsupportedError("Unbound type in substitution: $result.");
}
return result;
}
}
return this;
}
NamedTypeBuilder clone(List<TypeBuilder> newTypes) {
List<TypeBuilder> clonedArguments;
if (arguments != null) {
clonedArguments = new List<TypeBuilder>(arguments.length);
for (int i = 0; i < clonedArguments.length; i++) {
clonedArguments[i] = arguments[i].clone(newTypes);
}
}
NamedTypeBuilder newType =
new NamedTypeBuilder(name, nullabilityBuilder, clonedArguments);
newTypes.add(newType);
return newType;
}
NamedTypeBuilder withNullabilityBuilder(
NullabilityBuilder nullabilityBuilder) {
return new NamedTypeBuilder(name, nullabilityBuilder, arguments)
..bind(declaration);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/prefix_builder.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 fasta.prefix_builder;
import 'builder.dart' show LibraryBuilder, Scope;
import 'declaration.dart';
import 'package:kernel/ast.dart' show LibraryDependency;
import '../kernel/load_library_builder.dart' show LoadLibraryBuilder;
class PrefixBuilder extends BuilderImpl {
final String name;
final Scope exportScope = new Scope.top();
final LibraryBuilder parent;
final bool deferred;
@override
final int charOffset;
final int importIndex;
final LibraryDependency dependency;
LoadLibraryBuilder loadLibraryBuilder;
PrefixBuilder(this.name, this.deferred, this.parent, this.dependency,
this.charOffset, this.importIndex) {
if (deferred) {
loadLibraryBuilder =
new LoadLibraryBuilder(parent, dependency, charOffset);
addToExportScope('loadLibrary', loadLibraryBuilder, charOffset);
}
}
Uri get fileUri => parent.fileUri;
Builder lookup(String name, int charOffset, Uri fileUri) {
return exportScope.lookup(name, charOffset, fileUri);
}
void addToExportScope(String name, Builder member, int charOffset) {
Map<String, Builder> map =
member.isSetter ? exportScope.setters : exportScope.local;
Builder existing = map[name];
if (existing != null) {
map[name] = parent.computeAmbiguousDeclaration(
name, existing, member, charOffset,
isExport: true);
} else {
map[name] = member;
}
}
@override
String get fullNameForErrors => name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/function_type_builder.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 fasta.function_type_builder;
import 'builder.dart'
show LibraryBuilder, NullabilityBuilder, TypeBuilder, TypeVariableBuilder;
import 'package:kernel/ast.dart'
show
DartType,
DynamicType,
FunctionType,
NamedType,
Supertype,
TypeParameter,
TypedefType;
import '../fasta_codes.dart'
show LocatedMessage, messageSupertypeIsFunction, noLength;
import '../problems.dart' show unsupported;
import '../kernel/kernel_builder.dart'
show
FormalParameterBuilder,
LibraryBuilder,
TypeBuilder,
TypeVariableBuilder;
class FunctionTypeBuilder extends TypeBuilder {
final TypeBuilder returnType;
final List<TypeVariableBuilder> typeVariables;
final List<FormalParameterBuilder> formals;
final NullabilityBuilder nullabilityBuilder;
FunctionTypeBuilder(this.returnType, this.typeVariables, this.formals,
this.nullabilityBuilder);
@override
String get name => null;
@override
String get debugName => "Function";
@override
StringBuffer printOn(StringBuffer buffer) {
if (typeVariables != null) {
buffer.write("<");
bool isFirst = true;
for (TypeVariableBuilder t in typeVariables) {
if (!isFirst) {
buffer.write(", ");
} else {
isFirst = false;
}
buffer.write(t.name);
}
buffer.write(">");
}
buffer.write("(");
if (formals != null) {
bool isFirst = true;
for (dynamic t in formals) {
if (!isFirst) {
buffer.write(", ");
} else {
isFirst = false;
}
buffer.write(t?.fullNameForErrors);
}
}
buffer.write(") ->");
nullabilityBuilder.writeNullabilityOn(buffer);
buffer.write(" ");
buffer.write(returnType?.fullNameForErrors);
return buffer;
}
FunctionType build(LibraryBuilder library, [TypedefType origin]) {
DartType builtReturnType =
returnType?.build(library) ?? const DynamicType();
List<DartType> positionalParameters = <DartType>[];
List<NamedType> namedParameters;
int requiredParameterCount = 0;
if (formals != null) {
for (FormalParameterBuilder formal in formals) {
DartType type = formal.type?.build(library) ?? const DynamicType();
if (formal.isPositional) {
positionalParameters.add(type);
if (formal.isRequired) requiredParameterCount++;
} else if (formal.isNamed) {
namedParameters ??= <NamedType>[];
namedParameters.add(new NamedType(formal.name, type,
isRequired: formal.isNamedRequired));
}
}
if (namedParameters != null) {
namedParameters.sort();
}
}
List<TypeParameter> typeParameters;
if (typeVariables != null) {
typeParameters = <TypeParameter>[];
for (TypeVariableBuilder t in typeVariables) {
typeParameters.add(t.parameter);
}
}
return new FunctionType(positionalParameters, builtReturnType,
namedParameters: namedParameters ?? const <NamedType>[],
typeParameters: typeParameters ?? const <TypeParameter>[],
requiredParameterCount: requiredParameterCount,
typedefType: origin,
nullability: nullabilityBuilder.build(library));
}
Supertype buildSupertype(
LibraryBuilder library, int charOffset, Uri fileUri) {
library.addProblem(
messageSupertypeIsFunction, charOffset, noLength, fileUri);
return null;
}
Supertype buildMixedInType(
LibraryBuilder library, int charOffset, Uri fileUri) {
return buildSupertype(library, charOffset, fileUri);
}
@override
buildInvalidType(LocatedMessage message, {List<LocatedMessage> context}) {
return unsupported("buildInvalidType", message.charOffset, message.uri);
}
FunctionTypeBuilder clone(List<TypeBuilder> newTypes) {
List<TypeVariableBuilder> clonedTypeVariables;
if (typeVariables != null) {
clonedTypeVariables = new List<TypeVariableBuilder>(typeVariables.length);
for (int i = 0; i < clonedTypeVariables.length; i++) {
clonedTypeVariables[i] = typeVariables[i].clone(newTypes);
}
}
List<FormalParameterBuilder> clonedFormals;
if (formals != null) {
clonedFormals = new List<FormalParameterBuilder>(formals.length);
for (int i = 0; i < clonedFormals.length; i++) {
FormalParameterBuilder formal = formals[i];
clonedFormals[i] = formal.clone(newTypes);
}
}
FunctionTypeBuilder newType = new FunctionTypeBuilder(
returnType?.clone(newTypes),
clonedTypeVariables,
clonedFormals,
nullabilityBuilder);
newTypes.add(newType);
return newType;
}
FunctionTypeBuilder withNullabilityBuilder(
NullabilityBuilder nullabilityBuilder) {
return new FunctionTypeBuilder(
returnType, typeVariables, formals, nullabilityBuilder);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/builder.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 fasta.builder;
export '../identifiers.dart'
show
Identifier,
InitializedIdentifier,
QualifiedName,
deprecated_extractToken,
flattenName;
export '../scope.dart' show AccessErrorBuilder, Scope, ScopeBuilder;
export 'builtin_type_builder.dart' show BuiltinTypeBuilder;
export 'class_builder.dart' show ClassBuilder;
export 'constructor_reference_builder.dart' show ConstructorReferenceBuilder;
export 'declaration.dart' show Builder;
export 'dynamic_type_builder.dart' show DynamicTypeBuilder;
export 'enum_builder.dart' show EnumBuilder, EnumConstantInfo;
export 'field_builder.dart' show FieldBuilder;
export 'formal_parameter_builder.dart' show FormalParameterBuilder;
export 'procedure_builder.dart'
show
FunctionBuilder,
ConstructorBuilder,
ProcedureBuilder,
RedirectingFactoryBuilder;
export 'function_type_builder.dart' show FunctionTypeBuilder;
export 'invalid_type_builder.dart' show InvalidTypeBuilder;
export 'library_builder.dart' show LibraryBuilder;
export 'member_builder.dart' show MemberBuilder;
export 'metadata_builder.dart' show MetadataBuilder;
export 'mixin_application_builder.dart' show MixinApplicationBuilder;
export 'modifier_builder.dart' show ModifierBuilder;
export 'name_iterator.dart' show NameIterator;
export 'named_type_builder.dart' show NamedTypeBuilder;
export 'nullability_builder.dart' show NullabilityBuilder;
export 'prefix_builder.dart' show PrefixBuilder;
export 'type_alias_builder.dart' show TypeAliasBuilder;
export 'type_builder.dart' show TypeBuilder;
export 'type_declaration_builder.dart' show TypeDeclarationBuilder;
export 'type_variable_builder.dart' show TypeVariableBuilder;
export 'unresolved_type.dart' show UnresolvedType;
export 'void_type_builder.dart' show VoidTypeBuilder;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/builder/type_builder.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 fasta.type_builder;
import 'package:kernel/ast.dart' show DartType, Supertype;
import '../fasta_codes.dart' show LocatedMessage;
import '../scope.dart';
import 'library_builder.dart';
import 'nullability_builder.dart';
import 'type_declaration_builder.dart';
import 'type_variable_builder.dart';
abstract class TypeBuilder {
const TypeBuilder();
TypeDeclarationBuilder get declaration => null;
void resolveIn(
Scope scope, int charOffset, Uri fileUri, LibraryBuilder library) {}
/// See `UnresolvedType.checkType`.
void check(LibraryBuilder library, int charOffset, Uri fileUri) {}
/// See `UnresolvedType.normalizeType`.
void normalize(int charOffset, Uri fileUri) {}
void bind(TypeDeclarationBuilder builder) {}
/// May return null, for example, for mixin applications.
Object get name;
NullabilityBuilder get nullabilityBuilder;
String get debugName;
StringBuffer printOn(StringBuffer buffer);
String toString() => "$debugName(${printOn(new StringBuffer())})";
/// Returns the [TypeBuilder] for this type in which [TypeVariableBuilder]s
/// in [substitution] have been replaced by the corresponding [TypeBuilder]s.
///
/// If [unboundTypes] is provided, created type builders that are not bound
/// are added to [unboundTypes]. Otherwise, creating an unbound type builder
/// throws an error.
// TODO(johnniwinther): Change [NamedTypeBuilder] to hold the
// [TypeParameterScopeBuilder] should resolve it, so that we cannot create
// [NamedTypeBuilder]s that are orphaned.
TypeBuilder subst(Map<TypeVariableBuilder, TypeBuilder> substitution) => this;
/// Clones the type builder recursively without binding the subterms to
/// existing declaration or type variable builders. All newly built types
/// are added to [newTypes], so that they can be added to a proper scope and
/// resolved later.
TypeBuilder clone(List<TypeBuilder> newTypes);
buildInvalidType(LocatedMessage message, {List<LocatedMessage> context});
String get fullNameForErrors => "${printOn(new StringBuffer())}";
DartType build(LibraryBuilder library);
Supertype buildSupertype(LibraryBuilder library, int charOffset, Uri fileUri);
Supertype buildMixedInType(
LibraryBuilder library, int charOffset, Uri fileUri);
TypeBuilder withNullabilityBuilder(NullabilityBuilder nullabilityBuilder);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/scanner_main.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.md file.
library fasta.scanner.main;
import 'io.dart' show readBytesFromFileSync;
import '../scanner.dart' show ErrorToken, Token, scan;
scanAll(Map<Uri, List<int>> files, {bool verbose: false, bool verify: false}) {
Stopwatch sw = new Stopwatch()..start();
int byteCount = 0;
files.forEach((Uri uri, List<int> bytes) {
Token token = scan(bytes).tokens;
if (verbose) printTokens(token);
if (verify) verifyErrorTokens(token, uri);
byteCount += bytes.length - 1;
});
sw.stop();
print("Scanning files took: ${sw.elapsed}");
print("Bytes/ms: ${byteCount / sw.elapsedMilliseconds}");
}
void printTokens(Token token) {
while (!token.isEof) {
print("${token.charOffset}: $token");
token = token.next;
}
}
/// Verify that the fasta scanner recovery has moved all of the ErrorTokens
/// to the beginning of the stream. If an out-of-order ErrorToken is
/// found, then print some diagnostic information and throw an exception.
void verifyErrorTokens(Token firstToken, Uri uri) {
Token token = firstToken;
while (token is ErrorToken) {
token = token.next;
}
while (!token.isEof) {
if (token is ErrorToken) {
print('Found out-of-order ErrorTokens when scanning:\n $uri');
// Rescan the token stream up to the error token to find the 10 tokens
// before the out of order ErrorToken.
Token errorToken = token;
Token start = firstToken;
int count = 0;
token = firstToken;
while (token != errorToken) {
token = token.next;
if (count < 10) {
++count;
} else {
start = start.next;
}
}
// Print the out of order error token plus some tokens before and after.
count = 0;
token = start;
while (count < 20 && !token.isEof) {
print("${token.charOffset}: $token");
token = token.next;
++count;
}
throw 'Out of order ErrorToken: $errorToken';
}
token = token.next;
}
}
mainEntryPoint(List<String> arguments) {
Map<Uri, List<int>> files = <Uri, List<int>>{};
Stopwatch sw = new Stopwatch()..start();
bool verbose = const bool.fromEnvironment("printTokens");
bool verify = const bool.fromEnvironment('verifyErrorTokens');
for (String arg in arguments) {
if (arg.startsWith('--')) {
if (arg == '--print-tokens') {
verbose = true;
} else if (arg == '--verify-error-tokens') {
verify = true;
} else {
print('Unrecognized option: $arg');
}
continue;
}
Uri uri = Uri.base.resolve(arg);
List<int> bytes = readBytesFromFileSync(uri);
files[uri] = bytes;
}
sw.stop();
print("Reading files took: ${sw.elapsed}");
scanAll(files, verbose: verbose, verify: verify);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/string_canonicalizer.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 fasta.scanner.string_canonicalizer;
import 'dart:convert';
class Node {
dynamic /* String | List<int> */ data;
int start;
int end;
String payload;
Node next;
Node(this.data, this.start, this.end, this.payload, this.next);
}
/// A hash table for triples:
/// (list of bytes, start, end) --> canonicalized string
/// Using triples avoids allocating string slices before checking if they
/// are canonical.
///
/// Gives about 3% speedup on dart2js.
class StringCanonicalizer {
/// Mask away top bits to keep hash calculation within 32-bit SMI range.
static const int MASK = 16 * 1024 * 1024 - 1;
static const int INITIAL_SIZE = 8 * 1024;
/// Linear size of a hash table.
int _size = INITIAL_SIZE;
/// Items in a hash table.
int _count = 0;
/// The table itself.
List<Node> _nodes = new List<Node>(INITIAL_SIZE);
static String decode(List<int> data, int start, int end, bool asciiOnly) {
String s;
if (asciiOnly) {
s = new String.fromCharCodes(data, start, end);
} else {
s = new Utf8Decoder(allowMalformed: true).convert(data, start, end);
}
return s;
}
static int hashBytes(List<int> data, int start, int end) {
int h = 5381;
for (int i = start; i < end; i++) {
h = ((h << 5) + h + data[i]) & MASK;
}
return h;
}
static int hashString(String data, int start, int end) {
int h = 5381;
for (int i = start; i < end; i++) {
h = ((h << 5) + h + data.codeUnitAt(i)) & MASK;
}
return h;
}
rehash() {
int newSize = _size * 2;
List<Node> newNodes = new List<Node>(newSize);
for (int i = 0; i < _size; i++) {
Node t = _nodes[i];
while (t != null) {
Node n = t.next;
int newIndex = t.data is String
? hashString(t.data, t.start, t.end) & (newSize - 1)
: hashBytes(t.data, t.start, t.end) & (newSize - 1);
Node s = newNodes[newIndex];
t.next = s;
newNodes[newIndex] = t;
t = n;
}
}
_size = newSize;
_nodes = newNodes;
}
String canonicalize(data, int start, int end, bool asciiOnly) {
if (_count > _size) rehash();
int index = data is String
? hashString(data, start, end)
: hashBytes(data, start, end);
index = index & (_size - 1);
Node s = _nodes[index];
Node t = s;
int len = end - start;
while (t != null) {
if (t.end - t.start == len) {
int i = start, j = t.start;
while (i < end && data[i] == t.data[j]) {
i++;
j++;
}
if (i == end) {
return t.payload;
}
}
t = t.next;
}
String payload;
if (data is String) {
payload = data.substring(start, end);
} else {
payload = decode(data, start, end, asciiOnly);
}
_nodes[index] = new Node(data, start, end, payload, s);
_count++;
return payload;
}
clear() {
_size = INITIAL_SIZE;
_nodes = new List<Node>(_size);
_count = 0;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/recover.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 fasta.scanner.recover;
import '../../scanner/token.dart' show TokenType;
import '../../scanner/token.dart' show Token;
import 'token.dart' show StringToken;
import 'error_token.dart' show ErrorToken;
/// Recover from errors in [tokens]. The original sources are provided as
/// [bytes]. [lineStarts] are the beginning character offsets of lines, and
/// must be updated if recovery is performed rewriting the original source
/// code.
Token scannerRecovery(List<int> bytes, Token tokens, List<int> lineStarts) {
// Sanity check that all error tokens are prepended.
// TODO(danrubel): Remove this in a while after the dust has settled.
// Skip over prepended error tokens
Token token = tokens;
while (token is ErrorToken) {
token = token.next;
}
// Assert no error tokens in the remaining tokens
while (!token.isEof) {
if (token is ErrorToken) {
for (int count = 0; count < 3; ++count) {
Token previous = token.previous;
if (previous.isEof) break;
token = previous;
}
StringBuffer msg = new StringBuffer(
"Internal error: All error tokens should have been prepended:");
for (int count = 0; count < 7; ++count) {
if (token.isEof) break;
msg.write(' ${token.runtimeType},');
token = token.next;
}
throw msg.toString();
}
token = token.next;
}
return tokens;
}
Token synthesizeToken(int charOffset, String value, TokenType type) {
return new StringToken.fromString(type, value, charOffset);
}
Token skipToEof(Token token) {
while (!token.isEof) {
token = token.next;
}
return token;
}
String closeBraceFor(String openBrace) {
return const {
'(': ')',
'[': ']',
'{': '}',
'<': '>',
r'${': '}',
'?.[': ']',
}[openBrace];
}
String closeQuoteFor(String openQuote) {
return const {
'"': '"',
"'": "'",
'"""': '"""',
"'''": "'''",
'r"': '"',
"r'": "'",
'r"""': '"""',
"r'''": "'''",
}[openQuote];
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/string_scanner.dart | // Copyright (c) 2011, 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 dart2js.scanner.string_scanner;
import '../../scanner/token.dart' show Token, SyntheticStringToken, TokenType;
import '../../scanner/token.dart' as analyzer show StringToken;
import 'abstract_scanner.dart'
show AbstractScanner, LanguageVersionChanged, ScannerConfiguration;
import 'token.dart'
show CommentToken, DartDocToken, LanguageVersionToken, StringToken;
import 'error_token.dart' show ErrorToken;
/**
* Scanner that reads from a String and creates tokens that points to
* substrings.
*/
class StringScanner extends AbstractScanner {
/** The file content. */
String string;
/** The current offset in [string]. */
int scanOffset = -1;
StringScanner(String string,
{ScannerConfiguration configuration,
bool includeComments: false,
LanguageVersionChanged languageVersionChanged})
: string = ensureZeroTermination(string),
super(configuration, includeComments, languageVersionChanged);
static String ensureZeroTermination(String string) {
return (string.isEmpty || string.codeUnitAt(string.length - 1) != 0)
// TODO(lry): abort instead of copying the array, or warn?
? string + '\x00'
: string;
}
static bool isLegalIdentifier(String identifier) {
StringScanner scanner = new StringScanner(identifier);
Token startToken = scanner.tokenize();
return startToken is! ErrorToken && startToken.next.isEof;
}
int advance() => string.codeUnitAt(++scanOffset);
int peek() => string.codeUnitAt(scanOffset + 1);
int get stringOffset => scanOffset;
int currentAsUnicode(int next) => next;
void handleUnicode(int startScanOffset) {}
@override
analyzer.StringToken createSubstringToken(
TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]) {
return new StringToken.fromSubstring(
type, string, start, scanOffset + extraOffset, tokenStart,
canonicalize: true, precedingComments: comments);
}
@override
analyzer.StringToken createSyntheticSubstringToken(
TokenType type, int start, bool asciiOnly, String syntheticChars) {
String source = string.substring(start, scanOffset);
return new SyntheticStringToken(
type, source + syntheticChars, tokenStart, source.length);
}
@override
CommentToken createCommentToken(TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]) {
return new CommentToken.fromSubstring(
type, string, start, scanOffset + extraOffset, tokenStart,
canonicalize: true);
}
@override
DartDocToken createDartDocToken(TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]) {
return new DartDocToken.fromSubstring(
type, string, start, scanOffset + extraOffset, tokenStart,
canonicalize: true);
}
@override
LanguageVersionToken createLanguageVersionToken(
int start, int major, int minor) {
return new LanguageVersionToken.fromSubstring(
string, start, scanOffset, tokenStart, major, minor,
canonicalize: true);
}
bool atEndOfFile() => scanOffset >= string.length - 1;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/keyword_state.dart | // Copyright (c) 2011, 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 fasta.scanner.keywords;
import '../../scanner/token.dart' as analyzer;
import 'characters.dart' show $a, $z, $A, $Z;
/**
* Abstract state in a state machine for scanning keywords.
*/
abstract class KeywordState {
KeywordState next(int c);
KeywordState nextCapital(int c);
analyzer.Keyword get keyword;
static KeywordState _KEYWORD_STATE;
static KeywordState get KEYWORD_STATE {
if (_KEYWORD_STATE == null) {
List<String> strings = new List<String>(analyzer.Keyword.values.length);
for (int i = 0; i < analyzer.Keyword.values.length; i++) {
strings[i] = analyzer.Keyword.values[i].lexeme;
}
strings.sort((a, b) => a.compareTo(b));
_KEYWORD_STATE = computeKeywordStateTable(0, strings, 0, strings.length);
}
return _KEYWORD_STATE;
}
static KeywordState computeKeywordStateTable(
int start, List<String> strings, int offset, int length) {
bool isLowercase = true;
List<KeywordState> table = new List<KeywordState>($z - $A + 1);
assert(length != 0);
int chunk = 0;
int chunkStart = -1;
bool isLeaf = false;
for (int i = offset; i < offset + length; i++) {
if (strings[i].length == start) {
isLeaf = true;
}
if (strings[i].length > start) {
int c = strings[i].codeUnitAt(start);
if ($A <= c && c <= $Z) {
isLowercase = false;
}
if (chunk != c) {
if (chunkStart != -1) {
assert(table[chunk - $A] == null);
table[chunk - $A] = computeKeywordStateTable(
start + 1, strings, chunkStart, i - chunkStart);
}
chunkStart = i;
chunk = c;
}
}
}
if (chunkStart != -1) {
assert(table[chunk - $A] == null);
table[chunk - $A] = computeKeywordStateTable(
start + 1, strings, chunkStart, offset + length - chunkStart);
} else {
assert(length == 1);
return new LeafKeywordState(strings[offset]);
}
String syntax = isLeaf ? strings[offset] : null;
if (isLowercase) {
table = table.sublist($a - $A);
return new LowerCaseArrayKeywordState(table, syntax);
} else {
return new UpperCaseArrayKeywordState(table, syntax);
}
}
}
/**
* A state with multiple outgoing transitions.
*/
abstract class ArrayKeywordState implements KeywordState {
final List<KeywordState> table;
final analyzer.Keyword keyword;
ArrayKeywordState(this.table, String syntax)
: keyword = ((syntax == null) ? null : analyzer.Keyword.keywords[syntax]);
KeywordState next(int c);
KeywordState nextCapital(int c);
String toString() {
StringBuffer sb = new StringBuffer();
sb.write("[");
if (keyword != null) {
sb.write("*");
sb.write(keyword);
sb.write(" ");
}
List<KeywordState> foo = table;
for (int i = 0; i < foo.length; i++) {
if (foo[i] != null) {
sb.write("${new String.fromCharCodes([i + $a])}: "
"${foo[i]}; ");
}
}
sb.write("]");
return sb.toString();
}
}
class LowerCaseArrayKeywordState extends ArrayKeywordState {
LowerCaseArrayKeywordState(List<KeywordState> table, String syntax)
: super(table, syntax) {
assert(table.length == $z - $a + 1);
}
KeywordState next(int c) => table[c - $a];
KeywordState nextCapital(int c) => null;
}
class UpperCaseArrayKeywordState extends ArrayKeywordState {
UpperCaseArrayKeywordState(List<KeywordState> table, String syntax)
: super(table, syntax) {
assert(table.length == $z - $A + 1);
}
KeywordState next(int c) => table[c - $A];
KeywordState nextCapital(int c) => table[c - $A];
}
/**
* A state that has no outgoing transitions.
*/
class LeafKeywordState implements KeywordState {
final analyzer.Keyword keyword;
LeafKeywordState(String syntax) : keyword = analyzer.Keyword.keywords[syntax];
KeywordState next(int c) => null;
KeywordState nextCapital(int c) => null;
String toString() => keyword.lexeme;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/utf8_bytes_scanner.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.
library fasta.scanner.utf8_bytes_scanner;
import 'dart:convert' show unicodeBomCharacterRune, utf8;
import '../../scanner/token.dart' show SyntheticStringToken, TokenType;
import '../../scanner/token.dart' as analyzer show StringToken;
import '../scanner.dart' show unicodeReplacementCharacter;
import 'abstract_scanner.dart'
show AbstractScanner, LanguageVersionChanged, ScannerConfiguration;
import 'token.dart'
show CommentToken, DartDocToken, LanguageVersionToken, StringToken;
/**
* Scanner that reads from a UTF-8 encoded list of bytes and creates tokens
* that points to substrings.
*/
class Utf8BytesScanner extends AbstractScanner {
/**
* The file content.
*
* The content is zero-terminated.
*/
List<int> bytes;
/**
* Points to the offset of the last byte returned by [advance].
*
* After invoking [currentAsUnicode], the [byteOffset] points to the last
* byte that is part of the (unicode or ASCII) character. That way, [advance]
* can always increase the byte offset by 1.
*/
int byteOffset = -1;
/**
* The getter [scanOffset] is expected to return the index where the current
* character *starts*. In case of a non-ascii character, after invoking
* [currentAsUnicode], the byte offset points to the *last* byte.
*
* This field keeps track of the number of bytes for the current unicode
* character. For example, if bytes 7,8,9 encode one unicode character, the
* [byteOffset] is 9 (after invoking [currentAsUnicode]). The [scanSlack]
* will be 2, so that [scanOffset] returns 7.
*/
int scanSlack = 0;
/**
* Holds the [byteOffset] value for which the current [scanSlack] is valid.
*/
int scanSlackOffset = -1;
/**
* Returns the byte offset of the first byte that belongs to the current
* character.
*/
int get scanOffset {
if (byteOffset == scanSlackOffset) {
return byteOffset - scanSlack;
} else {
return byteOffset;
}
}
/**
* The difference between the number of bytes and the number of corresponding
* string characters, up to the current [byteOffset].
*/
int utf8Slack = 0;
/**
* Creates a new Utf8BytesScanner. The source file is expected to be a
* [Utf8BytesSourceFile] that holds a list of UTF-8 bytes. Otherwise the
* string text of the source file is decoded.
*
* The list of UTF-8 bytes [file.slowUtf8Bytes()] is expected to return an
* array whose last element is '0' to signal the end of the file. If this
* is not the case, the entire array is copied before scanning.
*/
Utf8BytesScanner(this.bytes,
{ScannerConfiguration configuration,
bool includeComments: false,
LanguageVersionChanged languageVersionChanged})
: super(configuration, includeComments, languageVersionChanged,
numberOfBytesHint: bytes.length) {
assert(bytes.last == 0);
// Skip a leading BOM.
if (containsBomAt(0)) byteOffset += 3;
}
bool containsBomAt(int offset) {
const List<int> BOM_UTF8 = const [0xEF, 0xBB, 0xBF];
return offset + 3 < bytes.length &&
bytes[offset] == BOM_UTF8[0] &&
bytes[offset + 1] == BOM_UTF8[1] &&
bytes[offset + 2] == BOM_UTF8[2];
}
int advance() => bytes[++byteOffset];
int peek() => bytes[byteOffset + 1];
/// Returns the unicode code point starting at the byte offset [startOffset]
/// with the byte [nextByte].
int nextCodePoint(int startOffset, int nextByte) {
int expectedHighBytes;
if (nextByte < 0xC2) {
expectedHighBytes = 1; // Bad code unit.
} else if (nextByte < 0xE0) {
expectedHighBytes = 2;
} else if (nextByte < 0xF0) {
expectedHighBytes = 3;
} else if (nextByte < 0xF5) {
expectedHighBytes = 4;
} else {
expectedHighBytes = 1; // Bad code unit.
}
int numBytes = 0;
for (int i = 0; i < expectedHighBytes; i++) {
if (bytes[byteOffset + i] < 0x80) {
break;
}
numBytes++;
}
int end = startOffset + numBytes;
byteOffset = end - 1;
if (expectedHighBytes == 1 || numBytes != expectedHighBytes) {
return unicodeReplacementCharacter;
}
// TODO(lry): measurably slow, decode creates first a Utf8Decoder and a
// _Utf8Decoder instance. Also the sublist is eagerly allocated.
String codePoint =
utf8.decode(bytes.sublist(startOffset, end), allowMalformed: true);
if (codePoint.length == 0) {
// The UTF-8 decoder discards leading BOM characters.
// TODO(floitsch): don't just assume that removed characters were the
// BOM.
assert(containsBomAt(startOffset));
codePoint = new String.fromCharCode(unicodeBomCharacterRune);
}
if (codePoint.length == 1) {
utf8Slack += (numBytes - 1);
scanSlack = numBytes - 1;
scanSlackOffset = byteOffset;
return codePoint.codeUnitAt(0);
} else if (codePoint.length == 2) {
utf8Slack += (numBytes - 2);
scanSlack = numBytes - 1;
scanSlackOffset = byteOffset;
stringOffsetSlackOffset = byteOffset;
// In case of a surrogate pair, return a single code point.
// Gracefully degrade given invalid UTF-8.
RuneIterator runes = codePoint.runes.iterator;
if (!runes.moveNext()) return unicodeReplacementCharacter;
int codeUnit = runes.current;
return !runes.moveNext() ? codeUnit : unicodeReplacementCharacter;
} else {
return unicodeReplacementCharacter;
}
}
int lastUnicodeOffset = -1;
int currentAsUnicode(int next) {
if (next < 128) return next;
// Check if currentAsUnicode was already invoked.
if (byteOffset == lastUnicodeOffset) return next;
int res = nextCodePoint(byteOffset, next);
lastUnicodeOffset = byteOffset;
return res;
}
void handleUnicode(int startScanOffset) {
int end = byteOffset;
// TODO(lry): this measurably slows down the scanner for files with unicode.
String s =
utf8.decode(bytes.sublist(startScanOffset, end), allowMalformed: true);
utf8Slack += (end - startScanOffset) - s.length;
}
/**
* This field remembers the byte offset of the last character decoded with
* [nextCodePoint] that used two code units in UTF-16.
*
* [nextCodePoint] returns a single code point for each unicode character,
* even if it needs two code units in UTF-16.
*
* For example, '\u{1d11e}' uses 4 bytes in UTF-8, and two code units in
* UTF-16. The [utf8Slack] is therefore 2. After invoking [nextCodePoint], the
* [byteOffset] points to the last (of 4) bytes. The [stringOffset] should
* return the offset of the first one, which is one position more left than
* the [utf8Slack].
*/
int stringOffsetSlackOffset = -1;
int get stringOffset {
if (stringOffsetSlackOffset == byteOffset) {
return byteOffset - utf8Slack - 1;
} else {
return byteOffset - utf8Slack;
}
}
@override
analyzer.StringToken createSubstringToken(
TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]) {
return new StringToken.fromUtf8Bytes(
type, bytes, start, byteOffset + extraOffset, asciiOnly, tokenStart,
precedingComments: comments);
}
@override
analyzer.StringToken createSyntheticSubstringToken(
TokenType type, int start, bool asciiOnly, String syntheticChars) {
String source = StringToken.decodeUtf8(bytes, start, byteOffset, asciiOnly);
return new SyntheticStringToken(
type, source + syntheticChars, tokenStart, source.length);
}
@override
CommentToken createCommentToken(TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]) {
return new CommentToken.fromUtf8Bytes(
type, bytes, start, byteOffset + extraOffset, asciiOnly, tokenStart);
}
@override
DartDocToken createDartDocToken(TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]) {
return new DartDocToken.fromUtf8Bytes(
type, bytes, start, byteOffset + extraOffset, asciiOnly, tokenStart);
}
@override
LanguageVersionToken createLanguageVersionToken(
int start, int major, int minor) {
return new LanguageVersionToken.fromUtf8Bytes(
bytes, start, byteOffset, tokenStart, major, minor);
}
bool atEndOfFile() => byteOffset >= bytes.length - 1;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/characters.dart | // Copyright (c) 2011, 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 fasta.scanner.characters;
const int $EOF = 0;
const int $STX = 2;
const int $BS = 8;
const int $TAB = 9;
const int $LF = 10;
const int $VTAB = 11;
const int $FF = 12;
const int $CR = 13;
const int $SPACE = 32;
const int $BANG = 33;
const int $DQ = 34;
const int $HASH = 35;
const int $$ = 36;
const int $PERCENT = 37;
const int $AMPERSAND = 38;
const int $SQ = 39;
const int $OPEN_PAREN = 40;
const int $CLOSE_PAREN = 41;
const int $STAR = 42;
const int $PLUS = 43;
const int $COMMA = 44;
const int $MINUS = 45;
const int $PERIOD = 46;
const int $SLASH = 47;
const int $0 = 48;
const int $1 = 49;
const int $2 = 50;
const int $3 = 51;
const int $4 = 52;
const int $5 = 53;
const int $6 = 54;
const int $7 = 55;
const int $8 = 56;
const int $9 = 57;
const int $COLON = 58;
const int $SEMICOLON = 59;
const int $LT = 60;
const int $EQ = 61;
const int $GT = 62;
const int $QUESTION = 63;
const int $AT = 64;
const int $A = 65;
const int $B = 66;
const int $C = 67;
const int $D = 68;
const int $E = 69;
const int $F = 70;
const int $G = 71;
const int $H = 72;
const int $I = 73;
const int $J = 74;
const int $K = 75;
const int $L = 76;
const int $M = 77;
const int $N = 78;
const int $O = 79;
const int $P = 80;
const int $Q = 81;
const int $R = 82;
const int $S = 83;
const int $T = 84;
const int $U = 85;
const int $V = 86;
const int $W = 87;
const int $X = 88;
const int $Y = 89;
const int $Z = 90;
const int $OPEN_SQUARE_BRACKET = 91;
const int $BACKSLASH = 92;
const int $CLOSE_SQUARE_BRACKET = 93;
const int $CARET = 94;
const int $_ = 95;
const int $BACKPING = 96;
const int $a = 97;
const int $b = 98;
const int $c = 99;
const int $d = 100;
const int $e = 101;
const int $f = 102;
const int $g = 103;
const int $h = 104;
const int $i = 105;
const int $j = 106;
const int $k = 107;
const int $l = 108;
const int $m = 109;
const int $n = 110;
const int $o = 111;
const int $p = 112;
const int $q = 113;
const int $r = 114;
const int $s = 115;
const int $t = 116;
const int $u = 117;
const int $v = 118;
const int $w = 119;
const int $x = 120;
const int $y = 121;
const int $z = 122;
const int $OPEN_CURLY_BRACKET = 123;
const int $BAR = 124;
const int $CLOSE_CURLY_BRACKET = 125;
const int $TILDE = 126;
const int $DEL = 127;
const int $NBSP = 160;
const int $LS = 0x2028;
const int $PS = 0x2029;
const int $FIRST_SURROGATE = 0xd800;
const int $LAST_SURROGATE = 0xdfff;
const int $LAST_CODE_POINT = 0x10ffff;
bool isDigit(int characterCode) {
return $0 <= characterCode && characterCode <= $9;
}
bool isHexDigit(int characterCode) {
if (characterCode <= $9) return $0 <= characterCode;
characterCode |= $a ^ $A;
return ($a <= characterCode && characterCode <= $f);
}
int hexDigitValue(int hexDigit) {
assert(isHexDigit(hexDigit));
// hexDigit is one of '0'..'9', 'A'..'F' and 'a'..'f'.
if (hexDigit <= $9) return hexDigit - $0;
return (hexDigit | ($a ^ $A)) - ($a - 10);
}
bool isUnicodeScalarValue(int value) {
return value < $FIRST_SURROGATE ||
(value > $LAST_SURROGATE && value <= $LAST_CODE_POINT);
}
bool isUtf16LeadSurrogate(int value) {
return value >= 0xd800 && value <= 0xdbff;
}
bool isUtf16TrailSurrogate(int value) {
return value >= 0xdc00 && value <= 0xdfff;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/token_constants.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.
library fasta.scanner.token_constants;
import 'characters.dart';
const int EOF_TOKEN = 0;
const int KEYWORD_TOKEN = $k;
const int IDENTIFIER_TOKEN = $a;
const int SCRIPT_TOKEN = $b;
const int BAD_INPUT_TOKEN = $X;
const int DOUBLE_TOKEN = $d;
const int INT_TOKEN = $i;
const int RECOVERY_TOKEN = $r;
const int HEXADECIMAL_TOKEN = $x;
const int STRING_TOKEN = $SQ;
const int AMPERSAND_TOKEN = $AMPERSAND;
const int BACKPING_TOKEN = $BACKPING;
const int BACKSLASH_TOKEN = $BACKSLASH;
const int BANG_TOKEN = $BANG;
const int BAR_TOKEN = $BAR;
const int COLON_TOKEN = $COLON;
const int COMMA_TOKEN = $COMMA;
const int EQ_TOKEN = $EQ;
const int GT_TOKEN = $GT;
const int HASH_TOKEN = $HASH;
const int OPEN_CURLY_BRACKET_TOKEN = $OPEN_CURLY_BRACKET;
const int OPEN_SQUARE_BRACKET_TOKEN = $OPEN_SQUARE_BRACKET;
const int OPEN_PAREN_TOKEN = $OPEN_PAREN;
const int LT_TOKEN = $LT;
const int MINUS_TOKEN = $MINUS;
const int PERIOD_TOKEN = $PERIOD;
const int PLUS_TOKEN = $PLUS;
const int QUESTION_TOKEN = $QUESTION;
const int AT_TOKEN = $AT;
const int CLOSE_CURLY_BRACKET_TOKEN = $CLOSE_CURLY_BRACKET;
const int CLOSE_SQUARE_BRACKET_TOKEN = $CLOSE_SQUARE_BRACKET;
const int CLOSE_PAREN_TOKEN = $CLOSE_PAREN;
const int SEMICOLON_TOKEN = $SEMICOLON;
const int SLASH_TOKEN = $SLASH;
const int TILDE_TOKEN = $TILDE;
const int STAR_TOKEN = $STAR;
const int PERCENT_TOKEN = $PERCENT;
const int CARET_TOKEN = $CARET;
const int STRING_INTERPOLATION_TOKEN = 128;
const int LT_EQ_TOKEN = STRING_INTERPOLATION_TOKEN + 1;
const int FUNCTION_TOKEN = LT_EQ_TOKEN + 1;
const int SLASH_EQ_TOKEN = FUNCTION_TOKEN + 1;
const int PERIOD_PERIOD_PERIOD_TOKEN = SLASH_EQ_TOKEN + 1;
const int PERIOD_PERIOD_TOKEN = PERIOD_PERIOD_PERIOD_TOKEN + 1;
const int EQ_EQ_EQ_TOKEN = PERIOD_PERIOD_TOKEN + 1;
const int EQ_EQ_TOKEN = EQ_EQ_EQ_TOKEN + 1;
const int LT_LT_EQ_TOKEN = EQ_EQ_TOKEN + 1;
const int LT_LT_TOKEN = LT_LT_EQ_TOKEN + 1;
const int GT_EQ_TOKEN = LT_LT_TOKEN + 1;
const int GT_GT_EQ_TOKEN = GT_EQ_TOKEN + 1;
const int INDEX_EQ_TOKEN = GT_GT_EQ_TOKEN + 1;
const int INDEX_TOKEN = INDEX_EQ_TOKEN + 1;
const int BANG_EQ_EQ_TOKEN = INDEX_TOKEN + 1;
const int BANG_EQ_TOKEN = BANG_EQ_EQ_TOKEN + 1;
const int AMPERSAND_AMPERSAND_TOKEN = BANG_EQ_TOKEN + 1;
const int AMPERSAND_AMPERSAND_EQ_TOKEN = AMPERSAND_AMPERSAND_TOKEN + 1;
const int AMPERSAND_EQ_TOKEN = AMPERSAND_AMPERSAND_EQ_TOKEN + 1;
const int BAR_BAR_TOKEN = AMPERSAND_EQ_TOKEN + 1;
const int BAR_BAR_EQ_TOKEN = BAR_BAR_TOKEN + 1;
const int BAR_EQ_TOKEN = BAR_BAR_EQ_TOKEN + 1;
const int STAR_EQ_TOKEN = BAR_EQ_TOKEN + 1;
const int PLUS_PLUS_TOKEN = STAR_EQ_TOKEN + 1;
const int PLUS_EQ_TOKEN = PLUS_PLUS_TOKEN + 1;
const int MINUS_MINUS_TOKEN = PLUS_EQ_TOKEN + 1;
const int MINUS_EQ_TOKEN = MINUS_MINUS_TOKEN + 1;
const int TILDE_SLASH_EQ_TOKEN = MINUS_EQ_TOKEN + 1;
const int TILDE_SLASH_TOKEN = TILDE_SLASH_EQ_TOKEN + 1;
const int PERCENT_EQ_TOKEN = TILDE_SLASH_TOKEN + 1;
const int GT_GT_TOKEN = PERCENT_EQ_TOKEN + 1;
const int CARET_EQ_TOKEN = GT_GT_TOKEN + 1;
const int COMMENT_TOKEN = CARET_EQ_TOKEN + 1;
const int STRING_INTERPOLATION_IDENTIFIER_TOKEN = COMMENT_TOKEN + 1;
const int QUESTION_PERIOD_TOKEN = STRING_INTERPOLATION_IDENTIFIER_TOKEN + 1;
const int QUESTION_QUESTION_TOKEN = QUESTION_PERIOD_TOKEN + 1;
const int QUESTION_QUESTION_EQ_TOKEN = QUESTION_QUESTION_TOKEN + 1;
const int GENERIC_METHOD_TYPE_ASSIGN_TOKEN = QUESTION_QUESTION_EQ_TOKEN + 1;
const int GENERIC_METHOD_TYPE_LIST_TOKEN = GENERIC_METHOD_TYPE_ASSIGN_TOKEN + 1;
const int GT_GT_GT_TOKEN = GENERIC_METHOD_TYPE_LIST_TOKEN + 1;
const int PERIOD_PERIOD_PERIOD_QUESTION_TOKEN = GT_GT_GT_TOKEN + 1;
const int GT_GT_GT_EQ_TOKEN = PERIOD_PERIOD_PERIOD_QUESTION_TOKEN + 1;
const int QUESTION_PERIOD_OPEN_SQUARE_BRACKET_TOKEN = GT_GT_GT_EQ_TOKEN + 1;
const int QUESTION_PERIOD_PERIOD_TOKEN =
QUESTION_PERIOD_OPEN_SQUARE_BRACKET_TOKEN + 1;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/token.dart | // Copyright (c) 2011, 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 fasta.scanner.token;
import '../../scanner/token.dart' as analyzer;
import '../../scanner/token.dart' show Token, TokenType;
import 'token_constants.dart' show IDENTIFIER_TOKEN;
import 'string_canonicalizer.dart';
/**
* A String-valued token. Represents identifiers, string literals,
* number literals, comments, and error tokens, using the corresponding
* precedence info.
*/
class StringToken extends analyzer.SimpleToken implements analyzer.StringToken {
/**
* The length threshold above which substring tokens are computed lazily.
*
* For string tokens that are substrings of the program source, the actual
* substring extraction is performed lazily. This is beneficial because
* not all scanned code are actually used. For unused parts, the substrings
* are never computed and allocated.
*/
static const int LAZY_THRESHOLD = 4;
dynamic /* String | LazySubstring */ valueOrLazySubstring;
/**
* Creates a non-lazy string token. If [canonicalize] is true, the string
* is canonicalized before the token is created.
*/
StringToken.fromString(TokenType type, String value, int charOffset,
{bool canonicalize: false, analyzer.CommentToken precedingComments})
: valueOrLazySubstring =
canonicalizedString(value, 0, value.length, canonicalize),
super(type, charOffset, precedingComments);
/**
* Creates a lazy string token. If [canonicalize] is true, the string
* is canonicalized before the token is created.
*/
StringToken.fromSubstring(
TokenType type, String data, int start, int end, int charOffset,
{bool canonicalize: false, analyzer.CommentToken precedingComments})
: super(type, charOffset, precedingComments) {
int length = end - start;
if (length <= LAZY_THRESHOLD) {
valueOrLazySubstring =
canonicalizedString(data, start, end, canonicalize);
} else {
valueOrLazySubstring =
new _LazySubstring(data, start, length, canonicalize);
}
}
/**
* Creates a lazy string token. If [asciiOnly] is false, the byte array
* is passed through a UTF-8 decoder.
*/
StringToken.fromUtf8Bytes(TokenType type, List<int> data, int start, int end,
bool asciiOnly, int charOffset,
{analyzer.CommentToken precedingComments})
: super(type, charOffset, precedingComments) {
int length = end - start;
if (length <= LAZY_THRESHOLD) {
valueOrLazySubstring = decodeUtf8(data, start, end, asciiOnly);
} else {
valueOrLazySubstring = new _LazySubstring(data, start, length, asciiOnly);
}
}
StringToken._(TokenType type, this.valueOrLazySubstring, int charOffset,
[analyzer.CommentToken precedingComments])
: super(type, charOffset, precedingComments);
@override
String get lexeme {
if (valueOrLazySubstring is String) {
return valueOrLazySubstring;
} else {
assert(valueOrLazySubstring is _LazySubstring);
dynamic data = valueOrLazySubstring.data;
int start = valueOrLazySubstring.start;
int end = start + valueOrLazySubstring.length;
if (data is String) {
valueOrLazySubstring = canonicalizedString(
data, start, end, valueOrLazySubstring.boolValue);
} else {
valueOrLazySubstring =
decodeUtf8(data, start, end, valueOrLazySubstring.boolValue);
}
return valueOrLazySubstring;
}
}
@override
bool get isIdentifier => identical(kind, IDENTIFIER_TOKEN);
@override
String toString() => lexeme;
static final StringCanonicalizer canonicalizer = new StringCanonicalizer();
static String canonicalizedString(
String s, int start, int end, bool canonicalize) {
if (!canonicalize) return s;
return canonicalizer.canonicalize(s, start, end, false);
}
static String decodeUtf8(List<int> data, int start, int end, bool asciiOnly) {
return canonicalizer.canonicalize(data, start, end, asciiOnly);
}
@override
Token copy() => new StringToken._(
type, valueOrLazySubstring, charOffset, copyComments(precedingComments));
@override
String value() => lexeme;
}
/**
* A String-valued token that does not exist in the original source.
*/
class SyntheticStringToken extends StringToken
implements analyzer.SyntheticStringToken {
SyntheticStringToken(TokenType type, String value, int offset,
[analyzer.CommentToken precedingComments])
: super._(type, value, offset, precedingComments);
@override
int get length => 0;
@override
Token copy() => new SyntheticStringToken(
type, valueOrLazySubstring, offset, copyComments(precedingComments));
}
class CommentToken extends StringToken implements analyzer.CommentToken {
@override
analyzer.SimpleToken parent;
/**
* Creates a lazy comment token. If [canonicalize] is true, the string
* is canonicalized before the token is created.
*/
CommentToken.fromSubstring(
TokenType type, String data, int start, int end, int charOffset,
{bool canonicalize: false})
: super.fromSubstring(type, data, start, end, charOffset,
canonicalize: canonicalize);
/**
* Creates a non-lazy comment token.
*/
CommentToken.fromString(TokenType type, String lexeme, int charOffset)
: super.fromString(type, lexeme, charOffset);
/**
* Creates a lazy string token. If [asciiOnly] is false, the byte array
* is passed through a UTF-8 decoder.
*/
CommentToken.fromUtf8Bytes(TokenType type, List<int> data, int start, int end,
bool asciiOnly, int charOffset)
: super.fromUtf8Bytes(type, data, start, end, asciiOnly, charOffset);
CommentToken._(TokenType type, valueOrLazySubstring, int charOffset)
: super._(type, valueOrLazySubstring, charOffset);
@override
CommentToken copy() =>
new CommentToken._(type, valueOrLazySubstring, charOffset);
@override
void remove() {
if (previous != null) {
previous.setNextWithoutSettingPrevious(next);
next?.previous = previous;
} else {
assert(parent.precedingComments == this);
parent.precedingComments = next as CommentToken;
}
}
}
/**
* A specialized comment token representing a language version
* (e.g. '// @dart = 2.1').
*/
class LanguageVersionToken extends CommentToken {
/**
* The major language version.
*/
int major;
/**
* The minor language version.
*/
int minor;
LanguageVersionToken.from(String text, int offset, this.major, this.minor)
: super.fromString(TokenType.SINGLE_LINE_COMMENT, text, offset);
LanguageVersionToken.fromSubstring(
String string, int start, int end, int tokenStart, this.major, this.minor,
{bool canonicalize})
: super.fromSubstring(
TokenType.SINGLE_LINE_COMMENT, string, start, end, tokenStart,
canonicalize: canonicalize);
LanguageVersionToken.fromUtf8Bytes(List<int> bytes, int start, int end,
int tokenStart, this.major, this.minor)
: super.fromUtf8Bytes(
TokenType.SINGLE_LINE_COMMENT, bytes, start, end, true, tokenStart);
@override
LanguageVersionToken copy() =>
new LanguageVersionToken.from(lexeme, offset, major, minor);
}
class DartDocToken extends CommentToken
implements analyzer.DocumentationCommentToken {
/**
* Creates a lazy comment token. If [canonicalize] is true, the string
* is canonicalized before the token is created.
*/
DartDocToken.fromSubstring(
TokenType type, String data, int start, int end, int charOffset,
{bool canonicalize: false})
: super.fromSubstring(type, data, start, end, charOffset,
canonicalize: canonicalize);
/**
* Creates a lazy string token. If [asciiOnly] is false, the byte array
* is passed through a UTF-8 decoder.
*/
DartDocToken.fromUtf8Bytes(TokenType type, List<int> data, int start, int end,
bool asciiOnly, int charOffset)
: super.fromUtf8Bytes(type, data, start, end, asciiOnly, charOffset);
DartDocToken._(TokenType type, valueOrLazySubstring, int charOffset)
: super._(type, valueOrLazySubstring, charOffset);
@override
DartDocToken copy() =>
new DartDocToken._(type, valueOrLazySubstring, charOffset);
}
/**
* This class represents the necessary information to compute a substring
* lazily. The substring can either originate from a string or from
* a [:List<int>:] of UTF-8 bytes.
*/
abstract class _LazySubstring {
/** The original data, either a string or a List<int> */
get data;
int get start;
int get length;
/**
* If this substring is based on a String, the [boolValue] indicates whether
* the resulting substring should be canonicalized.
*
* For substrings based on a byte array, the [boolValue] is true if the
* array only holds ASCII characters. The resulting substring will be
* canonicalized after decoding.
*/
bool get boolValue;
_LazySubstring.internal();
factory _LazySubstring(data, int start, int length, bool b) {
// See comment on [CompactLazySubstring].
if (start < 0x100000 && length < 0x200) {
int fields = (start << 9);
fields = fields | length;
fields = fields << 1;
if (b) fields |= 1;
return new _CompactLazySubstring(data, fields);
} else {
return new _FullLazySubstring(data, start, length, b);
}
}
}
/**
* This class encodes [start], [length] and [boolValue] in a single
* 30 bit integer. It uses 20 bits for [start], which covers source files
* of 1MB. [length] has 9 bits, which covers 512 characters.
*
* The file html_dart2js.dart is currently around 1MB.
*/
class _CompactLazySubstring extends _LazySubstring {
final dynamic data;
final int fields;
_CompactLazySubstring(this.data, this.fields) : super.internal();
int get start => fields >> 10;
int get length => (fields >> 1) & 0x1ff;
bool get boolValue => (fields & 1) == 1;
}
class _FullLazySubstring extends _LazySubstring {
final dynamic data;
final int start;
final int length;
final bool boolValue;
_FullLazySubstring(this.data, this.start, this.length, this.boolValue)
: super.internal();
}
bool isUserDefinableOperator(String value) {
return isBinaryOperator(value) ||
isMinusOperator(value) ||
isTernaryOperator(value) ||
isUnaryOperator(value);
}
bool isUnaryOperator(String value) => identical(value, "~");
bool isBinaryOperator(String value) {
return identical(value, "==") ||
identical(value, "[]") ||
identical(value, "*") ||
identical(value, "/") ||
identical(value, "%") ||
identical(value, "~/") ||
identical(value, "+") ||
identical(value, "<<") ||
identical(value, ">>") ||
identical(value, ">>>") ||
identical(value, ">=") ||
identical(value, ">") ||
identical(value, "<=") ||
identical(value, "<") ||
identical(value, "&") ||
identical(value, "^") ||
identical(value, "|");
}
bool isTernaryOperator(String value) => identical(value, "[]=");
bool isMinusOperator(String value) => identical(value, "-");
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/error_token.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 dart_scanner.error_token;
import '../../scanner/token.dart' show BeginToken, SimpleToken, TokenType;
import '../fasta_codes.dart'
show
Code,
Message,
messageEncoding,
templateAsciiControlCharacter,
templateNonAsciiIdentifier,
templateNonAsciiWhitespace,
templateUnmatchedToken,
templateUnsupportedOperator,
templateUnterminatedString;
import '../scanner.dart' show Token, unicodeReplacementCharacter;
import '../scanner/recover.dart' show closeBraceFor, closeQuoteFor;
ErrorToken buildUnexpectedCharacterToken(int character, int charOffset) {
if (character < 0x1f) {
return new AsciiControlCharacterToken(character, charOffset);
}
switch (character) {
case unicodeReplacementCharacter:
return new EncodingErrorToken(charOffset);
/// See [General Punctuation]
/// (http://www.unicode.org/charts/PDF/U2000.pdf).
case 0x00A0: // No-break space.
case 0x1680: // Ogham space mark.
case 0x180E: // Mongolian vowel separator.
case 0x2000: // En quad.
case 0x2001: // Em quad.
case 0x2002: // En space.
case 0x2003: // Em space.
case 0x2004: // Three-per-em space.
case 0x2005: // Four-per-em space.
case 0x2006: // Six-per-em space.
case 0x2007: // Figure space.
case 0x2008: // Punctuation space.
case 0x2009: // Thin space.
case 0x200A: // Hair space.
case 0x200B: // Zero width space.
case 0x2028: // Line separator.
case 0x2029: // Paragraph separator.
case 0x202F: // Narrow no-break space.
case 0x205F: // Medium mathematical space.
case 0x3000: // Ideographic space.
case 0xFEFF: // Zero width no-break space.
return new NonAsciiWhitespaceToken(character, charOffset);
default:
return new NonAsciiIdentifierToken(character, charOffset);
}
}
/// Common superclass for all error tokens.
///
/// It's considered an implementation error to access [lexeme] of an
/// [ErrorToken].
abstract class ErrorToken extends SimpleToken {
ErrorToken(int offset) : super(TokenType.BAD_INPUT, offset, null);
/// This is a token that wraps around an error message. Return 1
/// instead of the size of the length of the error message.
@override
int get length => 1;
String get lexeme {
String errorMsg = assertionMessage.message;
// Attempt to include the location which is calling the parser
// in an effort to debug https://github.com/dart-lang/sdk/issues/37528
RegExp pattern = new RegExp('^#[0-9]* *Parser');
List<String> traceLines = StackTrace.current.toString().split('\n');
for (int index = traceLines.length - 2; index >= 0; --index) {
String line = traceLines[index];
if (line.startsWith(pattern)) {
errorMsg = '$errorMsg - ${traceLines[index + 1]}';
break;
}
}
throw errorMsg;
}
Message get assertionMessage;
Code<dynamic> get errorCode => assertionMessage.code;
int get character => null;
String get start => null;
int get endOffset => null;
BeginToken get begin => null;
@override
Token copy() {
throw 'unsupported operation';
}
}
/// Represents an encoding error.
class EncodingErrorToken extends ErrorToken {
EncodingErrorToken(int charOffset) : super(charOffset);
String toString() => "EncodingErrorToken()";
Message get assertionMessage => messageEncoding;
}
/// Represents a non-ASCII character outside a string or comment.
class NonAsciiIdentifierToken extends ErrorToken {
final int character;
NonAsciiIdentifierToken(this.character, int charOffset) : super(charOffset);
String toString() => "NonAsciiIdentifierToken($character)";
Message get assertionMessage => templateNonAsciiIdentifier.withArguments(
new String.fromCharCodes([character]), character);
}
/// Represents a non-ASCII whitespace outside a string or comment.
class NonAsciiWhitespaceToken extends ErrorToken {
final int character;
NonAsciiWhitespaceToken(this.character, int charOffset) : super(charOffset);
String toString() => "NonAsciiWhitespaceToken($character)";
Message get assertionMessage =>
templateNonAsciiWhitespace.withArguments(character);
}
/// Represents an ASCII control character outside a string or comment.
class AsciiControlCharacterToken extends ErrorToken {
final int character;
AsciiControlCharacterToken(this.character, int charOffset)
: super(charOffset);
String toString() => "AsciiControlCharacterToken($character)";
Message get assertionMessage =>
templateAsciiControlCharacter.withArguments(character);
}
/// Denotes an operator that is not supported in the Dart language.
class UnsupportedOperator extends ErrorToken {
Token token;
UnsupportedOperator(this.token, int charOffset) : super(charOffset);
@override
Message get assertionMessage =>
templateUnsupportedOperator.withArguments(token);
@override
String toString() => "UnsupportedOperator(${token.lexeme})";
}
/// Represents an unterminated string.
class UnterminatedString extends ErrorToken {
final String start;
final int endOffset;
UnterminatedString(this.start, int charOffset, this.endOffset)
: super(charOffset);
String toString() => "UnterminatedString($start)";
int get charCount => endOffset - charOffset;
int get length => charCount;
Message get assertionMessage =>
templateUnterminatedString.withArguments(start, closeQuoteFor(start));
}
/// Represents an unterminated token.
class UnterminatedToken extends ErrorToken {
final Message assertionMessage;
final int endOffset;
UnterminatedToken(this.assertionMessage, int charOffset, this.endOffset)
: super(charOffset);
String toString() => "UnterminatedToken(${assertionMessage.code.name})";
int get charCount => endOffset - charOffset;
}
/// Represents an open brace without a matching close brace.
///
/// In this case, brace means any of `(`, `{`, `[`, and `<`, parenthesis, curly
/// brace, square brace, and angle brace, respectively.
class UnmatchedToken extends ErrorToken {
final BeginToken begin;
UnmatchedToken(BeginToken begin)
: this.begin = begin,
super(begin.charOffset);
String toString() => "UnmatchedToken(${begin.lexeme})";
Message get assertionMessage =>
templateUnmatchedToken.withArguments(closeBraceFor(begin.lexeme), begin);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/abstract_scanner.dart | // Copyright (c) 2012, 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 fasta.scanner.abstract_scanner;
import 'dart:collection' show ListMixin;
import 'dart:typed_data' show Uint16List, Uint32List;
import '../../scanner/token.dart'
show BeginToken, Keyword, KeywordToken, SyntheticToken, Token, TokenType;
import '../../scanner/token.dart' as analyzer show StringToken;
import '../fasta_codes.dart'
show
messageExpectedHexDigit,
messageMissingExponent,
messageUnexpectedDollarInString,
messageUnterminatedComment;
import '../scanner.dart'
show ErrorToken, Keyword, Scanner, buildUnexpectedCharacterToken;
import '../util/link.dart' show Link;
import 'error_token.dart'
show
NonAsciiIdentifierToken,
UnmatchedToken,
UnsupportedOperator,
UnterminatedString,
UnterminatedToken;
import 'keyword_state.dart' show KeywordState;
import 'token.dart'
show CommentToken, DartDocToken, LanguageVersionToken, StringToken;
import 'token_constants.dart';
import 'characters.dart';
typedef void LanguageVersionChanged(
Scanner scanner, LanguageVersionToken languageVersion);
abstract class AbstractScanner implements Scanner {
/**
* A flag indicating whether character sequences `&&=` and `||=`
* should be tokenized as the assignment operators
* [AMPERSAND_AMPERSAND_EQ_TOKEN] and [BAR_BAR_EQ_TOKEN] respectively.
* See issue https://github.com/dart-lang/sdk/issues/30340
*/
static const bool LAZY_ASSIGNMENT_ENABLED = false;
final bool includeComments;
/// Called when the scanner detects a language version comment
/// so that the listener can update the scanner configuration
/// based upon the specified language version.
final LanguageVersionChanged languageVersionChanged;
/// Experimental flag for enabling scanning of the `extension` token.
bool _enableExtensionMethods = false;
/// Experimental flag for enabling scanning of NNBD tokens
/// such as 'required' and 'late'.
bool _enableNonNullable = false;
/// Experimental flag for enabling scanning of `>>>`.
/// See https://github.com/dart-lang/language/issues/61
/// and https://github.com/dart-lang/language/issues/60
bool _enableTripleShift = false;
/**
* The string offset for the next token that will be created.
*
* Note that in the [Utf8BytesScanner], [stringOffset] and [scanOffset] values
* are different. One string character can be encoded using multiple UTF-8
* bytes.
*/
int tokenStart = -1;
/**
* A pointer to the token stream created by this scanner. The first token
* is a special token and not part of the source file. This is an
* implementation detail to avoids special cases in the scanner. This token
* is not exposed to clients of the scanner, which are expected to invoke
* [firstToken] to access the token stream.
*/
final Token tokens = new Token.eof(-1);
/**
* A pointer to the last scanned token.
*/
Token tail;
/**
* A pointer to the last prepended error token.
*/
Token errorTail;
bool hasErrors = false;
/**
* A pointer to the stream of comment tokens created by this scanner
* before they are assigned to the [Token] precedingComments field
* of a non-comment token. A value of `null` indicates no comment tokens.
*/
CommentToken comments;
/**
* A pointer to the last scanned comment token or `null` if none.
*/
Token commentsTail;
final List<int> lineStarts;
/**
* The stack of open groups, e.g [: { ... ( .. :]
* Each BeginToken has a pointer to the token where the group
* ends. This field is set when scanning the end group token.
*/
Link<BeginToken> groupingStack = const Link<BeginToken>();
AbstractScanner(ScannerConfiguration config, this.includeComments,
this.languageVersionChanged,
{int numberOfBytesHint})
: lineStarts = new LineStarts(numberOfBytesHint) {
this.tail = this.tokens;
this.errorTail = this.tokens;
this.configuration = config;
}
@override
set configuration(ScannerConfiguration config) {
if (config != null) {
_enableExtensionMethods = config.enableExtensionMethods;
_enableNonNullable = config.enableNonNullable;
_enableTripleShift = config.enableTripleShift;
}
}
/**
* Advances and returns the next character.
*
* If the next character is non-ASCII, then the returned value depends on the
* scanner implementation. The [Utf8BytesScanner] returns a UTF-8 byte, while
* the [StringScanner] returns a UTF-16 code unit.
*
* The scanner ensures that [advance] is not invoked after it returned [$EOF].
* This allows implementations to omit bound checks if the data structure ends
* with '0'.
*/
int advance();
/**
* Returns the current unicode character.
*
* If the current character is ASCII, then it is returned unchanged.
*
* The [Utf8BytesScanner] decodes the next unicode code point starting at the
* current position. Note that every unicode character is returned as a single
* code point, that is, for '\u{1d11e}' it returns 119070, and the following
* [advance] returns the next character.
*
* The [StringScanner] returns the current character unchanged, which might
* be a surrogate character. In the case of '\u{1d11e}', it returns the first
* code unit 55348, and the following [advance] returns the second code unit
* 56606.
*
* Invoking [currentAsUnicode] multiple times is safe, i.e.,
* [:currentAsUnicode(next) == currentAsUnicode(currentAsUnicode(next)):].
*/
int currentAsUnicode(int next);
/**
* Returns the character at the next position. Like in [advance], the
* [Utf8BytesScanner] returns a UTF-8 byte, while the [StringScanner] returns
* a UTF-16 code unit.
*/
int peek();
/**
* Notifies the scanner that unicode characters were detected in either a
* comment or a string literal between [startScanOffset] and the current
* scan offset.
*/
void handleUnicode(int startScanOffset);
/**
* Returns the current scan offset.
*
* In the [Utf8BytesScanner] this is the offset into the byte list, in the
* [StringScanner] the offset in the source string.
*/
int get scanOffset;
/**
* Returns the current string offset.
*
* In the [StringScanner] this is identical to the [scanOffset]. In the
* [Utf8BytesScanner] it is computed based on encountered UTF-8 characters.
*/
int get stringOffset;
/**
* Returns the first token scanned by this [Scanner].
*/
Token firstToken() => tokens.next;
/**
* Notifies that a new token starts at current offset.
*/
void beginToken() {
tokenStart = stringOffset;
}
/**
* Appends a substring from the scan offset [:start:] to the current
* [:scanOffset:] plus the [:extraOffset:]. For example, if the current
* scanOffset is 10, then [:appendSubstringToken(5, -1):] will append the
* substring string [5,9).
*
* Note that [extraOffset] can only be used if the covered character(s) are
* known to be ASCII.
*/
void appendSubstringToken(TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]) {
appendToken(createSubstringToken(type, start, asciiOnly, extraOffset));
}
/**
* Returns a new substring from the scan offset [start] to the current
* [scanOffset] plus the [extraOffset]. For example, if the current
* scanOffset is 10, then [appendSubstringToken(5, -1)] will append the
* substring string [5,9).
*
* Note that [extraOffset] can only be used if the covered character(s) are
* known to be ASCII.
*/
analyzer.StringToken createSubstringToken(
TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]);
/**
* Appends a substring from the scan offset [start] to the current
* [scanOffset] plus [syntheticChars]. The additional char(s) will be added
* to the unterminated string literal's lexeme but the returned
* token's length will *not* include those additional char(s)
* so as to be true to the original source.
*/
void appendSyntheticSubstringToken(
TokenType type, int start, bool asciiOnly, String syntheticChars) {
appendToken(
createSyntheticSubstringToken(type, start, asciiOnly, syntheticChars));
}
/**
* Returns a new synthetic substring from the scan offset [start]
* to the current [scanOffset] plus the [syntheticChars].
* The [syntheticChars] are appended to the unterminated string
* literal's lexeme but the returned token's length will *not* include
* those additional characters so as to be true to the original source.
*/
analyzer.StringToken createSyntheticSubstringToken(
TokenType type, int start, bool asciiOnly, String syntheticChars);
/**
* Appends a fixed token whose kind and content is determined by [type].
* Appends an *operator* token from [type].
*
* An operator token represent operators like ':', '.', ';', '&&', '==', '--',
* '=>', etc.
*/
void appendPrecedenceToken(TokenType type) {
appendToken(new Token(type, tokenStart, comments));
}
/**
* Appends a fixed token based on whether the current char is [choice] or not.
* If the current char is [choice] a fixed token whose kind and content
* is determined by [yes] is appended, otherwise a fixed token whose kind
* and content is determined by [no] is appended.
*/
int select(int choice, TokenType yes, TokenType no) {
int next = advance();
if (identical(next, choice)) {
appendPrecedenceToken(yes);
return advance();
} else {
appendPrecedenceToken(no);
return next;
}
}
/**
* Appends a keyword token whose kind is determined by [keyword].
*/
void appendKeywordToken(Keyword keyword) {
String syntax = keyword.lexeme;
// Type parameters and arguments cannot contain 'this'.
if (identical(syntax, 'this')) {
discardOpenLt();
}
appendToken(new KeywordToken(keyword, tokenStart, comments));
}
void appendEofToken() {
beginToken();
discardOpenLt();
while (!groupingStack.isEmpty) {
unmatchedBeginGroup(groupingStack.head);
groupingStack = groupingStack.tail;
}
appendToken(new Token.eof(tokenStart, comments));
}
/**
* Notifies scanning a whitespace character. Note that [appendWhiteSpace] is
* not always invoked for [$SPACE] characters.
*
* This method is used by the scanners to track line breaks and create the
* [lineStarts] map.
*/
void appendWhiteSpace(int next) {
if (next == $LF) {
lineStarts.add(stringOffset + 1); // +1, the line starts after the $LF.
}
}
/**
* Notifies on [$LF] characters in multi-line comments or strings.
*
* This method is used by the scanners to track line breaks and create the
* [lineStarts] map.
*/
void lineFeedInMultiline() {
lineStarts.add(stringOffset + 1);
}
/**
* Appends a token that begins a new group, represented by [type].
* Group begin tokens are '{', '(', '[', '<' and '${'.
*/
void appendBeginGroup(TokenType type) {
Token token = new BeginToken(type, tokenStart, comments);
appendToken(token);
// { [ ${ cannot appear inside a type parameters / arguments.
if (!identical(type.kind, LT_TOKEN) &&
!identical(type.kind, OPEN_PAREN_TOKEN)) {
discardOpenLt();
}
groupingStack = groupingStack.prepend(token);
}
/**
* Appends a token that begins an end group, represented by [type].
* It handles the group end tokens '}', ')' and ']'. The tokens '>' and
* '>>' are handled separately by [appendGt] and [appendGtGt].
*/
int appendEndGroup(TokenType type, int openKind) {
assert(!identical(openKind, LT_TOKEN)); // openKind is < for > and >>
if (!discardBeginGroupUntil(openKind)) {
// No begin group found. Just continue.
appendPrecedenceToken(type);
return advance();
}
appendPrecedenceToken(type);
Token close = tail;
BeginToken begin = groupingStack.head;
if (!identical(begin.kind, openKind) &&
!(begin.kind == QUESTION_PERIOD_OPEN_SQUARE_BRACKET_TOKEN &&
openKind == OPEN_SQUARE_BRACKET_TOKEN)) {
assert(begin.kind == STRING_INTERPOLATION_TOKEN &&
openKind == OPEN_CURLY_BRACKET_TOKEN);
// We're ending an interpolated expression.
begin.endGroup = close;
groupingStack = groupingStack.tail;
// Using "start-of-text" to signal that we're back in string
// scanning mode.
return $STX;
}
begin.endGroup = close;
groupingStack = groupingStack.tail;
return advance();
}
/**
* Appends a token for '>'.
* This method does not issue unmatched errors, because > is also the
* greater-than operator. It does not necessarily have to close a group.
*/
void appendGt(TokenType type) {
appendPrecedenceToken(type);
if (groupingStack.isEmpty) return;
if (identical(groupingStack.head.kind, LT_TOKEN)) {
groupingStack.head.endGroup = tail;
groupingStack = groupingStack.tail;
}
}
/**
* Appends a token for '>>'.
* This method does not issue unmatched errors, because >> is also the
* shift operator. It does not necessarily have to close a group.
*/
void appendGtGt(TokenType type) {
appendPrecedenceToken(type);
if (groupingStack.isEmpty) return;
if (identical(groupingStack.head.kind, LT_TOKEN)) {
// Don't assign endGroup: in "T<U<V>>", the '>>' token closes the outer
// '<', the inner '<' is left without endGroup.
groupingStack = groupingStack.tail;
}
if (groupingStack.isEmpty) return;
if (identical(groupingStack.head.kind, LT_TOKEN)) {
groupingStack.head.endGroup = tail;
groupingStack = groupingStack.tail;
}
}
/// Prepend [token] to the token stream.
void prependErrorToken(ErrorToken token) {
hasErrors = true;
if (errorTail == tail) {
appendToken(token);
errorTail = tail;
} else {
token.next = errorTail.next;
token.next.previous = token;
errorTail.next = token;
token.previous = errorTail;
errorTail = errorTail.next;
}
}
/**
* Returns a new comment from the scan offset [start] to the current
* [scanOffset] plus the [extraOffset]. For example, if the current
* scanOffset is 10, then [appendSubstringToken(5, -1)] will append the
* substring string [5,9).
*
* Note that [extraOffset] can only be used if the covered character(s) are
* known to be ASCII.
*/
CommentToken createCommentToken(TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]);
/**
* Returns a new dartdoc from the scan offset [start] to the current
* [scanOffset] plus the [extraOffset]. For example, if the current
* scanOffset is 10, then [appendSubstringToken(5, -1)] will append the
* substring string [5,9).
*
* Note that [extraOffset] can only be used if the covered character(s) are
* known to be ASCII.
*/
DartDocToken createDartDocToken(TokenType type, int start, bool asciiOnly,
[int extraOffset = 0]);
/**
* Returns a new language version token from the scan offset [start]
* to the current [scanOffset] similar to createCommentToken.
*/
LanguageVersionToken createLanguageVersionToken(
int start, int major, int minor);
/**
* If a begin group token matches [openKind],
* then discard begin group tokens up to that match and return `true`,
* otherwise return `false`.
* This recovers nicely from from situations like "{[}" and "{foo());}",
* but not "foo(() {bar());});
*/
bool discardBeginGroupUntil(int openKind) {
Link<BeginToken> originalStack = groupingStack;
bool first = true;
do {
// Don't report unmatched errors for <; it is also the less-than operator.
discardOpenLt();
if (groupingStack.isEmpty) break; // recover
BeginToken begin = groupingStack.head;
if (openKind == begin.kind ||
(openKind == OPEN_CURLY_BRACKET_TOKEN &&
begin.kind == STRING_INTERPOLATION_TOKEN) ||
(openKind == OPEN_SQUARE_BRACKET_TOKEN &&
begin.kind == QUESTION_PERIOD_OPEN_SQUARE_BRACKET_TOKEN)) {
if (first) {
// If the expected opener has been found on the first pass
// then no recovery necessary.
return true;
}
break; // recover
}
first = false;
groupingStack = groupingStack.tail;
} while (!groupingStack.isEmpty);
// If the stack does not have any opener of the given type,
// then return without discarding anything.
// This recovers nicely from from situations like "{foo());}".
if (groupingStack.isEmpty) {
groupingStack = originalStack;
return false;
}
// Insert synthetic closers and report errors for any unbalanced openers.
// This recovers nicely from from situations like "{[}".
while (!identical(originalStack, groupingStack)) {
// Don't report unmatched errors for <; it is also the less-than operator.
if (!identical(groupingStack.head.kind, LT_TOKEN)) {
unmatchedBeginGroup(originalStack.head);
}
originalStack = originalStack.tail;
}
return true;
}
/**
* This method is called to discard '<' from the "grouping" stack.
*
* [PartialParser.skipExpression] relies on the fact that we do not
* create groups for stuff like:
* [:a = b < c, d = e > f:].
*
* In other words, this method is called when the scanner recognizes
* something which cannot possibly be part of a type parameter/argument
* list, like the '=' in the above example.
*/
void discardOpenLt() {
while (!groupingStack.isEmpty &&
identical(groupingStack.head.kind, LT_TOKEN)) {
groupingStack = groupingStack.tail;
}
}
/**
* This method is called to discard '${' from the "grouping" stack.
*
* This method is called when the scanner finds an unterminated
* interpolation expression.
*/
void discardInterpolation() {
while (!groupingStack.isEmpty) {
BeginToken beginToken = groupingStack.head;
unmatchedBeginGroup(beginToken);
groupingStack = groupingStack.tail;
if (identical(beginToken.kind, STRING_INTERPOLATION_TOKEN)) break;
}
}
void unmatchedBeginGroup(BeginToken begin) {
// We want to ensure that unmatched BeginTokens are reported as
// errors. However, the diet parser assumes that groups are well-balanced
// and will never look at the endGroup token. This is a nice property that
// allows us to skip quickly over correct code. By inserting an additional
// synthetic token in the stream, we can keep ignoring endGroup tokens.
//
// [begin] --next--> [tail]
// [begin] --endG--> [synthetic] --next--> [next] --next--> [tail]
//
// This allows the diet parser to skip from [begin] via endGroup to
// [synthetic] and ignore the [synthetic] token (assuming it's correct),
// then the error will be reported when parsing the [next] token.
//
// For example, tokenize("{[1};") produces:
//
// SymbolToken({) --endGroup------------------------+
// | |
// next |
// v |
// SymbolToken([) --endGroup--+ |
// | | |
// next | |
// v | |
// StringToken(1) | |
// | | |
// next | |
// v | |
// SymbolToken(])<------------+ <-- Synthetic token |
// | |
// next |
// v |
// UnmatchedToken([) |
// | |
// next |
// v |
// SymbolToken(})<----------------------------------+
// |
// next
// v
// SymbolToken(;)
// |
// next
// v
// EOF
TokenType type = closeBraceInfoFor(begin);
appendToken(new SyntheticToken(type, tokenStart)..beforeSynthetic = tail);
begin.endGroup = tail;
prependErrorToken(new UnmatchedToken(begin));
}
/// Return true when at EOF.
bool atEndOfFile();
Token tokenize() {
while (!atEndOfFile()) {
int next = advance();
// Scan the header looking for a language version
if (!identical(next, $EOF)) {
Token oldTail = tail;
next = bigHeaderSwitch(next);
if (!identical(next, $EOF) && tail.kind == SCRIPT_TOKEN) {
oldTail = tail;
next = bigHeaderSwitch(next);
}
while (!identical(next, $EOF) && tail == oldTail) {
next = bigHeaderSwitch(next);
}
next = next;
}
while (!identical(next, $EOF)) {
next = bigSwitch(next);
}
if (atEndOfFile()) {
appendEofToken();
} else {
unexpected($EOF);
}
}
// Always pretend that there's a line at the end of the file.
lineStarts.add(stringOffset + 1);
return firstToken();
}
int bigHeaderSwitch(int next) {
if (!identical(next, $SLASH)) {
return bigSwitch(next);
}
beginToken();
if (!identical($SLASH, peek())) {
return tokenizeSlashOrComment(next);
}
return tokenizeLanguageVersionOrSingleLineComment(next);
}
int bigSwitch(int next) {
beginToken();
if (identical(next, $SPACE) ||
identical(next, $TAB) ||
identical(next, $LF) ||
identical(next, $CR)) {
appendWhiteSpace(next);
next = advance();
// Sequences of spaces are common, so advance through them fast.
while (identical(next, $SPACE)) {
// We don't invoke [:appendWhiteSpace(next):] here for efficiency,
// assuming that it does not do anything for space characters.
next = advance();
}
return next;
}
int nextLower = next | 0x20;
if ($a <= nextLower && nextLower <= $z) {
if (identical($r, next)) {
return tokenizeRawStringKeywordOrIdentifier(next);
}
return tokenizeKeywordOrIdentifier(next, true);
}
if (identical(next, $CLOSE_PAREN)) {
return appendEndGroup(TokenType.CLOSE_PAREN, OPEN_PAREN_TOKEN);
}
if (identical(next, $OPEN_PAREN)) {
appendBeginGroup(TokenType.OPEN_PAREN);
return advance();
}
if (identical(next, $SEMICOLON)) {
appendPrecedenceToken(TokenType.SEMICOLON);
// Type parameters and arguments cannot contain semicolon.
discardOpenLt();
return advance();
}
if (identical(next, $PERIOD)) {
return tokenizeDotsOrNumber(next);
}
if (identical(next, $COMMA)) {
appendPrecedenceToken(TokenType.COMMA);
return advance();
}
if (identical(next, $EQ)) {
return tokenizeEquals(next);
}
if (identical(next, $CLOSE_CURLY_BRACKET)) {
return appendEndGroup(
TokenType.CLOSE_CURLY_BRACKET, OPEN_CURLY_BRACKET_TOKEN);
}
if (identical(next, $SLASH)) {
return tokenizeSlashOrComment(next);
}
if (identical(next, $OPEN_CURLY_BRACKET)) {
appendBeginGroup(TokenType.OPEN_CURLY_BRACKET);
return advance();
}
if (identical(next, $DQ) || identical(next, $SQ)) {
return tokenizeString(next, scanOffset, false);
}
if (identical(next, $_)) {
return tokenizeKeywordOrIdentifier(next, true);
}
if (identical(next, $COLON)) {
appendPrecedenceToken(TokenType.COLON);
return advance();
}
if (identical(next, $LT)) {
return tokenizeLessThan(next);
}
if (identical(next, $GT)) {
return tokenizeGreaterThan(next);
}
if (identical(next, $BANG)) {
return tokenizeExclamation(next);
}
if (identical(next, $OPEN_SQUARE_BRACKET)) {
return tokenizeOpenSquareBracket(next);
}
if (identical(next, $CLOSE_SQUARE_BRACKET)) {
return appendEndGroup(
TokenType.CLOSE_SQUARE_BRACKET, OPEN_SQUARE_BRACKET_TOKEN);
}
if (identical(next, $AT)) {
return tokenizeAt(next);
}
if (next >= $1 && next <= $9) {
return tokenizeNumber(next);
}
if (identical(next, $AMPERSAND)) {
return tokenizeAmpersand(next);
}
if (identical(next, $0)) {
return tokenizeHexOrNumber(next);
}
if (identical(next, $QUESTION)) {
return tokenizeQuestion(next);
}
if (identical(next, $BAR)) {
return tokenizeBar(next);
}
if (identical(next, $PLUS)) {
return tokenizePlus(next);
}
if (identical(next, $$)) {
return tokenizeKeywordOrIdentifier(next, true);
}
if (identical(next, $MINUS)) {
return tokenizeMinus(next);
}
if (identical(next, $STAR)) {
return tokenizeMultiply(next);
}
if (identical(next, $CARET)) {
return tokenizeCaret(next);
}
if (identical(next, $TILDE)) {
return tokenizeTilde(next);
}
if (identical(next, $PERCENT)) {
return tokenizePercent(next);
}
if (identical(next, $BACKPING)) {
appendPrecedenceToken(TokenType.BACKPING);
return advance();
}
if (identical(next, $BACKSLASH)) {
appendPrecedenceToken(TokenType.BACKSLASH);
return advance();
}
if (identical(next, $HASH)) {
return tokenizeTag(next);
}
if (next < 0x1f) {
return unexpected(next);
}
next = currentAsUnicode(next);
return unexpected(next);
}
int tokenizeTag(int next) {
// # or #!.*[\n\r]
if (scanOffset == 0) {
if (identical(peek(), $BANG)) {
int start = scanOffset;
bool asciiOnly = true;
do {
next = advance();
if (next > 127) asciiOnly = false;
} while (!identical(next, $LF) &&
!identical(next, $CR) &&
!identical(next, $EOF));
if (!asciiOnly) handleUnicode(start);
appendSubstringToken(TokenType.SCRIPT_TAG, start, asciiOnly);
return next;
}
}
appendPrecedenceToken(TokenType.HASH);
return advance();
}
int tokenizeTilde(int next) {
// ~ ~/ ~/=
next = advance();
if (identical(next, $SLASH)) {
return select($EQ, TokenType.TILDE_SLASH_EQ, TokenType.TILDE_SLASH);
} else {
appendPrecedenceToken(TokenType.TILDE);
return next;
}
}
int tokenizeOpenSquareBracket(int next) {
// [ [] []=
next = advance();
if (identical(next, $CLOSE_SQUARE_BRACKET)) {
return select($EQ, TokenType.INDEX_EQ, TokenType.INDEX);
}
appendBeginGroup(TokenType.OPEN_SQUARE_BRACKET);
return next;
}
int tokenizeCaret(int next) {
// ^ ^=
return select($EQ, TokenType.CARET_EQ, TokenType.CARET);
}
int tokenizeQuestion(int next) {
// ? ?. ?.. ?? ??=
next = advance();
if (identical(next, $QUESTION)) {
return select(
$EQ, TokenType.QUESTION_QUESTION_EQ, TokenType.QUESTION_QUESTION);
} else if (identical(next, $PERIOD)) {
next = advance();
if (_enableNonNullable) {
if (identical($PERIOD, next)) {
appendPrecedenceToken(TokenType.QUESTION_PERIOD_PERIOD);
return advance();
}
if (identical($OPEN_SQUARE_BRACKET, next)) {
appendBeginGroup(TokenType.QUESTION_PERIOD_OPEN_SQUARE_BRACKET);
return advance();
}
}
appendPrecedenceToken(TokenType.QUESTION_PERIOD);
return next;
} else {
appendPrecedenceToken(TokenType.QUESTION);
return next;
}
}
int tokenizeBar(int next) {
// | || |= ||=
next = advance();
if (identical(next, $BAR)) {
next = advance();
if (LAZY_ASSIGNMENT_ENABLED && identical(next, $EQ)) {
appendPrecedenceToken(TokenType.BAR_BAR_EQ);
return advance();
}
appendPrecedenceToken(TokenType.BAR_BAR);
return next;
} else if (identical(next, $EQ)) {
appendPrecedenceToken(TokenType.BAR_EQ);
return advance();
} else {
appendPrecedenceToken(TokenType.BAR);
return next;
}
}
int tokenizeAmpersand(int next) {
// && &= & &&=
next = advance();
if (identical(next, $AMPERSAND)) {
next = advance();
if (LAZY_ASSIGNMENT_ENABLED && identical(next, $EQ)) {
appendPrecedenceToken(TokenType.AMPERSAND_AMPERSAND_EQ);
return advance();
}
appendPrecedenceToken(TokenType.AMPERSAND_AMPERSAND);
return next;
} else if (identical(next, $EQ)) {
appendPrecedenceToken(TokenType.AMPERSAND_EQ);
return advance();
} else {
appendPrecedenceToken(TokenType.AMPERSAND);
return next;
}
}
int tokenizePercent(int next) {
// % %=
return select($EQ, TokenType.PERCENT_EQ, TokenType.PERCENT);
}
int tokenizeMultiply(int next) {
// * *=
return select($EQ, TokenType.STAR_EQ, TokenType.STAR);
}
int tokenizeMinus(int next) {
// - -- -=
next = advance();
if (identical(next, $MINUS)) {
appendPrecedenceToken(TokenType.MINUS_MINUS);
return advance();
} else if (identical(next, $EQ)) {
appendPrecedenceToken(TokenType.MINUS_EQ);
return advance();
} else {
appendPrecedenceToken(TokenType.MINUS);
return next;
}
}
int tokenizePlus(int next) {
// + ++ +=
next = advance();
if (identical($PLUS, next)) {
appendPrecedenceToken(TokenType.PLUS_PLUS);
return advance();
} else if (identical($EQ, next)) {
appendPrecedenceToken(TokenType.PLUS_EQ);
return advance();
} else {
appendPrecedenceToken(TokenType.PLUS);
return next;
}
}
int tokenizeExclamation(int next) {
// ! !=
// !== is kept for user-friendly error reporting.
next = advance();
if (identical(next, $EQ)) {
//was `return select($EQ, TokenType.BANG_EQ_EQ, TokenType.BANG_EQ);`
int next = advance();
if (identical(next, $EQ)) {
appendPrecedenceToken(TokenType.BANG_EQ_EQ);
prependErrorToken(new UnsupportedOperator(tail, tokenStart));
return advance();
} else {
appendPrecedenceToken(TokenType.BANG_EQ);
return next;
}
}
appendPrecedenceToken(TokenType.BANG);
return next;
}
int tokenizeEquals(int next) {
// = == =>
// === is kept for user-friendly error reporting.
// Type parameters and arguments cannot contain any token that
// starts with '='.
discardOpenLt();
next = advance();
if (identical(next, $EQ)) {
// was `return select($EQ, TokenType.EQ_EQ_EQ, TokenType.EQ_EQ);`
int next = advance();
if (identical(next, $EQ)) {
appendPrecedenceToken(TokenType.EQ_EQ_EQ);
prependErrorToken(new UnsupportedOperator(tail, tokenStart));
return advance();
} else {
appendPrecedenceToken(TokenType.EQ_EQ);
return next;
}
} else if (identical(next, $GT)) {
appendPrecedenceToken(TokenType.FUNCTION);
return advance();
}
appendPrecedenceToken(TokenType.EQ);
return next;
}
int tokenizeGreaterThan(int next) {
// > >= >> >>= >>> >>>=
next = advance();
if (identical($EQ, next)) {
appendPrecedenceToken(TokenType.GT_EQ);
return advance();
} else if (identical($GT, next)) {
next = advance();
if (identical($EQ, next)) {
appendPrecedenceToken(TokenType.GT_GT_EQ);
return advance();
} else if (_enableTripleShift && identical($GT, next)) {
next = advance();
if (_enableTripleShift && identical($EQ, next)) {
appendPrecedenceToken(TokenType.GT_GT_GT_EQ);
return advance();
}
appendPrecedenceToken(TokenType.GT_GT_GT);
return next;
} else {
appendGtGt(TokenType.GT_GT);
return next;
}
} else {
appendGt(TokenType.GT);
return next;
}
}
int tokenizeLessThan(int next) {
// < <= << <<=
next = advance();
if (identical($EQ, next)) {
appendPrecedenceToken(TokenType.LT_EQ);
return advance();
} else if (identical($LT, next)) {
return select($EQ, TokenType.LT_LT_EQ, TokenType.LT_LT);
} else {
appendBeginGroup(TokenType.LT);
return next;
}
}
int tokenizeNumber(int next) {
int start = scanOffset;
while (true) {
next = advance();
if ($0 <= next && next <= $9) {
continue;
} else if (identical(next, $e) || identical(next, $E)) {
return tokenizeFractionPart(next, start);
} else {
if (identical(next, $PERIOD)) {
int nextnext = peek();
if ($0 <= nextnext && nextnext <= $9) {
return tokenizeFractionPart(advance(), start);
}
}
appendSubstringToken(TokenType.INT, start, true);
return next;
}
}
}
int tokenizeHexOrNumber(int next) {
int x = peek();
if (identical(x, $x) || identical(x, $X)) {
return tokenizeHex(next);
}
return tokenizeNumber(next);
}
int tokenizeHex(int next) {
int start = scanOffset;
next = advance(); // Advance past the $x or $X.
bool hasDigits = false;
while (true) {
next = advance();
if (($0 <= next && next <= $9) ||
($A <= next && next <= $F) ||
($a <= next && next <= $f)) {
hasDigits = true;
} else {
if (!hasDigits) {
prependErrorToken(new UnterminatedToken(
messageExpectedHexDigit, start, stringOffset));
// Recovery
appendSyntheticSubstringToken(
TokenType.HEXADECIMAL, start, true, "0");
return next;
}
appendSubstringToken(TokenType.HEXADECIMAL, start, true);
return next;
}
}
}
int tokenizeDotsOrNumber(int next) {
int start = scanOffset;
next = advance();
if (($0 <= next && next <= $9)) {
return tokenizeFractionPart(next, start);
} else if (identical($PERIOD, next)) {
next = advance();
if (identical(next, $PERIOD)) {
next = advance();
if (identical(next, $QUESTION)) {
appendPrecedenceToken(TokenType.PERIOD_PERIOD_PERIOD_QUESTION);
return advance();
} else {
appendPrecedenceToken(TokenType.PERIOD_PERIOD_PERIOD);
return next;
}
} else {
appendPrecedenceToken(TokenType.PERIOD_PERIOD);
return next;
}
} else {
appendPrecedenceToken(TokenType.PERIOD);
return next;
}
}
int tokenizeFractionPart(int next, int start) {
bool done = false;
bool hasDigit = false;
LOOP:
while (!done) {
if ($0 <= next && next <= $9) {
hasDigit = true;
} else if (identical($e, next) || identical($E, next)) {
hasDigit = true;
next = advance();
if (identical(next, $PLUS) || identical(next, $MINUS)) {
next = advance();
}
bool hasExponentDigits = false;
while (true) {
if ($0 <= next && next <= $9) {
hasExponentDigits = true;
} else {
if (!hasExponentDigits) {
appendSyntheticSubstringToken(TokenType.DOUBLE, start, true, '0');
prependErrorToken(new UnterminatedToken(
messageMissingExponent, tokenStart, stringOffset));
return next;
}
break;
}
next = advance();
}
done = true;
continue LOOP;
} else {
done = true;
continue LOOP;
}
next = advance();
}
if (!hasDigit) {
// Reduce offset, we already advanced to the token past the period.
appendSubstringToken(TokenType.INT, start, true, -1);
// TODO(ahe): Wrong offset for the period. Cannot call beginToken because
// the scanner already advanced past the period.
if (identical($PERIOD, next)) {
return select(
$PERIOD, TokenType.PERIOD_PERIOD_PERIOD, TokenType.PERIOD_PERIOD);
}
appendPrecedenceToken(TokenType.PERIOD);
return next;
}
appendSubstringToken(TokenType.DOUBLE, start, true);
return next;
}
int tokenizeSlashOrComment(int next) {
int start = scanOffset;
next = advance();
if (identical($STAR, next)) {
return tokenizeMultiLineComment(next, start);
} else if (identical($SLASH, next)) {
return tokenizeSingleLineComment(next, start);
} else if (identical($EQ, next)) {
appendPrecedenceToken(TokenType.SLASH_EQ);
return advance();
} else {
appendPrecedenceToken(TokenType.SLASH);
return next;
}
}
int tokenizeLanguageVersionOrSingleLineComment(int next) {
int start = scanOffset;
next = advance();
// Dart doc
if (identical($SLASH, peek())) {
return tokenizeSingleLineComment(next, start);
}
// "@dart"
next = advance();
while (identical($SPACE, next)) {
next = advance();
}
if (!identical($AT, next)) {
return tokenizeSingleLineCommentRest(next, start, false);
}
next = advance();
if (!identical($d, next)) {
return tokenizeSingleLineCommentRest(next, start, false);
}
next = advance();
if (!identical($a, next)) {
return tokenizeSingleLineCommentRest(next, start, false);
}
next = advance();
if (!identical($r, next)) {
return tokenizeSingleLineCommentRest(next, start, false);
}
next = advance();
if (!identical($t, next)) {
return tokenizeSingleLineCommentRest(next, start, false);
}
next = advance();
// "="
while (identical($SPACE, next)) {
next = advance();
}
if (!identical($EQ, next)) {
return tokenizeSingleLineCommentRest(next, start, false);
}
next = advance();
// major
while (identical($SPACE, next)) {
next = advance();
}
int major = 0;
int majorStart = scanOffset;
while (isDigit(next)) {
major = major * 10 + next - $0;
next = advance();
}
if (scanOffset == majorStart) {
return tokenizeSingleLineCommentRest(next, start, false);
}
// minor
if (!identical($PERIOD, next)) {
return tokenizeSingleLineCommentRest(next, start, false);
}
next = advance();
int minor = 0;
int minorStart = scanOffset;
while (isDigit(next)) {
minor = minor * 10 + next - $0;
next = advance();
}
if (scanOffset == minorStart) {
return tokenizeSingleLineCommentRest(next, start, false);
}
// trailing spaces
while (identical($SPACE, next)) {
next = advance();
}
if (next != $LF && next != $CR && next != $EOF) {
return tokenizeSingleLineCommentRest(next, start, false);
}
LanguageVersionToken languageVersion =
createLanguageVersionToken(start, major, minor);
if (languageVersionChanged != null) {
// TODO(danrubel): make this required and remove the languageVersion field
languageVersionChanged(this, languageVersion);
} else {
// TODO(danrubel): remove this hack and require listener to update
// the scanner's configuration.
configuration = ScannerConfiguration.classic;
}
if (includeComments) {
_appendToCommentStream(languageVersion);
}
return next;
}
int tokenizeSingleLineComment(int next, int start) {
bool dartdoc = identical($SLASH, peek());
next = advance();
return tokenizeSingleLineCommentRest(next, start, dartdoc);
}
int tokenizeSingleLineCommentRest(int next, int start, bool dartdoc) {
bool asciiOnly = true;
while (true) {
if (next > 127) asciiOnly = false;
if (identical($LF, next) ||
identical($CR, next) ||
identical($EOF, next)) {
if (!asciiOnly) handleUnicode(start);
if (dartdoc) {
appendDartDoc(start, TokenType.SINGLE_LINE_COMMENT, asciiOnly);
} else {
appendComment(start, TokenType.SINGLE_LINE_COMMENT, asciiOnly);
}
return next;
}
next = advance();
}
}
int tokenizeMultiLineComment(int next, int start) {
bool asciiOnlyComment = true; // Track if the entire comment is ASCII.
bool asciiOnlyLines = true; // Track ASCII since the last handleUnicode.
int unicodeStart = start;
int nesting = 1;
next = advance();
bool dartdoc = identical($STAR, next);
while (true) {
if (identical($EOF, next)) {
if (!asciiOnlyLines) handleUnicode(unicodeStart);
prependErrorToken(new UnterminatedToken(
messageUnterminatedComment, tokenStart, stringOffset));
advanceAfterError(true);
break;
} else if (identical($STAR, next)) {
next = advance();
if (identical($SLASH, next)) {
--nesting;
if (0 == nesting) {
if (!asciiOnlyLines) handleUnicode(unicodeStart);
next = advance();
if (dartdoc) {
appendDartDoc(
start, TokenType.MULTI_LINE_COMMENT, asciiOnlyComment);
} else {
appendComment(
start, TokenType.MULTI_LINE_COMMENT, asciiOnlyComment);
}
break;
} else {
next = advance();
}
}
} else if (identical($SLASH, next)) {
next = advance();
if (identical($STAR, next)) {
next = advance();
++nesting;
}
} else if (identical(next, $LF)) {
if (!asciiOnlyLines) {
// Synchronize the string offset in the utf8 scanner.
handleUnicode(unicodeStart);
asciiOnlyLines = true;
unicodeStart = scanOffset;
}
lineFeedInMultiline();
next = advance();
} else {
if (next > 127) {
asciiOnlyLines = false;
asciiOnlyComment = false;
}
next = advance();
}
}
return next;
}
void appendComment(int start, TokenType type, bool asciiOnly) {
if (!includeComments) return;
CommentToken newComment = createCommentToken(type, start, asciiOnly);
_appendToCommentStream(newComment);
}
void appendDartDoc(int start, TokenType type, bool asciiOnly) {
if (!includeComments) return;
Token newComment = createDartDocToken(type, start, asciiOnly);
_appendToCommentStream(newComment);
}
/**
* Append the given token to the [tail] of the current stream of tokens.
*/
void appendToken(Token token) {
tail.next = token;
token.previous = tail;
tail = token;
if (comments != null && comments == token.precedingComments) {
comments = null;
commentsTail = null;
} else {
// It is the responsibility of the caller to construct the token
// being appended with preceding comments if any
assert(comments == null || token.isSynthetic || token is ErrorToken);
}
}
void _appendToCommentStream(Token newComment) {
if (comments == null) {
comments = newComment;
commentsTail = comments;
} else {
commentsTail.next = newComment;
commentsTail.next.previous = commentsTail;
commentsTail = commentsTail.next;
}
}
int tokenizeRawStringKeywordOrIdentifier(int next) {
// [next] is $r.
int nextnext = peek();
if (identical(nextnext, $DQ) || identical(nextnext, $SQ)) {
int start = scanOffset;
next = advance();
return tokenizeString(next, start, true);
}
return tokenizeKeywordOrIdentifier(next, true);
}
int tokenizeKeywordOrIdentifier(int next, bool allowDollar) {
KeywordState state = KeywordState.KEYWORD_STATE;
int start = scanOffset;
// We allow a leading capital character.
if ($A <= next && next <= $Z) {
state = state.nextCapital(next);
next = advance();
} else if ($a <= next && next <= $z) {
// Do the first next call outside the loop to avoid an additional test
// and to make the loop monomorphic.
state = state.next(next);
next = advance();
}
while (state != null && $a <= next && next <= $z) {
state = state.next(next);
next = advance();
}
if (state == null || state.keyword == null) {
return tokenizeIdentifier(next, start, allowDollar);
}
if (!_enableExtensionMethods && state.keyword == Keyword.EXTENSION) {
return tokenizeIdentifier(next, start, allowDollar);
}
if (!_enableNonNullable &&
(state.keyword == Keyword.LATE || state.keyword == Keyword.REQUIRED)) {
return tokenizeIdentifier(next, start, allowDollar);
}
if (($A <= next && next <= $Z) ||
($0 <= next && next <= $9) ||
identical(next, $_) ||
identical(next, $$)) {
return tokenizeIdentifier(next, start, allowDollar);
} else {
appendKeywordToken(state.keyword);
return next;
}
}
/**
* [allowDollar] can exclude '$', which is not allowed as part of a string
* interpolation identifier.
*/
int tokenizeIdentifier(int next, int start, bool allowDollar) {
while (true) {
if (_isIdentifierChar(next, allowDollar)) {
next = advance();
} else {
// Identifier ends here.
if (start == scanOffset) {
return unexpected(next);
} else {
appendSubstringToken(TokenType.IDENTIFIER, start, true);
}
break;
}
}
return next;
}
int tokenizeAt(int next) {
appendPrecedenceToken(TokenType.AT);
return advance();
}
int tokenizeString(int next, int start, bool raw) {
int quoteChar = next;
next = advance();
if (identical(quoteChar, next)) {
next = advance();
if (identical(quoteChar, next)) {
// Multiline string.
return tokenizeMultiLineString(quoteChar, start, raw);
} else {
// Empty string.
appendSubstringToken(TokenType.STRING, start, true);
return next;
}
}
if (raw) {
return tokenizeSingleLineRawString(next, quoteChar, start);
} else {
return tokenizeSingleLineString(next, quoteChar, start);
}
}
/**
* [next] is the first character after the quote.
* [quoteStart] is the scanOffset of the quote.
*
* The token contains a substring of the source file, including the
* string quotes, backslashes for escaping. For interpolated strings,
* the parts before and after are separate tokens.
*
* "a $b c"
*
* gives StringToken("a $), StringToken(b) and StringToken( c").
*/
int tokenizeSingleLineString(int next, int quoteChar, int quoteStart) {
int start = quoteStart;
bool asciiOnly = true;
while (!identical(next, quoteChar)) {
if (identical(next, $BACKSLASH)) {
next = advance();
} else if (identical(next, $$)) {
if (!asciiOnly) handleUnicode(start);
next = tokenizeStringInterpolation(start, asciiOnly);
start = scanOffset;
asciiOnly = true;
continue;
}
if (next <= $CR &&
(identical(next, $LF) ||
identical(next, $CR) ||
identical(next, $EOF))) {
if (!asciiOnly) handleUnicode(start);
unterminatedString(quoteChar, quoteStart, start,
asciiOnly: asciiOnly, isMultiLine: false, isRaw: false);
return next;
}
if (next > 127) asciiOnly = false;
next = advance();
}
if (!asciiOnly) handleUnicode(start);
// Advance past the quote character.
next = advance();
appendSubstringToken(TokenType.STRING, start, asciiOnly);
return next;
}
int tokenizeStringInterpolation(int start, bool asciiOnly) {
appendSubstringToken(TokenType.STRING, start, asciiOnly);
beginToken(); // $ starts here.
int next = advance();
if (identical(next, $OPEN_CURLY_BRACKET)) {
return tokenizeInterpolatedExpression(next);
} else {
return tokenizeInterpolatedIdentifier(next);
}
}
int tokenizeInterpolatedExpression(int next) {
appendBeginGroup(TokenType.STRING_INTERPOLATION_EXPRESSION);
beginToken(); // The expression starts here.
next = advance(); // Move past the curly bracket.
while (!identical(next, $EOF) && !identical(next, $STX)) {
next = bigSwitch(next);
}
if (identical(next, $EOF)) {
beginToken();
discardInterpolation();
return next;
}
next = advance(); // Move past the $STX.
beginToken(); // The string interpolation suffix starts here.
return next;
}
int tokenizeInterpolatedIdentifier(int next) {
appendPrecedenceToken(TokenType.STRING_INTERPOLATION_IDENTIFIER);
if ($a <= next && next <= $z ||
$A <= next && next <= $Z ||
identical(next, $_)) {
beginToken(); // The identifier starts here.
next = tokenizeKeywordOrIdentifier(next, false);
} else {
beginToken(); // The synthetic identifier starts here.
appendSyntheticSubstringToken(TokenType.IDENTIFIER, scanOffset, true, '');
prependErrorToken(new UnterminatedToken(
messageUnexpectedDollarInString, tokenStart, stringOffset));
}
beginToken(); // The string interpolation suffix starts here.
return next;
}
int tokenizeSingleLineRawString(int next, int quoteChar, int quoteStart) {
bool asciiOnly = true;
while (next != $EOF) {
if (identical(next, quoteChar)) {
if (!asciiOnly) handleUnicode(quoteStart);
next = advance();
appendSubstringToken(TokenType.STRING, quoteStart, asciiOnly);
return next;
} else if (identical(next, $LF) || identical(next, $CR)) {
if (!asciiOnly) handleUnicode(quoteStart);
unterminatedString(quoteChar, quoteStart, quoteStart,
asciiOnly: asciiOnly, isMultiLine: false, isRaw: true);
return next;
} else if (next > 127) {
asciiOnly = false;
}
next = advance();
}
if (!asciiOnly) handleUnicode(quoteStart);
unterminatedString(quoteChar, quoteStart, quoteStart,
asciiOnly: asciiOnly, isMultiLine: false, isRaw: true);
return next;
}
int tokenizeMultiLineRawString(int quoteChar, int quoteStart) {
bool asciiOnlyString = true;
bool asciiOnlyLine = true;
int unicodeStart = quoteStart;
int next = advance(); // Advance past the (last) quote (of three).
outer:
while (!identical(next, $EOF)) {
while (!identical(next, quoteChar)) {
if (identical(next, $LF)) {
if (!asciiOnlyLine) {
// Synchronize the string offset in the utf8 scanner.
handleUnicode(unicodeStart);
asciiOnlyLine = true;
unicodeStart = scanOffset;
}
lineFeedInMultiline();
} else if (next > 127) {
asciiOnlyLine = false;
asciiOnlyString = false;
}
next = advance();
if (identical(next, $EOF)) break outer;
}
next = advance();
if (identical(next, quoteChar)) {
next = advance();
if (identical(next, quoteChar)) {
if (!asciiOnlyLine) handleUnicode(unicodeStart);
next = advance();
appendSubstringToken(TokenType.STRING, quoteStart, asciiOnlyString);
return next;
}
}
}
if (!asciiOnlyLine) handleUnicode(unicodeStart);
unterminatedString(quoteChar, quoteStart, quoteStart,
asciiOnly: asciiOnlyLine, isMultiLine: true, isRaw: true);
return next;
}
int tokenizeMultiLineString(int quoteChar, int quoteStart, bool raw) {
if (raw) return tokenizeMultiLineRawString(quoteChar, quoteStart);
int start = quoteStart;
bool asciiOnlyString = true;
bool asciiOnlyLine = true;
int unicodeStart = start;
int next = advance(); // Advance past the (last) quote (of three).
while (!identical(next, $EOF)) {
if (identical(next, $$)) {
if (!asciiOnlyLine) handleUnicode(unicodeStart);
next = tokenizeStringInterpolation(start, asciiOnlyString);
start = scanOffset;
unicodeStart = start;
asciiOnlyString = true; // A new string token is created for the rest.
asciiOnlyLine = true;
continue;
}
if (identical(next, quoteChar)) {
next = advance();
if (identical(next, quoteChar)) {
next = advance();
if (identical(next, quoteChar)) {
if (!asciiOnlyLine) handleUnicode(unicodeStart);
next = advance();
appendSubstringToken(TokenType.STRING, start, asciiOnlyString);
return next;
}
}
continue;
}
if (identical(next, $BACKSLASH)) {
next = advance();
if (identical(next, $EOF)) break;
}
if (identical(next, $LF)) {
if (!asciiOnlyLine) {
// Synchronize the string offset in the utf8 scanner.
handleUnicode(unicodeStart);
asciiOnlyLine = true;
unicodeStart = scanOffset;
}
lineFeedInMultiline();
} else if (next > 127) {
asciiOnlyString = false;
asciiOnlyLine = false;
}
next = advance();
}
if (!asciiOnlyLine) handleUnicode(unicodeStart);
unterminatedString(quoteChar, quoteStart, start,
asciiOnly: asciiOnlyString, isMultiLine: true, isRaw: false);
return next;
}
int unexpected(int character) {
ErrorToken errorToken =
buildUnexpectedCharacterToken(character, tokenStart);
if (errorToken is NonAsciiIdentifierToken) {
int charOffset;
List<int> codeUnits = <int>[];
if (tail.type == TokenType.IDENTIFIER && tail.charEnd == tokenStart) {
charOffset = tail.charOffset;
codeUnits.addAll(tail.lexeme.codeUnits);
tail = tail.previous;
} else {
charOffset = errorToken.charOffset;
}
codeUnits.add(errorToken.character);
prependErrorToken(errorToken);
int next = advanceAfterError(true);
while (_isIdentifierChar(next, true)) {
codeUnits.add(next);
next = advance();
}
appendToken(new StringToken.fromString(TokenType.IDENTIFIER,
new String.fromCharCodes(codeUnits), charOffset));
return next;
} else {
prependErrorToken(errorToken);
return advanceAfterError(true);
}
}
void unterminatedString(int quoteChar, int quoteStart, int start,
{bool asciiOnly, bool isMultiLine, bool isRaw}) {
String suffix = new String.fromCharCodes(
isMultiLine ? [quoteChar, quoteChar, quoteChar] : [quoteChar]);
String prefix = isRaw ? 'r$suffix' : suffix;
appendSyntheticSubstringToken(TokenType.STRING, start, asciiOnly, suffix);
// Ensure that the error is reported on a visible token
int errorStart = tokenStart < stringOffset ? tokenStart : quoteStart;
prependErrorToken(new UnterminatedString(prefix, errorStart, stringOffset));
}
int advanceAfterError(bool shouldAdvance) {
if (atEndOfFile()) return $EOF;
if (shouldAdvance) {
return advance(); // Ensure progress.
} else {
return -1;
}
}
}
TokenType closeBraceInfoFor(BeginToken begin) {
return const {
'(': TokenType.CLOSE_PAREN,
'[': TokenType.CLOSE_SQUARE_BRACKET,
'{': TokenType.CLOSE_CURLY_BRACKET,
'<': TokenType.GT,
r'${': TokenType.CLOSE_CURLY_BRACKET,
'?.[': TokenType.CLOSE_SQUARE_BRACKET,
}[begin.lexeme];
}
class LineStarts extends Object with ListMixin<int> {
List<int> array;
int arrayLength = 0;
LineStarts(int numberOfBytesHint) {
// Let's assume the average Dart file is 300 bytes.
if (numberOfBytesHint == null) numberOfBytesHint = 300;
// Let's assume we have on average 22 bytes per line.
final int expectedNumberOfLines = 1 + (numberOfBytesHint ~/ 22);
if (numberOfBytesHint > 65535) {
array = new Uint32List(expectedNumberOfLines);
} else {
array = new Uint16List(expectedNumberOfLines);
}
// The first line starts at character offset 0.
add(0);
}
// Implement abstract members used by [ListMixin]
int get length => arrayLength;
int operator [](int index) {
assert(index < arrayLength);
return array[index];
}
void set length(int newLength) {
if (newLength > array.length) {
grow(newLength);
}
arrayLength = newLength;
}
void operator []=(int index, int value) {
if (value > 65535 && array is! Uint32List) {
switchToUint32(array.length);
}
array[index] = value;
}
// Specialize methods from [ListMixin].
void add(int value) {
if (arrayLength >= array.length) {
grow(0);
}
if (value > 65535 && array is! Uint32List) {
switchToUint32(array.length);
}
array[arrayLength++] = value;
}
// Helper methods.
void grow(int newLengthMinimum) {
int newLength = array.length * 2;
if (newLength < newLengthMinimum) newLength = newLengthMinimum;
if (array is Uint16List) {
final Uint16List newArray = new Uint16List(newLength);
newArray.setRange(0, arrayLength, array);
array = newArray;
} else {
switchToUint32(newLength);
}
}
void switchToUint32(int newLength) {
final Uint32List newArray = new Uint32List(newLength);
newArray.setRange(0, arrayLength, array);
array = newArray;
}
}
/// [ScannerConfiguration] contains information for configuring which tokens
/// the scanner produces based upon the Dart language level.
class ScannerConfiguration {
static const ScannerConfiguration classic = const ScannerConfiguration();
static const ScannerConfiguration nonNullable =
const ScannerConfiguration(enableNonNullable: true);
/// Experimental flag for enabling scanning of the `extension` keyword.
final bool enableExtensionMethods;
/// Experimental flag for enabling scanning of NNBD tokens
/// such as 'required' and 'late'
final bool enableNonNullable;
/// Experimental flag for enabling scanning of `>>>`.
/// See https://github.com/dart-lang/language/issues/61
/// and https://github.com/dart-lang/language/issues/60
final bool enableTripleShift;
const ScannerConfiguration({
bool enableExtensionMethods,
bool enableNonNullable,
bool enableTripleShift,
}) : this.enableExtensionMethods = enableExtensionMethods ?? false,
this.enableNonNullable = enableNonNullable ?? false,
this.enableTripleShift = enableTripleShift ?? false;
}
bool _isIdentifierChar(int next, bool allowDollar) {
return ($a <= next && next <= $z) ||
($A <= next && next <= $Z) ||
($0 <= next && next <= $9) ||
identical(next, $_) ||
(identical(next, $$) && allowDollar);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/scanner/io.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.md file.
library fasta.scanner.io;
import 'dart:async' show Future;
import 'dart:io' show File, RandomAccessFile;
import 'dart:typed_data' show Uint8List;
List<int> readBytesFromFileSync(Uri uri) {
RandomAccessFile file = new File.fromUri(uri).openSync();
Uint8List list;
try {
int length = file.lengthSync();
// +1 to have a 0 terminated list, see [Scanner].
list = new Uint8List(length + 1);
file.readIntoSync(list, 0, length);
} finally {
file.closeSync();
}
return list;
}
Future<List<int>> readBytesFromFile(Uri uri,
{bool ensureZeroTermination: true}) async {
RandomAccessFile file = await new File.fromUri(uri).open();
Uint8List list;
try {
int length = await file.length();
// +1 to have a 0 terminated list, see [Scanner].
list = new Uint8List(ensureZeroTermination ? length + 1 : length);
int read = await file.readInto(list);
if (read != length) {
throw "Error reading file: ${uri}";
}
} finally {
await file.close();
}
return list;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/summary_generator.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.
/// Defines the front-end API for converting source code to summaries.
library front_end.summary_generator;
import 'dart:async';
import 'compiler_options.dart';
import '../base/processed_options.dart';
import '../kernel_generator_impl.dart';
/// Creates a summary representation of the build unit whose source files are in
/// [sources].
///
/// Intended to be a part of a modular compilation process.
///
/// Any dependency of [sources] that is not listed in
/// [CompilerOptions.inputSummaries] and [CompilerOptions.sdkSummary] is treated
/// as an additional source file for the build unit.
///
/// Any `part` declarations found in [sources] must refer to part files which
/// are also listed in the build unit sources, otherwise an error results. (It
/// is not permitted to refer to a part file declared in another build unit).
///
/// If [truncate] is true, the resulting summary doesn't include any references
/// to libraries loaded from the input summaries, and only contains code that
/// was compiled from sources.
///
/// The return value is a list of bytes to write to the summary file.
Future<List<int>> summaryFor(List<Uri> sources, CompilerOptions options,
{bool truncate: false}) async {
return (await generateKernel(
new ProcessedOptions(options: options, inputs: sources),
buildSummary: true,
buildComponent: false,
truncateSummary: truncate))
?.summary;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/compiler_options.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 front_end.compiler_options;
import 'package:kernel/ast.dart' as kernel show Library;
import 'package:kernel/target/targets.dart' show Target;
import 'diagnostic_message.dart' show DiagnosticMessageHandler;
import 'experimental_flags.dart'
show
defaultExperimentalFlags,
ExperimentalFlag,
expiredExperimentalFlags,
parseExperimentalFlag;
import 'file_system.dart' show FileSystem;
import 'standard_file_system.dart' show StandardFileSystem;
export 'diagnostic_message.dart' show DiagnosticMessage;
/// Front-end options relevant to compiler back ends.
///
/// Not intended to be implemented or extended by clients.
class CompilerOptions {
/// The URI of the root of the Dart SDK (typically a "file:" URI).
///
/// If `null`, the SDK will be searched for using
/// [Platform.resolvedExecutable] as a starting point.
Uri sdkRoot;
/// Uri to a platform libraries specification file.
///
/// A libraries specification file is a JSON file that describes how to map
/// `dart:*` libraries to URIs in the underlying [fileSystem]. See
/// `package:front_end/src/base/libraries_specification.dart` for details on
/// the format.
///
/// If a value is not specified and `compileSdk = true`, the compiler will
/// infer at a default location under [sdkRoot], typically under
/// `lib/libraries.json`.
Uri librariesSpecificationUri;
DiagnosticMessageHandler onDiagnostic;
/// URI of the ".packages" file (typically a "file:" URI).
///
/// If `null`, the ".packages" file will be found via the standard
/// package_config search algorithm.
///
/// If the URI's path component is empty (e.g. `new Uri()`), no packages file
/// will be used.
Uri packagesFileUri;
/// URIs of input summary files (excluding the SDK summary; typically these
/// will be "file:" URIs).
///
/// These files should be summary files generated by this package (and not the
/// similarly named summary files from `package:analyzer`.)
///
/// Summaries may be provided in any order, but they should be acyclic and
/// closed: any libraries that they reference should be defined in either one
/// of [inputSummaries] or [sdkSummary].
List<Uri> inputSummaries = [];
/// URIs of other kernel components to link.
///
/// Commonly used to link the code for the SDK libraries that was compiled
/// separately. For example, dart2js needs to link the SDK so it can
/// optimize and tree-shake the code for the application, whereas the VM
/// always embeds the SDK internally and doesn't need it as part of the
/// program.
///
/// The components provided here should be closed and acyclic: any libraries
/// that they reference should be defined in a component in
/// [linkedDependencies] or any of the [inputSummaries] or [sdkSummary].
List<Uri> linkedDependencies = [];
/// URI of the SDK summary file (typically a "file:" URI).
///
/// This should should be a summary previously generated by this package (and
/// not the similarly named summary files from `package:analyzer`.)
///
/// If `null` and [compileSdk] is false, the SDK summary will be searched for
/// at a default location within [sdkRoot].
Uri sdkSummary;
/// The declared variables for use by configurable imports and constant
/// evaluation.
Map<String, String> declaredVariables;
/// The [FileSystem] which should be used by the front end to access files.
///
/// All file system access performed by the front end goes through this
/// mechanism, with one exception: if no value is specified for
/// [packagesFileUri], the packages file is located using the actual physical
/// file system. TODO(paulberry): fix this.
FileSystem fileSystem = StandardFileSystem.instance;
/// Whether to generate code for the SDK.
///
/// By default the front end resolves components using a prebuilt SDK summary.
/// When this option is `true`, [sdkSummary] must be null.
bool compileSdk = false;
@deprecated
bool chaseDependencies;
/// Patch files to apply on the core libraries for a specific target platform.
///
/// Keys in the map are the name of the library with no `dart:` prefix, for
/// example:
///
/// {'core': [
/// 'file:///location/of/core/patch_file1.dart',
/// 'file:///location/of/core/patch_file2.dart',
/// ]}
///
/// The values can be either absolute or relative URIs. Absolute URIs are read
/// directly, while relative URIs are resolved from the [sdkRoot].
// TODO(sigmund): provide also a flag to load this data from a file (like
// libraries.json)
Map<String, List<Uri>> targetPatches = <String, List<Uri>>{};
/// Enable or disable experimental features. Features mapping to `true` are
/// explicitly enabled. Features mapping to `false` are explicitly disabled.
/// Features not mentioned in the map will have their default value.
Map<ExperimentalFlag, bool> experimentalFlags = <ExperimentalFlag, bool>{};
/// Environment map used when evaluating `bool.fromEnvironment`,
/// `int.fromEnvironment` and `String.fromEnvironment` during constant
/// evaluation. If the map is `null`, all environment constants will be left
/// unevaluated and can be evaluated by a constant evaluator later.
Map<String, String> environmentDefines = null;
/// Report an error if a constant could not be evaluated (either because it
/// is an environment constant and no environment was specified, or because
/// it refers to a constructor or variable initializer that is not available).
bool errorOnUnevaluatedConstant = false;
/// The target platform that will consume the compiled code.
///
/// Used to provide platform-specific details to the compiler like:
/// * the set of libraries are part of a platform's SDK (e.g. dart:html for
/// dart2js, dart:ui for flutter).
///
/// * what kernel transformations should be applied to the component
/// (async/await, mixin inlining, etc).
///
/// * how to deal with non-standard features like `native` extensions.
///
/// If not specified, the default target is the VM.
Target target;
/// Deprecated. Has no affect on front-end.
// TODO(dartbug.com/37514) Remove this field once DDK removes its uses of it.
bool enableAsserts = false;
/// Whether to show verbose messages (mainly for debugging and performance
/// tracking).
///
/// Messages are printed on stdout.
// TODO(sigmund): improve the diagnostics API to provide mechanism to
// intercept verbose data (Issue #30056)
bool verbose = false;
/// Whether to run extra verification steps to validate that compiled
/// components are well formed.
///
/// Errors are reported via the [onDiagnostic] callback.
bool verify = false;
/// Whether to dump generated components in a text format (also mainly for
/// debugging).
///
/// Dumped data is printed in stdout.
bool debugDump = false;
/// Whether to omit the platform when serializing the result from a `fasta
/// compile` run.
bool omitPlatform = false;
/// Whether to set the exit code to non-zero if any problem (including
/// warning, etc.) is encountered during compilation.
bool setExitCodeOnProblem = false;
/// Whether to embed the input sources in generated kernel components.
///
/// The kernel `Component` API includes a `uriToSource` map field that is used
/// to embed the entire contents of the source files. This part of the kernel
/// API is in flux and it is not necessary for some tools. Today it is used
/// for translating error locations and stack traces in the VM.
// TODO(sigmund): change the default.
bool embedSourceText = true;
/// Whether the compiler should throw as soon as it encounters a
/// compilation error.
///
/// Typically used by developers to debug internals of the compiler.
bool throwOnErrorsForDebugging = false;
/// Whether the compiler should throw as soon as it encounters a
/// compilation warning.
///
/// Typically used by developers to debug internals of the compiler.
bool throwOnWarningsForDebugging = false;
/// Whether to generate bytecode.
bool bytecode = false;
/// Whether to write a file (e.g. a dill file) when reporting a crash.
bool writeFileOnCrashReport = true;
/// The current sdk version string, e.g. "2.6.0-edge.sha1hash".
/// For instance used for language versioning (specifying the maximum
/// version).
String currentSdkVersion = "${kernel.Library.defaultLanguageVersionMajor}"
"."
"${kernel.Library.defaultLanguageVersionMinor}";
}
/// Parse experimental flag arguments of the form 'flag' or 'no-flag' into a map
/// from 'flag' to `true` or `false`, respectively.
Map<String, bool> parseExperimentalArguments(List<String> arguments) {
Map<String, bool> result = {};
if (arguments != null) {
for (String argument in arguments) {
for (String feature in argument.split(',')) {
if (feature.startsWith('no-')) {
result[feature.substring(3)] = false;
} else {
result[feature] = true;
}
}
}
}
return result;
}
/// Parse a map of experimental flags to values that can be passed to
/// [CompilerOptions.experimentalFlags].
/// The returned map is normalized to contain default values for unmentioned
/// flags.
///
/// If an unknown flag is mentioned, or a flag is mentioned more than once,
/// the supplied error handler is called with an error message.
///
/// If an expired flag is set to its non-default value the supplied error
/// handler is called with an error message.
///
/// If an expired flag is set to its default value the supplied warning
/// handler is called with a warning message.
Map<ExperimentalFlag, bool> parseExperimentalFlags(
Map<String, bool> experiments,
{void onError(String message),
void onWarning(String message)}) {
Map<ExperimentalFlag, bool> flags = <ExperimentalFlag, bool>{};
if (experiments != null) {
for (String experiment in experiments.keys) {
bool value = experiments[experiment];
ExperimentalFlag flag = parseExperimentalFlag(experiment);
if (flag == null) {
onError("Unknown experiment: " + experiment);
} else if (flags.containsKey(flag)) {
if (flags[flag] != value) {
onError(
"Experiment specified with conflicting values: " + experiment);
}
} else {
if (expiredExperimentalFlags[flag]) {
if (value != defaultExperimentalFlags[flag]) {
/// Produce an error when the value is not the default value.
if (value) {
onError("Enabling experiment " +
experiment +
" is no longer supported.");
} else {
onError("Disabling experiment " +
experiment +
" is no longer supported.");
}
value = defaultExperimentalFlags[flag];
} else if (onWarning != null) {
/// Produce a warning when the value is the default value.
if (value) {
onWarning("Experiment " +
experiment +
" is enabled by default. "
"The use of the flag is deprecated.");
} else {
onWarning("Experiment " +
experiment +
" is disabled by default. "
"The use of the flag is deprecated.");
}
}
flags[flag] = value;
} else {
flags[flag] = value;
}
}
}
}
for (ExperimentalFlag flag in ExperimentalFlag.values) {
assert(defaultExperimentalFlags.containsKey(flag),
"No default value for $flag.");
flags[flag] ??= defaultExperimentalFlags[flag];
}
return flags;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/memory_file_system.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 front_end.memory_file_system;
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'file_system.dart';
/// Concrete implementation of [FileSystem] which performs its operations on an
/// in-memory virtual file system.
///
/// Not intended to be implemented or extended by clients.
class MemoryFileSystem implements FileSystem {
final Map<Uri, Uint8List> _files = {};
final Set<Uri> _directories = new Set<Uri>();
/// The "current directory" in the in-memory virtual file system.
///
/// This is used to convert relative URIs to absolute URIs.
///
/// Always ends in a trailing '/'.
Uri currentDirectory;
MemoryFileSystem(Uri currentDirectory)
: currentDirectory = _addTrailingSlash(currentDirectory) {
_directories.add(currentDirectory);
}
@override
MemoryFileSystemEntity entityForUri(Uri uri) {
return new MemoryFileSystemEntity._(
this, currentDirectory.resolveUri(uri).normalizePath());
}
String get debugString {
StringBuffer sb = new StringBuffer();
_files.forEach((uri, _) => sb.write("- $uri\n"));
_directories.forEach((uri) => sb.write("- $uri\n"));
return '$sb';
}
static Uri _addTrailingSlash(Uri uri) {
if (!uri.path.endsWith('/')) {
uri = uri.replace(path: uri.path + '/');
}
return uri;
}
}
/// Concrete implementation of [FileSystemEntity] for use by
/// [MemoryFileSystem].
class MemoryFileSystemEntity implements FileSystemEntity {
final MemoryFileSystem _fileSystem;
@override
final Uri uri;
MemoryFileSystemEntity._(this._fileSystem, this.uri);
@override
int get hashCode => uri.hashCode;
@override
bool operator ==(Object other) =>
other is MemoryFileSystemEntity &&
other.uri == uri &&
identical(other._fileSystem, _fileSystem);
/// Create a directory for this file system entry.
///
/// If the entry is an existing file, this is an error.
void createDirectory() {
if (_fileSystem._files[uri] != null) {
throw new FileSystemException(uri, 'Entry $uri is a file.');
}
_fileSystem._directories.add(uri);
}
@override
Future<bool> exists() async {
return _fileSystem._files[uri] != null ||
_fileSystem._directories.contains(uri);
}
@override
Future<List<int>> readAsBytes() async {
Uint8List contents = _fileSystem._files[uri];
if (contents == null) {
throw new FileSystemException(uri, 'File $uri does not exist.');
}
return contents;
}
@override
Future<String> readAsString() async {
List<int> bytes = await readAsBytes();
try {
return utf8.decode(bytes);
} on FormatException catch (e) {
throw new FileSystemException(uri, e.message);
}
}
/// Writes the given raw bytes to this file system entity.
///
/// If no file exists, one is created. If a file exists already, it is
/// overwritten.
void writeAsBytesSync(List<int> bytes) {
if (bytes is Uint8List) {
_update(uri, bytes);
} else {
_update(uri, new Uint8List.fromList(bytes));
}
}
/// Writes the given string to this file system entity.
///
/// The string is encoded as UTF-8.
///
/// If no file exists, one is created. If a file exists already, it is
/// overwritten.
void writeAsStringSync(String s) {
// Note: the return type of utf8.encode is List<int>, but in practice it
// always returns Uint8List. We rely on that for efficiency, so that we
// don't have to make an extra copy.
_update(uri, utf8.encode(s) as Uint8List);
}
void _update(Uri uri, Uint8List data) {
if (_fileSystem._directories.contains(uri)) {
throw new FileSystemException(uri, 'Entry $uri is a directory.');
}
_fileSystem._files[uri] = data;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/file_system.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 front_end.file_system;
import 'dart:async';
/// Abstract interface to file system operations.
///
/// All front end interaction with the file system goes through this interface;
/// this makes it possible for clients to use the front end in a way that
/// doesn't require file system access (e.g. to run unit tests, or to run
/// inside a browser).
///
/// Not intended to be implemented or extended by clients.
abstract class FileSystem {
/// Returns a [FileSystemEntity] corresponding to the given [uri].
///
/// Uses of `..` and `.` in the URI are normalized before returning.
///
/// If the URI scheme is not supported by this file system, an [Error] will be
/// thrown.
///
/// Does not check whether a file or folder exists at the given location.
FileSystemEntity entityForUri(Uri uri);
}
/// Abstract representation of a file system entity that may or may not exist.
///
/// Instances of this class have suitable implementations of equality tests and
/// hashCode.
///
/// Not intended to be implemented or extended by clients.
abstract class FileSystemEntity {
/// The absolute normalized URI represented by this file system entity.
///
/// Note: this is not necessarily the same as the URI that was passed to
/// [FileSystem.entityForUri], since the URI might have been normalized.
Uri get uri;
/// Whether this file system entity exists.
Future<bool> exists();
/// Attempts to access this file system entity as a file and read its contents
/// as raw bytes.
///
/// If an error occurs while attempting to read the file (e.g. because no such
/// file exists, or the entity is a directory), the future is completed with
/// [FileSystemException].
Future<List<int>> readAsBytes();
/// Attempts to access this file system entity as a file and read its contents
/// as a string.
///
/// The file is assumed to be UTF-8 encoded.
///
/// If an error occurs while attempting to read the file (e.g. because no such
/// file exists, the entity is a directory, or the file is not valid UTF-8),
/// the future is completed with [FileSystemException].
Future<String> readAsString();
}
/**
* Base class for all file system exceptions.
*/
class FileSystemException implements Exception {
final Uri uri;
final String message;
FileSystemException(this.uri, this.message);
@override
String toString() => 'FileSystemException(uri=$uri; message=$message)';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/front_end.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.
/// The Dart Front End contains logic to build summaries and kernel programs
/// from Dart sources. The APIs exposed here are designed for tools in the Dart
/// ecosystem that need to load sources and convert them to these formats.
library front_end.front_end;
export 'compiler_options.dart';
export 'kernel_generator.dart';
export 'summary_generator.dart';
export 'file_system.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/kernel_generator.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.
/// Defines the front-end API for converting source code to Dart Kernel objects.
library front_end.kernel_generator;
import 'dart:async' show Future;
import 'package:kernel/ast.dart' show Component;
import 'package:kernel/class_hierarchy.dart' show ClassHierarchy;
import 'package:kernel/core_types.dart' show CoreTypes;
import '../base/processed_options.dart' show ProcessedOptions;
import '../fasta/compiler_context.dart' show CompilerContext;
import '../fasta/fasta_codes.dart' show messageMissingMain, noLength;
import '../fasta/severity.dart' show Severity;
import '../kernel_generator_impl.dart'
show generateKernel, generateKernelInternal;
import 'compiler_options.dart' show CompilerOptions;
/// Generates a kernel representation of the program whose main library is in
/// the given [source].
///
/// Intended for whole-program (non-modular) compilation.
///
/// Given the Uri of a file containing a program's `main` method, this function
/// follows `import`, `export`, and `part` declarations to discover the whole
/// program, and converts the result to Dart Kernel format.
///
/// If `compileSdk` in [options] is true, the generated [CompilerResult] will
/// include code for the SDK.
///
/// If summaries are provided in [options], the compiler will use them instead
/// of compiling the libraries contained in those summaries. This is useful, for
/// example, when compiling for platforms that already embed those sources (like
/// the sdk in the standalone VM).
///
/// The input [source] is expected to be a script with a main method, otherwise
/// an error is reported.
// TODO(sigmund): rename to kernelForScript?
Future<CompilerResult> kernelForProgram(
Uri source, CompilerOptions options) async {
return (await kernelForProgramInternal(source, options));
}
Future<CompilerResult> kernelForProgramInternal(
Uri source, CompilerOptions options,
{bool retainDataForTesting: false}) async {
ProcessedOptions pOptions =
new ProcessedOptions(options: options, inputs: [source]);
return await CompilerContext.runWithOptions(pOptions, (context) async {
CompilerResult result = await generateKernelInternal(
includeHierarchyAndCoreTypes: true,
retainDataForTesting: retainDataForTesting);
Component component = result?.component;
if (component == null) return null;
if (component.mainMethod == null) {
context.options.report(
messageMissingMain.withLocation(source, -1, noLength),
Severity.error);
return null;
}
return result;
});
}
/// Generates a kernel representation for a module containing [sources].
///
/// A module is a collection of libraries that are compiled together. Libraries
/// in the module may depend on each other and may have dependencies to
/// libraries in other modules. Unlike library dependencies, module dependencies
/// must be acyclic.
///
/// This API is intended for modular compilation. Dependencies to other modules
/// are specified using [CompilerOptions.inputSummaries]. Any dependency
/// of [sources] that is not listed in [CompilerOptions.inputSummaries] and
/// [CompilerOptions.sdkSummary] is treated as an additional source file for the
/// module.
///
/// Any `part` declarations found in [sources] must refer to part files which
/// are also listed in the module sources, otherwise an error results. (It
/// is not permitted to refer to a part file declared in another module).
///
/// The return value is a [CompilerResult] object with no main method set in
/// the [Component] of its `component` property. The [Component] includes
/// external libraries for those libraries loaded through summaries.
Future<CompilerResult> kernelForModule(
List<Uri> sources, CompilerOptions options) async {
return (await generateKernel(
new ProcessedOptions(options: options, inputs: sources),
includeHierarchyAndCoreTypes: true));
}
/// Result object for [kernelForProgram] and [kernelForModule].
abstract class CompilerResult {
/// The generated summary bytes, if it was requested.
List<int> get summary;
/// The generated component, if it was requested.
Component get component;
/// Dependencies traversed by the compiler. Used only for generating
/// dependency .GN files in the dart-sdk build system.
/// Note this might be removed when we switch to compute dependencies without
/// using the compiler itself.
List<Uri> get deps;
/// The [ClassHierarchy] for the compiled [component], if it was requested.
ClassHierarchy get classHierarchy;
/// The [CoreTypes] object for the compiled [component], if it was requested.
CoreTypes get coreTypes;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/constant_evaluator.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 front_end.constant_evaluator;
export '../fasta/kernel/constant_evaluator.dart'
show
ConstantEvaluator,
ConstantsTransformer,
ErrorReporter,
EvaluationEnvironment,
SimpleErrorReporter,
transformComponent,
transformLibraries;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/diagnostic_message.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 front_end.diagnostic_message;
import '../fasta/fasta_codes.dart'
show Code, DiagnosticMessageFromJson, FormattedMessage;
import '../fasta/severity.dart' show Severity;
/// The type of a diagnostic message callback. For example:
///
/// void handler(DiagnosticMessage message) {
/// if (enableTerminalColors) { // See [terminal_color_support.dart].
/// message.ansiFormatted.forEach(stderr.writeln);
/// } else {
/// message.plainTextFormatted.forEach(stderr.writeln);
/// }
/// }
typedef DiagnosticMessageHandler = void Function(DiagnosticMessage);
/// Represents a diagnostic message that can be reported from a tool, for
/// example, a compiler.
///
/// The word *diagnostic* is used loosely here, as a tool may also use this for
/// reporting any kind of message, including non-diagnostic messages such as
/// licensing, informal, or logging information. This allows a well-behaved
/// tool to never directly write to stdout or stderr.
abstract class DiagnosticMessage {
DiagnosticMessage._(); // Prevent subclassing.
Iterable<String> get ansiFormatted;
Iterable<String> get plainTextFormatted;
Severity get severity;
}
/// This method is subject to change.
Uri getMessageUri(DiagnosticMessage message) {
return message is FormattedMessage
? message.uri
: message is DiagnosticMessageFromJson ? message.uri : null;
}
/// This method is subject to change.
int getMessageCharOffset(DiagnosticMessage message) {
return message is FormattedMessage ? message.charOffset : null;
}
/// This method is subject to change.
int getMessageLength(DiagnosticMessage message) {
return message is FormattedMessage ? message.length : null;
}
/// This method is subject to change.
Code getMessageCodeObject(DiagnosticMessage message) {
return message is FormattedMessage ? message.code : null;
}
/// This method is subject to change.
String getMessageHeaderText(DiagnosticMessage message) {
return message is FormattedMessage ? message.message : null;
}
/// This method is subject to change.
int getMessageCode(DiagnosticMessage message) {
return message is FormattedMessage ? message.code.index : -1;
}
/// This method is subject to change.
Map<String, dynamic> getMessageArguments(DiagnosticMessage message) {
return message is FormattedMessage ? message.arguments : null;
}
/// This method is subject to change.
Iterable<DiagnosticMessage> getMessageRelatedInformation(
DiagnosticMessage message) {
return message is FormattedMessage ? message.relatedInformation : null;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/incremental_kernel_generator.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 'dart:async' show Future;
import 'package:kernel/class_hierarchy.dart' show ClassHierarchy;
import 'package:kernel/core_types.dart' show CoreTypes;
import 'package:kernel/kernel.dart'
show Component, Procedure, DartType, TypeParameter;
import '../base/processed_options.dart' show ProcessedOptions;
import '../fasta/compiler_context.dart' show CompilerContext;
import '../fasta/incremental_compiler.dart' show IncrementalCompiler;
import '../fasta/scanner/string_scanner.dart' show StringScanner;
import 'compiler_options.dart' show CompilerOptions;
abstract class IncrementalKernelGenerator {
factory IncrementalKernelGenerator(CompilerOptions options, Uri entryPoint,
[Uri initializeFromDillUri, bool outlineOnly]) {
return new IncrementalCompiler(
new CompilerContext(
new ProcessedOptions(options: options, inputs: [entryPoint])),
initializeFromDillUri,
outlineOnly);
}
/// Initialize the incremental compiler from a component.
///
/// Notice that the component has to include the platform, and that no other
/// platform will be loaded.
factory IncrementalKernelGenerator.fromComponent(
CompilerOptions options, Uri entryPoint, Component component,
[bool outlineOnly]) {
return new IncrementalCompiler.fromComponent(
new CompilerContext(
new ProcessedOptions(options: options, inputs: [entryPoint])),
component,
outlineOnly);
}
/// Returns a component whose libraries are the recompiled libraries,
/// or - in the case of [fullComponent] - a full Component.
Future<Component> computeDelta({List<Uri> entryPoints, bool fullComponent});
/// Returns [CoreTypes] used during compilation.
/// Valid after [computeDelta] is called.
CoreTypes getCoreTypes();
/// Returns [ClassHierarchy] used during compilation.
/// Valid after [computeDelta] is called.
ClassHierarchy getClassHierarchy();
/// Remove the file associated with the given file [uri] from the set of
/// valid files. This guarantees that those files will be re-read on the
/// next call to [computeDelta]).
void invalidate(Uri uri);
/// Invalidate all libraries that were build from source.
///
/// This is equivalent to a number of calls to [invalidate]: One for each URI
/// that happens to have been read from source.
/// Said another way, this invalidates everything not loaded from dill
/// (at startup) or via [setModulesToLoadOnNextComputeDelta].
void invalidateAllSources();
/// Set the given [components] as components to load on the next iteration
/// of [computeDelta].
///
/// If specified, all libraries not compiled from source and not included in
/// these components will be invalidated and the libraries inside these
/// components will be loaded instead.
///
/// Useful for, for instance, modular compilation, where modules
/// (created externally) via this functionality can be added, changed or
/// removed.
void setModulesToLoadOnNextComputeDelta(List<Component> components);
/// Compile [expression] as an [Expression]. A function returning that
/// expression is compiled.
///
/// [expression] may use the variables supplied in [definitions] as free
/// variables and [typeDefinitions] as free type variables. These will become
/// required parameters to the compiled function. All elements of
/// [definitions] and [typeDefinitions] will become parameters/type
/// parameters, whether or not they appear free in [expression]. The type
/// parameters should have a null parent pointer.
///
/// [libraryUri] must refer to either a previously compiled library.
/// [className] may optionally refer to a class within such library to use for
/// the scope of the expression. In that case, [isStatic] indicates whether
/// the scope can access [this].
///
/// It is illegal to use "await" in [expression] and the compiled function
/// will always be synchronous.
///
/// [computeDelta] must have been called at least once prior.
///
/// [compileExpression] will return [null] if the library or class for
/// [enclosingNode] could not be found. Otherwise, errors are reported in the
/// normal way.
Future<Procedure> compileExpression(
String expression,
Map<String, DartType> definitions,
List<TypeParameter> typeDefinitions,
String syntheticProcedureName,
Uri libraryUri,
[String className,
bool isStatic = false]);
}
bool isLegalIdentifier(String identifier) {
return StringScanner.isLegalIdentifier(identifier);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/terminal_color_support.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 front_end.terminal_color_support;
import 'dart:convert' show jsonEncode;
import 'dart:io' show Platform, Process, ProcessResult, stderr, stdout;
import '../fasta/colors.dart' show ALL_CODES, TERMINAL_CAPABILITIES;
import 'diagnostic_message.dart' show DiagnosticMessage;
/// True if we should enable colors in output.
///
/// We enable colors only when both [stdout] and [stderr] support ANSI escapes.
final bool enableTerminalColors = _computeEnableColors();
void printDiagnosticMessage(
DiagnosticMessage message, void Function(String) println) {
if (enableTerminalColors) {
message.ansiFormatted.forEach(println);
} else {
message.plainTextFormatted.forEach(println);
}
}
/// On Windows, colors are enabled if both stdout and stderr supports ANSI
/// escapes. On other platforms, we rely on the external programs `tty` and
/// `tput` to compute if ANSI colors are supported.
bool _computeEnableColors() {
const bool debug =
const bool.fromEnvironment("front_end.debug_compute_enable_colors");
if (Platform.isWindows) {
if (!stdout.supportsAnsiEscapes || !stderr.supportsAnsiEscapes) {
// In this case, either [stdout] or [stderr] did not support the property
// `supportsAnsiEscapes`. Since we do not have another way to determine
// support for colors, we disable them.
if (debug) {
print("Not enabling colors as ANSI is not supported.");
}
return false;
}
if (debug) {
print("Enabling colors as OS is Windows.");
}
return true;
}
// We have to check if the terminal actually supports colors. Currently, to
// avoid linking the Dart VM with ncurses, ANSI escape support is reduced to
// `Platform.environment['TERM'].contains("xterm")`.
// Check if stdin is a terminal (TTY).
ProcessResult result =
Process.runSync("/bin/sh", ["-c", "tty > /dev/null 2> /dev/null"]);
if (result.exitCode != 0) {
if (debug) {
print("Not enabling colors, stdin isn't a terminal.");
}
return false;
}
// The `-S` option of `tput` allows us to query multiple capabilities at
// once.
result = Process.runSync(
"/bin/sh", ["-c", "printf '%s' '$TERMINAL_CAPABILITIES' | tput -S"]);
if (result.exitCode != 0) {
if (debug) {
print("Not enabling colors, running tput failed.");
}
return false;
}
List<String> lines = result.stdout.split("\n");
if (lines.length != 2) {
if (debug) {
print("Not enabling colors, unexpected output from tput: "
"${jsonEncode(result.stdout)}.");
}
return false;
}
String numberOfColors = lines[0];
if ((int.tryParse(numberOfColors) ?? -1) < 8) {
if (debug) {
print("Not enabling colors, less than 8 colors supported: "
"${jsonEncode(numberOfColors)}.");
}
return false;
}
String allCodes = lines[1].trim();
if (ALL_CODES != allCodes) {
if (debug) {
print("Not enabling colors, color codes don't match: "
"${jsonEncode(ALL_CODES)} != ${jsonEncode(allCodes)}.");
}
return false;
}
if (debug) {
print("Enabling colors.");
}
return true;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/standard_file_system.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 front_end.standard_file_system;
import 'dart:async';
import 'dart:io' as io;
import 'file_system.dart';
import '../fasta/compiler_context.dart' show CompilerContext;
/// Concrete implementation of [FileSystem] handling standard URI schemes.
///
/// file: URIs are handled using file I/O.
/// data: URIs return their data contents.
///
/// Not intended to be implemented or extended by clients.
class StandardFileSystem implements FileSystem {
static final StandardFileSystem instance = new StandardFileSystem._();
StandardFileSystem._();
@override
FileSystemEntity entityForUri(Uri uri) {
if (uri.scheme == 'file' || uri.scheme == '') {
// TODO(askesc): Empty schemes should have been handled elsewhere.
return new _IoFileSystemEntity(Uri.base.resolveUri(uri));
} else if (uri.scheme == 'data') {
return new DataFileSystemEntity(Uri.base.resolveUri(uri));
} else {
throw new FileSystemException(
uri, 'StandardFileSystem only supports file:* and data:* URIs');
}
}
}
/// Concrete implementation of [FileSystemEntity] for file: URIs.
class _IoFileSystemEntity implements FileSystemEntity {
@override
final Uri uri;
_IoFileSystemEntity(this.uri);
@override
int get hashCode => uri.hashCode;
@override
bool operator ==(Object other) =>
other is _IoFileSystemEntity && other.uri == uri;
@override
Future<bool> exists() async {
if (await io.FileSystemEntity.isDirectory(uri.toFilePath())) {
return true;
} else {
return new io.File.fromUri(uri).exists();
}
}
@override
Future<List<int>> readAsBytes() async {
try {
CompilerContext.recordDependency(uri);
return new io.File.fromUri(uri).readAsBytesSync();
} on io.FileSystemException catch (exception) {
throw _toFileSystemException(exception);
}
}
@override
Future<String> readAsString() async {
try {
CompilerContext.recordDependency(uri);
return await new io.File.fromUri(uri).readAsString();
} on io.FileSystemException catch (exception) {
throw _toFileSystemException(exception);
}
}
/**
* Return the [FileSystemException] for the given I/O exception.
*/
FileSystemException _toFileSystemException(io.FileSystemException exception) {
String message = exception.message;
String osMessage = exception.osError?.message;
if (osMessage != null && osMessage.isNotEmpty) {
message = osMessage;
}
return new FileSystemException(uri, message);
}
}
/// Concrete implementation of [FileSystemEntity] for data: URIs.
class DataFileSystemEntity implements FileSystemEntity {
@override
final Uri uri;
DataFileSystemEntity(this.uri);
@override
int get hashCode => uri.hashCode;
@override
bool operator ==(Object other) =>
other is DataFileSystemEntity && other.uri == uri;
@override
Future<bool> exists() async {
return true;
}
@override
Future<List<int>> readAsBytes() async {
return uri.data.contentAsBytes();
}
@override
Future<String> readAsString() async {
return uri.data.contentAsString();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_prototype/experimental_flags.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.
// NOTE: THIS FILE IS GENERATED. DO NOT EDIT.
//
// Instead modify 'tools/experimental_features.yaml' and run
// 'pkg/front_end/tool/fasta generate-experimental-flags' to update.
enum ExperimentalFlag {
constantUpdate2018,
controlFlowCollections,
extensionMethods,
nonNullable,
setLiterals,
spreadCollections,
tripleShift,
variance,
}
ExperimentalFlag parseExperimentalFlag(String flag) {
switch (flag) {
case "constant-update-2018":
return ExperimentalFlag.constantUpdate2018;
case "control-flow-collections":
return ExperimentalFlag.controlFlowCollections;
case "extension-methods":
return ExperimentalFlag.extensionMethods;
case "non-nullable":
return ExperimentalFlag.nonNullable;
case "set-literals":
return ExperimentalFlag.setLiterals;
case "spread-collections":
return ExperimentalFlag.spreadCollections;
case "triple-shift":
return ExperimentalFlag.tripleShift;
case "variance":
return ExperimentalFlag.variance;
}
return null;
}
const Map<ExperimentalFlag, bool> defaultExperimentalFlags = {
ExperimentalFlag.constantUpdate2018: true,
ExperimentalFlag.controlFlowCollections: true,
ExperimentalFlag.extensionMethods: true,
ExperimentalFlag.nonNullable: false,
ExperimentalFlag.setLiterals: true,
ExperimentalFlag.spreadCollections: true,
ExperimentalFlag.tripleShift: false,
ExperimentalFlag.variance: false,
};
const Map<ExperimentalFlag, bool> expiredExperimentalFlags = {
ExperimentalFlag.constantUpdate2018: true,
ExperimentalFlag.controlFlowCollections: true,
ExperimentalFlag.extensionMethods: false,
ExperimentalFlag.nonNullable: false,
ExperimentalFlag.setLiterals: true,
ExperimentalFlag.spreadCollections: true,
ExperimentalFlag.tripleShift: false,
ExperimentalFlag.variance: false,
};
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/ddc.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 'dart:async' show Future;
import 'package:kernel/class_hierarchy.dart';
import 'package:kernel/kernel.dart' show Component;
import 'package:kernel/target/targets.dart' show Target;
import '../api_prototype/compiler_options.dart' show CompilerOptions;
import '../api_prototype/diagnostic_message.dart' show DiagnosticMessageHandler;
import '../api_prototype/experimental_flags.dart' show ExperimentalFlag;
import '../api_prototype/file_system.dart' show FileSystem;
import '../api_prototype/kernel_generator.dart' show CompilerResult;
import '../api_prototype/standard_file_system.dart' show StandardFileSystem;
import '../base/processed_options.dart' show ProcessedOptions;
import '../kernel_generator_impl.dart' show generateKernel;
import 'compiler_state.dart' show InitializedCompilerState;
import 'modular_incremental_compilation.dart' as modular
show initializeIncrementalCompiler;
import 'util.dart' show equalLists, equalMaps;
export '../api_prototype/compiler_options.dart'
show CompilerOptions, parseExperimentalFlags, parseExperimentalArguments;
export '../api_prototype/diagnostic_message.dart' show DiagnosticMessage;
export '../api_prototype/experimental_flags.dart'
show ExperimentalFlag, parseExperimentalFlag;
export '../api_prototype/kernel_generator.dart' show kernelForModule;
export '../api_prototype/memory_file_system.dart' show MemoryFileSystem;
export '../api_prototype/standard_file_system.dart' show StandardFileSystem;
export '../api_prototype/terminal_color_support.dart'
show printDiagnosticMessage;
export '../base/processed_options.dart' show ProcessedOptions;
export '../fasta/compiler_context.dart' show CompilerContext;
export '../fasta/incremental_compiler.dart' show IncrementalCompiler;
export '../fasta/kernel/redirecting_factory_body.dart'
show RedirectingFactoryBody;
export '../fasta/severity.dart' show Severity;
export '../fasta/type_inference/type_schema_environment.dart'
show TypeSchemaEnvironment;
export 'compiler_state.dart'
show InitializedCompilerState, WorkerInputComponent, digestsEqual;
class DdcResult {
final Component component;
final List<Component> inputSummaries;
final ClassHierarchy classHierarchy;
DdcResult(this.component, this.inputSummaries, this.classHierarchy)
: assert(classHierarchy != null);
}
Future<InitializedCompilerState> initializeCompiler(
InitializedCompilerState oldState,
bool compileSdk,
Uri sdkRoot,
Uri sdkSummary,
Uri packagesFile,
Uri librariesSpecificationUri,
List<Uri> inputSummaries,
Target target,
{FileSystem fileSystem,
Map<ExperimentalFlag, bool> experiments,
Map<String, String> environmentDefines}) async {
inputSummaries.sort((a, b) => a.toString().compareTo(b.toString()));
if (oldState != null &&
oldState.options.compileSdk == compileSdk &&
oldState.options.sdkSummary == sdkSummary &&
oldState.options.packagesFileUri == packagesFile &&
oldState.options.librariesSpecificationUri == librariesSpecificationUri &&
equalLists(oldState.options.inputSummaries, inputSummaries) &&
equalMaps(oldState.options.experimentalFlags, experiments) &&
equalMaps(oldState.options.environmentDefines, environmentDefines)) {
// Reuse old state.
// These libraries are marked external when compiling. If not un-marking
// them compilation will fail.
// Remove once [kernel_generator_impl.dart] no longer marks the libraries
// as external.
(await oldState.processedOpts.loadSdkSummary(null))
.libraries
.forEach((lib) => lib.isExternal = false);
(await oldState.processedOpts.loadInputSummaries(null))
.forEach((p) => p.libraries.forEach((lib) => lib.isExternal = false));
return oldState;
}
CompilerOptions options = new CompilerOptions()
..compileSdk = compileSdk
..sdkRoot = sdkRoot
..sdkSummary = sdkSummary
..packagesFileUri = packagesFile
..inputSummaries = inputSummaries
..librariesSpecificationUri = librariesSpecificationUri
..target = target
..fileSystem = fileSystem ?? StandardFileSystem.instance
..environmentDefines = environmentDefines;
if (experiments != null) options.experimentalFlags = experiments;
ProcessedOptions processedOpts = new ProcessedOptions(options: options);
return new InitializedCompilerState(options, processedOpts);
}
/// Initializes the compiler for a modular build.
///
/// Re-uses cached components from [oldState.workerInputCache], and reloads them
/// as necessary based on [workerInputDigests].
Future<InitializedCompilerState> initializeIncrementalCompiler(
InitializedCompilerState oldState,
Set<String> tags,
List<Component> doneInputSummaries,
bool compileSdk,
Uri sdkRoot,
Uri sdkSummary,
Uri packagesFile,
Uri librariesSpecificationUri,
List<Uri> inputSummaries,
Map<Uri, List<int>> workerInputDigests,
Target target,
{FileSystem fileSystem,
Map<ExperimentalFlag, bool> experiments,
Map<String, String> environmentDefines,
bool trackNeededDillLibraries: false}) async {
return modular.initializeIncrementalCompiler(
oldState,
tags,
doneInputSummaries,
sdkSummary,
packagesFile,
librariesSpecificationUri,
inputSummaries,
workerInputDigests,
target,
compileSdk: compileSdk,
sdkRoot: sdkRoot,
fileSystem: fileSystem ?? StandardFileSystem.instance,
experimentalFlags: experiments,
environmentDefines:
environmentDefines ?? const <ExperimentalFlag, bool>{},
outlineOnly: false,
omitPlatform: false,
trackNeededDillLibraries: trackNeededDillLibraries);
}
Future<DdcResult> compile(InitializedCompilerState compilerState,
List<Uri> inputs, DiagnosticMessageHandler diagnosticMessageHandler) async {
CompilerOptions options = compilerState.options;
options..onDiagnostic = diagnosticMessageHandler;
ProcessedOptions processedOpts = compilerState.processedOpts;
processedOpts.inputs.clear();
processedOpts.inputs.addAll(inputs);
CompilerResult compilerResult =
await generateKernel(processedOpts, includeHierarchyAndCoreTypes: true);
Component component = compilerResult?.component;
if (component == null) return null;
// This should be cached.
List<Component> summaries = await processedOpts.loadInputSummaries(null);
return new DdcResult(component, summaries, compilerResult.classHierarchy);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/compiler_state.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 '../api_prototype/compiler_options.dart' show CompilerOptions;
import '../base/processed_options.dart' show ProcessedOptions;
import 'package:front_end/src/fasta/incremental_compiler.dart'
show IncrementalCompiler;
import 'package:kernel/kernel.dart' show Component;
class InitializedCompilerState {
final CompilerOptions options;
final ProcessedOptions processedOpts;
final Map<Uri, WorkerInputComponent> workerInputCache;
/// A map from library import uri to dill uri, i.e. where a library came from,
/// for all cached libraries.
final Map<Uri, Uri> workerInputCacheLibs;
final IncrementalCompiler incrementalCompiler;
final Set<String> tags;
final Map<Uri, Uri> libraryToInputDill;
InitializedCompilerState(this.options, this.processedOpts,
{this.workerInputCache,
this.workerInputCacheLibs,
this.incrementalCompiler,
this.tags,
this.libraryToInputDill});
}
/// A cached [Component] for a summary input file.
///
/// Tracks the originally marked "external" libs so that they can be restored,
/// since the kernel generator mutates the state.
class WorkerInputComponent {
final List<int> digest;
final Component component;
final Set<Uri> externalLibs;
WorkerInputComponent(this.digest, this.component)
: externalLibs = component.libraries
.where((lib) => lib.isExternal)
.map((lib) => lib.importUri)
.toSet();
}
bool digestsEqual(List<int> a, List<int> b) {
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/vm.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.
export '../api_prototype/compiler_options.dart'
show CompilerOptions, parseExperimentalArguments, parseExperimentalFlags;
export '../api_prototype/diagnostic_message.dart'
show DiagnosticMessage, DiagnosticMessageHandler, getMessageUri;
export '../api_prototype/experimental_flags.dart'
show defaultExperimentalFlags, ExperimentalFlag;
export '../api_prototype/file_system.dart'
show FileSystem, FileSystemEntity, FileSystemException;
export '../api_prototype/front_end.dart' show CompilerResult;
export '../api_prototype/incremental_kernel_generator.dart'
show IncrementalKernelGenerator, isLegalIdentifier;
export '../api_prototype/kernel_generator.dart'
show kernelForModule, kernelForProgram;
export '../api_prototype/memory_file_system.dart' show MemoryFileSystem;
export '../api_prototype/standard_file_system.dart' show StandardFileSystem;
export '../api_prototype/terminal_color_support.dart'
show printDiagnosticMessage;
export '../base/processed_options.dart' show ProcessedOptions;
export '../compute_platform_binaries_location.dart'
show computePlatformBinariesLocation;
export '../fasta/compiler_context.dart' show CompilerContext;
export '../fasta/fasta_codes.dart'
show
LocatedMessage,
messageBytecodeLimitExceededTooManyArguments,
messageFfiExceptionalReturnNull,
messageFfiExpectedConstant,
noLength,
templateFfiDartTypeMismatch,
templateFfiExpectedExceptionalReturn,
templateFfiExpectedNoExceptionalReturn,
templateFfiExtendsOrImplementsSealedClass,
templateFfiFieldAnnotation,
templateFfiFieldInitializer,
templateFfiFieldNoAnnotation,
templateFfiNotStatic,
templateFfiStructGeneric,
templateFfiTypeInvalid,
templateFfiTypeMismatch,
templateFfiTypeUnsized,
templateFfiWrongStructInheritance,
templateIllegalRecursiveType;
export '../fasta/hybrid_file_system.dart' show HybridFileSystem;
export '../fasta/kernel/utils.dart'
show
createExpressionEvaluationComponent,
serializeComponent,
serializeProcedure;
export '../fasta/resolve_input_uri.dart' show resolveInputUri;
export '../fasta/severity.dart' show Severity;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/util.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.
bool equalLists<T>(List<T> a, List<T> b) {
if (identical(a, b)) return true;
if (a == null || b == null) return false;
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 equalSets<K>(Set<K> a, Set<K> b) {
if (identical(a, b)) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (K entry in a) {
if (!b.contains(entry)) return false;
}
return true;
}
bool equalMaps<K, V>(Map<K, V> a, Map<K, V> b) {
if (identical(a, b)) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (K key in a.keys) {
if (!b.containsKey(key) || a[key] != b[key]) return false;
}
return true;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/dart2js.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 'dart:async' show Future;
import 'package:kernel/kernel.dart' show Component, Statement;
import 'package:kernel/ast.dart' as ir;
import 'package:kernel/target/targets.dart' show Target;
import '../api_prototype/compiler_options.dart' show CompilerOptions;
import '../api_prototype/diagnostic_message.dart' show DiagnosticMessageHandler;
import '../api_prototype/experimental_flags.dart' show ExperimentalFlag;
import '../api_prototype/file_system.dart' show FileSystem;
import '../api_prototype/kernel_generator.dart' show CompilerResult;
import '../base/processed_options.dart' show ProcessedOptions;
import '../base/libraries_specification.dart' show LibrariesSpecification;
import '../fasta/compiler_context.dart' show CompilerContext;
import '../fasta/fasta_codes.dart' show messageMissingMain;
import '../fasta/severity.dart' show Severity;
import '../kernel_generator_impl.dart' show generateKernelInternal;
import '../fasta/scanner.dart' show ErrorToken, StringToken, Token;
import '../fasta/kernel/redirecting_factory_body.dart' as redirecting;
import 'compiler_state.dart' show InitializedCompilerState;
import 'util.dart' show equalLists, equalMaps;
export '../api_prototype/compiler_options.dart'
show CompilerOptions, parseExperimentalFlags, parseExperimentalArguments;
export '../api_prototype/diagnostic_message.dart'
show
DiagnosticMessage,
getMessageCharOffset,
getMessageHeaderText,
getMessageLength,
getMessageRelatedInformation,
getMessageUri;
export '../api_prototype/experimental_flags.dart'
show defaultExperimentalFlags, ExperimentalFlag;
export '../api_prototype/file_system.dart'
show FileSystem, FileSystemEntity, FileSystemException;
export '../api_prototype/kernel_generator.dart' show kernelForProgram;
export '../api_prototype/standard_file_system.dart' show DataFileSystemEntity;
export '../compute_platform_binaries_location.dart'
show computePlatformBinariesLocation;
export '../fasta/fasta_codes.dart' show LocatedMessage;
export '../fasta/operator.dart' show operatorFromString;
export '../fasta/parser/async_modifier.dart' show AsyncModifier;
export '../fasta/scanner.dart' show isUserDefinableOperator, isMinusOperator;
export '../fasta/scanner/characters.dart'
show
$$,
$0,
$9,
$A,
$BACKSLASH,
$CR,
$DEL,
$DQ,
$HASH,
$LF,
$LS,
$PS,
$TAB,
$Z,
$_,
$a,
$g,
$s,
$z;
export '../fasta/severity.dart' show Severity;
export '../fasta/util/link.dart' show Link, LinkBuilder;
export '../fasta/util/link_implementation.dart' show LinkEntry;
export '../fasta/util/relativize.dart' show relativizeUri;
export 'compiler_state.dart' show InitializedCompilerState;
void clearStringTokenCanonicalizer() {
// TODO(ahe): We should be able to remove this. Fasta should take care of
// clearing the cache when.
StringToken.canonicalizer.clear();
}
InitializedCompilerState initializeCompiler(
InitializedCompilerState oldState,
Target target,
Uri librariesSpecificationUri,
List<Uri> linkedDependencies,
Uri packagesFileUri,
{List<Uri> dependencies,
Map<ExperimentalFlag, bool> experimentalFlags,
bool verify: false}) {
linkedDependencies.sort((a, b) => a.toString().compareTo(b.toString()));
if (oldState != null &&
oldState.options.packagesFileUri == packagesFileUri &&
oldState.options.librariesSpecificationUri == librariesSpecificationUri &&
equalLists(oldState.options.linkedDependencies, linkedDependencies) &&
equalMaps(oldState.options.experimentalFlags, experimentalFlags)) {
return oldState;
}
CompilerOptions options = new CompilerOptions()
..target = target
..linkedDependencies = linkedDependencies
..librariesSpecificationUri = librariesSpecificationUri
..packagesFileUri = packagesFileUri
..experimentalFlags = experimentalFlags
..verify = verify;
ProcessedOptions processedOpts = new ProcessedOptions(options: options);
return new InitializedCompilerState(options, processedOpts);
}
Future<Component> compile(
InitializedCompilerState state,
bool verbose,
FileSystem fileSystem,
DiagnosticMessageHandler onDiagnostic,
Uri input) async {
CompilerOptions options = state.options;
options
..onDiagnostic = onDiagnostic
..verbose = verbose
..fileSystem = fileSystem;
ProcessedOptions processedOpts = state.processedOpts;
processedOpts.inputs.clear();
processedOpts.inputs.add(input);
processedOpts.clearFileSystemCache();
CompilerResult compilerResult = await CompilerContext.runWithOptions(
processedOpts, (CompilerContext context) async {
CompilerResult compilerResult = await generateKernelInternal();
Component component = compilerResult?.component;
if (component == null) return null;
if (component.mainMethod == null) {
context.options.report(
messageMissingMain.withLocation(input, -1, 0), Severity.error);
return null;
}
return compilerResult;
});
// Remove these parameters from [options] - they are no longer needed and
// retain state from the previous compile. (http://dartbug.com/33708)
options.onDiagnostic = null;
options.fileSystem = null;
return compilerResult?.component;
}
Object tokenToString(Object value) {
// TODO(ahe): This method is most likely unnecessary. Dart2js doesn't see
// tokens anymore.
if (value is ErrorToken) {
// Shouldn't happen.
return value.assertionMessage.message;
} else if (value is Token) {
return value.lexeme;
} else {
return value;
}
}
/// Retrieve the name of the libraries that are supported by [target] according
/// to the libraries specification [json] file.
///
/// Dart2js uses these names to determine the value of library environment
/// constants, such as `const bool.fromEnvironment("dart.library.io")`.
// TODO(sigmund): refactor dart2js so that we can retrieve this data later in
// the compilation pipeline. At that point we can get it from the CFE
// results directly and completely hide the libraries specification file from
// dart2js.
// TODO(sigmund): delete after all constant evaluation is done in the CFE, as
// this data will no longer be needed on the dart2js side.
Iterable<String> getSupportedLibraryNames(
Uri librariesSpecificationUri, String json, String target) {
return LibrariesSpecification.parse(librariesSpecificationUri, json)
.specificationFor(target)
.allLibraries
.where((l) => l.isSupported)
.map((l) => l.name);
}
/// Desugar API to determine whether [member] is a redirecting factory
/// constructor.
// TODO(sigmund): Delete this API once `member.isRedirectingFactoryConstructor`
// is implemented correctly for patch files (Issue #33495).
bool isRedirectingFactory(ir.Procedure member) {
if (member.kind == ir.ProcedureKind.Factory) {
Statement body = member.function.body;
if (body is redirecting.RedirectingFactoryBody) return true;
if (body is ir.ExpressionStatement) {
ir.Expression expression = body.expression;
if (expression is ir.Let) {
if (expression.variable.name == redirecting.letName) {
return true;
}
}
}
}
return false;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/bazel_worker.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.
/// API needed by `utils/front_end/summary_worker.dart`, a tool used to compute
/// summaries in build systems like bazel, pub-build, and package-build.
import 'dart:async' show Future;
import 'package:front_end/src/api_prototype/compiler_options.dart';
import 'package:kernel/kernel.dart' show Component, Library;
import 'package:kernel/target/targets.dart' show Target;
import '../api_prototype/compiler_options.dart'
show CompilerOptions, parseExperimentalFlags;
import '../api_prototype/diagnostic_message.dart' show DiagnosticMessageHandler;
import '../api_prototype/experimental_flags.dart' show ExperimentalFlag;
import '../api_prototype/file_system.dart' show FileSystem;
import '../api_prototype/front_end.dart' show CompilerResult;
import '../base/processed_options.dart' show ProcessedOptions;
import '../kernel_generator_impl.dart' show generateKernel;
import 'compiler_state.dart' show InitializedCompilerState;
import 'modular_incremental_compilation.dart' as modular
show initializeIncrementalCompiler;
export '../api_prototype/compiler_options.dart'
show parseExperimentalFlags, parseExperimentalArguments;
export '../api_prototype/diagnostic_message.dart' show DiagnosticMessage;
export '../api_prototype/experimental_flags.dart'
show ExperimentalFlag, parseExperimentalFlag;
export '../api_prototype/standard_file_system.dart' show StandardFileSystem;
export '../api_prototype/terminal_color_support.dart'
show printDiagnosticMessage;
export '../fasta/kernel/utils.dart' show serializeComponent;
export '../fasta/severity.dart' show Severity;
export 'compiler_state.dart' show InitializedCompilerState;
/// Initializes the compiler for a modular build.
///
/// Re-uses cached components from [oldState.workerInputCache], and reloads them
/// as necessary based on [workerInputDigests].
Future<InitializedCompilerState> initializeIncrementalCompiler(
InitializedCompilerState oldState,
Set<String> tags,
Uri sdkSummary,
Uri packagesFile,
Uri librariesSpecificationUri,
List<Uri> summaryInputs,
Map<Uri, List<int>> workerInputDigests,
Target target,
FileSystem fileSystem,
Iterable<String> experiments,
bool outlineOnly,
{bool trackNeededDillLibraries: false}) async {
List<Component> outputLoadedInputSummaries =
new List<Component>(summaryInputs.length);
Map<ExperimentalFlag, bool> experimentalFlags = parseExperimentalFlags(
parseExperimentalArguments(experiments),
onError: (e) => throw e);
return modular.initializeIncrementalCompiler(
oldState,
tags,
outputLoadedInputSummaries,
sdkSummary,
packagesFile,
librariesSpecificationUri,
summaryInputs,
workerInputDigests,
target,
fileSystem: fileSystem,
experimentalFlags: experimentalFlags,
outlineOnly: outlineOnly,
omitPlatform: true,
trackNeededDillLibraries: trackNeededDillLibraries);
}
Future<InitializedCompilerState> initializeCompiler(
InitializedCompilerState oldState,
Uri sdkSummary,
Uri librariesSpecificationUri,
Uri packagesFile,
List<Uri> summaryInputs,
List<Uri> linkedInputs,
Target target,
FileSystem fileSystem,
Iterable<String> experiments) async {
// TODO(sigmund): use incremental compiler when it supports our use case.
// Note: it is common for the summary worker to invoke the compiler with the
// same input summary URIs, but with different contents, so we'd need to be
// able to track shas or modification time-stamps to be able to invalidate the
// old state appropriately.
CompilerOptions options = new CompilerOptions()
..sdkSummary = sdkSummary
..packagesFileUri = packagesFile
..librariesSpecificationUri = librariesSpecificationUri
..inputSummaries = summaryInputs
..linkedDependencies = linkedInputs
..target = target
..fileSystem = fileSystem
..environmentDefines = const {}
..experimentalFlags = parseExperimentalFlags(
parseExperimentalArguments(experiments),
onError: (e) => throw e);
ProcessedOptions processedOpts = new ProcessedOptions(options: options);
return new InitializedCompilerState(options, processedOpts);
}
Future<CompilerResult> _compile(InitializedCompilerState compilerState,
List<Uri> inputs, DiagnosticMessageHandler diagnosticMessageHandler,
{bool summaryOnly, bool includeOffsets: true}) {
summaryOnly ??= true;
CompilerOptions options = compilerState.options;
options..onDiagnostic = diagnosticMessageHandler;
ProcessedOptions processedOpts = compilerState.processedOpts;
processedOpts.inputs.clear();
processedOpts.inputs.addAll(inputs);
return generateKernel(processedOpts,
buildSummary: summaryOnly,
buildComponent: !summaryOnly,
includeOffsets: includeOffsets);
}
Future<List<int>> compileSummary(InitializedCompilerState compilerState,
List<Uri> inputs, DiagnosticMessageHandler diagnosticMessageHandler,
{bool includeOffsets: false}) async {
CompilerResult result = await _compile(
compilerState, inputs, diagnosticMessageHandler,
summaryOnly: true, includeOffsets: includeOffsets);
return result?.summary;
}
Future<Component> compileComponent(InitializedCompilerState compilerState,
List<Uri> inputs, DiagnosticMessageHandler diagnosticMessageHandler) async {
CompilerResult result = await _compile(
compilerState, inputs, diagnosticMessageHandler,
summaryOnly: false);
Component component = result?.component;
if (component != null) {
for (Library lib in component.libraries) {
if (!inputs.contains(lib.importUri)) {
// Excluding the library also means that their canonical names will not
// be computed as part of serialization, so we need to do that
// preemptively here to avoid errors when serializing references to
// elements of these libraries.
component.root.getChildFromUri(lib.importUri).bindTo(lib.reference);
lib.computeCanonicalNames();
}
}
}
return component;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/modular_incremental_compilation.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:async' show Future;
import 'package:kernel/kernel.dart' show Component, CanonicalName, Library;
import 'package:kernel/target/targets.dart' show Target;
import '../api_prototype/compiler_options.dart' show CompilerOptions;
import '../api_prototype/experimental_flags.dart' show ExperimentalFlag;
import '../api_prototype/file_system.dart' show FileSystem;
import '../base/processed_options.dart' show ProcessedOptions;
import '../fasta/compiler_context.dart' show CompilerContext;
import '../fasta/incremental_compiler.dart' show IncrementalCompiler;
import 'compiler_state.dart'
show InitializedCompilerState, WorkerInputComponent, digestsEqual;
import 'util.dart' show equalMaps, equalSets;
/// Initializes the compiler for a modular build.
///
/// Re-uses cached components from [oldState.workerInputCache], and reloads them
/// as necessary based on [workerInputDigests].
///
/// Notes:
/// * [outputLoadedInputSummaries] should be given as an empty list of the same
/// size as the [inputSummaries]. The input summaries are loaded (or taken
/// from cache) and placed in this list in order, i.e. the `i`-th entry in
/// [outputLoadedInputSummaries] after this call corresponds to the component
/// loaded from the `i`-th entry in [inputSummaries].
Future<InitializedCompilerState> initializeIncrementalCompiler(
InitializedCompilerState oldState,
Set<String> tags,
List<Component> outputLoadedInputSummaries,
Uri sdkSummary,
Uri packagesFile,
Uri librariesSpecificationUri,
List<Uri> inputSummaries,
Map<Uri, List<int>> workerInputDigests,
Target target,
{bool compileSdk: false,
Uri sdkRoot: null,
FileSystem fileSystem,
Map<ExperimentalFlag, bool> experimentalFlags,
Map<String, String> environmentDefines: const {},
bool outlineOnly,
bool omitPlatform: false,
bool trackNeededDillLibraries: false}) async {
final List<int> sdkDigest = workerInputDigests[sdkSummary];
if (sdkDigest == null) {
throw new StateError("Expected to get digest for $sdkSummary");
}
Map<Uri, WorkerInputComponent> workerInputCache =
oldState?.workerInputCache ?? new Map<Uri, WorkerInputComponent>();
Map<Uri, Uri> workerInputCacheLibs =
oldState?.workerInputCacheLibs ?? new Map<Uri, Uri>();
WorkerInputComponent cachedSdkInput = workerInputCache[sdkSummary];
IncrementalCompiler incrementalCompiler;
CompilerOptions options;
ProcessedOptions processedOpts;
if (oldState == null ||
oldState.incrementalCompiler == null ||
oldState.options.compileSdk != compileSdk ||
oldState.incrementalCompiler.outlineOnly != outlineOnly ||
!equalMaps(oldState.options.experimentalFlags, experimentalFlags) ||
!equalMaps(oldState.options.environmentDefines, environmentDefines) ||
!equalSets(oldState.tags, tags) ||
cachedSdkInput == null ||
!digestsEqual(cachedSdkInput.digest, sdkDigest)) {
// No - or immediately not correct - previous state.
// We'll load a new sdk, anything loaded already will have a wrong root.
workerInputCache.clear();
workerInputCacheLibs.clear();
// The sdk was either not cached or it has changed.
options = new CompilerOptions()
..compileSdk = compileSdk
..sdkRoot = sdkRoot
..sdkSummary = sdkSummary
..packagesFileUri = packagesFile
..librariesSpecificationUri = librariesSpecificationUri
..target = target
..fileSystem = fileSystem
..omitPlatform = omitPlatform
..environmentDefines = environmentDefines
..experimentalFlags = experimentalFlags;
processedOpts = new ProcessedOptions(options: options);
cachedSdkInput = new WorkerInputComponent(
sdkDigest, await processedOpts.loadSdkSummary(null));
workerInputCache[sdkSummary] = cachedSdkInput;
for (Library lib in cachedSdkInput.component.libraries) {
if (workerInputCacheLibs.containsKey(lib.importUri)) {
throw new StateError("Duplicate sources in sdk.");
}
workerInputCacheLibs[lib.importUri] = sdkSummary;
}
incrementalCompiler = new IncrementalCompiler.fromComponent(
new CompilerContext(processedOpts),
cachedSdkInput.component,
outlineOnly);
incrementalCompiler.trackNeededDillLibraries = trackNeededDillLibraries;
} else {
options = oldState.options;
processedOpts = oldState.processedOpts;
Component sdkComponent = cachedSdkInput.component;
// Reset the state of the component.
for (Library lib in sdkComponent.libraries) {
lib.isExternal = cachedSdkInput.externalLibs.contains(lib.importUri);
}
// Make sure the canonical name root knows about the sdk - otherwise we
// won't be able to link to it when loading more outlines.
sdkComponent.adoptChildren();
// TODO(jensj): This is - at least currently - necessary,
// although it's not entirely obvious why.
// It likely has to do with several outlines containing the same libraries.
// Once that stops (and we check for it) we can probably remove this,
// and instead only do it when about to reuse an outline in the
// 'inputSummaries.add(component);' line further down.
for (WorkerInputComponent cachedInput in workerInputCache.values) {
cachedInput.component.adoptChildren();
}
// Reuse the incremental compiler, but reset as needed.
incrementalCompiler = oldState.incrementalCompiler;
incrementalCompiler.invalidateAllSources();
incrementalCompiler.trackNeededDillLibraries = trackNeededDillLibraries;
options.packagesFileUri = packagesFile;
options.fileSystem = fileSystem;
processedOpts.clearFileSystemCache();
}
// Then read all the input summary components.
CanonicalName nameRoot = cachedSdkInput.component.root;
Map<Uri, Uri> libraryToInputDill;
if (trackNeededDillLibraries) {
libraryToInputDill = new Map<Uri, Uri>();
}
List<int> loadFromDillIndexes = new List<int>();
// Notice that the ordering of the input summaries matter, so we need to
// keep them in order.
if (outputLoadedInputSummaries.length != inputSummaries.length) {
throw new ArgumentError("Invalid length.");
}
Set<Uri> inputSummariesSet = new Set<Uri>();
for (int i = 0; i < inputSummaries.length; i++) {
Uri summaryUri = inputSummaries[i];
inputSummariesSet.add(summaryUri);
WorkerInputComponent cachedInput = workerInputCache[summaryUri];
List<int> digest = workerInputDigests[summaryUri];
if (digest == null) {
throw new StateError("Expected to get digest for $summaryUri");
}
if (cachedInput == null ||
cachedInput.component.root != nameRoot ||
!digestsEqual(digest, cachedInput.digest)) {
// Remove any old libraries from workerInputCacheLibs.
Component component = cachedInput?.component;
if (component != null) {
for (Library lib in component.libraries) {
workerInputCacheLibs.remove(lib.importUri);
}
}
loadFromDillIndexes.add(i);
} else {
// Need to reset cached components so they are usable again.
Component component = cachedInput.component;
for (Library lib in component.libraries) {
lib.isExternal = cachedInput.externalLibs.contains(lib.importUri);
if (trackNeededDillLibraries) {
libraryToInputDill[lib.importUri] = summaryUri;
}
}
component.computeCanonicalNames(); // this isn't needed, is it?
outputLoadedInputSummaries[i] = component;
}
}
for (int i = 0; i < loadFromDillIndexes.length; i++) {
int index = loadFromDillIndexes[i];
Uri summaryUri = inputSummaries[index];
List<int> digest = workerInputDigests[summaryUri];
if (digest == null) {
throw new StateError("Expected to get digest for $summaryUri");
}
List<int> bytes = await fileSystem.entityForUri(summaryUri).readAsBytes();
WorkerInputComponent cachedInput = new WorkerInputComponent(
digest,
await processedOpts.loadComponent(bytes, nameRoot,
alwaysCreateNewNamedNodes: true));
workerInputCache[summaryUri] = cachedInput;
outputLoadedInputSummaries[index] = cachedInput.component;
for (Library lib in cachedInput.component.libraries) {
if (workerInputCacheLibs.containsKey(lib.importUri)) {
Uri fromSummary = workerInputCacheLibs[lib.importUri];
if (inputSummariesSet.contains(fromSummary)) {
throw new StateError(
"Asked to load several summaries that contain the same library.");
} else {
// Library contained in old cached component. Flush that cache.
Component component = workerInputCache.remove(fromSummary).component;
for (Library lib in component.libraries) {
workerInputCacheLibs.remove(lib.importUri);
}
}
} else {
workerInputCacheLibs[lib.importUri] = summaryUri;
}
if (trackNeededDillLibraries) {
libraryToInputDill[lib.importUri] = summaryUri;
}
}
}
incrementalCompiler
.setModulesToLoadOnNextComputeDelta(outputLoadedInputSummaries);
return new InitializedCompilerState(options, processedOpts,
workerInputCache: workerInputCache,
workerInputCacheLibs: workerInputCacheLibs,
incrementalCompiler: incrementalCompiler,
tags: tags,
libraryToInputDill: libraryToInputDill);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/api_unstable/build_integration.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.
export '../api_prototype/file_system.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/library_info.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.
/// A bit flag used by [LibraryInfo] indicating that a library is used by
/// dart2js.
///
/// This declaration duplicates the declaration in the SDK's "libraries.dart".
const int DART2JS_PLATFORM = 1;
/// A bit flag used by [LibraryInfo] indicating that a library is used by the
/// VM.
///
/// This declaration duplicates the declaration in the SDK's "libraries.dart".
const int VM_PLATFORM = 2;
/// Parse a category string in the SDK's "libraries.dart".
///
/// This declaration duplicates the declaration in the SDK's "libraries.dart".
Category parseCategory(String name) {
switch (name) {
case 'Client':
return Category.client;
case 'Server':
return Category.server;
case 'Embedded':
return Category.embedded;
}
return null;
}
/// The contexts that a library can be used from.
///
/// This declaration duplicates the declaration in the SDK's "libraries.dart".
enum Category {
/// Indicates that a library can be used in a browser context.
client,
/// Indicates that a library can be used in a command line context.
server,
/// Indicates that a library can be used from embedded devices.
embedded
}
/// Information about a "dart:" library gleaned from the SDK's "libraries.dart"
/// file.
///
/// This declaration duplicates the declaration in "libraries.dart".
class LibraryInfo {
/// Path to the library's *.dart file relative to the SDK's "lib" directory.
final String path;
/// The categories in which the library can be used, encoded as a
/// comma-separated String.
final String _categories;
/// Path to the dart2js library's *.dart file relative to the SDK's "lib"
/// directory, or null if dart2js uses the common library path defined above.
final String dart2jsPath;
/// Path to the dart2js library's patch file relative to the SDK's "lib"
/// directory, or null if no dart2js patch file associated with this library.
final String dart2jsPatchPath;
/// True if this library is documented and should be shown to the user.
final bool documented;
/// Bit flags indicating which platforms consume this library. See
/// [DART2JS_LIBRARY] and [VM_LIBRARY].
final int platforms;
/// True if the library contains implementation details for another library.
/// The implication is that these libraries are less commonly used and that
/// tools like the analysis server should not show these libraries in a list
/// of all libraries unless the user specifically asks the tool to do so.
final bool implementation;
/// States the current maturity of this library.
final Maturity maturity;
const LibraryInfo(this.path,
{String categories: "",
this.dart2jsPath,
this.dart2jsPatchPath,
this.implementation: false,
this.documented: true,
this.maturity: Maturity.UNSPECIFIED,
this.platforms: DART2JS_PLATFORM | VM_PLATFORM})
: _categories = categories;
/// The categories in which the library can be used.
///
/// If no categories are specified, the library is internal and cannot be
/// loaded by user code.
List<Category> get categories {
// `''.split(',')` returns [''], not [], so we handle that case separately.
if (_categories.isEmpty) return const <Category>[];
return _categories.split(',').map(parseCategory).toList();
}
/// The original "categories" String that was passed to the constructor.
///
/// Can be used to construct a slightly modified copy of this LibraryInfo.
String get categoriesString {
return _categories;
}
bool get isDart2jsLibrary => (platforms & DART2JS_PLATFORM) != 0;
bool get isInternal => categories.isEmpty;
bool get isVmLibrary => (platforms & VM_PLATFORM) != 0;
}
/// Abstraction to capture the maturity of a library.
class Maturity {
static const Maturity DEPRECATED = const Maturity(0, "Deprecated",
"This library will be remove before next major release.");
static const Maturity EXPERIMENTAL = const Maturity(
1,
"Experimental",
"This library is experimental and will likely change or be removed\n"
"in future versions.");
static const Maturity UNSTABLE = const Maturity(
2,
"Unstable",
"This library is in still changing and have not yet endured\n"
"sufficient real-world testing.\n"
"Backwards-compatibility is NOT guaranteed.");
static const Maturity WEB_STABLE = const Maturity(
3,
"Web Stable",
"This library is tracking the DOM evolution as defined by WC3.\n"
"Backwards-compatibility is NOT guaranteed.");
static const Maturity STABLE = const Maturity(
4,
"Stable",
"The library is stable. API backwards-compatibility is guaranteed.\n"
"However implementation details might change.");
static const Maturity LOCKED = const Maturity(5, "Locked",
"This library will not change except when serious bugs are encountered.");
static const Maturity UNSPECIFIED = const Maturity(-1, "Unspecified",
"The maturity for this library has not been specified.");
final int level;
final String name;
final String description;
const Maturity(this.level, this.name, this.description);
String toString() => "$name: $level\n$description\n";
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/resolve_relative_uri.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.
/**
* Resolve the [containedUri] against [baseUri] using Dart rules.
*
* This function behaves similarly to [Uri.resolveUri], except that it properly
* handles situations like the following:
*
* resolveRelativeUri(dart:core, bool.dart) -> dart:core/bool.dart
* resolveRelativeUri(package:a/b.dart, ../c.dart) -> package:a/c.dart
*/
Uri resolveRelativeUri(Uri baseUri, Uri containedUri) {
if (containedUri.isAbsolute) {
return containedUri;
}
String scheme = baseUri.scheme;
// dart:core => dart:core/core.dart
if (scheme == 'dart') {
String part = baseUri.path;
if (part.indexOf('/') < 0) {
baseUri = Uri.parse('$scheme:$part/$part.dart');
}
}
return baseUri.resolveUri(containedUri);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/syntactic_entity.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.
/**
* Interface representing a syntactic entity (either a token or an AST node)
* which has a location and extent in the source file.
*/
abstract class SyntacticEntity {
/**
* Return the offset from the beginning of the file to the character after the
* last character of the syntactic entity.
*/
int get end;
/**
* Return the number of characters in the syntactic entity's source range.
*/
int get length;
/**
* Return the offset from the beginning of the file to the first character in
* the syntactic entity.
*/
int get offset;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/libraries_specification.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 specification in-memory representation.
///
/// Many dart tools are configurable to support different target platforms. For
/// a given target, they need to know what libraries are available and where are
/// the sources and target-specific patches.
///
/// Here we define APIs to represent this specification and implement
/// serialization to (and deserialization from) a JSON file.
///
/// Here is an example specification JSON file:
///
/// {
/// "vm": {
/// "libraries": {
/// "core": {
/// "uri": "async/core.dart",
/// "patches": [
/// "path/to/core_patch.dart",
/// "path/to/list_patch.dart"
/// ]
/// }
/// "async": {
/// "uri": "async/async.dart",
/// "patches": "path/to/async_patch.dart"
/// }
/// "convert": {
/// "uri": "convert/convert.dart",
/// }
/// "mirrors": {
/// "uri": "mirrors/mirrors.dart",
/// "supported": false
/// }
/// }
/// }
/// }
///
/// The format contains:
/// - a top level entry for each target. Keys are target names (e.g. "vm"
/// above), and values contain the entire specification of a target.
///
/// - each target specification is a map. Today, only one key is supported on
/// this map: "libraries".
///
/// - The "libraries" entry contains details for how each platform library is
/// implemented. The entry is a map, where keys are the name of the platform
/// library and values contain details for where to find the implementation
/// fo that library.
///
/// - The name of the library is a single token (e.g. "core") that matches the
/// Uri path used after `dart:` (e.g. "dart:core").
///
/// - The "uri" entry on the library information is mandatory. The value is a
/// string URI reference. The "patches" entry is optional and may have as a
/// value a string URI reference or a list of URI references.
///
/// All URI references can either be a file URI or a relative URI path,
/// which will be resolved relative to the location of the library
/// specification file.
///
/// - The "supported" entry on the library information is optional. The value
/// is a boolean indicating whether the library is supported in the
/// underlying target. However, since the libraries are assumed to be
/// supported by default, we only expect users to use `false`.
///
/// The purpose of this value is to configure conditional imports and
/// environment constants. By default every platform library that is
/// available in the "libraries" section implicitly defines an environment
/// variable `dart.library.name` as `"true"`, to indicate that the library
/// is supported. Some backends allow imports to an unsupported platform
/// library (turning a static error into a runtime error when the library is
/// eventually accessed). These backends can use `supported: false` to
/// report that such library is still not supported in conditional imports
/// and const `fromEnvironment` expressions.
///
///
/// Note: we currently have several different files that need to be updated
/// when changing libraries, sources, and patch files:
/// * .platform files (for dart2js)
/// * .gypi files (for vm)
/// * sdk_library_metadata/lib/libraries.dart (for analyzer, ddc)
///
/// we are in the process of unifying them all under this format (see
/// https://github.com/dart-lang/sdk/issues/28836), but for now we need to pay
/// close attention to change them consistently.
// TODO(sigmund): move this file to a shared package.
import 'dart:convert' show jsonDecode, jsonEncode;
import '../fasta/util/relativize.dart' show relativizeUri;
import '../fasta/resolve_input_uri.dart' show isWindows;
/// Contents from a single library specification file.
///
/// Contains information about all libraries on all target platforms defined in
/// that file.
class LibrariesSpecification {
final Map<String, TargetLibrariesSpecification> _targets;
const LibrariesSpecification(
[this._targets = const <String, TargetLibrariesSpecification>{}]);
/// The library specification for a given [target], or throws if none is
/// available.
TargetLibrariesSpecification specificationFor(String target) {
TargetLibrariesSpecification targetSpec = _targets[target];
if (targetSpec == null) {
throw new LibrariesSpecificationException(
'No library specification for target "$target"');
}
return targetSpec;
}
/// Parse the given [json] as a library specification, resolving any relative
/// paths from [baseUri].
///
/// May throw an exception if [json] is not properly formatted or contains
/// invalid values.
static LibrariesSpecification parse(Uri baseUri, String json) {
if (json == null) return const LibrariesSpecification();
Map<String, dynamic> jsonData;
try {
dynamic data = jsonDecode(json);
if (data is! Map) {
return _reportError('top-level specification is not a map');
}
jsonData = data as Map;
} on FormatException catch (e) {
throw new LibrariesSpecificationException(e);
}
Map<String, TargetLibrariesSpecification> targets =
<String, TargetLibrariesSpecification>{};
jsonData.forEach((String targetName, targetData) {
if (targetName.startsWith("comment:")) return null;
Map<String, LibraryInfo> libraries = <String, LibraryInfo>{};
if (targetData is! Map) {
return _reportError(
"target specification for '$targetName' is not a map");
}
if (!targetData.containsKey("libraries")) {
return _reportError("target specification "
"for '$targetName' doesn't have a libraries entry");
}
dynamic librariesData = targetData["libraries"];
if (librariesData is! Map) {
return _reportError("libraries entry for '$targetName' is not a map");
}
librariesData.forEach((String name, data) {
if (data is! Map) {
return _reportError(
"library data for '$name' in target '$targetName' is not a map");
}
Uri checkAndResolve(uriString) {
if (uriString is! String) {
return _reportError("uri value '$uriString' is not a string"
"(from library '$name' in target '$targetName')");
}
Uri uri = Uri.parse(uriString);
if (uri.scheme != '' && uri.scheme != 'file') {
return _reportError("uri scheme in '$uriString' is not supported.");
}
return baseUri.resolveUri(uri);
}
Uri uri = checkAndResolve(data['uri']);
List<Uri> patches;
if (data['patches'] is List) {
patches =
data['patches'].map<Uri>((s) => baseUri.resolve(s)).toList();
} else if (data['patches'] is String) {
patches = [checkAndResolve(data['patches'])];
} else if (data['patches'] == null) {
patches = const [];
} else {
return _reportError(
"patches entry for '$name' is not a list or a string");
}
dynamic supported = data['supported'] ?? true;
if (supported is! bool) {
return _reportError("\"supported\" entry: expected a 'bool' but "
"got a '${supported.runtimeType}' ('$supported')");
}
libraries[name] =
new LibraryInfo(name, uri, patches, isSupported: supported);
});
targets[targetName] =
new TargetLibrariesSpecification(targetName, libraries);
});
return new LibrariesSpecification(targets);
}
static _reportError(String error) =>
throw new LibrariesSpecificationException(error);
/// Serialize this specification to json.
///
/// If possible serializes paths relative to [outputUri].
String toJsonString(Uri outputUri) => jsonEncode(toJsonMap(outputUri));
Map toJsonMap(Uri outputUri) {
Map result = {};
Uri dir = outputUri.resolve('.');
String pathFor(Uri uri) => relativizeUri(dir, uri, isWindows);
_targets.forEach((targetName, target) {
Map libraries = {};
target._libraries.forEach((name, lib) {
libraries[name] = {
'uri': pathFor(lib.uri),
'patches': lib.patches.map(pathFor).toList(),
};
if (!lib.isSupported) {
libraries[name]['supported'] = false;
}
});
result[targetName] = {'libraries': libraries};
});
return result;
}
}
/// Specifies information about all libraries supported by a given target.
class TargetLibrariesSpecification {
/// Name of the target platform.
final String targetName;
final Map<String, LibraryInfo> _libraries;
const TargetLibrariesSpecification(this.targetName,
[this._libraries = const <String, LibraryInfo>{}]);
/// Details about a library whose import is `dart:$name`.
LibraryInfo libraryInfoFor(String name) => _libraries[name];
Iterable<LibraryInfo> get allLibraries => _libraries.values;
}
/// Information about a `dart:` library in a specific target platform.
class LibraryInfo {
/// The name of the library, which is the path developers use to import this
/// library (as `dart:$name`).
final String name;
/// The file defining the main implementation of the library.
final Uri uri;
/// Patch files used for this library in the target platform, if any.
final List<Uri> patches;
/// Whether the library is supported and thus `dart.library.name` is "true"
/// for conditional imports and fromEnvironment constants.
final bool isSupported;
const LibraryInfo(this.name, this.uri, this.patches,
{this.isSupported: true});
}
class LibrariesSpecificationException {
Object error;
LibrariesSpecificationException(this.error);
String toString() => '$error';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/common.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.
/// If `true`, data that would not otherwise be kept is stored for testing.
bool retainDataForTesting = false;
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/errors.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.
/// An error code associated with an [AnalysisError].
///
/// Generally, messages should follow the [Guide for Writing
/// Diagnostics](../fasta/diagnostics.md).
abstract class ErrorCode {
/**
* The name of the error code.
*/
final String name;
/**
* The template used to create the message to be displayed for this error. The
* message should indicate what is wrong and why it is wrong.
*/
final String message;
/**
* The template used to create the correction to be displayed for this error,
* or `null` if there is no correction information for this error. The
* correction should indicate how the user can fix the error.
*/
final String correction;
/**
* Return `true` if diagnostics with this code have documentation for them
* that has been published.
*/
final bool hasPublishedDocs;
/**
* Whether this error is caused by an unresolved identifier.
*/
final bool isUnresolvedIdentifier;
/**
* Initialize a newly created error code to have the given [name]. The message
* associated with the error will be created from the given [message]
* template. The correction associated with the error will be created from the
* given [correction] template.
*/
const ErrorCode(this.name, this.message,
[this.correction, this.hasPublishedDocs = false])
: isUnresolvedIdentifier = false;
/**
* Initialize a newly created error code to have the given [name]. The message
* associated with the error will be created from the given [message]
* template. The correction associated with the error will be created from the
* given [correction] template.
*/
const ErrorCode.temporary(this.name, this.message,
{this.correction,
this.isUnresolvedIdentifier: false,
this.hasPublishedDocs = false});
/**
* The severity of the error.
*/
ErrorSeverity get errorSeverity;
/**
* The type of the error.
*/
ErrorType get type;
/**
* The unique name of this error code.
*/
String get uniqueName => "$runtimeType.$name";
/**
* Return a URL that can be used to access documentation for diagnostics with
* this code, or `null` if there is no published documentation.
*/
String get url {
if (hasPublishedDocs) {
return 'https://dart.dev/tools/diagnostic-messages#${name.toLowerCase()}';
}
return null;
}
@override
String toString() => uniqueName;
}
/**
* The severity of an [ErrorCode].
*/
class ErrorSeverity implements Comparable<ErrorSeverity> {
/**
* The severity representing a non-error. This is never used for any error
* code, but is useful for clients.
*/
static const ErrorSeverity NONE = const ErrorSeverity('NONE', 0, " ", "none");
/**
* The severity representing an informational level analysis issue.
*/
static const ErrorSeverity INFO = const ErrorSeverity('INFO', 1, "I", "info");
/**
* The severity representing a warning. Warnings can become errors if the
* `-Werror` command line flag is specified.
*/
static const ErrorSeverity WARNING =
const ErrorSeverity('WARNING', 2, "W", "warning");
/**
* The severity representing an error.
*/
static const ErrorSeverity ERROR =
const ErrorSeverity('ERROR', 3, "E", "error");
static const List<ErrorSeverity> values = const [NONE, INFO, WARNING, ERROR];
/**
* The name of this error code.
*/
final String name;
/**
* The ordinal value of the error code.
*/
final int ordinal;
/**
* The name of the severity used when producing machine output.
*/
final String machineCode;
/**
* The name of the severity used when producing readable output.
*/
final String displayName;
/**
* Initialize a newly created severity with the given names.
*/
const ErrorSeverity(
this.name, this.ordinal, this.machineCode, this.displayName);
@override
int get hashCode => ordinal;
@override
int compareTo(ErrorSeverity other) => ordinal - other.ordinal;
/**
* Return the severity constant that represents the greatest severity.
*/
ErrorSeverity max(ErrorSeverity severity) =>
this.ordinal >= severity.ordinal ? this : severity;
@override
String toString() => name;
}
/**
* The type of an [ErrorCode].
*/
class ErrorType implements Comparable<ErrorType> {
/**
* Task (todo) comments in user code.
*/
static const ErrorType TODO = const ErrorType('TODO', 0, ErrorSeverity.INFO);
/**
* Extra analysis run over the code to follow best practices, which are not in
* the Dart Language Specification.
*/
static const ErrorType HINT = const ErrorType('HINT', 1, ErrorSeverity.INFO);
/**
* Compile-time errors are errors that preclude execution. A compile time
* error must be reported by a Dart compiler before the erroneous code is
* executed.
*/
static const ErrorType COMPILE_TIME_ERROR =
const ErrorType('COMPILE_TIME_ERROR', 2, ErrorSeverity.ERROR);
/**
* Checked mode compile-time errors are errors that preclude execution in
* checked mode.
*/
static const ErrorType CHECKED_MODE_COMPILE_TIME_ERROR = const ErrorType(
'CHECKED_MODE_COMPILE_TIME_ERROR', 3, ErrorSeverity.ERROR);
/**
* Static warnings are those warnings reported by the static checker. They
* have no effect on execution. Static warnings must be provided by Dart
* compilers used during development.
*/
static const ErrorType STATIC_WARNING =
const ErrorType('STATIC_WARNING', 4, ErrorSeverity.WARNING);
/**
* Many, but not all, static warnings relate to types, in which case they are
* known as static type warnings.
*/
static const ErrorType STATIC_TYPE_WARNING =
const ErrorType('STATIC_TYPE_WARNING', 5, ErrorSeverity.WARNING);
/**
* Syntactic errors are errors produced as a result of input that does not
* conform to the grammar.
*/
static const ErrorType SYNTACTIC_ERROR =
const ErrorType('SYNTACTIC_ERROR', 6, ErrorSeverity.ERROR);
/**
* Lint warnings describe style and best practice recommendations that can be
* used to formalize a project's style guidelines.
*/
static const ErrorType LINT = const ErrorType('LINT', 7, ErrorSeverity.INFO);
static const List<ErrorType> values = const [
TODO,
HINT,
COMPILE_TIME_ERROR,
CHECKED_MODE_COMPILE_TIME_ERROR,
STATIC_WARNING,
STATIC_TYPE_WARNING,
SYNTACTIC_ERROR,
LINT
];
/**
* The name of this error type.
*/
final String name;
/**
* The ordinal value of the error type.
*/
final int ordinal;
/**
* The severity of this type of error.
*/
final ErrorSeverity severity;
/**
* Initialize a newly created error type to have the given [name] and
* [severity].
*/
const ErrorType(this.name, this.ordinal, this.severity);
String get displayName => name.toLowerCase().replaceAll('_', ' ');
@override
int get hashCode => ordinal;
@override
int compareTo(ErrorType other) => ordinal - other.ordinal;
@override
String toString() => name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/processed_options.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 'dart:io' show exitCode;
import 'dart:async' show Future;
import 'dart:typed_data' show Uint8List;
import 'package:kernel/binary/ast_from_binary.dart' show BinaryBuilder;
import 'package:kernel/kernel.dart' show CanonicalName, Component, Location;
import 'package:kernel/target/targets.dart'
show NoneTarget, Target, TargetFlags;
import 'package:package_config/packages.dart' show Packages;
import 'package:package_config/packages_file.dart' as package_config;
import 'package:package_config/src/packages_impl.dart' show MapPackages;
import '../api_prototype/compiler_options.dart'
show CompilerOptions, DiagnosticMessage;
import '../api_prototype/experimental_flags.dart'
show defaultExperimentalFlags, ExperimentalFlag, expiredExperimentalFlags;
import '../api_prototype/file_system.dart'
show FileSystem, FileSystemEntity, FileSystemException;
import '../api_prototype/terminal_color_support.dart'
show printDiagnosticMessage;
import '../fasta/command_line_reporting.dart' as command_line_reporting;
import '../fasta/compiler_context.dart' show CompilerContext;
import '../fasta/fasta_codes.dart'
show
FormattedMessage,
LocatedMessage,
Message,
messageCantInferPackagesFromManyInputs,
messageCantInferPackagesFromPackageUri,
messageInternalProblemProvidedBothCompileSdkAndSdkSummary,
messageMissingInput,
noLength,
templateCannotReadSdkSpecification,
templateCantReadFile,
templateInputFileNotFound,
templateInternalProblemUnsupported,
templatePackagesFileFormat,
templateSdkRootNotFound,
templateSdkSpecificationNotFound,
templateSdkSummaryNotFound;
import '../fasta/messages.dart' show getLocation;
import '../fasta/problems.dart' show DebugAbort, unimplemented;
import '../fasta/severity.dart' show Severity;
import '../fasta/ticker.dart' show Ticker;
import '../fasta/uri_translator.dart' show UriTranslator;
import 'libraries_specification.dart'
show
LibrariesSpecification,
LibrariesSpecificationException,
TargetLibrariesSpecification;
/// All options needed for the front end implementation.
///
/// This includes: all of [CompilerOptions] in a form useful to the
/// implementation, default values for options that were not provided,
/// and information derived from how the compiler was invoked (like the
/// entry-points given to the compiler and whether a modular or whole-program
/// API was used).
///
/// The intent is that the front end should immediately wrap any incoming
/// [CompilerOptions] object in this class before doing further processing, and
/// should thereafter access all options via the wrapper. This ensures that
/// options are interpreted in a consistent way and that data derived from
/// options is not unnecessarily recomputed.
class ProcessedOptions {
/// The raw [CompilerOptions] which this class wraps.
final CompilerOptions _raw;
/// The package map derived from the options, or `null` if the package map has
/// not been computed yet.
Packages _packages;
/// The uri for .packages derived from the options, or `null` if the package
/// map has not been computed yet or there is no .packages in effect.
Uri _packagesUri;
Uri get packagesUri => _packagesUri;
/// The object that knows how to resolve "package:" and "dart:" URIs,
/// or `null` if it has not been computed yet.
UriTranslator _uriTranslator;
/// The SDK summary, or `null` if it has not been read yet.
///
/// A summary, also referred to as "outline" internally, is a [Component]
/// where all method bodies are left out. In essence, it contains just API
/// signatures and constants. The summary should include inferred top-level
/// types unless legacy mode is enabled.
Component _sdkSummaryComponent;
/// The summary for each uri in `options.inputSummaries`.
///
/// A summary, also referred to as "outline" internally, is a [Component]
/// where all method bodies are left out. In essence, it contains just API
/// signatures and constants. The summaries should include inferred top-level
/// types unless legacy mode is enabled.
List<Component> _inputSummariesComponents;
/// Other components that are meant to be linked and compiled with the input
/// sources.
List<Component> _linkedDependencies;
/// The location of the SDK, or `null` if the location hasn't been determined
/// yet.
Uri _sdkRoot;
Uri get sdkRoot {
_ensureSdkDefaults();
return _sdkRoot;
}
Uri _sdkSummary;
Uri get sdkSummary {
_ensureSdkDefaults();
return _sdkSummary;
}
List<int> _sdkSummaryBytes;
/// Get the bytes of the SDK outline, if any.
Future<List<int>> loadSdkSummaryBytes() async {
if (_sdkSummaryBytes == null) {
if (sdkSummary == null) return null;
FileSystemEntity entry = fileSystem.entityForUri(sdkSummary);
_sdkSummaryBytes = await _readAsBytes(entry);
}
return _sdkSummaryBytes;
}
Uri _librariesSpecificationUri;
Uri get librariesSpecificationUri {
_ensureSdkDefaults();
return _librariesSpecificationUri;
}
Ticker ticker;
Uri get packagesUriRaw => _raw.packagesFileUri;
bool get verbose => _raw.verbose;
bool get verify => _raw.verify;
bool get debugDump => _raw.debugDump;
bool get omitPlatform => _raw.omitPlatform;
bool get setExitCodeOnProblem => _raw.setExitCodeOnProblem;
bool get embedSourceText => _raw.embedSourceText;
bool get throwOnErrorsForDebugging => _raw.throwOnErrorsForDebugging;
bool get throwOnWarningsForDebugging => _raw.throwOnWarningsForDebugging;
/// The entry-points provided to the compiler.
final List<Uri> inputs;
/// The Uri where output is generated, may be null.
final Uri output;
final Map<String, String> environmentDefines;
bool get errorOnUnevaluatedConstant => _raw.errorOnUnevaluatedConstant;
/// Initializes a [ProcessedOptions] object wrapping the given [rawOptions].
ProcessedOptions({CompilerOptions options, List<Uri> inputs, this.output})
: this._raw = options ?? new CompilerOptions(),
this.inputs = inputs ?? <Uri>[],
// TODO(askesc): Copy the map when kernel_service supports that.
this.environmentDefines = options?.environmentDefines,
// TODO(sigmund, ahe): create ticker even earlier or pass in a stopwatch
// collecting time since the start of the VM.
this.ticker = new Ticker(isVerbose: options?.verbose ?? false);
FormattedMessage format(
LocatedMessage message, Severity severity, List<LocatedMessage> context) {
int offset = message.charOffset;
Uri uri = message.uri;
Location location = offset == -1 ? null : getLocation(uri, offset);
String formatted =
command_line_reporting.format(message, severity, location: location);
List<FormattedMessage> formattedContext;
if (context != null && context.isNotEmpty) {
formattedContext = new List<FormattedMessage>(context.length);
for (int i = 0; i < context.length; i++) {
formattedContext[i] = format(context[i], Severity.context, null);
}
}
return message.withFormatting(formatted, location?.line ?? -1,
location?.column ?? -1, severity, formattedContext);
}
void report(LocatedMessage message, Severity severity,
{List<LocatedMessage> context}) {
if (command_line_reporting.isHidden(severity)) return;
if (command_line_reporting.isCompileTimeError(severity)) {
CompilerContext.current.logError(message, severity);
}
if (CompilerContext.current.options.setExitCodeOnProblem) {
exitCode = 1;
}
reportDiagnosticMessage(format(message, severity, context));
if (command_line_reporting.shouldThrowOn(severity)) {
throw new DebugAbort(
message.uri, message.charOffset, severity, StackTrace.current);
}
}
void reportDiagnosticMessage(DiagnosticMessage message) {
(_raw.onDiagnostic ?? _defaultDiagnosticMessageHandler)(message);
}
void _defaultDiagnosticMessageHandler(DiagnosticMessage message) {
printDiagnosticMessage(message, print);
}
// TODO(askesc): Remove this and direct callers directly to report.
void reportWithoutLocation(Message message, Severity severity) {
report(message.withoutLocation(), severity);
}
/// Runs various validations checks on the input options. For instance,
/// if an option is a path to a file, it checks that the file exists.
Future<bool> validateOptions({bool errorOnMissingInput: true}) async {
if (verbose) print(debugString());
if (errorOnMissingInput && inputs.isEmpty) {
reportWithoutLocation(messageMissingInput, Severity.error);
return false;
}
if (_raw.sdkRoot != null &&
!await fileSystem.entityForUri(sdkRoot).exists()) {
reportWithoutLocation(
templateSdkRootNotFound.withArguments(sdkRoot), Severity.error);
return false;
}
Uri summary = sdkSummary;
if (summary != null && !await fileSystem.entityForUri(summary).exists()) {
reportWithoutLocation(
templateSdkSummaryNotFound.withArguments(summary), Severity.error);
return false;
}
if (compileSdk && summary != null) {
reportWithoutLocation(
messageInternalProblemProvidedBothCompileSdkAndSdkSummary,
Severity.internalProblem);
return false;
}
for (Uri source in _raw.linkedDependencies) {
// TODO(ahe): Remove this check, the compiler itself should handle and
// recover from this.
if (!await fileSystem.entityForUri(source).exists()) {
reportWithoutLocation(
templateInputFileNotFound.withArguments(source), Severity.error);
return false;
}
}
return true;
}
/// Determine whether to generate code for the SDK when compiling a
/// whole-program.
bool get compileSdk => _raw.compileSdk;
FileSystem _fileSystem;
/// Get the [FileSystem] which should be used by the front end to access
/// files.
FileSystem get fileSystem => _fileSystem ??= _createFileSystem();
/// Clear the file system so any CompilerOptions fileSystem change will have
/// effect.
void clearFileSystemCache() => _fileSystem = null;
/// Whether to generate bytecode.
bool get bytecode => _raw.bytecode;
/// Whether to write a file (e.g. a dill file) when reporting a crash.
bool get writeFileOnCrashReport => _raw.writeFileOnCrashReport;
/// The current sdk version string, e.g. "2.6.0-edge.sha1hash".
/// For instance used for language versioning (specifying the maximum
/// version).
String get currentSdkVersion => _raw.currentSdkVersion;
Target _target;
Target get target =>
_target ??= _raw.target ?? new NoneTarget(new TargetFlags());
bool isExperimentEnabled(ExperimentalFlag flag) {
assert(defaultExperimentalFlags.containsKey(flag),
"No default value for $flag.");
assert(expiredExperimentalFlags.containsKey(flag),
"No expired value for $flag.");
if (expiredExperimentalFlags[flag]) {
return defaultExperimentalFlags[flag];
}
return _raw.experimentalFlags[flag] ?? defaultExperimentalFlags[flag];
}
/// Get an outline component that summarizes the SDK, if any.
// TODO(sigmund): move, this doesn't feel like an "option".
Future<Component> loadSdkSummary(CanonicalName nameRoot) async {
if (_sdkSummaryComponent == null) {
if (sdkSummary == null) return null;
List<int> bytes = await loadSdkSummaryBytes();
if (bytes != null && bytes.isNotEmpty) {
_sdkSummaryComponent = loadComponent(bytes, nameRoot);
}
}
return _sdkSummaryComponent;
}
void set sdkSummaryComponent(Component platform) {
if (_sdkSummaryComponent != null) {
throw new StateError("sdkSummary already loaded.");
}
_sdkSummaryComponent = platform;
}
/// Get the summary programs for each of the underlying `inputSummaries`
/// provided via [CompilerOptions].
// TODO(sigmund): move, this doesn't feel like an "option".
Future<List<Component>> loadInputSummaries(CanonicalName nameRoot) async {
if (_inputSummariesComponents == null) {
List<Uri> uris = _raw.inputSummaries;
if (uris == null || uris.isEmpty) return const <Component>[];
// TODO(sigmund): throttle # of concurrent operations.
List<List<int>> allBytes = await Future.wait(
uris.map((uri) => _readAsBytes(fileSystem.entityForUri(uri))));
_inputSummariesComponents =
allBytes.map((bytes) => loadComponent(bytes, nameRoot)).toList();
}
return _inputSummariesComponents;
}
void set inputSummariesComponents(List<Component> components) {
if (_inputSummariesComponents != null) {
throw new StateError("inputSummariesComponents already loaded.");
}
_inputSummariesComponents = components;
}
/// Load each of the [CompilerOptions.linkedDependencies] components.
// TODO(sigmund): move, this doesn't feel like an "option".
Future<List<Component>> loadLinkDependencies(CanonicalName nameRoot) async {
if (_linkedDependencies == null) {
List<Uri> uris = _raw.linkedDependencies;
if (uris == null || uris.isEmpty) return const <Component>[];
// TODO(sigmund): throttle # of concurrent operations.
List<List<int>> allBytes = await Future.wait(
uris.map((uri) => _readAsBytes(fileSystem.entityForUri(uri))));
_linkedDependencies =
allBytes.map((bytes) => loadComponent(bytes, nameRoot)).toList();
}
return _linkedDependencies;
}
/// Helper to load a .dill file from [uri] using the existing [nameRoot].
Component loadComponent(List<int> bytes, CanonicalName nameRoot,
{bool alwaysCreateNewNamedNodes}) {
Component component =
target.configureComponent(new Component(nameRoot: nameRoot));
// TODO(ahe): Pass file name to BinaryBuilder.
// TODO(ahe): Control lazy loading via an option.
new BinaryBuilder(bytes,
filename: null,
disableLazyReading: false,
alwaysCreateNewNamedNodes: alwaysCreateNewNamedNodes)
.readComponent(component);
return component;
}
/// Get the [UriTranslator] which resolves "package:" and "dart:" URIs.
///
/// This is an asynchronous method since file system operations may be
/// required to locate/read the packages file as well as SDK metadata.
Future<UriTranslator> getUriTranslator({bool bypassCache: false}) async {
if (bypassCache) {
_uriTranslator = null;
_packages = null;
}
if (_uriTranslator == null) {
ticker.logMs("Started building UriTranslator");
TargetLibrariesSpecification libraries =
await _computeLibrarySpecification();
ticker.logMs("Read libraries file");
Packages packages = await _getPackages();
ticker.logMs("Read packages file");
_uriTranslator = new UriTranslator(libraries, packages);
}
return _uriTranslator;
}
Future<TargetLibrariesSpecification> _computeLibrarySpecification() async {
String name = target.name;
// TODO(sigmund): Eek! We should get to the point where there is no
// fasta-specific targets and the target names are meaningful.
if (name.endsWith('_fasta')) name = name.substring(0, name.length - 6);
if (librariesSpecificationUri == null ||
!await fileSystem.entityForUri(librariesSpecificationUri).exists()) {
if (compileSdk) {
reportWithoutLocation(
templateSdkSpecificationNotFound
.withArguments(librariesSpecificationUri),
Severity.error);
}
return new TargetLibrariesSpecification(name);
}
String json =
await fileSystem.entityForUri(librariesSpecificationUri).readAsString();
try {
LibrariesSpecification spec =
await LibrariesSpecification.parse(librariesSpecificationUri, json);
return spec.specificationFor(name);
} on LibrariesSpecificationException catch (e) {
reportWithoutLocation(
templateCannotReadSdkSpecification.withArguments('${e.error}'),
Severity.error);
return new TargetLibrariesSpecification(name);
}
}
/// Get the package map which maps package names to URIs.
///
/// This is an asynchronous getter since file system operations may be
/// required to locate/read the packages file.
Future<Packages> _getPackages() async {
if (_packages != null) return _packages;
_packagesUri = null;
if (_raw.packagesFileUri != null) {
return _packages = await createPackagesFromFile(_raw.packagesFileUri);
}
if (inputs.length > 1) {
// TODO(sigmund): consider not reporting an error if we would infer
// the same .packages file from all of the inputs.
reportWithoutLocation(
messageCantInferPackagesFromManyInputs, Severity.error);
return _packages = Packages.noPackages;
}
Uri input = inputs.first;
// When compiling the SDK the input files are normally `dart:` URIs.
if (input.scheme == 'dart') return _packages = Packages.noPackages;
if (input.scheme == 'packages') {
report(
messageCantInferPackagesFromPackageUri.withLocation(
input, -1, noLength),
Severity.error);
return _packages = Packages.noPackages;
}
return _packages = await _findPackages(inputs.first);
}
/// Create a [Packages] given the Uri to a `.packages` file.
Future<Packages> createPackagesFromFile(Uri file) async {
List<int> contents;
try {
// TODO(ahe): We need to compute line endings for this file.
contents = await fileSystem.entityForUri(file).readAsBytes();
} on FileSystemException catch (e) {
reportWithoutLocation(
templateCantReadFile.withArguments(file, e.message), Severity.error);
}
if (contents != null) {
_packagesUri = file;
try {
Map<String, Uri> map =
package_config.parse(contents, file, allowDefaultPackage: true);
return new MapPackages(map);
} on FormatException catch (e) {
report(
templatePackagesFileFormat
.withArguments(e.message)
.withLocation(file, e.offset, noLength),
Severity.error);
} catch (e) {
reportWithoutLocation(
templateCantReadFile.withArguments(file, "$e"), Severity.error);
}
}
_packagesUri = null;
return Packages.noPackages;
}
/// Finds a package resolution strategy using a [FileSystem].
///
/// The [scriptUri] points to a Dart script with a valid scheme accepted by
/// the [FileSystem].
///
/// This function first tries to locate a `.packages` file in the `scriptUri`
/// directory. If that is not found, it starts checking parent directories for
/// a `.packages` file, and stops if it finds it. Otherwise it gives up and
/// returns [Packages.noPackages].
///
/// Note: this is a fork from `package:package_config/discovery.dart` to adapt
/// it to use [FileSystem]. The logic here is a mix of the logic in the
/// `findPackagesFromFile` and `findPackagesFromNonFile`:
///
/// * Like `findPackagesFromFile` resolution searches for parent
/// directories
///
/// * Unlike package:package_config, it does not look for a `packages/`
/// directory, as that won't be supported in Dart 2.
Future<Packages> _findPackages(Uri scriptUri) async {
Uri dir = scriptUri.resolve('.');
if (!dir.isAbsolute) {
reportWithoutLocation(
templateInternalProblemUnsupported
.withArguments("Expected input Uri to be absolute: $scriptUri."),
Severity.internalProblem);
return Packages.noPackages;
}
Future<Uri> checkInDir(Uri dir) async {
Uri candidate = dir.resolve('.packages');
if (await fileSystem.entityForUri(candidate).exists()) return candidate;
return null;
}
// Check for $cwd/.packages
Uri candidate = await checkInDir(dir);
if (candidate != null) return createPackagesFromFile(candidate);
// Check for cwd(/..)+/.packages
Uri parentDir = dir.resolve('..');
while (parentDir.path != dir.path) {
candidate = await checkInDir(parentDir);
if (candidate != null) break;
dir = parentDir;
parentDir = dir.resolve('..');
}
if (candidate != null) return createPackagesFromFile(candidate);
return Packages.noPackages;
}
bool _computedSdkDefaults = false;
/// Ensure [_sdkRoot], [_sdkSummary] and [_librarySpecUri] are initialized.
///
/// If they are not set explicitly, they are inferred based on the default
/// behavior described in [CompilerOptions].
void _ensureSdkDefaults() {
if (_computedSdkDefaults) return;
_computedSdkDefaults = true;
Uri root = _raw.sdkRoot;
if (root != null) {
// Normalize to always end in '/'
if (!root.path.endsWith('/')) {
root = root.replace(path: root.path + '/');
}
_sdkRoot = root;
} else if (compileSdk) {
// TODO(paulberry): implement the algorithm for finding the SDK
// automagically.
unimplemented('infer the default sdk location', -1, null);
}
if (_raw.sdkSummary != null) {
_sdkSummary = _raw.sdkSummary;
} else if (!compileSdk) {
// Infer based on the sdkRoot, but only when `compileSdk` is false,
// otherwise the default intent was to compile the sdk from sources and
// not to load an sdk summary file.
_sdkSummary = root?.resolve("vm_platform_strong.dill");
}
if (_raw.librariesSpecificationUri != null) {
_librariesSpecificationUri = _raw.librariesSpecificationUri;
} else if (compileSdk) {
_librariesSpecificationUri = sdkRoot.resolve('lib/libraries.json');
}
}
/// Create a [FileSystem] specific to the current options.
FileSystem _createFileSystem() {
return _raw.fileSystem;
}
String debugString() {
StringBuffer sb = new StringBuffer();
writeList(String name, List elements) {
if (elements.isEmpty) {
sb.writeln('$name: <empty>');
return;
}
sb.writeln('$name:');
elements.forEach((s) {
sb.writeln(' - $s');
});
}
sb.writeln('Inputs: ${inputs}');
sb.writeln('Output: ${output}');
sb.writeln('Was diagnostic message handler provided: '
'${_raw.onDiagnostic == null ? "no" : "yes"}');
sb.writeln('FileSystem: ${_fileSystem.runtimeType} '
'(provided: ${_raw.fileSystem.runtimeType})');
writeList('Input Summaries', _raw.inputSummaries);
writeList('Linked Dependencies', _raw.linkedDependencies);
sb.writeln('Packages uri: ${_raw.packagesFileUri}');
sb.writeln('Packages: ${_packages}');
sb.writeln('Compile SDK: ${compileSdk}');
sb.writeln('SDK root: ${_sdkRoot} (provided: ${_raw.sdkRoot})');
sb.writeln('SDK specification: ${_librariesSpecificationUri} '
'(provided: ${_raw.librariesSpecificationUri})');
sb.writeln('SDK summary: ${_sdkSummary} (provided: ${_raw.sdkSummary})');
sb.writeln('Target: ${_target?.name} (provided: ${_raw.target?.name})');
sb.writeln('throwOnErrorsForDebugging: ${throwOnErrorsForDebugging}');
sb.writeln('throwOnWarningsForDebugging: ${throwOnWarningsForDebugging}');
sb.writeln('exit on problem: ${setExitCodeOnProblem}');
sb.writeln('Embed sources: ${embedSourceText}');
sb.writeln('debugDump: ${debugDump}');
sb.writeln('verbose: ${verbose}');
sb.writeln('verify: ${verify}');
return '$sb';
}
Future<List<int>> _readAsBytes(FileSystemEntity file) async {
try {
return await file.readAsBytes();
} on FileSystemException catch (error) {
report(
templateCantReadFile
.withArguments(error.uri, error.message)
.withoutLocation(),
Severity.error);
return new Uint8List(0);
}
}
}
/// A [FileSystem] that only allows access to files that have been explicitly
/// whitelisted.
class HermeticFileSystem implements FileSystem {
final Set<Uri> includedFiles;
final FileSystem _realFileSystem;
HermeticFileSystem(this.includedFiles, this._realFileSystem);
FileSystemEntity entityForUri(Uri uri) {
if (includedFiles.contains(uri)) return _realFileSystem.entityForUri(uri);
throw new HermeticAccessException(uri);
}
}
class HermeticAccessException extends FileSystemException {
HermeticAccessException(Uri uri)
: super(
uri,
'Invalid access to $uri: '
'the file is accessed in a modular hermetic build, '
'but it was not explicitly listed as an input.');
@override
String toString() => message;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/base/instrumentation.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' show DartType, Member;
/// Convert '→' to '->' because '→' doesn't show up in some terminals.
/// Remove prefixes that are used very often in tests.
String _shortenInstrumentationString(String s) => s
.replaceAll('→', '->')
.replaceAll('dart.core::', '')
.replaceAll('dart.async::', '')
.replaceAll('test::', '')
.replaceAll(new RegExp(r'\s*/\*.*?\*/\s*'), '');
/// Interface providing the ability to record property/value pairs associated
/// with source file locations. Intended to facilitate testing.
abstract class Instrumentation {
/// Records a property/value pair associated with the given URI and offset.
void record(Uri uri, int offset, String property, InstrumentationValue value);
}
/// Interface for values recorded by [Instrumentation].
abstract class InstrumentationValue {
const InstrumentationValue();
/// Checks if the given String is an accurate description of this value.
///
/// The default implementation just checks for equality with the return value
/// of [toString], however derived classes may want a more sophisticated
/// implementation (e.g. to allow abbreviations in the description).
///
/// Derived classes should ensure that the invariant holds:
/// `this.matches(this.toString())` should always return `true`.
bool matches(String description) => description == toString();
}
/// Instance of [InstrumentationValue] describing a [Member].
class InstrumentationValueForMember extends InstrumentationValue {
final Member member;
InstrumentationValueForMember(this.member);
@override
String toString() => _shortenInstrumentationString(member.toString());
}
/// Instance of [InstrumentationValue] describing a [DartType].
class InstrumentationValueForType extends InstrumentationValue {
final DartType type;
InstrumentationValueForType(this.type);
@override
String toString() => _shortenInstrumentationString(type.toString());
}
/// Instance of [InstrumentationValue] describing a list of [DartType]s.
class InstrumentationValueForTypeArgs extends InstrumentationValue {
final List<DartType> types;
InstrumentationValueForTypeArgs(this.types);
@override
String toString() => types
.map((type) => new InstrumentationValueForType(type).toString())
.join(', ');
}
/// Instance of [InstrumentationValue] which only matches the given literal
/// string.
class InstrumentationValueLiteral extends InstrumentationValue {
final String value;
const InstrumentationValueLiteral(this.value);
@override
String toString() => value;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/scanner/string_utilities.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 'interner.dart';
class StringUtilities {
static Interner INTERNER = new NullInterner();
static String intern(String string) => INTERNER.intern(string);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/scanner/interner.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.
/**
* The interface `Interner` defines the behavior of objects that can intern
* strings.
*/
abstract class Interner {
/**
* Return a string that is identical to all of the other strings that have
* been interned that are equal to the given [string].
*/
String intern(String string);
}
/**
* The class `NullInterner` implements an interner that does nothing (does not
* actually intern any strings).
*/
class NullInterner implements Interner {
@override
String intern(String string) => string;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/scanner/token.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.
/**
* Defines the tokens that are produced by the scanner, used by the parser, and
* referenced from the [AST structure](ast.dart).
*/
import 'dart:collection';
import '../base/syntactic_entity.dart';
import '../fasta/scanner/token_constants.dart';
import 'string_utilities.dart';
const int NO_PRECEDENCE = 0;
const int ASSIGNMENT_PRECEDENCE = 1;
const int CASCADE_PRECEDENCE = 2;
const int CONDITIONAL_PRECEDENCE = 3;
const int IF_NULL_PRECEDENCE = 4;
const int LOGICAL_OR_PRECEDENCE = 5;
const int LOGICAL_AND_PRECEDENCE = 6;
const int EQUALITY_PRECEDENCE = 7;
const int RELATIONAL_PRECEDENCE = 8;
const int BITWISE_OR_PRECEDENCE = 9;
const int BITWISE_XOR_PRECEDENCE = 10;
const int BITWISE_AND_PRECEDENCE = 11;
const int SHIFT_PRECEDENCE = 12;
const int ADDITIVE_PRECEDENCE = 13;
const int MULTIPLICATIVE_PRECEDENCE = 14;
const int PREFIX_PRECEDENCE = 15;
const int POSTFIX_PRECEDENCE = 16;
const int SELECTOR_PRECEDENCE = 17;
/**
* The opening half of a grouping pair of tokens. This is used for curly
* brackets ('{'), parentheses ('('), and square brackets ('[').
*/
class BeginToken extends SimpleToken {
/**
* The token that corresponds to this token.
*/
Token endToken;
/**
* Initialize a newly created token to have the given [type] at the given
* [offset].
*/
BeginToken(TokenType type, int offset, [CommentToken precedingComment])
: super(type, offset, precedingComment) {
assert(type == TokenType.LT ||
type == TokenType.OPEN_CURLY_BRACKET ||
type == TokenType.OPEN_PAREN ||
type == TokenType.OPEN_SQUARE_BRACKET ||
type == TokenType.QUESTION_PERIOD_OPEN_SQUARE_BRACKET ||
type == TokenType.STRING_INTERPOLATION_EXPRESSION);
}
@override
Token copy() => new BeginToken(type, offset, copyComments(precedingComments));
@override
Token get endGroup => endToken;
/**
* Set the token that corresponds to this token.
*/
set endGroup(Token token) {
endToken = token;
}
}
/**
* A token representing a comment.
*/
class CommentToken extends StringToken {
/**
* The token that contains this comment.
*/
SimpleToken parent;
/**
* Initialize a newly created token to represent a token of the given [type]
* with the given [value] at the given [offset].
*/
CommentToken(TokenType type, String value, int offset)
: super(type, value, offset);
@override
CommentToken copy() => new CommentToken(type, _value, offset);
/**
* Remove this comment token from the list.
*
* This is used when we decide to interpret the comment as syntax.
*/
void remove() {
if (previous != null) {
previous.setNextWithoutSettingPrevious(next);
next?.previous = previous;
} else {
assert(parent.precedingComments == this);
parent.precedingComments = next;
}
}
}
/**
* A documentation comment token.
*/
class DocumentationCommentToken extends CommentToken {
/**
* Initialize a newly created token to represent a token of the given [type]
* with the given [value] at the given [offset].
*/
DocumentationCommentToken(TokenType type, String value, int offset)
: super(type, value, offset);
@override
CommentToken copy() => new DocumentationCommentToken(type, _value, offset);
}
/**
* The keywords in the Dart programming language.
*
* Clients may not extend, implement or mix-in this class.
*/
class Keyword extends TokenType {
static const Keyword ABSTRACT =
const Keyword("abstract", "ABSTRACT", isBuiltIn: true, isModifier: true);
static const Keyword AS = const Keyword("as", "AS",
precedence: RELATIONAL_PRECEDENCE, isBuiltIn: true);
static const Keyword ASSERT = const Keyword("assert", "ASSERT");
static const Keyword ASYNC = const Keyword("async", "ASYNC", isPseudo: true);
static const Keyword AWAIT = const Keyword("await", "AWAIT", isPseudo: true);
static const Keyword BREAK = const Keyword("break", "BREAK");
static const Keyword CASE = const Keyword("case", "CASE");
static const Keyword CATCH = const Keyword("catch", "CATCH");
static const Keyword CLASS =
const Keyword("class", "CLASS", isTopLevelKeyword: true);
static const Keyword CONST =
const Keyword("const", "CONST", isModifier: true);
static const Keyword CONTINUE = const Keyword("continue", "CONTINUE");
static const Keyword COVARIANT = const Keyword("covariant", "COVARIANT",
isBuiltIn: true, isModifier: true);
static const Keyword DEFAULT = const Keyword("default", "DEFAULT");
static const Keyword DEFERRED =
const Keyword("deferred", "DEFERRED", isBuiltIn: true);
static const Keyword DO = const Keyword("do", "DO");
static const Keyword DYNAMIC =
const Keyword("dynamic", "DYNAMIC", isBuiltIn: true);
static const Keyword ELSE = const Keyword("else", "ELSE");
static const Keyword ENUM =
const Keyword("enum", "ENUM", isTopLevelKeyword: true);
static const Keyword EXPORT = const Keyword("export", "EXPORT",
isBuiltIn: true, isTopLevelKeyword: true);
static const Keyword EXTENDS = const Keyword("extends", "EXTENDS");
static const Keyword EXTENSION = const Keyword("extension", "EXTENSION",
isBuiltIn: true, isTopLevelKeyword: true);
static const Keyword EXTERNAL =
const Keyword("external", "EXTERNAL", isBuiltIn: true, isModifier: true);
static const Keyword FACTORY =
const Keyword("factory", "FACTORY", isBuiltIn: true);
static const Keyword FALSE = const Keyword("false", "FALSE");
static const Keyword FINAL =
const Keyword("final", "FINAL", isModifier: true);
static const Keyword FINALLY = const Keyword("finally", "FINALLY");
static const Keyword FOR = const Keyword("for", "FOR");
static const Keyword FUNCTION =
const Keyword("Function", "FUNCTION", isPseudo: true);
static const Keyword GET = const Keyword("get", "GET", isBuiltIn: true);
static const Keyword HIDE = const Keyword("hide", "HIDE", isPseudo: true);
static const Keyword IF = const Keyword("if", "IF");
static const Keyword IMPLEMENTS =
const Keyword("implements", "IMPLEMENTS", isBuiltIn: true);
static const Keyword IMPORT = const Keyword("import", "IMPORT",
isBuiltIn: true, isTopLevelKeyword: true);
static const Keyword IN = const Keyword("in", "IN");
static const Keyword INOUT = const Keyword("inout", "INOUT", isPseudo: true);
static const Keyword INTERFACE =
const Keyword("interface", "INTERFACE", isBuiltIn: true);
static const Keyword IS =
const Keyword("is", "IS", precedence: RELATIONAL_PRECEDENCE);
static const Keyword LATE = const Keyword("late", "LATE", isModifier: true);
static const Keyword LIBRARY = const Keyword("library", "LIBRARY",
isBuiltIn: true, isTopLevelKeyword: true);
static const Keyword MIXIN =
const Keyword("mixin", "MIXIN", isBuiltIn: true, isTopLevelKeyword: true);
static const Keyword NATIVE =
const Keyword("native", "NATIVE", isPseudo: true);
static const Keyword NEW = const Keyword("new", "NEW");
static const Keyword NULL = const Keyword("null", "NULL");
static const Keyword OF = const Keyword("of", "OF", isPseudo: true);
static const Keyword ON = const Keyword("on", "ON", isPseudo: true);
static const Keyword OPERATOR =
const Keyword("operator", "OPERATOR", isBuiltIn: true);
static const Keyword OUT = const Keyword("out", "OUT", isPseudo: true);
static const Keyword PART =
const Keyword("part", "PART", isBuiltIn: true, isTopLevelKeyword: true);
static const Keyword PATCH = const Keyword("patch", "PATCH", isPseudo: true);
static const Keyword REQUIRED =
const Keyword("required", "REQUIRED", isBuiltIn: true, isModifier: true);
static const Keyword RETHROW = const Keyword("rethrow", "RETHROW");
static const Keyword RETURN = const Keyword("return", "RETURN");
static const Keyword SET = const Keyword("set", "SET", isBuiltIn: true);
static const Keyword SHOW = const Keyword("show", "SHOW", isPseudo: true);
static const Keyword SOURCE =
const Keyword("source", "SOURCE", isPseudo: true);
static const Keyword STATIC =
const Keyword("static", "STATIC", isBuiltIn: true, isModifier: true);
static const Keyword SUPER = const Keyword("super", "SUPER");
static const Keyword SWITCH = const Keyword("switch", "SWITCH");
static const Keyword SYNC = const Keyword("sync", "SYNC", isPseudo: true);
static const Keyword THIS = const Keyword("this", "THIS");
static const Keyword THROW = const Keyword("throw", "THROW");
static const Keyword TRUE = const Keyword("true", "TRUE");
static const Keyword TRY = const Keyword("try", "TRY");
static const Keyword TYPEDEF = const Keyword("typedef", "TYPEDEF",
isBuiltIn: true, isTopLevelKeyword: true);
static const Keyword VAR = const Keyword("var", "VAR", isModifier: true);
static const Keyword VOID = const Keyword("void", "VOID");
static const Keyword WHILE = const Keyword("while", "WHILE");
static const Keyword WITH = const Keyword("with", "WITH");
static const Keyword YIELD = const Keyword("yield", "YIELD", isPseudo: true);
static const List<Keyword> values = const <Keyword>[
ABSTRACT,
AS,
ASSERT,
ASYNC,
AWAIT,
BREAK,
CASE,
CATCH,
CLASS,
CONST,
CONTINUE,
COVARIANT,
DEFAULT,
DEFERRED,
DO,
DYNAMIC,
ELSE,
ENUM,
EXPORT,
EXTENDS,
EXTENSION,
EXTERNAL,
FACTORY,
FALSE,
FINAL,
FINALLY,
FOR,
FUNCTION,
GET,
HIDE,
IF,
IMPLEMENTS,
IMPORT,
IN,
INOUT,
INTERFACE,
IS,
LATE,
LIBRARY,
MIXIN,
NATIVE,
NEW,
NULL,
OF,
ON,
OPERATOR,
OUT,
PART,
PATCH,
REQUIRED,
RETHROW,
RETURN,
SET,
SHOW,
SOURCE,
STATIC,
SUPER,
SWITCH,
SYNC,
THIS,
THROW,
TRUE,
TRY,
TYPEDEF,
VAR,
VOID,
WHILE,
WITH,
YIELD,
];
/**
* A table mapping the lexemes of keywords to the corresponding keyword.
*/
static final Map<String, Keyword> keywords = _createKeywordMap();
/**
* A flag indicating whether the keyword is "built-in" identifier.
*/
@override
final bool isBuiltIn;
@override
final bool isPseudo;
/**
* Initialize a newly created keyword.
*/
const Keyword(String lexeme, String name,
{this.isBuiltIn: false,
bool isModifier: false,
this.isPseudo: false,
bool isTopLevelKeyword: false,
int precedence: NO_PRECEDENCE})
: super(lexeme, name, precedence, KEYWORD_TOKEN,
isModifier: isModifier, isTopLevelKeyword: isTopLevelKeyword);
bool get isBuiltInOrPseudo => isBuiltIn || isPseudo;
/**
* A flag indicating whether the keyword is "built-in" identifier.
* This method exists for backward compatibility and will be removed.
* Use [isBuiltIn] instead.
*/
@deprecated
bool get isPseudoKeyword => isBuiltIn; // TODO (danrubel): remove this
/**
* The name of the keyword type.
*/
String get name => lexeme.toUpperCase();
/**
* The lexeme for the keyword.
*
* Deprecated - use [lexeme] instead.
*/
@deprecated
String get syntax => lexeme;
@override
String toString() => name;
/**
* Create a table mapping the lexemes of keywords to the corresponding keyword
* and return the table that was created.
*/
static Map<String, Keyword> _createKeywordMap() {
LinkedHashMap<String, Keyword> result =
new LinkedHashMap<String, Keyword>();
for (Keyword keyword in values) {
result[keyword.lexeme] = keyword;
}
return result;
}
}
/**
* A token representing a keyword in the language.
*/
class KeywordToken extends SimpleToken {
@override
final Keyword keyword;
/**
* Initialize a newly created token to represent the given [keyword] at the
* given [offset].
*/
KeywordToken(this.keyword, int offset, [CommentToken precedingComment])
: super(keyword, offset, precedingComment);
@override
Token copy() =>
new KeywordToken(keyword, offset, copyComments(precedingComments));
@override
bool get isIdentifier => keyword.isPseudo || keyword.isBuiltIn;
@override
bool get isKeyword => true;
@override
bool get isKeywordOrIdentifier => true;
@override
Object value() => keyword;
}
/**
* A token that was scanned from the input. Each token knows which tokens
* precede and follow it, acting as a link in a doubly linked list of tokens.
*/
class SimpleToken implements Token {
/**
* The type of the token.
*/
@override
final TokenType type;
/**
* The offset from the beginning of the file to the first character in the
* token.
*/
@override
int offset = 0;
/**
* The previous token in the token stream.
*/
@override
Token previous;
@override
Token next;
/**
* The first comment in the list of comments that precede this token.
*/
CommentToken _precedingComment;
/**
* Initialize a newly created token to have the given [type] and [offset].
*/
SimpleToken(this.type, this.offset, [this._precedingComment]) {
_setCommentParent(_precedingComment);
}
@override
int get charCount => length;
@override
int get charOffset => offset;
@override
int get charEnd => end;
@override
Token get beforeSynthetic => null;
@override
set beforeSynthetic(Token previous) {
// ignored
}
@override
int get end => offset + length;
@override
Token get endGroup => null;
@override
bool get isEof => type == TokenType.EOF;
@override
bool get isIdentifier => false;
@override
bool get isKeyword => false;
@override
bool get isKeywordOrIdentifier => isIdentifier;
@override
bool get isModifier => type.isModifier;
@override
bool get isOperator => type.isOperator;
@override
bool get isSynthetic => length == 0;
@override
bool get isTopLevelKeyword => type.isTopLevelKeyword;
@override
bool get isUserDefinableOperator => type.isUserDefinableOperator;
@override
Keyword get keyword => null;
@override
int get kind => type.kind;
@override
int get length => lexeme.length;
@override
String get lexeme => type.lexeme;
@override
CommentToken get precedingComments => _precedingComment;
void set precedingComments(CommentToken comment) {
_precedingComment = comment;
_setCommentParent(_precedingComment);
}
@override
String get stringValue => type.stringValue;
@override
Token copy() =>
new SimpleToken(type, offset, copyComments(precedingComments));
@override
Token copyComments(Token token) {
if (token == null) {
return null;
}
Token head = token.copy();
Token tail = head;
token = token.next;
while (token != null) {
tail = tail.setNext(token.copy());
token = token.next;
}
return head;
}
@override
bool matchesAny(List<TokenType> types) {
for (TokenType type in types) {
if (this.type == type) {
return true;
}
}
return false;
}
@override
Token setNext(Token token) {
next = token;
token.previous = this;
token.beforeSynthetic = this;
return token;
}
@override
Token setNextWithoutSettingPrevious(Token token) {
next = token;
return token;
}
@override
String toString() => lexeme;
@override
Object value() => lexeme;
/**
* Sets the `parent` property to `this` for the given [comment] and all the
* next tokens.
*/
void _setCommentParent(CommentToken comment) {
while (comment != null) {
comment.parent = this;
comment = comment.next;
}
}
}
/**
* A token whose value is independent of it's type.
*/
class StringToken extends SimpleToken {
/**
* The lexeme represented by this token.
*/
String _value;
/**
* Initialize a newly created token to represent a token of the given [type]
* with the given [value] at the given [offset].
*/
StringToken(TokenType type, String value, int offset,
[CommentToken precedingComment])
: super(type, offset, precedingComment) {
this._value = StringUtilities.intern(value);
}
@override
bool get isIdentifier => identical(kind, IDENTIFIER_TOKEN);
@override
String get lexeme => _value;
@override
Token copy() =>
new StringToken(type, _value, offset, copyComments(precedingComments));
@override
String value() => _value;
}
/**
* A synthetic begin token.
*/
class SyntheticBeginToken extends BeginToken {
/**
* Initialize a newly created token to have the given [type] at the given
* [offset].
*/
SyntheticBeginToken(TokenType type, int offset,
[CommentToken precedingComment])
: super(type, offset, precedingComment);
@override
Token copy() =>
new SyntheticBeginToken(type, offset, copyComments(precedingComments));
@override
bool get isSynthetic => true;
@override
int get length => 0;
}
/**
* A synthetic keyword token.
*/
class SyntheticKeywordToken extends KeywordToken {
/**
* Initialize a newly created token to represent the given [keyword] at the
* given [offset].
*/
SyntheticKeywordToken(Keyword keyword, int offset) : super(keyword, offset);
@override
int get length => 0;
@override
Token copy() => new SyntheticKeywordToken(keyword, offset);
}
/**
* A token whose value is independent of it's type.
*/
class SyntheticStringToken extends StringToken {
final int _length;
/**
* Initialize a newly created token to represent a token of the given [type]
* with the given [value] at the given [offset]. If the [length] is
* not specified, then it defaults to the length of [value].
*/
SyntheticStringToken(TokenType type, String value, int offset, [this._length])
: super(type, value, offset);
@override
bool get isSynthetic => true;
@override
int get length => _length ?? super.length;
@override
Token copy() => new SyntheticStringToken(type, _value, offset, _length);
}
/**
* A synthetic token.
*/
class SyntheticToken extends SimpleToken {
SyntheticToken(TokenType type, int offset) : super(type, offset);
@override
Token beforeSynthetic;
@override
bool get isSynthetic => true;
@override
int get length => 0;
@override
Token copy() => new SyntheticToken(type, offset);
}
/**
* A token that was scanned from the input. Each token knows which tokens
* precede and follow it, acting as a link in a doubly linked list of tokens.
*
* Clients may not extend, implement or mix-in this class.
*/
abstract class Token implements SyntacticEntity {
/**
* Initialize a newly created token to have the given [type] and [offset].
*/
factory Token(TokenType type, int offset, [CommentToken preceedingComment]) =
SimpleToken;
/**
* Initialize a newly created end-of-file token to have the given [offset].
*/
factory Token.eof(int offset, [CommentToken precedingComments]) {
Token eof = new SimpleToken(TokenType.EOF, offset, precedingComments);
// EOF points to itself so there's always infinite look-ahead.
eof.previous = eof;
eof.next = eof;
return eof;
}
/**
* The number of characters parsed by this token.
*/
int get charCount;
/**
* The character offset of the start of this token within the source text.
*/
int get charOffset;
/**
* The character offset of the end of this token within the source text.
*/
int get charEnd;
/**
* The token before this synthetic token,
* or `null` if this is not a synthetic `)`, `]`, `}`, or `>` token.
*/
Token get beforeSynthetic;
/**
* Set token before this synthetic `)`, `]`, `}`, or `>` token,
* and ignored otherwise.
*/
set beforeSynthetic(Token previous);
@override
int get end;
/**
* The token that corresponds to this token, or `null` if this token is not
* the first of a pair of matching tokens (such as parentheses).
*/
Token get endGroup => null;
/**
* Return `true` if this token represents an end of file.
*/
bool get isEof;
/**
* True if this token is an identifier. Some keywords allowed as identifiers,
* see implementation in [KeywordToken].
*/
bool get isIdentifier;
/**
* True if this token is a keyword. Some keywords allowed as identifiers,
* see implementation in [KeywordToken].
*/
bool get isKeyword;
/**
* True if this token is a keyword or an identifier.
*/
bool get isKeywordOrIdentifier;
/**
* Return `true` if this token is a modifier such as `abstract` or `const`.
*/
bool get isModifier;
/**
* Return `true` if this token represents an operator.
*/
bool get isOperator;
/**
* Return `true` if this token is a synthetic token. A synthetic token is a
* token that was introduced by the parser in order to recover from an error
* in the code.
*/
bool get isSynthetic;
/**
* Return `true` if this token is a keyword starting a top level declaration
* such as `class`, `enum`, `import`, etc.
*/
bool get isTopLevelKeyword;
/**
* Return `true` if this token represents an operator that can be defined by
* users.
*/
bool get isUserDefinableOperator;
/**
* Return the keyword, if a keyword token, or `null` otherwise.
*/
Keyword get keyword;
/**
* The kind enum of this token as determined by its [type].
*/
int get kind;
@override
int get length;
/**
* Return the lexeme that represents this token.
*
* For [StringToken]s the [lexeme] includes the quotes, explicit escapes, etc.
*/
String get lexeme;
/**
* Return the next token in the token stream.
*/
Token get next;
/**
* Return the next token in the token stream.
*/
void set next(Token next);
@override
int get offset;
/**
* Set the offset from the beginning of the file to the first character in
* the token to the given [offset].
*/
void set offset(int offset);
/**
* Return the first comment in the list of comments that precede this token,
* or `null` if there are no comments preceding this token. Additional
* comments can be reached by following the token stream using [next] until
* `null` is returned.
*
* For example, if the original contents were `/* one */ /* two */ id`, then
* the first preceding comment token will have a lexeme of `/* one */` and
* the next comment token will have a lexeme of `/* two */`.
*/
Token get precedingComments;
/**
* Return the previous token in the token stream.
*/
Token get previous;
/**
* Set the previous token in the token stream to the given [token].
*/
void set previous(Token token);
/**
* For symbol and keyword tokens, returns the string value represented by this
* token. For [StringToken]s this method returns [:null:].
*
* For [SymbolToken]s and [KeywordToken]s, the string value is a compile-time
* constant originating in the [TokenType] or in the [Keyword] instance.
* This allows testing for keywords and symbols using [:identical:], e.g.,
* [:identical('class', token.value):].
*
* Note that returning [:null:] for string tokens is important to identify
* symbols and keywords, we cannot use [lexeme] instead. The string literal
* "$a($b"
* produces ..., SymbolToken($), StringToken(a), StringToken((), ...
*
* After parsing the identifier 'a', the parser tests for a function
* declaration using [:identical(next.stringValue, '('):], which (rightfully)
* returns false because stringValue returns [:null:].
*/
String get stringValue;
/**
* Return the type of the token.
*/
TokenType get type;
/**
* Return a newly created token that is a copy of this tokens
* including any [preceedingComment] tokens,
* but that is not a part of any token stream.
*/
Token copy();
/**
* Copy a linked list of comment tokens identical to the given comment tokens.
*/
Token copyComments(Token token);
/**
* Return `true` if this token has any one of the given [types].
*/
bool matchesAny(List<TokenType> types);
/**
* Set the next token in the token stream to the given [token]. This has the
* side-effect of setting this token to be the previous token for the given
* token. Return the token that was passed in.
*/
Token setNext(Token token);
/**
* Set the next token in the token stream to the given token without changing
* which token is the previous token for the given token. Return the token
* that was passed in.
*/
Token setNextWithoutSettingPrevious(Token token);
/**
* Returns a textual representation of this token to be used for debugging
* purposes. The resulting string might contain information about the
* structure of the token, for example 'StringToken(foo)' for the identifier
* token 'foo'.
*
* Use [lexeme] for the text actually parsed by the token.
*/
@override
String toString();
/**
* Return the value of this token. For keyword tokens, this is the keyword
* associated with the token, for other tokens it is the lexeme associated
* with the token.
*/
Object value();
/**
* Compare the given [tokens] to find the token that appears first in the
* source being parsed. That is, return the left-most of all of the tokens.
* The list must be non-`null`, but the elements of the list are allowed to be
* `null`. Return the token with the smallest offset, or `null` if the list is
* empty or if all of the elements of the list are `null`.
*/
static Token lexicallyFirst(List<Token> tokens) {
Token first = null;
int offset = -1;
int length = tokens.length;
for (int i = 0; i < length; i++) {
Token token = tokens[i];
if (token != null && (offset < 0 || token.offset < offset)) {
first = token;
offset = token.offset;
}
}
return first;
}
}
/**
* The classes (or groups) of tokens with a similar use.
*/
class TokenClass {
/**
* A value used to indicate that the token type is not part of any specific
* class of token.
*/
static const TokenClass NO_CLASS = const TokenClass('NO_CLASS');
/**
* A value used to indicate that the token type is an additive operator.
*/
static const TokenClass ADDITIVE_OPERATOR =
const TokenClass('ADDITIVE_OPERATOR', ADDITIVE_PRECEDENCE);
/**
* A value used to indicate that the token type is an assignment operator.
*/
static const TokenClass ASSIGNMENT_OPERATOR =
const TokenClass('ASSIGNMENT_OPERATOR', ASSIGNMENT_PRECEDENCE);
/**
* A value used to indicate that the token type is a bitwise-and operator.
*/
static const TokenClass BITWISE_AND_OPERATOR =
const TokenClass('BITWISE_AND_OPERATOR', BITWISE_AND_PRECEDENCE);
/**
* A value used to indicate that the token type is a bitwise-or operator.
*/
static const TokenClass BITWISE_OR_OPERATOR =
const TokenClass('BITWISE_OR_OPERATOR', BITWISE_OR_PRECEDENCE);
/**
* A value used to indicate that the token type is a bitwise-xor operator.
*/
static const TokenClass BITWISE_XOR_OPERATOR =
const TokenClass('BITWISE_XOR_OPERATOR', BITWISE_XOR_PRECEDENCE);
/**
* A value used to indicate that the token type is a cascade operator.
*/
static const TokenClass CASCADE_OPERATOR =
const TokenClass('CASCADE_OPERATOR', CASCADE_PRECEDENCE);
/**
* A value used to indicate that the token type is a conditional operator.
*/
static const TokenClass CONDITIONAL_OPERATOR =
const TokenClass('CONDITIONAL_OPERATOR', CONDITIONAL_PRECEDENCE);
/**
* A value used to indicate that the token type is an equality operator.
*/
static const TokenClass EQUALITY_OPERATOR =
const TokenClass('EQUALITY_OPERATOR', EQUALITY_PRECEDENCE);
/**
* A value used to indicate that the token type is an if-null operator.
*/
static const TokenClass IF_NULL_OPERATOR =
const TokenClass('IF_NULL_OPERATOR', IF_NULL_PRECEDENCE);
/**
* A value used to indicate that the token type is a logical-and operator.
*/
static const TokenClass LOGICAL_AND_OPERATOR =
const TokenClass('LOGICAL_AND_OPERATOR', LOGICAL_AND_PRECEDENCE);
/**
* A value used to indicate that the token type is a logical-or operator.
*/
static const TokenClass LOGICAL_OR_OPERATOR =
const TokenClass('LOGICAL_OR_OPERATOR', LOGICAL_OR_PRECEDENCE);
/**
* A value used to indicate that the token type is a multiplicative operator.
*/
static const TokenClass MULTIPLICATIVE_OPERATOR =
const TokenClass('MULTIPLICATIVE_OPERATOR', MULTIPLICATIVE_PRECEDENCE);
/**
* A value used to indicate that the token type is a relational operator.
*/
static const TokenClass RELATIONAL_OPERATOR =
const TokenClass('RELATIONAL_OPERATOR', RELATIONAL_PRECEDENCE);
/**
* A value used to indicate that the token type is a shift operator.
*/
static const TokenClass SHIFT_OPERATOR =
const TokenClass('SHIFT_OPERATOR', SHIFT_PRECEDENCE);
/**
* A value used to indicate that the token type is a unary operator.
*/
static const TokenClass UNARY_POSTFIX_OPERATOR =
const TokenClass('UNARY_POSTFIX_OPERATOR', POSTFIX_PRECEDENCE);
/**
* A value used to indicate that the token type is a unary operator.
*/
static const TokenClass UNARY_PREFIX_OPERATOR =
const TokenClass('UNARY_PREFIX_OPERATOR', PREFIX_PRECEDENCE);
/**
* The name of the token class.
*/
final String name;
/**
* The precedence of tokens of this class, or `0` if the such tokens do not
* represent an operator.
*/
final int precedence;
/**
* Initialize a newly created class of tokens to have the given [name] and
* [precedence].
*/
const TokenClass(this.name, [this.precedence = NO_PRECEDENCE]);
@override
String toString() => name;
}
/**
* The types of tokens that can be returned by the scanner.
*
* Clients may not extend, implement or mix-in this class.
*/
class TokenType {
/**
* The type of the token that marks the start or end of the input.
*/
static const TokenType EOF =
const TokenType('', 'EOF', NO_PRECEDENCE, EOF_TOKEN);
static const TokenType DOUBLE = const TokenType(
'double', 'DOUBLE', NO_PRECEDENCE, DOUBLE_TOKEN,
stringValue: null);
static const TokenType HEXADECIMAL = const TokenType(
'hexadecimal', 'HEXADECIMAL', NO_PRECEDENCE, HEXADECIMAL_TOKEN,
stringValue: null);
static const TokenType IDENTIFIER = const TokenType(
'identifier', 'IDENTIFIER', NO_PRECEDENCE, IDENTIFIER_TOKEN,
stringValue: null);
static const TokenType INT = const TokenType(
'int', 'INT', NO_PRECEDENCE, INT_TOKEN,
stringValue: null);
static const TokenType MULTI_LINE_COMMENT = const TokenType(
'comment', 'MULTI_LINE_COMMENT', NO_PRECEDENCE, COMMENT_TOKEN,
stringValue: null);
static const TokenType SCRIPT_TAG =
const TokenType('script', 'SCRIPT_TAG', NO_PRECEDENCE, SCRIPT_TOKEN);
static const TokenType SINGLE_LINE_COMMENT = const TokenType(
'comment', 'SINGLE_LINE_COMMENT', NO_PRECEDENCE, COMMENT_TOKEN,
stringValue: null);
static const TokenType STRING = const TokenType(
'string', 'STRING', NO_PRECEDENCE, STRING_TOKEN,
stringValue: null);
static const TokenType AMPERSAND = const TokenType(
'&', 'AMPERSAND', BITWISE_AND_PRECEDENCE, AMPERSAND_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType AMPERSAND_AMPERSAND = const TokenType('&&',
'AMPERSAND_AMPERSAND', LOGICAL_AND_PRECEDENCE, AMPERSAND_AMPERSAND_TOKEN,
isOperator: true);
// This is not yet part of the language and not supported by fasta
static const TokenType AMPERSAND_AMPERSAND_EQ = const TokenType(
'&&=',
'AMPERSAND_AMPERSAND_EQ',
ASSIGNMENT_PRECEDENCE,
AMPERSAND_AMPERSAND_EQ_TOKEN,
isOperator: true);
static const TokenType AMPERSAND_EQ = const TokenType(
'&=', 'AMPERSAND_EQ', ASSIGNMENT_PRECEDENCE, AMPERSAND_EQ_TOKEN,
isOperator: true);
static const TokenType AT =
const TokenType('@', 'AT', NO_PRECEDENCE, AT_TOKEN);
static const TokenType BANG = const TokenType(
'!', 'BANG', PREFIX_PRECEDENCE, BANG_TOKEN,
isOperator: true);
static const TokenType BANG_EQ = const TokenType(
'!=', 'BANG_EQ', EQUALITY_PRECEDENCE, BANG_EQ_TOKEN,
isOperator: true);
static const TokenType BANG_EQ_EQ = const TokenType(
'!==', 'BANG_EQ_EQ', EQUALITY_PRECEDENCE, BANG_EQ_EQ_TOKEN);
static const TokenType BAR = const TokenType(
'|', 'BAR', BITWISE_OR_PRECEDENCE, BAR_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType BAR_BAR = const TokenType(
'||', 'BAR_BAR', LOGICAL_OR_PRECEDENCE, BAR_BAR_TOKEN,
isOperator: true);
// This is not yet part of the language and not supported by fasta
static const TokenType BAR_BAR_EQ = const TokenType(
'||=', 'BAR_BAR_EQ', ASSIGNMENT_PRECEDENCE, BAR_BAR_EQ_TOKEN,
isOperator: true);
static const TokenType BAR_EQ = const TokenType(
'|=', 'BAR_EQ', ASSIGNMENT_PRECEDENCE, BAR_EQ_TOKEN,
isOperator: true);
static const TokenType COLON =
const TokenType(':', 'COLON', NO_PRECEDENCE, COLON_TOKEN);
static const TokenType COMMA =
const TokenType(',', 'COMMA', NO_PRECEDENCE, COMMA_TOKEN);
static const TokenType CARET = const TokenType(
'^', 'CARET', BITWISE_XOR_PRECEDENCE, CARET_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType CARET_EQ = const TokenType(
'^=', 'CARET_EQ', ASSIGNMENT_PRECEDENCE, CARET_EQ_TOKEN,
isOperator: true);
static const TokenType CLOSE_CURLY_BRACKET = const TokenType(
'}', 'CLOSE_CURLY_BRACKET', NO_PRECEDENCE, CLOSE_CURLY_BRACKET_TOKEN);
static const TokenType CLOSE_PAREN =
const TokenType(')', 'CLOSE_PAREN', NO_PRECEDENCE, CLOSE_PAREN_TOKEN);
static const TokenType CLOSE_SQUARE_BRACKET = const TokenType(
']', 'CLOSE_SQUARE_BRACKET', NO_PRECEDENCE, CLOSE_SQUARE_BRACKET_TOKEN);
static const TokenType EQ = const TokenType(
'=', 'EQ', ASSIGNMENT_PRECEDENCE, EQ_TOKEN,
isOperator: true);
static const TokenType EQ_EQ = const TokenType(
'==', 'EQ_EQ', EQUALITY_PRECEDENCE, EQ_EQ_TOKEN,
isOperator: true, isUserDefinableOperator: true);
/// The `===` operator is not supported in the Dart language
/// but is parsed as such by the scanner to support better recovery
/// when a JavaScript code snippet is pasted into a Dart file.
static const TokenType EQ_EQ_EQ =
const TokenType('===', 'EQ_EQ_EQ', EQUALITY_PRECEDENCE, EQ_EQ_EQ_TOKEN);
static const TokenType FUNCTION =
const TokenType('=>', 'FUNCTION', NO_PRECEDENCE, FUNCTION_TOKEN);
static const TokenType GT = const TokenType(
'>', 'GT', RELATIONAL_PRECEDENCE, GT_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType GT_EQ = const TokenType(
'>=', 'GT_EQ', RELATIONAL_PRECEDENCE, GT_EQ_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType GT_GT = const TokenType(
'>>', 'GT_GT', SHIFT_PRECEDENCE, GT_GT_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType GT_GT_EQ = const TokenType(
'>>=', 'GT_GT_EQ', ASSIGNMENT_PRECEDENCE, GT_GT_EQ_TOKEN,
isOperator: true);
static const TokenType GT_GT_GT = const TokenType(
'>>>', 'GT_GT_GT', SHIFT_PRECEDENCE, GT_GT_GT_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType GT_GT_GT_EQ = const TokenType(
'>>>=', 'GT_GT_GT_EQ', ASSIGNMENT_PRECEDENCE, GT_GT_GT_EQ_TOKEN,
isOperator: true);
static const TokenType HASH =
const TokenType('#', 'HASH', NO_PRECEDENCE, HASH_TOKEN);
static const TokenType INDEX = const TokenType(
'[]', 'INDEX', SELECTOR_PRECEDENCE, INDEX_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType INDEX_EQ = const TokenType(
'[]=', 'INDEX_EQ', NO_PRECEDENCE, INDEX_EQ_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType LT = const TokenType(
'<', 'LT', RELATIONAL_PRECEDENCE, LT_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType LT_EQ = const TokenType(
'<=', 'LT_EQ', RELATIONAL_PRECEDENCE, LT_EQ_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType LT_LT = const TokenType(
'<<', 'LT_LT', SHIFT_PRECEDENCE, LT_LT_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType LT_LT_EQ = const TokenType(
'<<=', 'LT_LT_EQ', ASSIGNMENT_PRECEDENCE, LT_LT_EQ_TOKEN,
isOperator: true);
static const TokenType MINUS = const TokenType(
'-', 'MINUS', ADDITIVE_PRECEDENCE, MINUS_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType MINUS_EQ = const TokenType(
'-=', 'MINUS_EQ', ASSIGNMENT_PRECEDENCE, MINUS_EQ_TOKEN,
isOperator: true);
static const TokenType MINUS_MINUS = const TokenType(
'--', 'MINUS_MINUS', POSTFIX_PRECEDENCE, MINUS_MINUS_TOKEN,
isOperator: true);
static const TokenType OPEN_CURLY_BRACKET = const TokenType(
'{', 'OPEN_CURLY_BRACKET', NO_PRECEDENCE, OPEN_CURLY_BRACKET_TOKEN);
static const TokenType OPEN_PAREN =
const TokenType('(', 'OPEN_PAREN', SELECTOR_PRECEDENCE, OPEN_PAREN_TOKEN);
static const TokenType OPEN_SQUARE_BRACKET = const TokenType('[',
'OPEN_SQUARE_BRACKET', SELECTOR_PRECEDENCE, OPEN_SQUARE_BRACKET_TOKEN);
static const TokenType PERCENT = const TokenType(
'%', 'PERCENT', MULTIPLICATIVE_PRECEDENCE, PERCENT_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType PERCENT_EQ = const TokenType(
'%=', 'PERCENT_EQ', ASSIGNMENT_PRECEDENCE, PERCENT_EQ_TOKEN,
isOperator: true);
static const TokenType PERIOD =
const TokenType('.', 'PERIOD', SELECTOR_PRECEDENCE, PERIOD_TOKEN);
static const TokenType PERIOD_PERIOD = const TokenType(
'..', 'PERIOD_PERIOD', CASCADE_PRECEDENCE, PERIOD_PERIOD_TOKEN,
isOperator: true);
static const TokenType PLUS = const TokenType(
'+', 'PLUS', ADDITIVE_PRECEDENCE, PLUS_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType PLUS_EQ = const TokenType(
'+=', 'PLUS_EQ', ASSIGNMENT_PRECEDENCE, PLUS_EQ_TOKEN,
isOperator: true);
static const TokenType PLUS_PLUS = const TokenType(
'++', 'PLUS_PLUS', POSTFIX_PRECEDENCE, PLUS_PLUS_TOKEN,
isOperator: true);
static const TokenType QUESTION = const TokenType(
'?', 'QUESTION', CONDITIONAL_PRECEDENCE, QUESTION_TOKEN,
isOperator: true);
static const TokenType QUESTION_PERIOD = const TokenType(
'?.', 'QUESTION_PERIOD', SELECTOR_PRECEDENCE, QUESTION_PERIOD_TOKEN,
isOperator: true);
static const TokenType QUESTION_QUESTION = const TokenType(
'??', 'QUESTION_QUESTION', IF_NULL_PRECEDENCE, QUESTION_QUESTION_TOKEN,
isOperator: true);
static const TokenType QUESTION_QUESTION_EQ = const TokenType('??=',
'QUESTION_QUESTION_EQ', ASSIGNMENT_PRECEDENCE, QUESTION_QUESTION_EQ_TOKEN,
isOperator: true);
static const TokenType SEMICOLON =
const TokenType(';', 'SEMICOLON', NO_PRECEDENCE, SEMICOLON_TOKEN);
static const TokenType SLASH = const TokenType(
'/', 'SLASH', MULTIPLICATIVE_PRECEDENCE, SLASH_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType SLASH_EQ = const TokenType(
'/=', 'SLASH_EQ', ASSIGNMENT_PRECEDENCE, SLASH_EQ_TOKEN,
isOperator: true);
static const TokenType STAR = const TokenType(
'*', 'STAR', MULTIPLICATIVE_PRECEDENCE, STAR_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType STAR_EQ = const TokenType(
'*=', 'STAR_EQ', ASSIGNMENT_PRECEDENCE, STAR_EQ_TOKEN,
isOperator: true);
static const TokenType STRING_INTERPOLATION_EXPRESSION = const TokenType(
'\${',
'STRING_INTERPOLATION_EXPRESSION',
NO_PRECEDENCE,
STRING_INTERPOLATION_TOKEN);
static const TokenType STRING_INTERPOLATION_IDENTIFIER = const TokenType(
'\$',
'STRING_INTERPOLATION_IDENTIFIER',
NO_PRECEDENCE,
STRING_INTERPOLATION_IDENTIFIER_TOKEN);
static const TokenType TILDE = const TokenType(
'~', 'TILDE', PREFIX_PRECEDENCE, TILDE_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType TILDE_SLASH = const TokenType(
'~/', 'TILDE_SLASH', MULTIPLICATIVE_PRECEDENCE, TILDE_SLASH_TOKEN,
isOperator: true, isUserDefinableOperator: true);
static const TokenType TILDE_SLASH_EQ = const TokenType(
'~/=', 'TILDE_SLASH_EQ', ASSIGNMENT_PRECEDENCE, TILDE_SLASH_EQ_TOKEN,
isOperator: true);
static const TokenType BACKPING =
const TokenType('`', 'BACKPING', NO_PRECEDENCE, BACKPING_TOKEN);
static const TokenType BACKSLASH =
const TokenType('\\', 'BACKSLASH', NO_PRECEDENCE, BACKSLASH_TOKEN);
static const TokenType PERIOD_PERIOD_PERIOD = const TokenType(
'...', 'PERIOD_PERIOD_PERIOD', NO_PRECEDENCE, PERIOD_PERIOD_PERIOD_TOKEN);
static const TokenType PERIOD_PERIOD_PERIOD_QUESTION = const TokenType(
'...?',
'PERIOD_PERIOD_PERIOD_QUESTION',
NO_PRECEDENCE,
PERIOD_PERIOD_PERIOD_QUESTION_TOKEN);
static const TokenType QUESTION_PERIOD_OPEN_SQUARE_BRACKET = const TokenType(
'?.[',
'QUESTION_PERIOD_OPEN_SQUARE_BRACKET',
SELECTOR_PRECEDENCE,
QUESTION_PERIOD_OPEN_SQUARE_BRACKET_TOKEN);
static const TokenType QUESTION_PERIOD_PERIOD = const TokenType(
'?..',
'QUESTION_PERIOD_PERIOD',
CASCADE_PRECEDENCE,
QUESTION_PERIOD_PERIOD_TOKEN);
static const TokenType AS = Keyword.AS;
static const TokenType IS = Keyword.IS;
/**
* Token type used by error tokens.
*/
static const TokenType BAD_INPUT = const TokenType(
'malformed input', 'BAD_INPUT', NO_PRECEDENCE, BAD_INPUT_TOKEN,
stringValue: null);
/**
* Token type used by synthetic tokens that are created during parser
* recovery (non-analyzer use case).
*/
static const TokenType RECOVERY = const TokenType(
'recovery', 'RECOVERY', NO_PRECEDENCE, RECOVERY_TOKEN,
stringValue: null);
// TODO(danrubel): "all" is misleading
// because this list does not include all TokenType instances.
static const List<TokenType> all = const <TokenType>[
TokenType.EOF,
TokenType.DOUBLE,
TokenType.HEXADECIMAL,
TokenType.IDENTIFIER,
TokenType.INT,
TokenType.MULTI_LINE_COMMENT,
TokenType.SCRIPT_TAG,
TokenType.SINGLE_LINE_COMMENT,
TokenType.STRING,
TokenType.AMPERSAND,
TokenType.AMPERSAND_AMPERSAND,
TokenType.AMPERSAND_EQ,
TokenType.AT,
TokenType.BANG,
TokenType.BANG_EQ,
TokenType.BAR,
TokenType.BAR_BAR,
TokenType.BAR_EQ,
TokenType.COLON,
TokenType.COMMA,
TokenType.CARET,
TokenType.CARET_EQ,
TokenType.CLOSE_CURLY_BRACKET,
TokenType.CLOSE_PAREN,
TokenType.CLOSE_SQUARE_BRACKET,
TokenType.EQ,
TokenType.EQ_EQ,
TokenType.FUNCTION,
TokenType.GT,
TokenType.GT_EQ,
TokenType.GT_GT,
TokenType.GT_GT_EQ,
TokenType.HASH,
TokenType.INDEX,
TokenType.INDEX_EQ,
TokenType.LT,
TokenType.LT_EQ,
TokenType.LT_LT,
TokenType.LT_LT_EQ,
TokenType.MINUS,
TokenType.MINUS_EQ,
TokenType.MINUS_MINUS,
TokenType.OPEN_CURLY_BRACKET,
TokenType.OPEN_PAREN,
TokenType.OPEN_SQUARE_BRACKET,
TokenType.PERCENT,
TokenType.PERCENT_EQ,
TokenType.PERIOD,
TokenType.PERIOD_PERIOD,
TokenType.PLUS,
TokenType.PLUS_EQ,
TokenType.PLUS_PLUS,
TokenType.QUESTION,
TokenType.QUESTION_PERIOD,
TokenType.QUESTION_QUESTION,
TokenType.QUESTION_QUESTION_EQ,
TokenType.SEMICOLON,
TokenType.SLASH,
TokenType.SLASH_EQ,
TokenType.STAR,
TokenType.STAR_EQ,
TokenType.STRING_INTERPOLATION_EXPRESSION,
TokenType.STRING_INTERPOLATION_IDENTIFIER,
TokenType.TILDE,
TokenType.TILDE_SLASH,
TokenType.TILDE_SLASH_EQ,
TokenType.BACKPING,
TokenType.BACKSLASH,
TokenType.PERIOD_PERIOD_PERIOD,
TokenType.PERIOD_PERIOD_PERIOD_QUESTION,
// TODO(danrubel): Should these be added to the "all" list?
//TokenType.IS,
//TokenType.AS,
// These are not yet part of the language and not supported by fasta
//TokenType.AMPERSAND_AMPERSAND_EQ,
//TokenType.BAR_BAR_EQ,
// Supported by fasta but not part of the language
//TokenType.BANG_EQ_EQ,
//TokenType.EQ_EQ_EQ,
// Used by synthetic tokens generated during recovery
//TokenType.BAD_INPUT,
//TokenType.RECOVERY,
];
final int kind;
/**
* `true` if this token type represents a modifier
* such as `abstract` or `const`.
*/
final bool isModifier;
/**
* `true` if this token type represents an operator.
*/
final bool isOperator;
/**
* `true` if this token type represents a keyword starting a top level
* declaration such as `class`, `enum`, `import`, etc.
*/
final bool isTopLevelKeyword;
/**
* `true` if this token type represents an operator
* that can be defined by users.
*/
final bool isUserDefinableOperator;
/**
* The lexeme that defines this type of token,
* or `null` if there is more than one possible lexeme for this type of token.
*/
final String lexeme;
/**
* The name of the token type.
*/
final String name;
/**
* The precedence of this type of token,
* or `0` if the token does not represent an operator.
*/
final int precedence;
/**
* See [Token.stringValue] for an explanation.
*/
final String stringValue;
const TokenType(this.lexeme, this.name, this.precedence, this.kind,
{this.isModifier: false,
this.isOperator: false,
this.isTopLevelKeyword: false,
this.isUserDefinableOperator: false,
String stringValue: 'unspecified'})
: this.stringValue = stringValue == 'unspecified' ? lexeme : stringValue;
/**
* Return `true` if this type of token represents an additive operator.
*/
bool get isAdditiveOperator => precedence == ADDITIVE_PRECEDENCE;
/**
* Return `true` if this type of token represents an assignment operator.
*/
bool get isAssignmentOperator => precedence == ASSIGNMENT_PRECEDENCE;
/**
* Return `true` if this type of token represents an associative operator. An
* associative operator is an operator for which the following equality is
* true: `(a * b) * c == a * (b * c)`. In other words, if the result of
* applying the operator to multiple operands does not depend on the order in
* which those applications occur.
*
* Note: This method considers the logical-and and logical-or operators to be
* associative, even though the order in which the application of those
* operators can have an effect because evaluation of the right-hand operand
* is conditional.
*/
bool get isAssociativeOperator =>
this == TokenType.AMPERSAND ||
this == TokenType.AMPERSAND_AMPERSAND ||
this == TokenType.BAR ||
this == TokenType.BAR_BAR ||
this == TokenType.CARET ||
this == TokenType.PLUS ||
this == TokenType.STAR;
/**
* A flag indicating whether the keyword is a "built-in" identifier.
*/
bool get isBuiltIn => false;
/**
* Return `true` if this type of token represents an equality operator.
*/
bool get isEqualityOperator =>
this == TokenType.BANG_EQ || this == TokenType.EQ_EQ;
/**
* Return `true` if this type of token represents an increment operator.
*/
bool get isIncrementOperator =>
this == TokenType.PLUS_PLUS || this == TokenType.MINUS_MINUS;
/**
* Return `true` if this type of token is a keyword.
*/
bool get isKeyword => kind == KEYWORD_TOKEN;
/**
* A flag indicating whether the keyword can be used as an identifier
* in some situations.
*/
bool get isPseudo => false;
/**
* Return `true` if this type of token represents a multiplicative operator.
*/
bool get isMultiplicativeOperator => precedence == MULTIPLICATIVE_PRECEDENCE;
/**
* Return `true` if this type of token represents a relational operator.
*/
bool get isRelationalOperator =>
this == TokenType.LT ||
this == TokenType.LT_EQ ||
this == TokenType.GT ||
this == TokenType.GT_EQ;
/**
* Return `true` if this type of token represents a shift operator.
*/
bool get isShiftOperator => precedence == SHIFT_PRECEDENCE;
/**
* Return `true` if this type of token represents a unary postfix operator.
*/
bool get isUnaryPostfixOperator => precedence == POSTFIX_PRECEDENCE;
/**
* Return `true` if this type of token represents a unary prefix operator.
*/
bool get isUnaryPrefixOperator =>
precedence == PREFIX_PRECEDENCE ||
this == TokenType.MINUS ||
this == TokenType.PLUS_PLUS ||
this == TokenType.MINUS_MINUS;
/**
* Return `true` if this type of token represents a selector operator
* (starting token of a selector).
*/
bool get isSelectorOperator => precedence == SELECTOR_PRECEDENCE;
@override
String toString() => name;
/**
* Use [lexeme] instead of this method
*/
@deprecated
String get value => lexeme;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/scanner/errors.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 '../base/errors.dart';
import '../fasta/fasta_codes.dart';
import '../fasta/scanner/error_token.dart';
import 'token.dart' show Token, TokenType;
import '../fasta/scanner/token_constants.dart';
/**
* The error codes used for errors detected by the scanner.
*/
class ScannerErrorCode extends ErrorCode {
/**
* Parameters:
* 0: the token that was expected but not found
*/
static const ScannerErrorCode EXPECTED_TOKEN =
const ScannerErrorCode('EXPECTED_TOKEN', "Expected to find '{0}'.");
/**
* Parameters:
* 0: the illegal character
*/
static const ScannerErrorCode ILLEGAL_CHARACTER =
const ScannerErrorCode('ILLEGAL_CHARACTER', "Illegal character '{0}'.");
static const ScannerErrorCode MISSING_DIGIT =
const ScannerErrorCode('MISSING_DIGIT', "Decimal digit expected.");
static const ScannerErrorCode MISSING_HEX_DIGIT = const ScannerErrorCode(
'MISSING_HEX_DIGIT', "Hexadecimal digit expected.");
static const ScannerErrorCode MISSING_IDENTIFIER =
const ScannerErrorCode('MISSING_IDENTIFIER', "Expected an identifier.");
static const ScannerErrorCode MISSING_QUOTE =
const ScannerErrorCode('MISSING_QUOTE', "Expected quote (' or \").");
/**
* Parameters:
* 0: the path of the file that cannot be read
*/
static const ScannerErrorCode UNABLE_GET_CONTENT = const ScannerErrorCode(
'UNABLE_GET_CONTENT', "Unable to get content of '{0}'.");
static const ScannerErrorCode UNEXPECTED_DOLLAR_IN_STRING =
const ScannerErrorCode(
'UNEXPECTED_DOLLAR_IN_STRING',
"A '\$' has special meaning inside a string, and must be followed by "
"an identifier or an expression in curly braces ({}).",
correction: "Try adding a backslash (\\) to escape the '\$'.");
/**
* Parameters:
* 0: the unsupported operator
*/
static const ScannerErrorCode UNSUPPORTED_OPERATOR = const ScannerErrorCode(
'UNSUPPORTED_OPERATOR', "The '{0}' operator is not supported.");
static const ScannerErrorCode UNTERMINATED_MULTI_LINE_COMMENT =
const ScannerErrorCode(
'UNTERMINATED_MULTI_LINE_COMMENT', "Unterminated multi-line comment.",
correction: "Try terminating the comment with '*/', or "
"removing any unbalanced occurrences of '/*'"
" (because comments nest in Dart).");
static const ScannerErrorCode UNTERMINATED_STRING_LITERAL =
const ScannerErrorCode(
'UNTERMINATED_STRING_LITERAL', "Unterminated string literal.");
/**
* Initialize a newly created error code to have the given [name]. The message
* associated with the error will be created from the given [message]
* template. The correction associated with the error will be created from the
* given [correction] template.
*/
const ScannerErrorCode(String name, String message, {String correction})
: super.temporary(name, message, correction: correction);
@override
ErrorSeverity get errorSeverity => ErrorSeverity.ERROR;
@override
ErrorType get type => ErrorType.SYNTACTIC_ERROR;
}
/**
* Used to report a scan error at the given offset.
* The [errorCode] is the error code indicating the nature of the error.
* The [arguments] are any arguments needed to complete the error message.
*/
typedef ReportError(
ScannerErrorCode errorCode, int offset, List<Object> arguments);
/**
* Translates the given error [token] into an analyzer error and reports it
* using [reportError].
*/
void translateErrorToken(ErrorToken token, ReportError reportError) {
int charOffset = token.charOffset;
// TODO(paulberry,ahe): why is endOffset sometimes null?
int endOffset = token.endOffset ?? charOffset;
void _makeError(ScannerErrorCode errorCode, List<Object> arguments) {
if (_isAtEnd(token, charOffset)) {
// Analyzer never generates an error message past the end of the input,
// since such an error would not be visible in an editor.
// TODO(paulberry,ahe): would it make sense to replicate this behavior
// in fasta, or move it elsewhere in analyzer?
charOffset--;
}
reportError(errorCode, charOffset, arguments);
}
Code<dynamic> errorCode = token.errorCode;
switch (errorCode.analyzerCodes?.first) {
case "UNTERMINATED_STRING_LITERAL":
// TODO(paulberry,ahe): Fasta reports the error location as the entire
// string; analyzer expects the end of the string.
reportError(
ScannerErrorCode.UNTERMINATED_STRING_LITERAL, endOffset - 1, null);
return;
case "UNTERMINATED_MULTI_LINE_COMMENT":
// TODO(paulberry,ahe): Fasta reports the error location as the entire
// comment; analyzer expects the end of the comment.
reportError(ScannerErrorCode.UNTERMINATED_MULTI_LINE_COMMENT,
endOffset - 1, null);
return;
case "MISSING_DIGIT":
// TODO(paulberry,ahe): Fasta reports the error location as the entire
// number; analyzer expects the end of the number.
charOffset = endOffset - 1;
return _makeError(ScannerErrorCode.MISSING_DIGIT, null);
case "MISSING_HEX_DIGIT":
// TODO(paulberry,ahe): Fasta reports the error location as the entire
// number; analyzer expects the end of the number.
charOffset = endOffset - 1;
return _makeError(ScannerErrorCode.MISSING_HEX_DIGIT, null);
case "ILLEGAL_CHARACTER":
return _makeError(ScannerErrorCode.ILLEGAL_CHARACTER, [token.character]);
case "UNSUPPORTED_OPERATOR":
return _makeError(ScannerErrorCode.UNSUPPORTED_OPERATOR,
[(token as UnsupportedOperator).token.lexeme]);
default:
if (errorCode == codeUnmatchedToken) {
charOffset = token.begin.endToken.charOffset;
TokenType type = token.begin?.type;
if (type == TokenType.OPEN_CURLY_BRACKET ||
type == TokenType.STRING_INTERPOLATION_EXPRESSION) {
return _makeError(ScannerErrorCode.EXPECTED_TOKEN, ['}']);
}
if (type == TokenType.OPEN_SQUARE_BRACKET ||
type == TokenType.QUESTION_PERIOD_OPEN_SQUARE_BRACKET) {
return _makeError(ScannerErrorCode.EXPECTED_TOKEN, [']']);
}
if (type == TokenType.OPEN_PAREN) {
return _makeError(ScannerErrorCode.EXPECTED_TOKEN, [')']);
}
if (type == TokenType.LT) {
return _makeError(ScannerErrorCode.EXPECTED_TOKEN, ['>']);
}
} else if (errorCode == codeUnexpectedDollarInString) {
return _makeError(ScannerErrorCode.MISSING_IDENTIFIER, null);
}
throw new UnimplementedError(
'$errorCode "${errorCode.analyzerCodes?.first}"');
}
}
/**
* Determines whether the given [charOffset], which came from the non-EOF token
* [token], represents the end of the input.
*/
bool _isAtEnd(Token token, int charOffset) {
while (true) {
// Skip to the next token.
token = token.next;
// If we've found an EOF token, its charOffset indicates where the end of
// the input is.
if (token.isEof) return token.charOffset == charOffset;
// If we've found a non-error token, then we know there is additional input
// text after [charOffset].
if (token.type.kind != BAD_INPUT_TOKEN) return false;
// Otherwise keep looking.
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/scanner/reader.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.
/**
* An object used by the scanner to read the characters to be scanned.
*/
abstract class CharacterReader {
/**
* The current offset relative to the beginning of the source. Return the
* initial offset if the scanner has not yet scanned the source code, and one
* (1) past the end of the source code if the entire source code has been
* scanned.
*/
int get offset;
/**
* Set the current offset relative to the beginning of the source to the given
* [offset]. The new offset must be between the initial offset and one (1)
* past the end of the source code.
*/
void set offset(int offset);
/**
* Advance the current position and return the character at the new current
* position.
*/
int advance();
/**
* Return the source to be scanned.
*/
String getContents();
/**
* Return the substring of the source code between the [start] offset and the
* modified current position. The current position is modified by adding the
* [endDelta], which is the number of characters after the current location to
* be included in the string, or the number of characters before the current
* location to be excluded if the offset is negative.
*/
String getString(int start, int endDelta);
/**
* Return the character at the current position without changing the current
* position.
*/
int peek();
}
/**
* A [CharacterReader] that reads characters from a character sequence.
*/
class CharSequenceReader implements CharacterReader {
/**
* The sequence from which characters will be read.
*/
final String _sequence;
/**
* The number of characters in the string.
*/
int _stringLength;
/**
* The index, relative to the string, of the next character to be read.
*/
int _charOffset;
/**
* Initialize a newly created reader to read the characters in the given
* [_sequence].
*/
CharSequenceReader(this._sequence) {
this._stringLength = _sequence.length;
this._charOffset = 0;
}
@override
int get offset => _charOffset - 1;
@override
void set offset(int offset) {
_charOffset = offset + 1;
}
@override
int advance() {
if (_charOffset >= _stringLength) {
return -1;
}
return _sequence.codeUnitAt(_charOffset++);
}
@override
String getContents() => _sequence;
@override
String getString(int start, int endDelta) =>
_sequence.substring(start, _charOffset + endDelta);
@override
int peek() {
if (_charOffset >= _stringLength) {
return -1;
}
return _sequence.codeUnitAt(_charOffset);
}
}
/**
* A [CharacterReader] that reads characters from a character sequence, but adds
* a delta when reporting the current character offset so that the character
* sequence can be a subsequence from a larger sequence.
*/
class SubSequenceReader extends CharSequenceReader {
/**
* The offset from the beginning of the file to the beginning of the source
* being scanned.
*/
final int _offsetDelta;
/**
* Initialize a newly created reader to read the characters in the given
* [sequence]. The [_offsetDelta] is the offset from the beginning of the file
* to the beginning of the source being scanned
*/
SubSequenceReader(String sequence, this._offsetDelta) : super(sequence);
@override
int get offset => _offsetDelta + super.offset;
@override
void set offset(int offset) {
super.offset = offset - _offsetDelta;
}
@override
String getContents() => super.getContents();
@override
String getString(int start, int endDelta) =>
super.getString(start - _offsetDelta, endDelta);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/mime.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.
/// Help for working with file format identifiers
/// such as `text/html` and `image/png`.
///
/// More details, including a list of types, are in the Wikipedia article
/// [Internet media type](http://en.wikipedia.org/wiki/Internet_media_type).
library mime;
export 'src/mime_multipart_transformer.dart';
export 'src/mime_shared.dart';
export 'src/mime_type.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/src/mime_type.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.
library mime.mime_type;
import 'default_extension_map.dart';
import 'magic_number.dart';
final MimeTypeResolver _globalResolver = MimeTypeResolver();
/// The maximum number of bytes needed, to match all default magic-numbers.
int get defaultMagicNumbersMaxLength => _globalResolver.magicNumbersMaxLength;
/// Extract the extension from [path] and use that for MIME-type lookup, using
/// the default extension map.
///
/// If no matching MIME-type was found, `null` is returned.
///
/// If [headerBytes] is present, a match for known magic-numbers will be
/// performed first. This allows the correct mime-type to be found, even though
/// a file have been saved using the wrong file-name extension. If less than
/// [defaultMagicNumbersMaxLength] bytes was provided, some magic-numbers won't
/// be matched against.
String lookupMimeType(String path, {List<int> headerBytes}) =>
_globalResolver.lookup(path, headerBytes: headerBytes);
/// Returns the extension for the given MIME type.
///
/// If there are multiple extensions for [mime], return the first occurrence in
/// the map. If there are no extensions for [mime], return [mime].
String extensionFromMime(String mime) {
mime = mime.toLowerCase();
for (final entry in defaultExtensionMap.entries) {
if (defaultExtensionMap[entry.key] == mime) {
return entry.key;
}
}
return mime;
}
/// MIME-type resolver class, used to customize the lookup of mime-types.
class MimeTypeResolver {
final Map<String, String> _extensionMap = {};
final List<MagicNumber> _magicNumbers = [];
final bool _useDefault;
int _magicNumbersMaxLength;
/// Create a new empty [MimeTypeResolver].
MimeTypeResolver.empty()
: _useDefault = false,
_magicNumbersMaxLength = 0;
/// Create a new [MimeTypeResolver] containing the default scope.
MimeTypeResolver()
: _useDefault = true,
_magicNumbersMaxLength = DEFAULT_MAGIC_NUMBERS_MAX_LENGTH;
/// Get the maximum number of bytes required to match all magic numbers, when
/// performing [lookup] with headerBytes present.
int get magicNumbersMaxLength => _magicNumbersMaxLength;
/// Extract the extension from [path] and use that for MIME-type lookup.
///
/// If no matching MIME-type was found, `null` is returned.
///
/// If [headerBytes] is present, a match for known magic-numbers will be
/// performed first. This allows the correct mime-type to be found, even
/// though a file have been saved using the wrong file-name extension. If less
/// than [magicNumbersMaxLength] bytes was provided, some magic-numbers won't
/// be matched against.
String lookup(String path, {List<int> headerBytes}) {
String result;
if (headerBytes != null) {
result = _matchMagic(headerBytes, _magicNumbers);
if (result != null) return result;
if (_useDefault) {
result = _matchMagic(headerBytes, DEFAULT_MAGIC_NUMBERS);
if (result != null) return result;
}
}
var ext = _ext(path);
result = _extensionMap[ext];
if (result != null) return result;
if (_useDefault) {
result = defaultExtensionMap[ext];
if (result != null) return result;
}
return null;
}
/// Add a new MIME-type mapping to the [MimeTypeResolver]. If the [extension]
/// is already present in the [MimeTypeResolver], it'll be overwritten.
void addExtension(String extension, String mimeType) {
_extensionMap[extension] = mimeType;
}
/// Add a new magic-number mapping to the [MimeTypeResolver].
///
/// If [mask] is present,the [mask] is used to only perform matching on
/// selective bits. The [mask] must have the same length as [bytes].
void addMagicNumber(List<int> bytes, String mimeType, {List<int> mask}) {
if (mask != null && bytes.length != mask.length) {
throw ArgumentError('Bytes and mask are of different lengths');
}
if (bytes.length > _magicNumbersMaxLength) {
_magicNumbersMaxLength = bytes.length;
}
_magicNumbers.add(MagicNumber(mimeType, bytes, mask: mask));
}
static String _matchMagic(
List<int> headerBytes, List<MagicNumber> magicNumbers) {
for (var mn in magicNumbers) {
if (mn.matches(headerBytes)) return mn.mimeType;
}
return null;
}
static String _ext(String path) {
var index = path.lastIndexOf('.');
if (index < 0 || index + 1 >= path.length) return path;
return path.substring(index + 1).toLowerCase();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/src/char_code.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.
library mime.char_code;
class CharCode {
static const int HT = 9;
static const int LF = 10;
static const int CR = 13;
static const int SP = 32;
static const int DASH = 45;
static const int COLON = 58;
static const int UPPER_A = 65;
static const int UPPER_Z = 90;
static const int LOWER_A = 97;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/src/mime_shared.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.
library mime.shared;
import 'dart:async';
class MimeMultipartException implements Exception {
final String message;
const MimeMultipartException([this.message = '']);
@override
String toString() => 'MimeMultipartException: $message';
}
/// A Mime Multipart class representing each part parsed by
/// [MimeMultipartTransformer]. The data is streamed in as it become available.
abstract class MimeMultipart extends Stream<List<int>> {
Map<String, String> get headers;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/src/mime_multipart_transformer.dart | // Copyright (c) 2012, 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 mime.multipart_transformer;
import 'dart:async';
import 'dart:typed_data';
import 'bound_multipart_stream.dart';
import 'char_code.dart';
import 'mime_shared.dart';
Uint8List _getBoundary(String boundary) {
var charCodes = boundary.codeUnits;
var boundaryList = Uint8List(4 + charCodes.length);
// Set-up the matching boundary preceding it with CRLF and two
// dashes.
boundaryList[0] = CharCode.CR;
boundaryList[1] = CharCode.LF;
boundaryList[2] = CharCode.DASH;
boundaryList[3] = CharCode.DASH;
boundaryList.setRange(4, 4 + charCodes.length, charCodes);
return boundaryList;
}
/// Parser for MIME multipart types of data as described in RFC 2046
/// section 5.1.1. The data is transformed into [MimeMultipart] objects, each
/// of them streaming the multipart data.
class MimeMultipartTransformer
extends StreamTransformerBase<List<int>, MimeMultipart> {
final List<int> _boundary;
/// Construct a new MIME multipart parser with the boundary
/// [boundary]. The boundary should be as specified in the content
/// type parameter, that is without the -- prefix.
MimeMultipartTransformer(String boundary)
: _boundary = _getBoundary(boundary);
@override
Stream<MimeMultipart> bind(Stream<List<int>> stream) {
return BoundMultipartStream(_boundary, stream).stream;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/src/bound_multipart_stream.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.
library mime.bound_multipart_stream;
import 'dart:async';
import 'dart:convert';
import 'char_code.dart';
import 'mime_shared.dart';
// Bytes for '()<>@,;:\\"/[]?={} \t'.
const _SEPARATORS = [
40,
41,
60,
62,
64,
44,
59,
58,
92,
34,
47,
91,
93,
63,
61,
123,
125,
32,
9
];
bool _isTokenChar(int byte) {
return byte > 31 && byte < 128 && !_SEPARATORS.contains(byte);
}
int _toLowerCase(int byte) {
const delta = CharCode.LOWER_A - CharCode.UPPER_A;
return (CharCode.UPPER_A <= byte && byte <= CharCode.UPPER_Z)
? byte + delta
: byte;
}
void _expectByteValue(int val1, int val2) {
if (val1 != val2) {
throw MimeMultipartException('Failed to parse multipart mime 1');
}
}
void _expectWhitespace(int byte) {
if (byte != CharCode.SP && byte != CharCode.HT) {
throw MimeMultipartException('Failed to parse multipart mime 2');
}
}
class _MimeMultipart extends MimeMultipart {
@override
final Map<String, String> headers;
final Stream<List<int>> _stream;
_MimeMultipart(this.headers, this._stream);
@override
StreamSubscription<List<int>> listen(void Function(List<int> data) onData,
{void Function() onDone, Function onError, bool cancelOnError}) {
return _stream.listen(onData,
onDone: onDone, onError: onError, cancelOnError: cancelOnError);
}
}
class BoundMultipartStream {
static const int _START = 0;
static const int _BOUNDARY_ENDING = 1;
static const int _BOUNDARY_END = 2;
static const int _HEADER_START = 3;
static const int _HEADER_FIELD = 4;
static const int _HEADER_VALUE_START = 5;
static const int _HEADER_VALUE = 6;
static const int _HEADER_VALUE_FOLDING_OR_ENDING = 7;
static const int _HEADER_VALUE_FOLD_OR_END = 8;
static const int _HEADER_ENDING = 9;
static const int _CONTENT = 10;
static const int _LAST_BOUNDARY_DASH2 = 11;
static const int _LAST_BOUNDARY_ENDING = 12;
static const int _LAST_BOUNDARY_END = 13;
static const int _DONE = 14;
static const int _FAIL = 15;
final List<int> _boundary;
final List<int> _headerField = [];
final List<int> _headerValue = [];
// The following states belong to `_controller`, state changes will not be
// immediately acted upon but rather only after the current
// `_multipartController` is done.
static const int _CONTROLLER_STATE_IDLE = 0;
static const int _CONTROLLER_STATE_ACTIVE = 1;
static const int _CONTROLLER_STATE_PAUSED = 2;
static const int _CONTROLLER_STATE_CANCELED = 3;
int _controllerState = _CONTROLLER_STATE_IDLE;
StreamController<MimeMultipart> _controller;
Stream<MimeMultipart> get stream => _controller.stream;
StreamSubscription _subscription;
StreamController<List<int>> _multipartController;
Map<String, String> _headers;
int _state = _START;
int _boundaryIndex = 2;
// Current index in the data buffer. If index is negative then it
// is the index into the artificial prefix of the boundary string.
int _index;
List<int> _buffer;
BoundMultipartStream(this._boundary, Stream<List<int>> stream) {
_controller = StreamController(
sync: true,
onPause: _pauseStream,
onResume: _resumeStream,
onCancel: () {
_controllerState = _CONTROLLER_STATE_CANCELED;
_tryPropagateControllerState();
},
onListen: () {
_controllerState = _CONTROLLER_STATE_ACTIVE;
_subscription = stream.listen((data) {
assert(_buffer == null);
_subscription.pause();
_buffer = data;
_index = 0;
_parse();
}, onDone: () {
if (_state != _DONE) {
_controller
.addError(MimeMultipartException('Bad multipart ending'));
}
_controller.close();
}, onError: _controller.addError);
});
}
void _resumeStream() {
assert(_controllerState == _CONTROLLER_STATE_PAUSED);
_controllerState = _CONTROLLER_STATE_ACTIVE;
_tryPropagateControllerState();
}
void _pauseStream() {
_controllerState = _CONTROLLER_STATE_PAUSED;
_tryPropagateControllerState();
}
void _tryPropagateControllerState() {
if (_multipartController == null) {
switch (_controllerState) {
case _CONTROLLER_STATE_ACTIVE:
if (_subscription.isPaused) _subscription.resume();
break;
case _CONTROLLER_STATE_PAUSED:
if (!_subscription.isPaused) _subscription.pause();
break;
case _CONTROLLER_STATE_CANCELED:
_subscription.cancel();
break;
default:
throw StateError('This code should never be reached.');
}
}
}
void _parse() {
// Number of boundary bytes to artificially place before the supplied data.
var boundaryPrefix = 0;
// Position where content starts. Will be null if no known content
// start exists. Will be negative of the content starts in the
// boundary prefix. Will be zero or position if the content starts
// in the current buffer.
int contentStartIndex;
// Function to report content data for the current part. The data
// reported is from the current content start index up til the
// current index. As the data can be artificially prefixed with a
// prefix of the boundary both the content start index and index
// can be negative.
void reportData() {
if (contentStartIndex < 0) {
var contentLength = boundaryPrefix + _index - _boundaryIndex;
if (contentLength <= boundaryPrefix) {
_multipartController.add(_boundary.sublist(0, contentLength));
} else {
_multipartController.add(_boundary.sublist(0, boundaryPrefix));
_multipartController
.add(_buffer.sublist(0, contentLength - boundaryPrefix));
}
} else {
var contentEndIndex = _index - _boundaryIndex;
_multipartController
.add(_buffer.sublist(contentStartIndex, contentEndIndex));
}
}
if (_state == _CONTENT && _boundaryIndex == 0) {
contentStartIndex = 0;
} else {
contentStartIndex = null;
}
// The data to parse might be 'artificially' prefixed with a
// partial match of the boundary.
boundaryPrefix = _boundaryIndex;
while ((_index < _buffer.length) && _state != _FAIL && _state != _DONE) {
int byte;
if (_index < 0) {
byte = _boundary[boundaryPrefix + _index];
} else {
byte = _buffer[_index];
}
switch (_state) {
case _START:
if (byte == _boundary[_boundaryIndex]) {
_boundaryIndex++;
if (_boundaryIndex == _boundary.length) {
_state = _BOUNDARY_ENDING;
_boundaryIndex = 0;
}
} else {
// Restart matching of the boundary.
_index = _index - _boundaryIndex;
_boundaryIndex = 0;
}
break;
case _BOUNDARY_ENDING:
if (byte == CharCode.CR) {
_state = _BOUNDARY_END;
} else if (byte == CharCode.DASH) {
_state = _LAST_BOUNDARY_DASH2;
} else {
_expectWhitespace(byte);
}
break;
case _BOUNDARY_END:
_expectByteValue(byte, CharCode.LF);
if (_multipartController != null) {
_multipartController.close();
_multipartController = null;
_tryPropagateControllerState();
}
_state = _HEADER_START;
break;
case _HEADER_START:
_headers = <String, String>{};
if (byte == CharCode.CR) {
_state = _HEADER_ENDING;
} else {
// Start of new header field.
_headerField.add(_toLowerCase(byte));
_state = _HEADER_FIELD;
}
break;
case _HEADER_FIELD:
if (byte == CharCode.COLON) {
_state = _HEADER_VALUE_START;
} else {
if (!_isTokenChar(byte)) {
throw MimeMultipartException('Invalid header field name');
}
_headerField.add(_toLowerCase(byte));
}
break;
case _HEADER_VALUE_START:
if (byte == CharCode.CR) {
_state = _HEADER_VALUE_FOLDING_OR_ENDING;
} else if (byte != CharCode.SP && byte != CharCode.HT) {
// Start of new header value.
_headerValue.add(byte);
_state = _HEADER_VALUE;
}
break;
case _HEADER_VALUE:
if (byte == CharCode.CR) {
_state = _HEADER_VALUE_FOLDING_OR_ENDING;
} else {
_headerValue.add(byte);
}
break;
case _HEADER_VALUE_FOLDING_OR_ENDING:
_expectByteValue(byte, CharCode.LF);
_state = _HEADER_VALUE_FOLD_OR_END;
break;
case _HEADER_VALUE_FOLD_OR_END:
if (byte == CharCode.SP || byte == CharCode.HT) {
_state = _HEADER_VALUE_START;
} else {
var headerField = utf8.decode(_headerField);
var headerValue = utf8.decode(_headerValue);
_headers[headerField.toLowerCase()] = headerValue;
_headerField.clear();
_headerValue.clear();
if (byte == CharCode.CR) {
_state = _HEADER_ENDING;
} else {
// Start of new header field.
_headerField.add(_toLowerCase(byte));
_state = _HEADER_FIELD;
}
}
break;
case _HEADER_ENDING:
_expectByteValue(byte, CharCode.LF);
_multipartController = StreamController(
sync: true,
onListen: () {
if (_subscription.isPaused) _subscription.resume();
},
onPause: _subscription.pause,
onResume: _subscription.resume);
_controller
.add(_MimeMultipart(_headers, _multipartController.stream));
_headers = null;
_state = _CONTENT;
contentStartIndex = _index + 1;
break;
case _CONTENT:
if (byte == _boundary[_boundaryIndex]) {
_boundaryIndex++;
if (_boundaryIndex == _boundary.length) {
if (contentStartIndex != null) {
_index++;
reportData();
_index--;
}
_multipartController.close();
_multipartController = null;
_tryPropagateControllerState();
_boundaryIndex = 0;
_state = _BOUNDARY_ENDING;
}
} else {
// Restart matching of the boundary.
_index = _index - _boundaryIndex;
contentStartIndex ??= _index;
_boundaryIndex = 0;
}
break;
case _LAST_BOUNDARY_DASH2:
_expectByteValue(byte, CharCode.DASH);
_state = _LAST_BOUNDARY_ENDING;
break;
case _LAST_BOUNDARY_ENDING:
if (byte == CharCode.CR) {
_state = _LAST_BOUNDARY_END;
} else {
_expectWhitespace(byte);
}
break;
case _LAST_BOUNDARY_END:
_expectByteValue(byte, CharCode.LF);
if (_multipartController != null) {
_multipartController.close();
_multipartController = null;
_tryPropagateControllerState();
}
_state = _DONE;
break;
default:
// Should be unreachable.
assert(false);
break;
}
// Move to the next byte.
_index++;
}
// Report any known content.
if (_state == _CONTENT && contentStartIndex != null) {
reportData();
}
// Resume if at end.
if (_index == _buffer.length) {
_buffer = null;
_index = null;
_subscription.resume();
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/src/magic_number.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.
library mime.magic_number;
class MagicNumber {
final String mimeType;
final List<int> numbers;
final List<int> mask;
const MagicNumber(this.mimeType, this.numbers, {this.mask});
bool matches(List<int> header) {
if (header.length < numbers.length) return false;
for (var i = 0; i < numbers.length; i++) {
if (mask != null) {
if ((mask[i] & numbers[i]) != (mask[i] & header[i])) return false;
} else {
if (numbers[i] != header[i]) return false;
}
}
return true;
}
}
const int DEFAULT_MAGIC_NUMBERS_MAX_LENGTH = 12;
const List<MagicNumber> DEFAULT_MAGIC_NUMBERS = [
MagicNumber('application/pdf', [0x25, 0x50, 0x44, 0x46]),
MagicNumber('application/postscript', [0x25, 0x51]),
MagicNumber('image/gif', [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]),
MagicNumber('image/gif', [0x47, 0x49, 0x46, 0x38, 0x39, 0x61]),
MagicNumber('image/jpeg', [0xFF, 0xD8]),
MagicNumber('image/png', [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
MagicNumber('image/tiff', [0x49, 0x49, 0x2A, 0x00]),
MagicNumber('image/tiff', [0x4D, 0x4D, 0x00, 0x2A]),
MagicNumber('video/mp4', [
0x00,
0x00,
0x00,
0x00,
0x66,
0x74,
0x79,
0x70,
0x33,
0x67,
0x70,
0x35
], mask: [
0xFF,
0xFF,
0xFF,
0x00,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF
]),
MagicNumber('model/gltf-binary', [0x46, 0x54, 0x6C, 0x67]),
];
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/mime/src/default_extension_map.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.
library mime.extension_map;
const Map<String, String> defaultExtensionMap = <String, String>{
'123': 'application/vnd.lotus-1-2-3',
'3dml': 'text/vnd.in3d.3dml',
'3ds': 'image/x-3ds',
'3g2': 'video/3gpp2',
'3gp': 'video/3gpp',
'7z': 'application/x-7z-compressed',
'aab': 'application/x-authorware-bin',
'aac': 'audio/x-aac',
'aam': 'application/x-authorware-map',
'aas': 'application/x-authorware-seg',
'abw': 'application/x-abiword',
'ac': 'application/pkix-attr-cert',
'acc': 'application/vnd.americandynamics.acc',
'ace': 'application/x-ace-compressed',
'acu': 'application/vnd.acucobol',
'acutc': 'application/vnd.acucorp',
'adp': 'audio/adpcm',
'aep': 'application/vnd.audiograph',
'afm': 'application/x-font-type1',
'afp': 'application/vnd.ibm.modcap',
'ahead': 'application/vnd.ahead.space',
'ai': 'application/postscript',
'aif': 'audio/x-aiff',
'aifc': 'audio/x-aiff',
'aiff': 'audio/x-aiff',
'air': 'application/vnd.adobe.air-application-installer-package+zip',
'ait': 'application/vnd.dvb.ait',
'ami': 'application/vnd.amiga.ami',
'apk': 'application/vnd.android.package-archive',
'appcache': 'text/cache-manifest',
'application': 'application/x-ms-application',
'apr': 'application/vnd.lotus-approach',
'arc': 'application/x-freearc',
'asc': 'application/pgp-signature',
'asf': 'video/x-ms-asf',
'asm': 'text/x-asm',
'aso': 'application/vnd.accpac.simply.aso',
'asx': 'video/x-ms-asf',
'atc': 'application/vnd.acucorp',
'atom': 'application/atom+xml',
'atomcat': 'application/atomcat+xml',
'atomsvc': 'application/atomsvc+xml',
'atx': 'application/vnd.antix.game-component',
'au': 'audio/basic',
'avi': 'video/x-msvideo',
'aw': 'application/applixware',
'azf': 'application/vnd.airzip.filesecure.azf',
'azs': 'application/vnd.airzip.filesecure.azs',
'azw': 'application/vnd.amazon.ebook',
'bat': 'application/x-msdownload',
'bcpio': 'application/x-bcpio',
'bdf': 'application/x-font-bdf',
'bdm': 'application/vnd.syncml.dm+wbxml',
'bed': 'application/vnd.realvnc.bed',
'bh2': 'application/vnd.fujitsu.oasysprs',
'bin': 'application/octet-stream',
'blb': 'application/x-blorb',
'blorb': 'application/x-blorb',
'bmi': 'application/vnd.bmi',
'bmp': 'image/bmp',
'book': 'application/vnd.framemaker',
'box': 'application/vnd.previewsystems.box',
'boz': 'application/x-bzip2',
'bpk': 'application/octet-stream',
'btif': 'image/prs.btif',
'bz': 'application/x-bzip',
'bz2': 'application/x-bzip2',
'c': 'text/x-c',
'c11amc': 'application/vnd.cluetrust.cartomobile-config',
'c11amz': 'application/vnd.cluetrust.cartomobile-config-pkg',
'c4d': 'application/vnd.clonk.c4group',
'c4f': 'application/vnd.clonk.c4group',
'c4g': 'application/vnd.clonk.c4group',
'c4p': 'application/vnd.clonk.c4group',
'c4u': 'application/vnd.clonk.c4group',
'cab': 'application/vnd.ms-cab-compressed',
'caf': 'audio/x-caf',
'cap': 'application/vnd.tcpdump.pcap',
'car': 'application/vnd.curl.car',
'cat': 'application/vnd.ms-pki.seccat',
'cb7': 'application/x-cbr',
'cba': 'application/x-cbr',
'cbr': 'application/x-cbr',
'cbt': 'application/x-cbr',
'cbz': 'application/x-cbr',
'cc': 'text/x-c',
'cct': 'application/x-director',
'ccxml': 'application/ccxml+xml',
'cdbcmsg': 'application/vnd.contact.cmsg',
'cdf': 'application/x-netcdf',
'cdkey': 'application/vnd.mediastation.cdkey',
'cdmia': 'application/cdmi-capability',
'cdmic': 'application/cdmi-container',
'cdmid': 'application/cdmi-domain',
'cdmio': 'application/cdmi-object',
'cdmiq': 'application/cdmi-queue',
'cdx': 'chemical/x-cdx',
'cdxml': 'application/vnd.chemdraw+xml',
'cdy': 'application/vnd.cinderella',
'cer': 'application/pkix-cert',
'cfs': 'application/x-cfs-compressed',
'cgm': 'image/cgm',
'chat': 'application/x-chat',
'chm': 'application/vnd.ms-htmlhelp',
'chrt': 'application/vnd.kde.kchart',
'cif': 'chemical/x-cif',
'cii': 'application/vnd.anser-web-certificate-issue-initiation',
'cil': 'application/vnd.ms-artgalry',
'cla': 'application/vnd.claymore',
'class': 'application/java-vm',
'clkk': 'application/vnd.crick.clicker.keyboard',
'clkp': 'application/vnd.crick.clicker.palette',
'clkt': 'application/vnd.crick.clicker.template',
'clkw': 'application/vnd.crick.clicker.wordbank',
'clkx': 'application/vnd.crick.clicker',
'clp': 'application/x-msclip',
'cmc': 'application/vnd.cosmocaller',
'cmdf': 'chemical/x-cmdf',
'cml': 'chemical/x-cml',
'cmp': 'application/vnd.yellowriver-custom-menu',
'cmx': 'image/x-cmx',
'cod': 'application/vnd.rim.cod',
'com': 'application/x-msdownload',
'conf': 'text/plain',
'cpio': 'application/x-cpio',
'cpp': 'text/x-c',
'cpt': 'application/mac-compactpro',
'crd': 'application/x-mscardfile',
'crl': 'application/pkix-crl',
'crt': 'application/x-x509-ca-cert',
'cryptonote': 'application/vnd.rig.cryptonote',
'csh': 'application/x-csh',
'csml': 'chemical/x-csml',
'csp': 'application/vnd.commonspace',
'css': 'text/css',
'cst': 'application/x-director',
'csv': 'text/csv',
'cu': 'application/cu-seeme',
'curl': 'text/vnd.curl',
'cww': 'application/prs.cww',
'cxt': 'application/x-director',
'cxx': 'text/x-c',
'dae': 'model/vnd.collada+xml',
'daf': 'application/vnd.mobius.daf',
'dart': 'text/x-dart',
'dataless': 'application/vnd.fdsn.seed',
'davmount': 'application/davmount+xml',
'dbk': 'application/docbook+xml',
'dcr': 'application/x-director',
'dcurl': 'text/vnd.curl.dcurl',
'dd2': 'application/vnd.oma.dd2+xml',
'ddd': 'application/vnd.fujixerox.ddd',
'deb': 'application/x-debian-package',
'def': 'text/plain',
'deploy': 'application/octet-stream',
'der': 'application/x-x509-ca-cert',
'dfac': 'application/vnd.dreamfactory',
'dgc': 'application/x-dgc-compressed',
'dic': 'text/x-c',
'dir': 'application/x-director',
'dis': 'application/vnd.mobius.dis',
'dist': 'application/octet-stream',
'distz': 'application/octet-stream',
'djv': 'image/vnd.djvu',
'djvu': 'image/vnd.djvu',
'dll': 'application/x-msdownload',
'dmg': 'application/x-apple-diskimage',
'dmp': 'application/vnd.tcpdump.pcap',
'dms': 'application/octet-stream',
'dna': 'application/vnd.dna',
'doc': 'application/msword',
'docm': 'application/vnd.ms-word.document.macroenabled.12',
'docx':
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dot': 'application/msword',
'dotm': 'application/vnd.ms-word.template.macroenabled.12',
'dotx':
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'dp': 'application/vnd.osgi.dp',
'dpg': 'application/vnd.dpgraph',
'dra': 'audio/vnd.dra',
'dsc': 'text/prs.lines.tag',
'dssc': 'application/dssc+der',
'dtb': 'application/x-dtbook+xml',
'dtd': 'application/xml-dtd',
'dts': 'audio/vnd.dts',
'dtshd': 'audio/vnd.dts.hd',
'dump': 'application/octet-stream',
'dvb': 'video/vnd.dvb.file',
'dvi': 'application/x-dvi',
'dwf': 'model/vnd.dwf',
'dwg': 'image/vnd.dwg',
'dxf': 'image/vnd.dxf',
'dxp': 'application/vnd.spotfire.dxp',
'dxr': 'application/x-director',
'ecelp4800': 'audio/vnd.nuera.ecelp4800',
'ecelp7470': 'audio/vnd.nuera.ecelp7470',
'ecelp9600': 'audio/vnd.nuera.ecelp9600',
'ecma': 'application/ecmascript',
'edm': 'application/vnd.novadigm.edm',
'edx': 'application/vnd.novadigm.edx',
'efif': 'application/vnd.picsel',
'ei6': 'application/vnd.pg.osasli',
'elc': 'application/octet-stream',
'emf': 'application/x-msmetafile',
'eml': 'message/rfc822',
'emma': 'application/emma+xml',
'emz': 'application/x-msmetafile',
'eol': 'audio/vnd.digital-winds',
'eot': 'application/vnd.ms-fontobject',
'eps': 'application/postscript',
'epub': 'application/epub+zip',
'es3': 'application/vnd.eszigno3+xml',
'esa': 'application/vnd.osgi.subsystem',
'esf': 'application/vnd.epson.esf',
'et3': 'application/vnd.eszigno3+xml',
'etx': 'text/x-setext',
'eva': 'application/x-eva',
'evy': 'application/x-envoy',
'exe': 'application/x-msdownload',
'exi': 'application/exi',
'ext': 'application/vnd.novadigm.ext',
'ez': 'application/andrew-inset',
'ez2': 'application/vnd.ezpix-album',
'ez3': 'application/vnd.ezpix-package',
'f': 'text/x-fortran',
'f4v': 'video/x-f4v',
'f77': 'text/x-fortran',
'f90': 'text/x-fortran',
'fbs': 'image/vnd.fastbidsheet',
'fcdt': 'application/vnd.adobe.formscentral.fcdt',
'fcs': 'application/vnd.isac.fcs',
'fdf': 'application/vnd.fdf',
'fe_launch': 'application/vnd.denovo.fcselayout-link',
'fg5': 'application/vnd.fujitsu.oasysgp',
'fgd': 'application/x-director',
'fh': 'image/x-freehand',
'fh4': 'image/x-freehand',
'fh5': 'image/x-freehand',
'fh7': 'image/x-freehand',
'fhc': 'image/x-freehand',
'fig': 'application/x-xfig',
'flac': 'audio/x-flac',
'fli': 'video/x-fli',
'flo': 'application/vnd.micrografx.flo',
'flv': 'video/x-flv',
'flw': 'application/vnd.kde.kivio',
'flx': 'text/vnd.fmi.flexstor',
'fly': 'text/vnd.fly',
'fm': 'application/vnd.framemaker',
'fnc': 'application/vnd.frogans.fnc',
'for': 'text/x-fortran',
'fpx': 'image/vnd.fpx',
'frame': 'application/vnd.framemaker',
'fsc': 'application/vnd.fsc.weblaunch',
'fst': 'image/vnd.fst',
'ftc': 'application/vnd.fluxtime.clip',
'fti': 'application/vnd.anser-web-funds-transfer-initiation',
'fvt': 'video/vnd.fvt',
'fxp': 'application/vnd.adobe.fxp',
'fxpl': 'application/vnd.adobe.fxp',
'fzs': 'application/vnd.fuzzysheet',
'g2w': 'application/vnd.geoplan',
'g3': 'image/g3fax',
'g3w': 'application/vnd.geospace',
'gac': 'application/vnd.groove-account',
'gam': 'application/x-tads',
'gbr': 'application/rpki-ghostbusters',
'gca': 'application/x-gca-compressed',
'gdl': 'model/vnd.gdl',
'geo': 'application/vnd.dynageo',
'gex': 'application/vnd.geometry-explorer',
'ggb': 'application/vnd.geogebra.file',
'ggt': 'application/vnd.geogebra.tool',
'ghf': 'application/vnd.groove-help',
'gif': 'image/gif',
'gim': 'application/vnd.groove-identity-message',
'glb': 'model/gltf-binary',
'gltf': 'model/gltf+json',
'gml': 'application/gml+xml',
'gmx': 'application/vnd.gmx',
'gnumeric': 'application/x-gnumeric',
'gph': 'application/vnd.flographit',
'gpx': 'application/gpx+xml',
'gqf': 'application/vnd.grafeq',
'gqs': 'application/vnd.grafeq',
'gram': 'application/srgs',
'gramps': 'application/x-gramps-xml',
'gre': 'application/vnd.geometry-explorer',
'grv': 'application/vnd.groove-injector',
'grxml': 'application/srgs+xml',
'gsf': 'application/x-font-ghostscript',
'gtar': 'application/x-gtar',
'gtm': 'application/vnd.groove-tool-message',
'gtw': 'model/vnd.gtw',
'gv': 'text/vnd.graphviz',
'gxf': 'application/gxf',
'gxt': 'application/vnd.geonext',
'h': 'text/x-c',
'h261': 'video/h261',
'h263': 'video/h263',
'h264': 'video/h264',
'hal': 'application/vnd.hal+xml',
'hbci': 'application/vnd.hbci',
'hdf': 'application/x-hdf',
'hh': 'text/x-c',
'hlp': 'application/winhlp',
'hpgl': 'application/vnd.hp-hpgl',
'hpid': 'application/vnd.hp-hpid',
'hps': 'application/vnd.hp-hps',
'hqx': 'application/mac-binhex40',
'htke': 'application/vnd.kenameaapp',
'htm': 'text/html',
'html': 'text/html',
'hvd': 'application/vnd.yamaha.hv-dic',
'hvp': 'application/vnd.yamaha.hv-voice',
'hvs': 'application/vnd.yamaha.hv-script',
'i2g': 'application/vnd.intergeo',
'icc': 'application/vnd.iccprofile',
'ice': 'x-conference/x-cooltalk',
'icm': 'application/vnd.iccprofile',
'ico': 'image/x-icon',
'ics': 'text/calendar',
'ief': 'image/ief',
'ifb': 'text/calendar',
'ifm': 'application/vnd.shana.informed.formdata',
'iges': 'model/iges',
'igl': 'application/vnd.igloader',
'igm': 'application/vnd.insors.igm',
'igs': 'model/iges',
'igx': 'application/vnd.micrografx.igx',
'iif': 'application/vnd.shana.informed.interchange',
'imp': 'application/vnd.accpac.simply.imp',
'ims': 'application/vnd.ms-ims',
'in': 'text/plain',
'ink': 'application/inkml+xml',
'inkml': 'application/inkml+xml',
'install': 'application/x-install-instructions',
'iota': 'application/vnd.astraea-software.iota',
'ipfix': 'application/ipfix',
'ipk': 'application/vnd.shana.informed.package',
'irm': 'application/vnd.ibm.rights-management',
'irp': 'application/vnd.irepository.package+xml',
'iso': 'application/x-iso9660-image',
'itp': 'application/vnd.shana.informed.formtemplate',
'ivp': 'application/vnd.immervision-ivp',
'ivu': 'application/vnd.immervision-ivu',
'jad': 'text/vnd.sun.j2me.app-descriptor',
'jam': 'application/vnd.jam',
'jar': 'application/java-archive',
'java': 'text/x-java-source',
'jisp': 'application/vnd.jisp',
'jlt': 'application/vnd.hp-jlyt',
'jnlp': 'application/x-java-jnlp-file',
'joda': 'application/vnd.joost.joda-archive',
'jpe': 'image/jpeg',
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'jpgm': 'video/jpm',
'jpgv': 'video/jpeg',
'jpm': 'video/jpm',
'js': 'application/javascript',
'json': 'application/json',
'jsonml': 'application/jsonml+json',
'kar': 'audio/midi',
'karbon': 'application/vnd.kde.karbon',
'kfo': 'application/vnd.kde.kformula',
'kia': 'application/vnd.kidspiration',
'kml': 'application/vnd.google-earth.kml+xml',
'kmz': 'application/vnd.google-earth.kmz',
'kne': 'application/vnd.kinar',
'knp': 'application/vnd.kinar',
'kon': 'application/vnd.kde.kontour',
'kpr': 'application/vnd.kde.kpresenter',
'kpt': 'application/vnd.kde.kpresenter',
'kpxx': 'application/vnd.ds-keypoint',
'ksp': 'application/vnd.kde.kspread',
'ktr': 'application/vnd.kahootz',
'ktx': 'image/ktx',
'ktz': 'application/vnd.kahootz',
'kwd': 'application/vnd.kde.kword',
'kwt': 'application/vnd.kde.kword',
'lasxml': 'application/vnd.las.las+xml',
'latex': 'application/x-latex',
'lbd': 'application/vnd.llamagraphics.life-balance.desktop',
'lbe': 'application/vnd.llamagraphics.life-balance.exchange+xml',
'les': 'application/vnd.hhe.lesson-player',
'lha': 'application/x-lzh-compressed',
'link66': 'application/vnd.route66.link66+xml',
'list': 'text/plain',
'list3820': 'application/vnd.ibm.modcap',
'listafp': 'application/vnd.ibm.modcap',
'lnk': 'application/x-ms-shortcut',
'log': 'text/plain',
'lostxml': 'application/lost+xml',
'lrf': 'application/octet-stream',
'lrm': 'application/vnd.ms-lrm',
'ltf': 'application/vnd.frogans.ltf',
'lvp': 'audio/vnd.lucent.voice',
'lwp': 'application/vnd.lotus-wordpro',
'lzh': 'application/x-lzh-compressed',
'm13': 'application/x-msmediaview',
'm14': 'application/x-msmediaview',
'm1v': 'video/mpeg',
'm21': 'application/mp21',
'm2a': 'audio/mpeg',
'm2v': 'video/mpeg',
'm3a': 'audio/mpeg',
'm3u': 'audio/x-mpegurl',
'm3u8': 'application/vnd.apple.mpegurl',
'm4u': 'video/vnd.mpegurl',
'm4v': 'video/x-m4v',
'ma': 'application/mathematica',
'mads': 'application/mads+xml',
'mag': 'application/vnd.ecowin.chart',
'maker': 'application/vnd.framemaker',
'man': 'text/troff',
'mar': 'application/octet-stream',
'mathml': 'application/mathml+xml',
'mb': 'application/mathematica',
'mbk': 'application/vnd.mobius.mbk',
'mbox': 'application/mbox',
'mc1': 'application/vnd.medcalcdata',
'mcd': 'application/vnd.mcd',
'mcurl': 'text/vnd.curl.mcurl',
'mdb': 'application/x-msaccess',
'mdi': 'image/vnd.ms-modi',
'me': 'text/troff',
'mesh': 'model/mesh',
'meta4': 'application/metalink4+xml',
'metalink': 'application/metalink+xml',
'mets': 'application/mets+xml',
'mfm': 'application/vnd.mfmp',
'mft': 'application/rpki-manifest',
'mgp': 'application/vnd.osgeo.mapguide.package',
'mgz': 'application/vnd.proteus.magazine',
'mid': 'audio/midi',
'midi': 'audio/midi',
'mie': 'application/x-mie',
'mif': 'application/vnd.mif',
'mime': 'message/rfc822',
'mj2': 'video/mj2',
'mjp2': 'video/mj2',
'mk3d': 'video/x-matroska',
'mka': 'audio/x-matroska',
'mks': 'video/x-matroska',
'mkv': 'video/x-matroska',
'mlp': 'application/vnd.dolby.mlp',
'mmd': 'application/vnd.chipnuts.karaoke-mmd',
'mmf': 'application/vnd.smaf',
'mmr': 'image/vnd.fujixerox.edmics-mmr',
'mng': 'video/x-mng',
'mny': 'application/x-msmoney',
'mobi': 'application/x-mobipocket-ebook',
'mods': 'application/mods+xml',
'mov': 'video/quicktime',
'movie': 'video/x-sgi-movie',
'mp2': 'audio/mpeg',
'mp21': 'application/mp21',
'mp2a': 'audio/mpeg',
'mp3': 'audio/mpeg',
'mp4': 'video/mp4',
'mp4a': 'audio/mp4',
'mp4s': 'application/mp4',
'mp4v': 'video/mp4',
'mpc': 'application/vnd.mophun.certificate',
'mpe': 'video/mpeg',
'mpeg': 'video/mpeg',
'mpg': 'video/mpeg',
'mpg4': 'video/mp4',
'mpga': 'audio/mpeg',
'mpkg': 'application/vnd.apple.installer+xml',
'mpm': 'application/vnd.blueice.multipass',
'mpn': 'application/vnd.mophun.application',
'mpp': 'application/vnd.ms-project',
'mpt': 'application/vnd.ms-project',
'mpy': 'application/vnd.ibm.minipay',
'mqy': 'application/vnd.mobius.mqy',
'mrc': 'application/marc',
'mrcx': 'application/marcxml+xml',
'ms': 'text/troff',
'mscml': 'application/mediaservercontrol+xml',
'mseed': 'application/vnd.fdsn.mseed',
'mseq': 'application/vnd.mseq',
'msf': 'application/vnd.epson.msf',
'msh': 'model/mesh',
'msi': 'application/x-msdownload',
'msl': 'application/vnd.mobius.msl',
'msty': 'application/vnd.muvee.style',
'mts': 'model/vnd.mts',
'mus': 'application/vnd.musician',
'musicxml': 'application/vnd.recordare.musicxml+xml',
'mvb': 'application/x-msmediaview',
'mwf': 'application/vnd.mfer',
'mxf': 'application/mxf',
'mxl': 'application/vnd.recordare.musicxml',
'mxml': 'application/xv+xml',
'mxs': 'application/vnd.triscape.mxs',
'mxu': 'video/vnd.mpegurl',
'n-gage': 'application/vnd.nokia.n-gage.symbian.install',
'n3': 'text/n3',
'nb': 'application/mathematica',
'nbp': 'application/vnd.wolfram.player',
'nc': 'application/x-netcdf',
'ncx': 'application/x-dtbncx+xml',
'nfo': 'text/x-nfo',
'ngdat': 'application/vnd.nokia.n-gage.data',
'nitf': 'application/vnd.nitf',
'nlu': 'application/vnd.neurolanguage.nlu',
'nml': 'application/vnd.enliven',
'nnd': 'application/vnd.noblenet-directory',
'nns': 'application/vnd.noblenet-sealer',
'nnw': 'application/vnd.noblenet-web',
'npx': 'image/vnd.net-fpx',
'nsc': 'application/x-conference',
'nsf': 'application/vnd.lotus-notes',
'ntf': 'application/vnd.nitf',
'nzb': 'application/x-nzb',
'oa2': 'application/vnd.fujitsu.oasys2',
'oa3': 'application/vnd.fujitsu.oasys3',
'oas': 'application/vnd.fujitsu.oasys',
'obd': 'application/x-msbinder',
'obj': 'application/x-tgif',
'oda': 'application/oda',
'odb': 'application/vnd.oasis.opendocument.database',
'odc': 'application/vnd.oasis.opendocument.chart',
'odf': 'application/vnd.oasis.opendocument.formula',
'odft': 'application/vnd.oasis.opendocument.formula-template',
'odg': 'application/vnd.oasis.opendocument.graphics',
'odi': 'application/vnd.oasis.opendocument.image',
'odm': 'application/vnd.oasis.opendocument.text-master',
'odp': 'application/vnd.oasis.opendocument.presentation',
'ods': 'application/vnd.oasis.opendocument.spreadsheet',
'odt': 'application/vnd.oasis.opendocument.text',
'oga': 'audio/ogg',
'ogg': 'audio/ogg',
'ogv': 'video/ogg',
'ogx': 'application/ogg',
'omdoc': 'application/omdoc+xml',
'onepkg': 'application/onenote',
'onetmp': 'application/onenote',
'onetoc': 'application/onenote',
'onetoc2': 'application/onenote',
'opf': 'application/oebps-package+xml',
'opml': 'text/x-opml',
'oprc': 'application/vnd.palm',
'org': 'application/vnd.lotus-organizer',
'osf': 'application/vnd.yamaha.openscoreformat',
'osfpvg': 'application/vnd.yamaha.openscoreformat.osfpvg+xml',
'otc': 'application/vnd.oasis.opendocument.chart-template',
'otf': 'application/x-font-otf',
'otg': 'application/vnd.oasis.opendocument.graphics-template',
'oth': 'application/vnd.oasis.opendocument.text-web',
'oti': 'application/vnd.oasis.opendocument.image-template',
'otp': 'application/vnd.oasis.opendocument.presentation-template',
'ots': 'application/vnd.oasis.opendocument.spreadsheet-template',
'ott': 'application/vnd.oasis.opendocument.text-template',
'oxps': 'application/oxps',
'oxt': 'application/vnd.openofficeorg.extension',
'p': 'text/x-pascal',
'p10': 'application/pkcs10',
'p12': 'application/x-pkcs12',
'p7b': 'application/x-pkcs7-certificates',
'p7c': 'application/pkcs7-mime',
'p7m': 'application/pkcs7-mime',
'p7r': 'application/x-pkcs7-certreqresp',
'p7s': 'application/pkcs7-signature',
'p8': 'application/pkcs8',
'pas': 'text/x-pascal',
'paw': 'application/vnd.pawaafile',
'pbd': 'application/vnd.powerbuilder6',
'pbm': 'image/x-portable-bitmap',
'pcap': 'application/vnd.tcpdump.pcap',
'pcf': 'application/x-font-pcf',
'pcl': 'application/vnd.hp-pcl',
'pclxl': 'application/vnd.hp-pclxl',
'pct': 'image/x-pict',
'pcurl': 'application/vnd.curl.pcurl',
'pcx': 'image/x-pcx',
'pdb': 'application/vnd.palm',
'pdf': 'application/pdf',
'pfa': 'application/x-font-type1',
'pfb': 'application/x-font-type1',
'pfm': 'application/x-font-type1',
'pfr': 'application/font-tdpfr',
'pfx': 'application/x-pkcs12',
'pgm': 'image/x-portable-graymap',
'pgn': 'application/x-chess-pgn',
'pgp': 'application/pgp-encrypted',
'pic': 'image/x-pict',
'pkg': 'application/octet-stream',
'pki': 'application/pkixcmp',
'pkipath': 'application/pkix-pkipath',
'plb': 'application/vnd.3gpp.pic-bw-large',
'plc': 'application/vnd.mobius.plc',
'plf': 'application/vnd.pocketlearn',
'pls': 'application/pls+xml',
'pml': 'application/vnd.ctc-posml',
'png': 'image/png',
'pnm': 'image/x-portable-anymap',
'portpkg': 'application/vnd.macports.portpkg',
'pot': 'application/vnd.ms-powerpoint',
'potm': 'application/vnd.ms-powerpoint.template.macroenabled.12',
'potx':
'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppam': 'application/vnd.ms-powerpoint.addin.macroenabled.12',
'ppd': 'application/vnd.cups-ppd',
'ppm': 'image/x-portable-pixmap',
'pps': 'application/vnd.ms-powerpoint',
'ppsm': 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
'ppsx':
'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'ppt': 'application/vnd.ms-powerpoint',
'pptm': 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
'pptx':
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pqa': 'application/vnd.palm',
'prc': 'application/x-mobipocket-ebook',
'pre': 'application/vnd.lotus-freelance',
'prf': 'application/pics-rules',
'ps': 'application/postscript',
'psb': 'application/vnd.3gpp.pic-bw-small',
'psd': 'image/vnd.adobe.photoshop',
'psf': 'application/x-font-linux-psf',
'pskcxml': 'application/pskc+xml',
'ptid': 'application/vnd.pvi.ptid1',
'pub': 'application/x-mspublisher',
'pvb': 'application/vnd.3gpp.pic-bw-var',
'pwn': 'application/vnd.3m.post-it-notes',
'pya': 'audio/vnd.ms-playready.media.pya',
'pyv': 'video/vnd.ms-playready.media.pyv',
'qam': 'application/vnd.epson.quickanime',
'qbo': 'application/vnd.intu.qbo',
'qfx': 'application/vnd.intu.qfx',
'qps': 'application/vnd.publishare-delta-tree',
'qt': 'video/quicktime',
'qwd': 'application/vnd.quark.quarkxpress',
'qwt': 'application/vnd.quark.quarkxpress',
'qxb': 'application/vnd.quark.quarkxpress',
'qxd': 'application/vnd.quark.quarkxpress',
'qxl': 'application/vnd.quark.quarkxpress',
'qxt': 'application/vnd.quark.quarkxpress',
'ra': 'audio/x-pn-realaudio',
'ram': 'audio/x-pn-realaudio',
'rar': 'application/x-rar-compressed',
'ras': 'image/x-cmu-raster',
'rcprofile': 'application/vnd.ipunplugged.rcprofile',
'rdf': 'application/rdf+xml',
'rdz': 'application/vnd.data-vision.rdz',
'rep': 'application/vnd.businessobjects',
'res': 'application/x-dtbresource+xml',
'rgb': 'image/x-rgb',
'rif': 'application/reginfo+xml',
'rip': 'audio/vnd.rip',
'ris': 'application/x-research-info-systems',
'rl': 'application/resource-lists+xml',
'rlc': 'image/vnd.fujixerox.edmics-rlc',
'rld': 'application/resource-lists-diff+xml',
'rm': 'application/vnd.rn-realmedia',
'rmi': 'audio/midi',
'rmp': 'audio/x-pn-realaudio-plugin',
'rms': 'application/vnd.jcp.javame.midlet-rms',
'rmvb': 'application/vnd.rn-realmedia-vbr',
'rnc': 'application/relax-ng-compact-syntax',
'roa': 'application/rpki-roa',
'roff': 'text/troff',
'rp9': 'application/vnd.cloanto.rp9',
'rpss': 'application/vnd.nokia.radio-presets',
'rpst': 'application/vnd.nokia.radio-preset',
'rq': 'application/sparql-query',
'rs': 'application/rls-services+xml',
'rsd': 'application/rsd+xml',
'rss': 'application/rss+xml',
'rtf': 'application/rtf',
'rtx': 'text/richtext',
's': 'text/x-asm',
's3m': 'audio/s3m',
'saf': 'application/vnd.yamaha.smaf-audio',
'sbml': 'application/sbml+xml',
'sc': 'application/vnd.ibm.secure-container',
'scd': 'application/x-msschedule',
'scm': 'application/vnd.lotus-screencam',
'scq': 'application/scvp-cv-request',
'scs': 'application/scvp-cv-response',
'scurl': 'text/vnd.curl.scurl',
'sda': 'application/vnd.stardivision.draw',
'sdc': 'application/vnd.stardivision.calc',
'sdd': 'application/vnd.stardivision.impress',
'sdkd': 'application/vnd.solent.sdkm+xml',
'sdkm': 'application/vnd.solent.sdkm+xml',
'sdp': 'application/sdp',
'sdw': 'application/vnd.stardivision.writer',
'see': 'application/vnd.seemail',
'seed': 'application/vnd.fdsn.seed',
'sema': 'application/vnd.sema',
'semd': 'application/vnd.semd',
'semf': 'application/vnd.semf',
'ser': 'application/java-serialized-object',
'setpay': 'application/set-payment-initiation',
'setreg': 'application/set-registration-initiation',
'sfd-hdstx': 'application/vnd.hydrostatix.sof-data',
'sfs': 'application/vnd.spotfire.sfs',
'sfv': 'text/x-sfv',
'sgi': 'image/sgi',
'sgl': 'application/vnd.stardivision.writer-global',
'sgm': 'text/sgml',
'sgml': 'text/sgml',
'sh': 'application/x-sh',
'shar': 'application/x-shar',
'shf': 'application/shf+xml',
'sid': 'image/x-mrsid-image',
'sig': 'application/pgp-signature',
'sil': 'audio/silk',
'silo': 'model/mesh',
'sis': 'application/vnd.symbian.install',
'sisx': 'application/vnd.symbian.install',
'sit': 'application/x-stuffit',
'sitx': 'application/x-stuffitx',
'skd': 'application/vnd.koan',
'skm': 'application/vnd.koan',
'skp': 'application/vnd.koan',
'skt': 'application/vnd.koan',
'sldm': 'application/vnd.ms-powerpoint.slide.macroenabled.12',
'sldx': 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'slt': 'application/vnd.epson.salt',
'sm': 'application/vnd.stepmania.stepchart',
'smf': 'application/vnd.stardivision.math',
'smi': 'application/smil+xml',
'smil': 'application/smil+xml',
'smv': 'video/x-smv',
'smzip': 'application/vnd.stepmania.package',
'snd': 'audio/basic',
'snf': 'application/x-font-snf',
'so': 'application/octet-stream',
'spc': 'application/x-pkcs7-certificates',
'spf': 'application/vnd.yamaha.smaf-phrase',
'spl': 'application/x-futuresplash',
'spot': 'text/vnd.in3d.spot',
'spp': 'application/scvp-vp-response',
'spq': 'application/scvp-vp-request',
'spx': 'audio/ogg',
'sql': 'application/x-sql',
'src': 'application/x-wais-source',
'srt': 'application/x-subrip',
'sru': 'application/sru+xml',
'srx': 'application/sparql-results+xml',
'ssdl': 'application/ssdl+xml',
'sse': 'application/vnd.kodak-descriptor',
'ssf': 'application/vnd.epson.ssf',
'ssml': 'application/ssml+xml',
'st': 'application/vnd.sailingtracker.track',
'stc': 'application/vnd.sun.xml.calc.template',
'std': 'application/vnd.sun.xml.draw.template',
'stf': 'application/vnd.wt.stf',
'sti': 'application/vnd.sun.xml.impress.template',
'stk': 'application/hyperstudio',
'stl': 'application/vnd.ms-pki.stl',
'str': 'application/vnd.pg.format',
'stw': 'application/vnd.sun.xml.writer.template',
'sub': 'text/vnd.dvb.subtitle',
'sus': 'application/vnd.sus-calendar',
'susp': 'application/vnd.sus-calendar',
'sv4cpio': 'application/x-sv4cpio',
'sv4crc': 'application/x-sv4crc',
'svc': 'application/vnd.dvb.service',
'svd': 'application/vnd.svd',
'svg': 'image/svg+xml',
'svgz': 'image/svg+xml',
'swa': 'application/x-director',
'swf': 'application/x-shockwave-flash',
'swi': 'application/vnd.aristanetworks.swi',
'sxc': 'application/vnd.sun.xml.calc',
'sxd': 'application/vnd.sun.xml.draw',
'sxg': 'application/vnd.sun.xml.writer.global',
'sxi': 'application/vnd.sun.xml.impress',
'sxm': 'application/vnd.sun.xml.math',
'sxw': 'application/vnd.sun.xml.writer',
't': 'text/troff',
't3': 'application/x-t3vm-image',
'taglet': 'application/vnd.mynfc',
'tao': 'application/vnd.tao.intent-module-archive',
'tar': 'application/x-tar',
'tcap': 'application/vnd.3gpp2.tcap',
'tcl': 'application/x-tcl',
'teacher': 'application/vnd.smart.teacher',
'tei': 'application/tei+xml',
'teicorpus': 'application/tei+xml',
'tex': 'application/x-tex',
'texi': 'application/x-texinfo',
'texinfo': 'application/x-texinfo',
'text': 'text/plain',
'tfi': 'application/thraud+xml',
'tfm': 'application/x-tex-tfm',
'tga': 'image/x-tga',
'thmx': 'application/vnd.ms-officetheme',
'tif': 'image/tiff',
'tiff': 'image/tiff',
'tmo': 'application/vnd.tmobile-livetv',
'torrent': 'application/x-bittorrent',
'tpl': 'application/vnd.groove-tool-template',
'tpt': 'application/vnd.trid.tpt',
'tr': 'text/troff',
'tra': 'application/vnd.trueapp',
'trm': 'application/x-msterminal',
'tsd': 'application/timestamped-data',
'tsv': 'text/tab-separated-values',
'ttc': 'application/x-font-ttf',
'ttf': 'application/x-font-ttf',
'ttl': 'text/turtle',
'twd': 'application/vnd.simtech-mindmapper',
'twds': 'application/vnd.simtech-mindmapper',
'txd': 'application/vnd.genomatix.tuxedo',
'txf': 'application/vnd.mobius.txf',
'txt': 'text/plain',
'u32': 'application/x-authorware-bin',
'udeb': 'application/x-debian-package',
'ufd': 'application/vnd.ufdl',
'ufdl': 'application/vnd.ufdl',
'ulx': 'application/x-glulx',
'umj': 'application/vnd.umajin',
'unityweb': 'application/vnd.unity',
'uoml': 'application/vnd.uoml+xml',
'uri': 'text/uri-list',
'uris': 'text/uri-list',
'urls': 'text/uri-list',
'ustar': 'application/x-ustar',
'utz': 'application/vnd.uiq.theme',
'uu': 'text/x-uuencode',
'uva': 'audio/vnd.dece.audio',
'uvd': 'application/vnd.dece.data',
'uvf': 'application/vnd.dece.data',
'uvg': 'image/vnd.dece.graphic',
'uvh': 'video/vnd.dece.hd',
'uvi': 'image/vnd.dece.graphic',
'uvm': 'video/vnd.dece.mobile',
'uvp': 'video/vnd.dece.pd',
'uvs': 'video/vnd.dece.sd',
'uvt': 'application/vnd.dece.ttml+xml',
'uvu': 'video/vnd.uvvu.mp4',
'uvv': 'video/vnd.dece.video',
'uvva': 'audio/vnd.dece.audio',
'uvvd': 'application/vnd.dece.data',
'uvvf': 'application/vnd.dece.data',
'uvvg': 'image/vnd.dece.graphic',
'uvvh': 'video/vnd.dece.hd',
'uvvi': 'image/vnd.dece.graphic',
'uvvm': 'video/vnd.dece.mobile',
'uvvp': 'video/vnd.dece.pd',
'uvvs': 'video/vnd.dece.sd',
'uvvt': 'application/vnd.dece.ttml+xml',
'uvvu': 'video/vnd.uvvu.mp4',
'uvvv': 'video/vnd.dece.video',
'uvvx': 'application/vnd.dece.unspecified',
'uvvz': 'application/vnd.dece.zip',
'uvx': 'application/vnd.dece.unspecified',
'uvz': 'application/vnd.dece.zip',
'vcard': 'text/vcard',
'vcd': 'application/x-cdlink',
'vcf': 'text/x-vcard',
'vcg': 'application/vnd.groove-vcard',
'vcs': 'text/x-vcalendar',
'vcx': 'application/vnd.vcx',
'vis': 'application/vnd.visionary',
'viv': 'video/vnd.vivo',
'vob': 'video/x-ms-vob',
'vor': 'application/vnd.stardivision.writer',
'vox': 'application/x-authorware-bin',
'vrml': 'model/vrml',
'vsd': 'application/vnd.visio',
'vsf': 'application/vnd.vsf',
'vss': 'application/vnd.visio',
'vst': 'application/vnd.visio',
'vsw': 'application/vnd.visio',
'vtu': 'model/vnd.vtu',
'vxml': 'application/voicexml+xml',
'w3d': 'application/x-director',
'wad': 'application/x-doom',
'wasm': 'application/wasm',
'wav': 'audio/x-wav',
'wax': 'audio/x-ms-wax',
'wbmp': 'image/vnd.wap.wbmp',
'wbs': 'application/vnd.criticaltools.wbs+xml',
'wbxml': 'application/vnd.wap.wbxml',
'wcm': 'application/vnd.ms-works',
'wdb': 'application/vnd.ms-works',
'wdp': 'image/vnd.ms-photo',
'weba': 'audio/webm',
'webm': 'video/webm',
'webp': 'image/webp',
'wg': 'application/vnd.pmi.widget',
'wgt': 'application/widget',
'wks': 'application/vnd.ms-works',
'wm': 'video/x-ms-wm',
'wma': 'audio/x-ms-wma',
'wmd': 'application/x-ms-wmd',
'wmf': 'application/x-msmetafile',
'wml': 'text/vnd.wap.wml',
'wmlc': 'application/vnd.wap.wmlc',
'wmls': 'text/vnd.wap.wmlscript',
'wmlsc': 'application/vnd.wap.wmlscriptc',
'wmv': 'video/x-ms-wmv',
'wmx': 'video/x-ms-wmx',
'wmz': 'application/x-ms-wmz',
'woff': 'application/x-font-woff',
'wpd': 'application/vnd.wordperfect',
'wpl': 'application/vnd.ms-wpl',
'wps': 'application/vnd.ms-works',
'wqd': 'application/vnd.wqd',
'wri': 'application/x-mswrite',
'wrl': 'model/vrml',
'wsdl': 'application/wsdl+xml',
'wspolicy': 'application/wspolicy+xml',
'wtb': 'application/vnd.webturbo',
'wvx': 'video/x-ms-wvx',
'x32': 'application/x-authorware-bin',
'x3d': 'model/x3d+xml',
'x3db': 'model/x3d+binary',
'x3dbz': 'model/x3d+binary',
'x3dv': 'model/x3d+vrml',
'x3dvz': 'model/x3d+vrml',
'x3dz': 'model/x3d+xml',
'xaml': 'application/xaml+xml',
'xap': 'application/x-silverlight-app',
'xar': 'application/vnd.xara',
'xbap': 'application/x-ms-xbap',
'xbd': 'application/vnd.fujixerox.docuworks.binder',
'xbm': 'image/x-xbitmap',
'xdf': 'application/xcap-diff+xml',
'xdm': 'application/vnd.syncml.dm+xml',
'xdp': 'application/vnd.adobe.xdp+xml',
'xdssc': 'application/dssc+xml',
'xdw': 'application/vnd.fujixerox.docuworks',
'xenc': 'application/xenc+xml',
'xer': 'application/patch-ops-error+xml',
'xfdf': 'application/vnd.adobe.xfdf',
'xfdl': 'application/vnd.xfdl',
'xht': 'application/xhtml+xml',
'xhtml': 'application/xhtml+xml',
'xhvml': 'application/xv+xml',
'xif': 'image/vnd.xiff',
'xla': 'application/vnd.ms-excel',
'xlam': 'application/vnd.ms-excel.addin.macroenabled.12',
'xlc': 'application/vnd.ms-excel',
'xlf': 'application/x-xliff+xml',
'xlm': 'application/vnd.ms-excel',
'xls': 'application/vnd.ms-excel',
'xlsb': 'application/vnd.ms-excel.sheet.binary.macroenabled.12',
'xlsm': 'application/vnd.ms-excel.sheet.macroenabled.12',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlt': 'application/vnd.ms-excel',
'xltm': 'application/vnd.ms-excel.template.macroenabled.12',
'xltx':
'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'xlw': 'application/vnd.ms-excel',
'xm': 'audio/xm',
'xml': 'application/xml',
'xo': 'application/vnd.olpc-sugar',
'xop': 'application/xop+xml',
'xpi': 'application/x-xpinstall',
'xpl': 'application/xproc+xml',
'xpm': 'image/x-xpixmap',
'xpr': 'application/vnd.is-xpr',
'xps': 'application/vnd.ms-xpsdocument',
'xpw': 'application/vnd.intercon.formnet',
'xpx': 'application/vnd.intercon.formnet',
'xsl': 'application/xml',
'xslt': 'application/xslt+xml',
'xsm': 'application/vnd.syncml+xml',
'xspf': 'application/xspf+xml',
'xul': 'application/vnd.mozilla.xul+xml',
'xvm': 'application/xv+xml',
'xvml': 'application/xv+xml',
'xwd': 'image/x-xwindowdump',
'xyz': 'chemical/x-xyz',
'xz': 'application/x-xz',
'yang': 'application/yang',
'yin': 'application/yin+xml',
'z1': 'application/x-zmachine',
'z2': 'application/x-zmachine',
'z3': 'application/x-zmachine',
'z4': 'application/x-zmachine',
'z5': 'application/x-zmachine',
'z6': 'application/x-zmachine',
'z7': 'application/x-zmachine',
'z8': 'application/x-zmachine',
'zaz': 'application/vnd.zzazz.deck+xml',
'zip': 'application/zip',
'zir': 'application/vnd.zul',
'zirz': 'application/vnd.zul',
'zmm': 'application/vnd.handheld-entertainment+xml',
};
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/async.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.
export 'src/async_cache.dart';
export 'src/async_memoizer.dart';
export 'src/byte_collector.dart';
export 'src/cancelable_operation.dart';
export 'src/delegate/event_sink.dart';
export 'src/delegate/future.dart';
export 'src/delegate/sink.dart';
export 'src/delegate/stream.dart';
export 'src/delegate/stream_consumer.dart';
export 'src/delegate/stream_sink.dart';
export 'src/delegate/stream_subscription.dart';
export 'src/future_group.dart';
export 'src/lazy_stream.dart';
export 'src/null_stream_sink.dart';
export 'src/restartable_timer.dart';
export 'src/result/result.dart';
export 'src/result/error.dart';
export 'src/result/future.dart';
export 'src/result/value.dart';
export 'src/single_subscription_transformer.dart';
export 'src/stream_completer.dart';
export 'src/stream_group.dart';
export 'src/stream_queue.dart';
export 'src/stream_sink_completer.dart';
export 'src/stream_sink_transformer.dart';
export 'src/stream_splitter.dart';
export 'src/stream_subscription_transformer.dart';
export 'src/stream_zip.dart';
export 'src/subscription_stream.dart';
export 'src/typed_stream_transformer.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_queue.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:collection';
import 'package:collection/collection.dart';
import 'cancelable_operation.dart';
import 'result/result.dart';
import 'subscription_stream.dart';
import 'stream_completer.dart';
import 'stream_splitter.dart';
/// An asynchronous pull-based interface for accessing stream events.
///
/// Wraps a stream and makes individual events available on request.
///
/// You can request (and reserve) one or more events from the stream,
/// and after all previous requests have been fulfilled, stream events
/// go towards fulfilling your request.
///
/// For example, if you ask for [next] two times, the returned futures
/// will be completed by the next two unrequested events from the stream.
///
/// The stream subscription is paused when there are no active
/// requests.
///
/// Some streams, including broadcast streams, will buffer
/// events while paused, so waiting too long between requests may
/// cause memory bloat somewhere else.
///
/// This is similar to, but more convenient than, a [StreamIterator].
/// A `StreamIterator` requires you to manually check when a new event is
/// available and you can only access the value of that event until you
/// check for the next one. A `StreamQueue` allows you to request, for example,
/// three events at a time, either individually, as a group using [take]
/// or [skip], or in any combination.
///
/// You can also ask to have the [rest] of the stream provided as
/// a new stream. This allows, for example, taking the first event
/// out of a stream and continuing to use the rest of the stream as a stream.
///
/// Example:
///
/// var events = StreamQueue<String>(someStreamOfLines);
/// var first = await events.next;
/// while (first.startsWith('#')) {
/// // Skip comments.
/// first = await events.next;
/// }
///
/// if (first.startsWith(MAGIC_MARKER)) {
/// var headerCount =
/// first.parseInt(first.substring(MAGIC_MARKER.length + 1));
/// handleMessage(headers: await events.take(headerCount),
/// body: events.rest);
/// return;
/// }
/// // Error handling.
///
/// When you need no further events the `StreamQueue` should be closed
/// using [cancel]. This releases the underlying stream subscription.
class StreamQueue<T> {
// This class maintains two queues: one of events and one of requests.
// The active request (the one in front of the queue) is called with
// the current event queue when it becomes active, every time a
// new event arrives, and when the event source closes.
//
// If the request returns `true`, it's complete and will be removed from the
// request queue.
// If the request returns `false`, it needs more events, and will be called
// again when new events are available. It may trigger a call itself by
// calling [_updateRequests].
// The request can remove events that it uses, or keep them in the event
// queue until it has all that it needs.
//
// This model is very flexible and easily extensible.
// It allows requests that don't consume events (like [hasNext]) or
// potentially a request that takes either five or zero events, determined
// by the content of the fifth event.
final Stream<T> _source;
/// Subscription on [_source] while listening for events.
///
/// Set to subscription when listening, and set to `null` when the
/// subscription is done (and [_isDone] is set to true).
StreamSubscription<T> _subscription;
/// Whether the event source is done.
bool _isDone = false;
/// Whether a closing operation has been performed on the stream queue.
///
/// Closing operations are [cancel] and [rest].
bool _isClosed = false;
/// The number of events dispatched by this queue.
///
/// This counts error events. It doesn't count done events, or events
/// dispatched to a stream returned by [rest].
int get eventsDispatched => _eventsReceived - _eventQueue.length;
/// The number of events received by this queue.
var _eventsReceived = 0;
/// Queue of events not used by a request yet.
final QueueList<Result<T>> _eventQueue = QueueList();
/// Queue of pending requests.
///
/// Access through methods below to ensure consistency.
final Queue<_EventRequest> _requestQueue = Queue();
/// Create a `StreamQueue` of the events of [source].
factory StreamQueue(Stream<T> source) => StreamQueue._(source);
// Private generative constructor to avoid subclasses.
StreamQueue._(this._source) {
// Start listening immediately if we could otherwise lose events.
if (_source.isBroadcast) {
_ensureListening();
_pause();
}
}
/// Asks if the stream has any more events.
///
/// Returns a future that completes with `true` if the stream has any
/// more events, whether data or error.
/// If the stream closes without producing any more events, the returned
/// future completes with `false`.
///
/// Can be used before using [next] to avoid getting an error in the
/// future returned by `next` in the case where there are no more events.
/// Another alternative is to use `take(1)` which returns either zero or
/// one events.
Future<bool> get hasNext {
if (!_isClosed) {
var hasNextRequest = _HasNextRequest<T>();
_addRequest(hasNextRequest);
return hasNextRequest.future;
}
throw _failClosed();
}
/// Look at the next [count] data events without consuming them.
///
/// Works like [take] except that the events are left in the queue.
/// If one of the next [count] events is an error, the returned future
/// completes with this error, and the error is still left in the queue.
Future<List<T>> lookAhead(int count) {
if (count < 0) throw RangeError.range(count, 0, null, 'count');
if (!_isClosed) {
var request = _LookAheadRequest<T>(count);
_addRequest(request);
return request.future;
}
throw _failClosed();
}
/// Requests the next (yet unrequested) event from the stream.
///
/// When the requested event arrives, the returned future is completed with
/// the event.
/// If the event is a data event, the returned future completes
/// with its value.
/// If the event is an error event, the returned future completes with
/// its error and stack trace.
/// If the stream closes before an event arrives, the returned future
/// completes with a [StateError].
///
/// It's possible to have several pending [next] calls (or other requests),
/// and they will be completed in the order they were requested, by the
/// first events that were not consumed by previous requeusts.
Future<T> get next {
if (!_isClosed) {
var nextRequest = _NextRequest<T>();
_addRequest(nextRequest);
return nextRequest.future;
}
throw _failClosed();
}
/// Looks at the next (yet unrequested) event from the stream.
///
/// Like [next] except that the event is not consumed.
/// If the next event is an error event, it stays in the queue.
Future<T> get peek {
if (!_isClosed) {
var nextRequest = _PeekRequest<T>();
_addRequest(nextRequest);
return nextRequest.future;
}
throw _failClosed();
}
/// Returns a stream of all the remaning events of the source stream.
///
/// All requested [next], [skip] or [take] operations are completed
/// first, and then any remaining events are provided as events of
/// the returned stream.
///
/// Using `rest` closes this stream queue. After getting the
/// `rest` the caller may no longer request other events, like
/// after calling [cancel].
Stream<T> get rest {
if (_isClosed) {
throw _failClosed();
}
var request = _RestRequest<T>(this);
_isClosed = true;
_addRequest(request);
return request.stream;
}
/// Skips the next [count] *data* events.
///
/// The [count] must be non-negative.
///
/// When successful, this is equivalent to using [take]
/// and ignoring the result.
///
/// If an error occurs before `count` data events have been skipped,
/// the returned future completes with that error instead.
///
/// If the stream closes before `count` data events,
/// the remaining unskipped event count is returned.
/// If the returned future completes with the integer `0`,
/// then all events were succssfully skipped. If the value
/// is greater than zero then the stream ended early.
Future<int> skip(int count) {
if (count < 0) throw RangeError.range(count, 0, null, 'count');
if (!_isClosed) {
var request = _SkipRequest<T>(count);
_addRequest(request);
return request.future;
}
throw _failClosed();
}
/// Requests the next [count] data events as a list.
///
/// The [count] must be non-negative.
///
/// Equivalent to calling [next] `count` times and
/// storing the data values in a list.
///
/// If an error occurs before `count` data events has
/// been collected, the returned future completes with
/// that error instead.
///
/// If the stream closes before `count` data events,
/// the returned future completes with the list
/// of data collected so far. That is, the returned
/// list may have fewer than [count] elements.
Future<List<T>> take(int count) {
if (count < 0) throw RangeError.range(count, 0, null, 'count');
if (!_isClosed) {
var request = _TakeRequest<T>(count);
_addRequest(request);
return request.future;
}
throw _failClosed();
}
/// Requests a transaction that can conditionally consume events.
///
/// The transaction can create copies of this queue at the current position
/// using [StreamQueueTransaction.newQueue]. Each of these queues is
/// independent of one another and of the parent queue. The transaction
/// finishes when one of two methods is called:
///
/// * [StreamQueueTransaction.commit] updates the parent queue's position to
/// match that of one of the copies.
///
/// * [StreamQueueTransaction.reject] causes the parent queue to continue as
/// though [startTransaction] hadn't been called.
///
/// Until the transaction finishes, this queue won't emit any events.
///
/// See also [withTransaction] and [cancelable].
///
/// ```dart
/// /// Consumes all empty lines from the beginning of [lines].
/// Future consumeEmptyLines(StreamQueue<String> lines) async {
/// while (await lines.hasNext) {
/// var transaction = lines.startTransaction();
/// var queue = transaction.newQueue();
/// if ((await queue.next).isNotEmpty) {
/// transaction.reject();
/// return;
/// } else {
/// transaction.commit(queue);
/// }
/// }
/// }
/// ```
StreamQueueTransaction<T> startTransaction() {
if (_isClosed) throw _failClosed();
var request = _TransactionRequest(this);
_addRequest(request);
return request.transaction;
}
/// Passes a copy of this queue to [callback], and updates this queue to match
/// the copy's position if [callback] returns `true`.
///
/// This queue won't emit any events until [callback] returns. If it returns
/// `false`, this queue continues as though [withTransaction] hadn't been
/// called. If it throws an error, this updates this queue to match the copy's
/// position and throws the error from the returned `Future`.
///
/// Returns the same value as [callback].
///
/// See also [startTransaction] and [cancelable].
///
/// ```dart
/// /// Consumes all empty lines from the beginning of [lines].
/// Future consumeEmptyLines(StreamQueue<String> lines) async {
/// while (await lines.hasNext) {
/// // Consume a line if it's empty, otherwise return.
/// if (!await lines.withTransaction(
/// (queue) async => (await queue.next).isEmpty)) {
/// return;
/// }
/// }
/// }
/// ```
Future<bool> withTransaction(Future<bool> Function(StreamQueue<T>) callback) {
var transaction = startTransaction();
/// Avoid async/await to ensure that [startTransaction] is called
/// synchronously and so ends up in the right place in the request queue.
var queue = transaction.newQueue();
return callback(queue).then((result) {
if (result) {
transaction.commit(queue);
} else {
transaction.reject();
}
return result;
}, onError: (error) {
transaction.commit(queue);
throw error;
});
}
/// Passes a copy of this queue to [callback], and updates this queue to match
/// the copy's position once [callback] completes.
///
/// If the returned [CancelableOperation] is canceled, this queue instead
/// continues as though [cancelable] hadn't been called. Otherwise, it emits
/// the same value or error as [callback].
///
/// See also [startTransaction] and [withTransaction].
///
/// ```dart
/// final _stdinQueue = StreamQueue(stdin);
///
/// /// Returns an operation that completes when the user sends a line to
/// /// standard input.
/// ///
/// /// If the operation is canceled, stops waiting for user input.
/// CancelableOperation<String> nextStdinLine() =>
/// _stdinQueue.cancelable((queue) => queue.next);
/// ```
CancelableOperation<S> cancelable<S>(
Future<S> Function(StreamQueue<T>) callback) {
var transaction = startTransaction();
var completer = CancelableCompleter<S>(onCancel: () {
transaction.reject();
});
var queue = transaction.newQueue();
completer.complete(callback(queue).whenComplete(() {
if (!completer.isCanceled) transaction.commit(queue);
}));
return completer.operation;
}
/// Cancels the underlying event source.
///
/// If [immediate] is `false` (the default), the cancel operation waits until
/// all previously requested events have been processed, then it cancels the
/// subscription providing the events.
///
/// If [immediate] is `true`, the source is instead canceled
/// immediately. Any pending events are completed as though the underlying
/// stream had closed.
///
/// The returned future completes with the result of calling
/// `cancel`.
///
/// After calling `cancel`, no further events can be requested.
/// None of [lookAhead], [next], [peek], [rest], [skip], [take] or [cancel]
/// may be called again.
Future cancel({bool immediate = false}) {
if (_isClosed) throw _failClosed();
_isClosed = true;
if (!immediate) {
var request = _CancelRequest<T>(this);
_addRequest(request);
return request.future;
}
if (_isDone && _eventQueue.isEmpty) return Future.value();
return _cancel();
}
// ------------------------------------------------------------------
// Methods that may be called from the request implementations to
// control the event stream.
/// Matches events with requests.
///
/// Called after receiving an event or when the event source closes.
///
/// May be called by requests which have returned `false` (saying they
/// are not yet done) so they can be checked again before any new
/// events arrive.
/// Any request returing `false` from `update` when `isDone` is `true`
/// *must* call `_updateRequests` when they are ready to continue
/// (since no further events will trigger the call).
void _updateRequests() {
while (_requestQueue.isNotEmpty) {
if (_requestQueue.first.update(_eventQueue, _isDone)) {
_requestQueue.removeFirst();
} else {
return;
}
}
if (!_isDone) {
_pause();
}
}
/// Extracts a stream from the event source and makes this stream queue
/// unusable.
///
/// Can only be used by the very last request (the stream queue must
/// be closed by that request).
/// Only used by [rest].
Stream<T> _extractStream() {
assert(_isClosed);
if (_isDone) {
return Stream<T>.empty();
}
_isDone = true;
if (_subscription == null) {
return _source;
}
var subscription = _subscription;
_subscription = null;
var wasPaused = subscription.isPaused;
var result = SubscriptionStream<T>(subscription);
// Resume after creating stream because that pauses the subscription too.
// This way there won't be a short resumption in the middle.
if (wasPaused) subscription.resume();
return result;
}
/// Requests that the event source pauses events.
///
/// This is called automatically when the request queue is empty.
///
/// The event source is restarted by the next call to [_ensureListening].
void _pause() {
_subscription.pause();
}
/// Ensures that we are listening on events from the event source.
///
/// Starts listening for the first time or resumes after a [_pause].
///
/// Is called automatically if a request requires more events.
void _ensureListening() {
if (_isDone) return;
if (_subscription == null) {
_subscription = _source.listen((data) {
_addResult(Result.value(data));
}, onError: (error, StackTrace stackTrace) {
_addResult(Result.error(error, stackTrace));
}, onDone: () {
_subscription = null;
_close();
});
} else {
_subscription.resume();
}
}
/// Cancels the underlying event source.
Future _cancel() {
if (_isDone) return null;
_subscription ??= _source.listen(null);
var future = _subscription.cancel();
_close();
return future;
}
// ------------------------------------------------------------------
// Methods called by the event source to add events or say that it's
// done.
/// Called when the event source adds a new data or error event.
/// Always calls [_updateRequests] after adding.
void _addResult(Result<T> result) {
_eventsReceived++;
_eventQueue.add(result);
_updateRequests();
}
/// Called when the event source is done.
/// Always calls [_updateRequests] after adding.
void _close() {
_isDone = true;
_updateRequests();
}
// ------------------------------------------------------------------
// Internal helper methods.
/// Returns an error for when a request is made after cancel.
///
/// Returns a [StateError] with a message saying that either
/// [cancel] or [rest] have already been called.
Error _failClosed() {
return StateError('Already cancelled');
}
/// Adds a new request to the queue.
///
/// If the request queue is empty and the request can be completed
/// immediately, it skips the queue.
void _addRequest(_EventRequest<T> request) {
if (_requestQueue.isEmpty) {
if (request.update(_eventQueue, _isDone)) return;
_ensureListening();
}
_requestQueue.add(request);
}
}
/// A transaction on a [StreamQueue], created by [StreamQueue.startTransaction].
///
/// Copies of the parent queue may be created using [newQueue]. Calling [commit]
/// moves the parent queue to a copy's position, and calling [reject] causes it
/// to continue as though [StreamQueue.startTransaction] was never called.
class StreamQueueTransaction<T> {
/// The parent queue on which this transaction is active.
final StreamQueue<T> _parent;
/// The splitter that produces copies of the parent queue's stream.
final StreamSplitter<T> _splitter;
/// Queues created using [newQueue].
final _queues = <StreamQueue>{};
/// Whether [commit] has been called.
var _committed = false;
/// Whether [reject] has been called.
var _rejected = false;
StreamQueueTransaction._(this._parent, Stream<T> source)
: _splitter = StreamSplitter(source);
/// Creates a new copy of the parent queue.
///
/// This copy starts at the parent queue's position when
/// [StreamQueue.startTransaction] was called. Its position can be committed
/// to the parent queue using [commit].
StreamQueue<T> newQueue() {
var queue = StreamQueue(_splitter.split());
_queues.add(queue);
return queue;
}
/// Commits a queue created using [newQueue].
///
/// The parent queue's position is updated to be the same as [queue]'s.
/// Further requests on all queues created by this transaction, including
/// [queue], will complete as though [cancel] were called with `immediate:
/// true`.
///
/// Throws a [StateError] if [commit] or [reject] have already been called, or
/// if there are pending requests on [queue].
void commit(StreamQueue<T> queue) {
_assertActive();
if (!_queues.contains(queue)) {
throw ArgumentError("Queue doesn't belong to this transaction.");
} else if (queue._requestQueue.isNotEmpty) {
throw StateError("A queue with pending requests can't be committed.");
}
_committed = true;
// Remove all events from the parent queue that were consumed by the
// child queue.
for (var j = 0; j < queue.eventsDispatched; j++) {
_parent._eventQueue.removeFirst();
}
_done();
}
/// Rejects this transaction without updating the parent queue.
///
/// The parent will continue as though [StreamQueue.startTransaction] hadn't
/// been called. Further requests on all queues created by this transaction
/// will complete as though [cancel] were called with `immediate: true`.
///
/// Throws a [StateError] if [commit] or [reject] have already been called.
void reject() {
_assertActive();
_rejected = true;
_done();
}
// Cancels all [_queues], removes the [_TransactionRequest] from [_parent]'s
// request queue, and runs the next request.
void _done() {
_splitter.close();
for (var queue in _queues) {
queue._cancel();
}
// If this is the active request in the queue, mark it as finished.
var currentRequest = _parent._requestQueue.first;
if (currentRequest is _TransactionRequest &&
currentRequest.transaction == this) {
_parent._requestQueue.removeFirst();
_parent._updateRequests();
}
}
/// Throws a [StateError] if [accept] or [reject] has already been called.
void _assertActive() {
if (_committed) {
throw StateError('This transaction has already been accepted.');
} else if (_rejected) {
throw StateError('This transaction has already been rejected.');
}
}
}
/// Request object that receives events when they arrive, until fulfilled.
///
/// Each request that cannot be fulfilled immediately is represented by
/// an `_EventRequest` object in the request queue.
///
/// Events from the source stream are sent to the first request in the
/// queue until it reports itself as [isComplete].
///
/// When the first request in the queue `isComplete`, either when becoming
/// the first request or after receiving an event, its [close] methods is
/// called.
///
/// The [close] method is also called immediately when the source stream
/// is done.
abstract class _EventRequest<T> {
/// Handle available events.
///
/// The available events are provided as a queue. The `update` function
/// should only remove events from the front of the event queue, e.g.,
/// using [removeFirst].
///
/// Returns `true` if the request is completed, or `false` if it needs
/// more events.
/// The call may keep events in the queue until the requeust is complete,
/// or it may remove them immediately.
///
/// If the method returns true, the request is considered fulfilled, and
/// will never be called again.
///
/// This method is called when a request reaches the front of the request
/// queue, and if it returns `false`, it's called again every time a new event
/// becomes available, or when the stream closes.
/// If the function returns `false` when the stream has already closed
/// ([isDone] is true), then the request must call
/// [StreamQueue._updateRequests] itself when it's ready to continue.
bool update(QueueList<Result<T>> events, bool isDone);
}
/// Request for a [StreamQueue.next] call.
///
/// Completes the returned future when receiving the first event,
/// and is then complete.
class _NextRequest<T> implements _EventRequest<T> {
/// Completer for the future returned by [StreamQueue.next].
final _completer = Completer<T>();
_NextRequest();
Future<T> get future => _completer.future;
@override
bool update(QueueList<Result<T>> events, bool isDone) {
if (events.isNotEmpty) {
events.removeFirst().complete(_completer);
return true;
}
if (isDone) {
_completer.completeError(StateError('No elements'), StackTrace.current);
return true;
}
return false;
}
}
/// Request for a [StreamQueue.peek] call.
///
/// Completes the returned future when receiving the first event,
/// and is then complete, but doesn't consume the event.
class _PeekRequest<T> implements _EventRequest<T> {
/// Completer for the future returned by [StreamQueue.next].
final _completer = Completer<T>();
_PeekRequest();
Future<T> get future => _completer.future;
@override
bool update(QueueList<Result<T>> events, bool isDone) {
if (events.isNotEmpty) {
events.first.complete(_completer);
return true;
}
if (isDone) {
_completer.completeError(StateError('No elements'), StackTrace.current);
return true;
}
return false;
}
}
/// Request for a [StreamQueue.skip] call.
class _SkipRequest<T> implements _EventRequest<T> {
/// Completer for the future returned by the skip call.
final _completer = Completer<int>();
/// Number of remaining events to skip.
///
/// The request [isComplete] when the values reaches zero.
///
/// Decremented when an event is seen.
/// Set to zero when an error is seen since errors abort the skip request.
int _eventsToSkip;
_SkipRequest(this._eventsToSkip);
/// The future completed when the correct number of events have been skipped.
Future<int> get future => _completer.future;
@override
bool update(QueueList<Result<T>> events, bool isDone) {
while (_eventsToSkip > 0) {
if (events.isEmpty) {
if (isDone) break;
return false;
}
_eventsToSkip--;
var event = events.removeFirst();
if (event.isError) {
_completer.completeError(event.asError.error, event.asError.stackTrace);
return true;
}
}
_completer.complete(_eventsToSkip);
return true;
}
}
/// Common superclass for [_TakeRequest] and [_LookAheadRequest].
abstract class _ListRequest<T> implements _EventRequest<T> {
/// Completer for the future returned by the take call.
final _completer = Completer<List<T>>();
/// List collecting events until enough have been seen.
final _list = <T>[];
/// Number of events to capture.
///
/// The request [isComplete] when the length of [_list] reaches
/// this value.
final int _eventsToTake;
_ListRequest(this._eventsToTake);
/// The future completed when the correct number of events have been captured.
Future<List<T>> get future => _completer.future;
}
/// Request for a [StreamQueue.take] call.
class _TakeRequest<T> extends _ListRequest<T> {
_TakeRequest(int eventsToTake) : super(eventsToTake);
@override
bool update(QueueList<Result<T>> events, bool isDone) {
while (_list.length < _eventsToTake) {
if (events.isEmpty) {
if (isDone) break;
return false;
}
var event = events.removeFirst();
if (event.isError) {
event.asError.complete(_completer);
return true;
}
_list.add(event.asValue.value);
}
_completer.complete(_list);
return true;
}
}
/// Request for a [StreamQueue.lookAhead] call.
class _LookAheadRequest<T> extends _ListRequest<T> {
_LookAheadRequest(int eventsToTake) : super(eventsToTake);
@override
bool update(QueueList<Result<T>> events, bool isDone) {
while (_list.length < _eventsToTake) {
if (events.length == _list.length) {
if (isDone) break;
return false;
}
var event = events.elementAt(_list.length);
if (event.isError) {
event.asError.complete(_completer);
return true;
}
_list.add(event.asValue.value);
}
_completer.complete(_list);
return true;
}
}
/// Request for a [StreamQueue.cancel] call.
///
/// The request needs no events, it just waits in the request queue
/// until all previous events are fulfilled, then it cancels the stream queue
/// source subscription.
class _CancelRequest<T> implements _EventRequest<T> {
/// Completer for the future returned by the `cancel` call.
final _completer = Completer<void>();
/// When the event is completed, it needs to cancel the active subscription
/// of the `StreamQueue` object, if any.
final StreamQueue _streamQueue;
_CancelRequest(this._streamQueue);
/// The future completed when the cancel request is completed.
Future get future => _completer.future;
@override
bool update(QueueList<Result<T>> events, bool isDone) {
if (_streamQueue._isDone) {
_completer.complete();
} else {
_streamQueue._ensureListening();
_completer.complete(_streamQueue._extractStream().listen(null).cancel());
}
return true;
}
}
/// Request for a [StreamQueue.rest] call.
///
/// The request is always complete, it just waits in the request queue
/// until all previous events are fulfilled, then it takes over the
/// stream events subscription and creates a stream from it.
class _RestRequest<T> implements _EventRequest<T> {
/// Completer for the stream returned by the `rest` call.
final _completer = StreamCompleter<T>();
/// The [StreamQueue] object that has this request queued.
///
/// When the event is completed, it needs to cancel the active subscription
/// of the `StreamQueue` object, if any.
final StreamQueue<T> _streamQueue;
_RestRequest(this._streamQueue);
/// The stream which will contain the remaining events of [_streamQueue].
Stream<T> get stream => _completer.stream;
@override
bool update(QueueList<Result<T>> events, bool isDone) {
if (events.isEmpty) {
if (_streamQueue._isDone) {
_completer.setEmpty();
} else {
_completer.setSourceStream(_streamQueue._extractStream());
}
} else {
// There are prefetched events which needs to be added before the
// remaining stream.
var controller = StreamController<T>();
for (var event in events) {
event.addTo(controller);
}
controller
.addStream(_streamQueue._extractStream(), cancelOnError: false)
.whenComplete(controller.close);
_completer.setSourceStream(controller.stream);
}
return true;
}
}
/// Request for a [StreamQueue.hasNext] call.
///
/// Completes the [future] with `true` if it sees any event,
/// but doesn't consume the event.
/// If the request is closed without seeing an event, then
/// the [future] is completed with `false`.
class _HasNextRequest<T> implements _EventRequest<T> {
final _completer = Completer<bool>();
Future<bool> get future => _completer.future;
@override
bool update(QueueList<Result<T>> events, bool isDone) {
if (events.isNotEmpty) {
_completer.complete(true);
return true;
}
if (isDone) {
_completer.complete(false);
return true;
}
return false;
}
}
/// Request for a [StreamQueue.startTransaction] call.
///
/// This request isn't complete until the user calls
/// [StreamQueueTransaction.commit] or [StreamQueueTransaction.reject], at which
/// point it manually removes itself from the request queue and calls
/// [StreamQueue._updateRequests].
class _TransactionRequest<T> implements _EventRequest<T> {
/// The transaction created by this request.
StreamQueueTransaction<T> get transaction => _transaction;
StreamQueueTransaction<T> _transaction;
/// The controller that passes events to [transaction].
final _controller = StreamController<T>(sync: true);
/// The number of events passed to [_controller] so far.
var _eventsSent = 0;
_TransactionRequest(StreamQueue<T> parent) {
_transaction = StreamQueueTransaction._(parent, _controller.stream);
}
@override
bool update(QueueList<Result<T>> events, bool isDone) {
while (_eventsSent < events.length) {
events[_eventsSent++].addTo(_controller);
}
if (isDone && !_controller.isClosed) _controller.close();
return transaction._committed || _transaction._rejected;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/lazy_stream.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 'stream_completer.dart';
import 'utils.dart';
/// A [Stream] wrapper that forwards to another [Stream] that's initialized
/// lazily.
///
/// This class allows a concrete `Stream` to be created only once it has a
/// listener. It's useful to wrapping APIs that do expensive computation to
/// produce a `Stream`.
class LazyStream<T> extends Stream<T> {
/// The callback that's called to create the inner stream.
FutureOrCallback<Stream<T>> _callback;
/// Creates a single-subscription `Stream` that calls [callback] when it gets
/// a listener and forwards to the returned stream.
LazyStream(FutureOr<Stream<T>> Function() callback) : _callback = callback {
// Explicitly check for null because we null out [_callback] internally.
if (_callback == null) throw ArgumentError.notNull('callback');
}
@override
StreamSubscription<T> listen(void Function(T) onData,
{Function onError, void Function() onDone, bool cancelOnError}) {
if (_callback == null) {
throw StateError('Stream has already been listened to.');
}
// Null out the callback before we invoke it to ensure that even while
// running it, this can't be called twice.
var callback = _callback;
_callback = null;
var result = callback();
Stream<T> stream;
if (result is Future<Stream<T>>) {
stream = StreamCompleter.fromFuture(result);
} else {
stream = result as Stream<T>;
}
return stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_splitter.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 'future_group.dart';
import 'result/result.dart';
/// A class that splits a single source stream into an arbitrary number of
/// (single-subscription) streams (called "branch") that emit the same events.
///
/// Each branch will emit all the same values and errors as the source stream,
/// regardless of which values have been emitted on other branches. This means
/// that the splitter stores every event that has been emitted so far, which may
/// consume a lot of memory. The user can call [close] to indicate that no more
/// branches will be created, and this memory will be released.
///
/// The source stream is only listened to once a branch is created *and listened
/// to*. It's paused when all branches are paused *or when all branches are
/// canceled*, and resumed once there's at least one branch that's listening and
/// unpaused. It's not canceled unless no branches are listening and [close] has
/// been called.
class StreamSplitter<T> {
/// The wrapped stream.
final Stream<T> _stream;
/// The subscription to [_stream].
///
/// This will be `null` until a branch has a listener.
StreamSubscription<T> _subscription;
/// The buffer of events or errors that have already been emitted by
/// [_stream].
final _buffer = <Result<T>>[];
/// The controllers for branches that are listening for future events from
/// [_stream].
///
/// Once a branch is canceled, it's removed from this list. When [_stream] is
/// done, all branches are removed.
final _controllers = <StreamController<T>>{};
/// A group of futures returned by [close].
///
/// This is used to ensure that [close] doesn't complete until all
/// [StreamController.close] and [StreamSubscription.cancel] calls complete.
final _closeGroup = FutureGroup();
/// Whether [_stream] is done emitting events.
var _isDone = false;
/// Whether [close] has been called.
var _isClosed = false;
/// Splits [stream] into [count] identical streams.
///
/// [count] defaults to 2. This is the same as creating [count] branches and
/// then closing the [StreamSplitter].
static List<Stream<T>> splitFrom<T>(Stream<T> stream, [int count]) {
count ??= 2;
var splitter = StreamSplitter<T>(stream);
var streams = List<Stream<T>>.generate(count, (_) => splitter.split());
splitter.close();
return streams;
}
StreamSplitter(this._stream);
/// Returns a single-subscription stream that's a copy of the input stream.
///
/// This will throw a [StateError] if [close] has been called.
Stream<T> split() {
if (_isClosed) {
throw StateError("Can't call split() on a closed StreamSplitter.");
}
var controller = StreamController<T>(
onListen: _onListen, onPause: _onPause, onResume: _onResume);
controller.onCancel = () => _onCancel(controller);
for (var result in _buffer) {
result.addTo(controller);
}
if (_isDone) {
_closeGroup.add(controller.close());
} else {
_controllers.add(controller);
}
return controller.stream;
}
/// Indicates that no more branches will be requested via [split].
///
/// This clears the internal buffer of events. If there are no branches or all
/// branches have been canceled, this cancels the subscription to the input
/// stream.
///
/// Returns a [Future] that completes once all events have been processed by
/// all branches and (if applicable) the subscription to the input stream has
/// been canceled.
Future close() {
if (_isClosed) return _closeGroup.future;
_isClosed = true;
_buffer.clear();
if (_controllers.isEmpty) _cancelSubscription();
return _closeGroup.future;
}
/// Cancel [_subscription] and close [_closeGroup].
///
/// This should be called after all the branches' subscriptions have been
/// canceled and the splitter has been closed. In that case, we won't use the
/// events from [_subscription] any more, since there's nothing to pipe them
/// to and no more branches will be created. If [_subscription] is done,
/// canceling it will be a no-op.
///
/// This may also be called before any branches have been created, in which
/// case [_subscription] will be `null`.
void _cancelSubscription() {
assert(_controllers.isEmpty);
assert(_isClosed);
Future future;
if (_subscription != null) future = _subscription.cancel();
if (future != null) _closeGroup.add(future);
_closeGroup.close();
}
// StreamController events
/// Subscribe to [_stream] if we haven't yet done so, and resume the
/// subscription if we have.
void _onListen() {
if (_isDone) return;
if (_subscription != null) {
// Resume the subscription in case it was paused, either because all the
// controllers were paused or because the last one was canceled. If it
// wasn't paused, this will be a no-op.
_subscription.resume();
} else {
_subscription =
_stream.listen(_onData, onError: _onError, onDone: _onDone);
}
}
/// Pauses [_subscription] if every controller is paused.
void _onPause() {
if (!_controllers.every((controller) => controller.isPaused)) return;
_subscription.pause();
}
/// Resumes [_subscription].
///
/// If [_subscription] wasn't paused, this is a no-op.
void _onResume() {
_subscription.resume();
}
/// Removes [controller] from [_controllers] and cancels or pauses
/// [_subscription] as appropriate.
///
/// Since the controller emitting a done event will cause it to register as
/// canceled, this is the only way that a controller is ever removed from
/// [_controllers].
void _onCancel(StreamController controller) {
_controllers.remove(controller);
if (_controllers.isNotEmpty) return;
if (_isClosed) {
_cancelSubscription();
} else {
_subscription.pause();
}
}
// Stream events
/// Buffers [data] and passes it to [_controllers].
void _onData(T data) {
if (!_isClosed) _buffer.add(Result.value(data));
for (var controller in _controllers) {
controller.add(data);
}
}
/// Buffers [error] and passes it to [_controllers].
void _onError(Object error, StackTrace stackTrace) {
if (!_isClosed) _buffer.add(Result.error(error, stackTrace));
for (var controller in _controllers) {
controller.addError(error, stackTrace);
}
}
/// Marks [_controllers] as done.
void _onDone() {
_isDone = true;
for (var controller in _controllers) {
_closeGroup.add(controller.close());
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_sink_completer.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:async';
import 'null_stream_sink.dart';
/// A [sink] where the destination is provided later.
///
/// The [sink] is a normal sink that you can add events to to immediately, but
/// until [setDestinationSink] is called, the events will be buffered.
///
/// The same effect can be achieved by using a [StreamController] and adding it
/// to the sink using [Sink.addStream] when the destination sink is ready. This
/// class attempts to shortcut some of the overhead when possible. For example,
/// if the [sink] only has events added after the destination sink has been set,
/// those events are added directly to the sink.
class StreamSinkCompleter<T> {
/// The sink for this completer.
///
/// When a destination sink is provided, events that have been passed to the
/// sink will be forwarded to the destination.
///
/// Events can be added to the sink either before or after a destination sink
/// is set.
final StreamSink<T> sink = _CompleterSink<T>();
/// Returns [sink] typed as a [_CompleterSink].
_CompleterSink<T> get _sink => sink as _CompleterSink<T>;
/// Convert a `Future<StreamSink>` to a `StreamSink`.
///
/// This creates a sink using a sink completer, and sets the destination sink
/// to the result of the future when the future completes.
///
/// If the future completes with an error, the returned sink will instead
/// be closed. Its [Sink.done] future will contain the error.
static StreamSink<T> fromFuture<T>(Future<StreamSink<T>> sinkFuture) {
var completer = StreamSinkCompleter<T>();
sinkFuture.then(completer.setDestinationSink, onError: completer.setError);
return completer.sink;
}
/// Sets a sink as the destination for events from the [StreamSinkCompleter]'s
/// [sink].
///
/// The completer's [sink] will act exactly as [destinationSink].
///
/// If the destination sink is set before events are added to [sink], further
/// events are forwarded directly to [destinationSink].
///
/// If events are added to [sink] before setting the destination sink, they're
/// buffered until the destination is available.
///
/// A destination sink may be set at most once.
///
/// Either of [setDestinationSink] or [setError] may be called at most once.
/// Trying to call either of them again will fail.
void setDestinationSink(StreamSink<T> destinationSink) {
if (_sink._destinationSink != null) {
throw StateError('Destination sink already set');
}
_sink._setDestinationSink(destinationSink);
}
/// Completes this to a closed sink whose [Sink.done] future emits [error].
///
/// This is useful when the process of loading the sink fails.
///
/// Either of [setDestinationSink] or [setError] may be called at most once.
/// Trying to call either of them again will fail.
void setError(error, [StackTrace stackTrace]) {
setDestinationSink(NullStreamSink.error(error, stackTrace));
}
}
/// [StreamSink] completed by [StreamSinkCompleter].
class _CompleterSink<T> implements StreamSink<T> {
/// Controller for an intermediate sink.
///
/// Created if the user adds events to this sink before the destination sink
/// is set.
StreamController<T> _controller;
/// Completer for [done].
///
/// Created if the user requests the [done] future before the destination sink
/// is set.
Completer _doneCompleter;
/// Destination sink for the events added to this sink.
///
/// Set when [StreamSinkCompleter.setDestinationSink] is called.
StreamSink<T> _destinationSink;
/// Whether events should be sent directly to [_destinationSink], as opposed
/// to going through [_controller].
bool get _canSendDirectly => _controller == null && _destinationSink != null;
@override
Future get done {
if (_doneCompleter != null) return _doneCompleter.future;
if (_destinationSink == null) {
_doneCompleter = Completer.sync();
return _doneCompleter.future;
}
return _destinationSink.done;
}
@override
void add(T event) {
if (_canSendDirectly) {
_destinationSink.add(event);
} else {
_ensureController();
_controller.add(event);
}
}
@override
void addError(error, [StackTrace stackTrace]) {
if (_canSendDirectly) {
_destinationSink.addError(error, stackTrace);
} else {
_ensureController();
_controller.addError(error, stackTrace);
}
}
@override
Future addStream(Stream<T> stream) {
if (_canSendDirectly) return _destinationSink.addStream(stream);
_ensureController();
return _controller.addStream(stream, cancelOnError: false);
}
@override
Future close() {
if (_canSendDirectly) {
_destinationSink.close();
} else {
_ensureController();
_controller.close();
}
return done;
}
/// Create [_controller] if it doesn't yet exist.
void _ensureController() {
_controller ??= StreamController(sync: true);
}
/// Sets the destination sink to which events from this sink will be provided.
///
/// If set before the user adds events, events will be added directly to the
/// destination sink. If the user adds events earlier, an intermediate sink is
/// created using a stream controller, and the destination sink is linked to
/// it later.
void _setDestinationSink(StreamSink<T> sink) {
assert(_destinationSink == null);
_destinationSink = sink;
// If the user has already added data, it's buffered in the controller, so
// we add it to the sink.
if (_controller != null) {
// Catch any error that may come from [addStream] or [sink.close]. They'll
// be reported through [done] anyway.
sink
.addStream(_controller.stream)
.whenComplete(sink.close)
.catchError((_) {});
}
// If the user has already asked when the sink is done, connect the sink's
// done callback to that completer.
if (_doneCompleter != null) {
_doneCompleter.complete(sink.done);
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/subscription_stream.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 'delegate/stream_subscription.dart';
/// A [Stream] adapter for a [StreamSubscription].
///
/// This class allows a `StreamSubscription` to be treated as a `Stream`.
///
/// The subscription is paused until the stream is listened to,
/// then it is resumed and the events are passed on to the
/// stream's new subscription.
///
/// This class assumes that is has control over the original subscription.
/// If other code is accessing the subscription, results may be unpredictable.
class SubscriptionStream<T> extends Stream<T> {
/// The subscription providing the events for this stream.
StreamSubscription<T> _source;
/// Create a single-subscription `Stream` from [subscription].
///
/// The `subscription` should not be paused. This class will not resume prior
/// pauses, so being paused is indistinguishable from not providing any
/// events.
///
/// If the `subscription` doesn't send any `done` events, neither will this
/// stream. That may be an issue if `subscription` was made to cancel on
/// an error.
SubscriptionStream(StreamSubscription<T> subscription)
: _source = subscription {
_source.pause();
// Clear callbacks to avoid keeping them alive unnecessarily.
_source.onData(null);
_source.onError(null);
_source.onDone(null);
}
@override
StreamSubscription<T> listen(void Function(T) onData,
{Function onError, void Function() onDone, bool cancelOnError}) {
if (_source == null) {
throw StateError('Stream has already been listened to.');
}
cancelOnError = (true == cancelOnError);
var subscription = _source;
_source = null;
var result = cancelOnError
? _CancelOnErrorSubscriptionWrapper<T>(subscription)
: subscription;
result.onData(onData);
result.onError(onError);
result.onDone(onDone);
subscription.resume();
return result;
}
}
/// Subscription wrapper that cancels on error.
///
/// Used by [SubscriptionStream] when forwarding a subscription
/// created with `cancelOnError` as `true` to one with (assumed)
/// `cancelOnError` as `false`. It automatically cancels the
/// source subscription on the first error.
class _CancelOnErrorSubscriptionWrapper<T>
extends DelegatingStreamSubscription<T> {
_CancelOnErrorSubscriptionWrapper(StreamSubscription<T> subscription)
: super(subscription);
@override
void onError(Function handleError) {
// Cancel when receiving an error.
super.onError((error, StackTrace stackTrace) {
var cancelFuture = super.cancel();
if (cancelFuture != null) {
// Wait for the cancel to complete before sending the error event.
cancelFuture.whenComplete(() {
if (handleError is ZoneBinaryCallback) {
handleError(error, stackTrace);
} else {
handleError(error);
}
});
} else {
if (handleError is ZoneBinaryCallback) {
handleError(error, stackTrace);
} else {
handleError(error);
}
}
});
}
}
| 0 |
Subsets and Splits