blob: a3d119ddc59ec69bf9347e86e374a37b247b4a7c [file] [log] [blame]
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library fasta.body_builder;
import 'dart:core' hide MapEntry;
import '../constant_context.dart' show ConstantContext;
import '../fasta_codes.dart' as fasta;
import '../fasta_codes.dart' show LocatedMessage, Message, noLength, Template;
import '../messages.dart' as messages show getLocationFromUri;
import '../modifier.dart' show Modifier, constMask, covariantMask, finalMask;
import '../names.dart'
show callName, emptyName, indexGetName, indexSetName, minusName, plusName;
import '../parser.dart'
show
Assert,
Parser,
FormalParameterKind,
IdentifierContext,
MemberKind,
lengthForToken,
lengthOfSpan,
offsetForToken,
optional;
import '../problems.dart' show unexpected, unhandled, unsupported;
import '../quote.dart'
show
Quote,
analyzeQuote,
unescape,
unescapeFirstStringPart,
unescapeLastStringPart,
unescapeString;
import '../scanner.dart' show Token;
import '../scanner/token.dart' show isBinaryOperator, isMinusOperator;
import '../scope.dart' show ProblemBuilder;
import '../severity.dart' show Severity;
import '../source/scope_listener.dart'
show
FixedNullableList,
GrowableList,
JumpTargetKind,
NullValue,
ParserRecovery,
ScopeListener;
import '../type_inference/type_inferrer.dart' show TypeInferrer;
import '../type_inference/type_promotion.dart'
show TypePromoter, TypePromotionFact, TypePromotionScope;
import 'constness.dart' show Constness;
import 'expression_generator.dart'
show
DelayedAssignment,
DelayedPostfixIncrement,
Generator,
IncompleteErrorGenerator,
IncompletePropertyAccessGenerator,
IncompleteSendGenerator,
IndexedAccessGenerator,
LoadLibraryGenerator,
ParenthesizedExpressionGenerator,
ParserErrorGenerator,
PrefixUseGenerator,
ReadOnlyAccessGenerator,
SendAccessGenerator,
StaticAccessGenerator,
SuperIndexedAccessGenerator,
ThisAccessGenerator,
ThisPropertyAccessGenerator,
TypeUseGenerator,
UnlinkedGenerator,
UnresolvedNameGenerator,
VariableUseGenerator,
buildIsNull;
import 'expression_generator_helper.dart' show ExpressionGeneratorHelper;
import 'forest.dart' show Forest;
import 'redirecting_factory_body.dart'
show
RedirectingFactoryBody,
RedirectionTarget,
getRedirectingFactoryBody,
getRedirectionTarget,
isRedirectingFactory;
import 'kernel_api.dart';
import 'kernel_ast_api.dart';
import 'kernel_builder.dart';
import 'type_algorithms.dart' show calculateBounds;
// TODO(ahe): Remove this and ensure all nodes have a location.
const noLocation = null;
abstract class BodyBuilder extends ScopeListener<JumpTarget>
implements ExpressionGeneratorHelper {
// TODO(ahe): Rename [library] to 'part'.
@override
final KernelLibraryBuilder library;
final ModifierBuilder member;
final KernelClassBuilder classBuilder;
final ClassHierarchy hierarchy;
@override
final CoreTypes coreTypes;
final bool isInstanceMember;
final Scope enclosingScope;
final bool enableNative;
final bool stringExpectedAfterNative;
/// Whether to ignore an unresolved reference to `main` within the body of
/// `_getMainClosure` when compiling the current library.
///
/// This as a temporary workaround. The standalone VM and flutter have
/// special logic to resolve `main` in `_getMainClosure`, this flag is used to
/// ignore that reference to `main`, but only on libraries where we expect to
/// see it (today that is dart:_builtin and dart:ui).
///
// TODO(ahe,sigmund): remove when the VM gets rid of the special rule, see
// https://github.com/dart-lang/sdk/issues/28989.
final bool ignoreMainInGetMainClosure;
// TODO(ahe): Consider renaming [uri] to 'partUri'.
@override
final Uri uri;
final TypeInferrer _typeInferrer;
@override
final TypePromoter typePromoter;
/// Only used when [member] is a constructor. It tracks if an implicit super
/// initializer is needed.
///
/// An implicit super initializer isn't needed
///
/// 1. if the current class is Object,
/// 2. if there is an explicit super initializer,
/// 3. if there is a redirecting (this) initializer, or
/// 4. if a compile-time error prevented us from generating code for an
/// initializer. This avoids cascading errors.
bool needsImplicitSuperInitializer;
Scope formalParameterScope;
/// This is set to true when we start parsing an initializer. We use this to
/// find the correct scope for initializers like in this example:
///
/// class C {
/// final x;
/// C(x) : x = x;
/// }
///
/// When parsing this initializer `x = x`, `x` must be resolved in two
/// different scopes. The first `x` must be resolved in the class' scope, the
/// second in the formal parameter scope.
bool inInitializer = false;
bool inFieldInitializer = false;
bool inCatchClause = false;
bool inCatchBlock = false;
int functionNestingLevel = 0;
Statement problemInLoopOrSwitch;
Scope switchScope;
CloneVisitor cloner;
ConstantContext constantContext = ConstantContext.none;
UnresolvedType<KernelTypeBuilder> currentLocalVariableType;
// Using non-null value to initialize this field based on performance advice
// from VM engineers. TODO(ahe): Does this still apply?
int currentLocalVariableModifiers = -1;
/// If non-null, records instance fields which have already been initialized
/// and where that was.
Map<String, int> initializedFields;
/// List of built redirecting factory invocations. The targets of the
/// invocations are to be resolved in a separate step.
final List<Expression> redirectingFactoryInvocations = <Expression>[];
BodyBuilder(
this.library,
this.member,
this.enclosingScope,
this.formalParameterScope,
this.hierarchy,
this.coreTypes,
this.classBuilder,
this.isInstanceMember,
this.uri,
this._typeInferrer)
: enableNative =
library.loader.target.backendTarget.enableNative(library.uri),
stringExpectedAfterNative =
library.loader.target.backendTarget.nativeExtensionExpectsString,
ignoreMainInGetMainClosure = library.uri.scheme == 'dart' &&
(library.uri.path == "_builtin" || library.uri.path == "ui"),
needsImplicitSuperInitializer =
coreTypes?.objectClass != classBuilder?.cls,
typePromoter = _typeInferrer?.typePromoter,
super(enclosingScope);
BodyBuilder.withParents(KernelFieldBuilder field, KernelLibraryBuilder part,
KernelClassBuilder classBuilder, TypeInferrer typeInferrer)
: this(
part,
field,
classBuilder?.scope ?? field.library.scope,
null,
part.loader.hierarchy,
part.loader.coreTypes,
classBuilder,
field.isInstanceMember,
field.fileUri,
typeInferrer);
BodyBuilder.forField(KernelFieldBuilder field, TypeInferrer typeInferrer)
: this.withParents(
field,
field.parent is KernelClassBuilder
? field.parent.parent
: field.parent,
field.parent is KernelClassBuilder ? field.parent : null,
typeInferrer);
bool get inConstructor {
return functionNestingLevel == 0 && member is KernelConstructorBuilder;
}
bool get isInstanceContext {
return isInstanceMember || member is KernelConstructorBuilder;
}
TypeEnvironment get typeEnvironment => _typeInferrer?.typeSchemaEnvironment;
@override
void push(Object node) {
if (node is DartType) {
unhandled("DartType", "push", -1, uri);
}
inInitializer = false;
super.push(node);
}
Expression popForValue() => toValue(pop());
Expression popForEffect() => toEffect(pop());
Expression popForValueIfNotNull(Object value) {
return value == null ? null : popForValue();
}
@override
Expression toValue(Object node) {
if (node is Generator) {
return node.buildSimpleRead();
} else if (node is Expression) {
return node;
} else if (node is SuperInitializer) {
return buildProblem(
fasta.messageSuperAsExpression, node.fileOffset, noLength);
} else if (node is ProblemBuilder) {
return buildProblem(node.message, node.charOffset, noLength);
} else {
return unhandled("${node.runtimeType}", "toValue", -1, uri);
}
}
Expression toEffect(Object node) {
if (node is Generator) return node.buildForEffect();
return toValue(node);
}
List<Expression> popListForValue(int n) {
List<Expression> list =
new List<Expression>.filled(n, null, growable: true);
for (int i = n - 1; i >= 0; i--) {
list[i] = popForValue();
}
return list;
}
List<Expression> popListForEffect(int n) {
List<Expression> list =
new List<Expression>.filled(n, null, growable: true);
for (int i = n - 1; i >= 0; i--) {
list[i] = popForEffect();
}
return list;
}
Statement popBlock(int count, Token openBrace, Token closeBrace) {
return forest.block(
openBrace,
const GrowableList<Statement>().pop(stack, count) ?? <Statement>[],
closeBrace);
}
Statement popStatementIfNotNull(Object value) {
return value == null ? null : popStatement();
}
Statement popStatement() => forest.wrapVariables(pop());
void enterSwitchScope() {
push(switchScope ?? NullValue.SwitchScope);
switchScope = scope;
}
void exitSwitchScope() {
Scope outerSwitchScope = pop();
if (switchScope.unclaimedForwardDeclarations != null) {
switchScope.unclaimedForwardDeclarations
.forEach((String name, Declaration declaration) {
if (outerSwitchScope == null) {
JumpTarget target = declaration;
for (Statement statement in target.users) {
statement.parent.replaceChild(
statement,
wrapInProblemStatement(statement,
fasta.templateLabelNotFound.withArguments(name)));
}
} else {
outerSwitchScope.forwardDeclareLabel(name, declaration);
}
});
}
switchScope = outerSwitchScope;
}
void wrapVariableInitializerInError(
VariableDeclaration variable,
Template<Message Function(String name)> template,
List<LocatedMessage> context) {
String name = variable.name;
int offset = variable.fileOffset;
Message message = template.withArguments(name);
if (variable.initializer == null) {
variable.initializer =
buildProblem(message, offset, name.length, context: context)
..parent = variable;
} else {
variable.initializer = wrapInLocatedProblem(
variable.initializer, message.withLocation(uri, offset, name.length),
context: context)
..parent = variable;
}
}
void declareVariable(VariableDeclaration variable, Scope scope) {
String name = variable.name;
Declaration existing = scope.local[name];
if (existing != null) {
// This reports an error for duplicated declarations in the same scope:
// `{ var x; var x; }`
wrapVariableInitializerInError(
variable, fasta.templateDuplicatedDeclaration, <LocatedMessage>[
fasta.templateDuplicatedDeclarationCause
.withArguments(name)
.withLocation(uri, existing.charOffset, name.length)
]);
return;
}
LocatedMessage context = scope.declare(
variable.name,
new KernelVariableBuilder(
variable, member ?? classBuilder ?? library, uri),
uri);
if (context != null) {
// This case is different from the above error. In this case, the problem
// is using `x` before it's declared: `{ var x; { print(x); var x;
// }}`. In this case, we want two errors, the `x` in `print(x)` and the
// second (or innermost declaration) of `x`.
wrapVariableInitializerInError(
variable,
fasta.templateDuplicatedNamePreviouslyUsed,
<LocatedMessage>[context]);
}
}
@override
JumpTarget createJumpTarget(JumpTargetKind kind, int charOffset) {
return new JumpTarget(kind, functionNestingLevel, member, charOffset);
}
@override
void beginMetadata(Token token) {
debugEvent("beginMetadata");
super.push(constantContext);
constantContext = ConstantContext.inferred;
}
@override
void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) {
debugEvent("Metadata");
Arguments arguments = pop();
pushQualifiedReference(beginToken.next, periodBeforeName);
if (arguments != null) {
push(arguments);
buildConstructorReferenceInvocation(
beginToken.next, beginToken.offset, Constness.explicitConst);
push(popForValue());
} else {
pop(); // Name last identifier
String name = pop();
pop(); // Type arguments (ignored, already reported by parser).
Object expression = pop();
if (expression is Identifier) {
Identifier identifier = expression;
expression = new UnresolvedNameGenerator(
this,
deprecated_extractToken(identifier),
new Name(identifier.name, library.library));
}
if (name?.isNotEmpty ?? false) {
Token period = periodBeforeName ?? beginToken.next.next;
Generator generator = expression;
expression = generator.buildPropertyAccess(
new IncompletePropertyAccessGenerator(
this, period.next, new Name(name, library.library)),
period.next.offset,
false);
}
ConstantContext savedConstantContext = pop();
if (expression is! StaticAccessGenerator) {
push(wrapInProblem(
toValue(expression), fasta.messageExpressionNotMetadata, noLength));
} else {
push(toValue(expression));
}
constantContext = savedConstantContext;
}
}
@override
void endMetadataStar(int count) {
debugEvent("MetadataStar");
if (count == 0) {
push(NullValue.Metadata);
} else {
push(const GrowableList<Expression>().pop(stack, count) ??
NullValue.Metadata /* Ignore parser recovery */);
}
}
@override
void endTopLevelFields(Token staticToken, Token covariantToken,
Token varFinalOrConst, int count, Token beginToken, Token endToken) {
debugEvent("TopLevelFields");
push(count);
}
@override
void endFields(Token staticToken, Token covariantToken, Token varFinalOrConst,
int count, Token beginToken, Token endToken) {
debugEvent("Fields");
push(count);
}
@override
void finishFields() {
debugEvent("finishFields");
int count = pop();
List<FieldBuilder<Object>> fields = <FieldBuilder<Object>>[];
for (int i = 0; i < count; i++) {
Expression initializer = pop();
Identifier identifier = pop();
String name = identifier.name;
Declaration declaration;
if (classBuilder != null) {
declaration = classBuilder[name];
} else {
declaration = library[name];
}
FieldBuilder<Object> field;
if (declaration.isField && declaration.next == null) {
field = declaration;
} else {
continue;
}
fields.add(field);
if (initializer != null) {
if (field.next != null) {
// Duplicate definition. The field might not be the correct one,
// so we skip inference of the initializer.
// Error reporting and recovery is handled elsewhere.
} else {
field.initializer = initializer;
_typeInferrer.inferFieldInitializer(
this,
field.hasTypeInferredFromInitializer ? null : field.builtType,
initializer);
}
}
}
{
// TODO(ahe): The type we compute here may be different from what is
// computed in the outline phase. We should make sure that the outline
// phase computes the same type. See
// pkg/front_end/testcases/regress/issue_32200.dart for an example where
// not calling [buildDartType] leads to a missing compile-time
// error. Also, notice that the type of the problematic field isn't
// `invalid-type`.
buildDartType(pop()); // Type.
}
List<Expression> annotations = pop();
if (annotations != null) {
_typeInferrer.inferMetadata(this, annotations);
Field field = fields.first.target;
// The first (and often only field) will not get a clone.
annotations.forEach((annotation) => field.addAnnotation(annotation));
for (int i = 1; i < fields.length; i++) {
// We have to clone the annotations on the remaining fields.
field = fields[i].target;
cloner ??= new CloneVisitor();
for (Expression annotation in annotations) {
field.addAnnotation(cloner.clone(annotation));
}
}
}
resolveRedirectingFactoryTargets();
}
@override
void endMember() {
debugEvent("Member");
}
@override
void endBlockFunctionBody(int count, Token openBrace, Token closeBrace) {
debugEvent("BlockFunctionBody");
if (openBrace == null) {
assert(count == 0);
push(NullValue.Block);
} else {
Statement block = popBlock(count, openBrace, closeBrace);
exitLocalScope();
push(block);
}
}
void prepareInitializers() {
ProcedureBuilder<TypeBuilder> member = this.member;
scope = member.computeFormalParameterInitializerScope(scope);
if (member is KernelConstructorBuilder) {
if (member.isConst &&
(classBuilder.cls.superclass?.isMixinApplication ?? false)) {
addProblem(fasta.messageConstConstructorInSubclassOfMixinApplication,
member.charOffset, member.name.length);
}
if (member.formals != null) {
for (KernelFormalParameterBuilder formal in member.formals) {
if (formal.hasThis) {
Initializer initializer;
if (member.isExternal) {
initializer = buildInvalidInitializer(
buildProblem(
fasta.messageExternalConstructorWithFieldInitializers,
formal.charOffset,
formal.name.length)
.desugared,
formal.charOffset);
} else {
initializer = buildFieldInitializer(true, formal.name,
formal.charOffset, new VariableGet(formal.declaration),
formalType: formal.declaration.type);
}
member.addInitializer(initializer, this);
}
}
}
}
}
@override
void handleNoInitializers() {
debugEvent("NoInitializers");
if (functionNestingLevel == 0) {
prepareInitializers();
scope = formalParameterScope;
}
}
@override
void beginInitializers(Token token) {
debugEvent("beginInitializers");
if (functionNestingLevel == 0) {
prepareInitializers();
}
}
@override
void endInitializers(int count, Token beginToken, Token endToken) {
debugEvent("Initializers");
if (functionNestingLevel == 0) {
scope = formalParameterScope;
}
}
@override
void beginInitializer(Token token) {
debugEvent("beginInitializer");
inInitializer = true;
inFieldInitializer = true;
}
@override
void endInitializer(Token token) {
debugEvent("endInitializer");
inFieldInitializer = false;
assert(!inInitializer);
final member = this.member;
Object node = pop();
Initializer initializer;
if (node is Initializer) {
initializer = node;
} else if (node is Generator) {
initializer = node.buildFieldInitializer(initializedFields);
} else if (node is ConstructorInvocation) {
initializer = buildSuperInitializer(
false, node.target, node.arguments, token.charOffset);
} else {
Expression value = toValue(node);
if (!forest.isThrow(node)) {
value =
wrapInProblem(value, fasta.messageExpectedAnInitializer, noLength);
}
initializer = buildInvalidInitializer(node, token.charOffset);
}
_typeInferrer.inferInitializer(this, initializer);
if (member is KernelConstructorBuilder && !member.isExternal) {
member.addInitializer(initializer, this);
} else {
addProblem(
fasta.templateInitializerOutsideConstructor
.withArguments(member.name),
token.charOffset,
member.name.length);
}
}
DartType _computeReturnTypeContext(MemberBuilder member) {
if (member is KernelProcedureBuilder) {
return member.procedure.function.returnType;
} else {
assert(member is KernelConstructorBuilder);
return const DynamicType();
}
}
@override
void finishFunction(List<Expression> annotations, FormalParameters formals,
AsyncMarker asyncModifier, Statement body) {
debugEvent("finishFunction");
typePromoter.finished();
KernelFunctionBuilder builder = member;
if (formals?.parameters != null) {
for (int i = 0; i < formals.parameters.length; i++) {
KernelFormalParameterBuilder parameter = formals.parameters[i];
if (parameter.isOptional) {
VariableDeclaration realParameter = builder.formals[i].target;
Expression initializer =
parameter.target.initializer ?? forest.literalNull(
// TODO(ahe): Should store: realParameter.fileOffset
// https://github.com/dart-lang/sdk/issues/32289
null);
realParameter.initializer = initializer..parent = realParameter;
_typeInferrer.inferParameterInitializer(
this, initializer, realParameter.type);
}
}
}
_typeInferrer.inferFunctionBody(
this, _computeReturnTypeContext(member), asyncModifier, body);
// For async, async*, and sync* functions with declared return types, we need
// to determine whether those types are valid.
// TODO(hillerstrom): currently, we need to check whether [strongMode] is
// enabled for two reasons:
// 1) the [isSubtypeOf] predicate produces false-negatives when [strongMode]
// is false.
// 2) the member [typeEnvironment] might be null when [strongMode] is false.
// This particular behaviour can be observed when running the fasta perf
// benchmarks.
bool strongMode = library.loader.target.strongMode;
if (strongMode && builder.returnType != null) {
DartType returnType = builder.function.returnType;
// We use the same trick in each case below. For example to decide whether
// Future<T> <: [returnType] for every T, we rely on Future<Bot> and
// transitivity of the subtyping relation because Future<Bot> <: Future<T>
// for every T.
// We use [problem == null] to signal success.
Message problem;
switch (asyncModifier) {
case AsyncMarker.Async:
DartType futureBottomType = library.loader.futureOfBottom;
if (!typeEnvironment.isSubtypeOf(futureBottomType, returnType)) {
problem = fasta.messageIllegalAsyncReturnType;
}
break;
case AsyncMarker.AsyncStar:
DartType streamBottomType = library.loader.streamOfBottom;
if (returnType is VoidType) {
problem = fasta.messageIllegalAsyncGeneratorVoidReturnType;
} else if (!typeEnvironment.isSubtypeOf(
streamBottomType, returnType)) {
problem = fasta.messageIllegalAsyncGeneratorReturnType;
}
break;
case AsyncMarker.SyncStar:
DartType iterableBottomType = library.loader.iterableOfBottom;
if (returnType is VoidType) {
problem = fasta.messageIllegalSyncGeneratorVoidReturnType;
} else if (!typeEnvironment.isSubtypeOf(
iterableBottomType, returnType)) {
problem = fasta.messageIllegalSyncGeneratorReturnType;
}
break;
case AsyncMarker.Sync:
break; // skip
case AsyncMarker.SyncYielding:
unexpected("async, async*, sync, or sync*", "$asyncModifier",
member.charOffset, uri);
break;
}
if (problem != null) {
// TODO(hillerstrom): once types get annotated with location
// information, we can improve the quality of the error message by
// using the offset of [returnType] (and the length of its name).
addProblem(problem, member.charOffset, member.name.length);
}
}
if (builder.kind == ProcedureKind.Setter) {
if (formals?.parameters == null ||
formals.parameters.length != 1 ||
formals.parameters.single.isOptional) {
int charOffset = formals?.charOffset ??
body?.fileOffset ??
builder.target.fileOffset;
if (body == null) {
body = new EmptyStatement()..fileOffset = charOffset;
}
if (builder.formals != null) {
// Illegal parameters were removed by the function builder.
// Add them as local variable to put them in scope of the body.
List<Statement> statements = <Statement>[];
for (KernelFormalParameterBuilder parameter in builder.formals) {
statements.add(parameter.target);
}
statements.add(body);
body = forest.block(null, statements, null)..fileOffset = charOffset;
}
body = wrapInProblemStatement(
body, fasta.messageSetterWithWrongNumberOfFormals);
}
}
// No-such-method forwarders get their bodies injected during outline
// building, so we should skip them here.
bool isNoSuchMethodForwarder = (builder.function.parent is Procedure &&
(builder.function.parent as Procedure).isNoSuchMethodForwarder);
if (!builder.isExternal && !isNoSuchMethodForwarder) {
builder.body = body;
} else {
if (body != null) {
builder.body =
wrapInProblemStatement(body, fasta.messageExternalMethodWithBody);
}
}
Member target = builder.target;
_typeInferrer.inferMetadata(this, annotations);
for (Expression annotation in annotations ?? const []) {
target.addAnnotation(annotation);
}
if (builder is KernelConstructorBuilder) {
finishConstructor(builder, asyncModifier);
} else if (builder is KernelProcedureBuilder) {
builder.asyncModifier = asyncModifier;
} else {
unhandled("${builder.runtimeType}", "finishFunction", builder.charOffset,
builder.fileUri);
}
resolveRedirectingFactoryTargets();
}
void resolveRedirectingFactoryTargets() {
for (StaticInvocation invocation in redirectingFactoryInvocations) {
// If the invocation was invalid, it has already been desugared into
// an exception throwing expression. There is nothing to resolve anymore.
if (invocation.parent == null) {
continue;
}
Procedure initialTarget = invocation.target;
Expression replacementNode;
RedirectionTarget redirectionTarget = getRedirectionTarget(initialTarget,
strongMode: library.loader.target.strongMode);
Member resolvedTarget = redirectionTarget?.target;
if (resolvedTarget == null) {
String name = constructorNameForDiagnostics(initialTarget.name.name,
className: initialTarget.enclosingClass.name);
// TODO(dmitryas): Report this error earlier.
replacementNode = buildProblem(
fasta.templateCyclicRedirectingFactoryConstructors
.withArguments(name),
initialTarget.fileOffset,
name.length)
.desugared;
} else if (resolvedTarget is Constructor &&
resolvedTarget.enclosingClass.isAbstract) {
replacementNode = evaluateArgumentsBefore(
forest.arguments(invocation.arguments.positional, null,
types: invocation.arguments.types,
named: invocation.arguments.named),
buildAbstractClassInstantiationError(
fasta.templateAbstractRedirectedClassInstantiation
.withArguments(resolvedTarget.enclosingClass.name),
resolvedTarget.enclosingClass.name,
initialTarget.fileOffset));
} else {
RedirectingFactoryBody redirectingFactoryBody =
getRedirectingFactoryBody(resolvedTarget);
if (redirectingFactoryBody != null) {
// If the redirection target is itself a redirecting factory, it means
// that it is unresolved.
assert(redirectingFactoryBody.isUnresolved);
String errorName = redirectingFactoryBody.unresolvedName;
replacementNode = new SyntheticExpressionJudgment(
throwNoSuchMethodError(
forest.literalNull(null)..fileOffset = invocation.fileOffset,
errorName,
forest.arguments(invocation.arguments.positional, null,
types: invocation.arguments.types,
named: invocation.arguments.named),
initialTarget.fileOffset));
} else {
Substitution substitution = Substitution.fromPairs(
initialTarget.function.typeParameters,
invocation.arguments.types);
invocation.arguments.types.clear();
invocation.arguments.types.length =
redirectionTarget.typeArguments.length;
for (int i = 0; i < invocation.arguments.types.length; i++) {
invocation.arguments.types[i] =
substitution.substituteType(redirectionTarget.typeArguments[i]);
}
replacementNode = buildStaticInvocation(
resolvedTarget,
forest.arguments(invocation.arguments.positional, null,
types: invocation.arguments.types,
named: invocation.arguments.named),
constness: invocation.isConst
? Constness.explicitConst
: Constness.explicitNew,
charOffset: invocation.fileOffset);
// TODO(dmitryas): Find a better way to unwrap
// [SyntheticExpressionJudgment] or not to build it in the first place
// when it's not needed.
if (replacementNode is SyntheticExpressionJudgment) {
replacementNode =
(replacementNode as SyntheticExpressionJudgment).desugared;
}
}
}
invocation.replaceWith(replacementNode);
}
redirectingFactoryInvocations.clear();
}
@override
List<Expression> finishMetadata(TreeNode parent) {
List<Expression> expressions = pop();
_typeInferrer.inferMetadata(this, expressions);
// The invocation of [resolveRedirectingFactoryTargets] below may change the
// root nodes of the annotation expressions. We need to have a parent of
// the annotation nodes before the resolution is performed, to collect and
// return them later. If [parent] is not provided, [temporaryParent] is
// used.
ListLiteral temporaryParent;
if (parent is Class) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else if (parent is Library) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else if (parent is LibraryDependency) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else if (parent is LibraryPart) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else if (parent is Member) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else if (parent is Typedef) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else if (parent is TypeParameter) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else if (parent is VariableDeclaration) {
for (Expression expression in expressions) {
parent.addAnnotation(expression);
}
} else {
temporaryParent = new ListLiteral(expressions);
}
resolveRedirectingFactoryTargets();
return temporaryParent != null ? temporaryParent.expressions : expressions;
}
@override
Expression parseSingleExpression(
Parser parser, Token token, FunctionNode parameters) {
List<KernelTypeVariableBuilder> typeParameterBuilders;
for (TypeParameter typeParameter in parameters.typeParameters) {
typeParameterBuilders ??= <KernelTypeVariableBuilder>[];
typeParameterBuilders.add(
new KernelTypeVariableBuilder.fromKernel(typeParameter, library));
}
enterFunctionTypeScope(typeParameterBuilders);
List<KernelFormalParameterBuilder> formals =
parameters.positionalParameters.length == 0
? null
: new List<KernelFormalParameterBuilder>(
parameters.positionalParameters.length);
for (int i = 0; i < parameters.positionalParameters.length; i++) {
VariableDeclaration formal = parameters.positionalParameters[i];
formals[i] = new KernelFormalParameterBuilder(
null, 0, null, formal.name, false, library, formal.fileOffset)
..declaration = formal;
}
enterLocalScope(
null,
new FormalParameters(formals, offsetForToken(token), noLength, uri)
.computeFormalParameterScope(scope, member, this));
token = parser.parseExpression(parser.syntheticPreviousToken(token));
Expression expression = popForValue();
Token eof = token.next;
if (!eof.isEof) {
expression = wrapInLocatedProblem(
expression,
fasta.messageExpectedOneExpression
.withLocation(uri, eof.charOffset, eof.length));
}
ReturnJudgment fakeReturn = new ReturnJudgment(null, expression);
_typeInferrer.inferFunctionBody(
this, const DynamicType(), AsyncMarker.Sync, fakeReturn);
return fakeReturn.expression;
}
Expression parseFieldInitializer(Token token) {
Parser parser = new Parser(this);
token = parser.parseExpression(parser.syntheticPreviousToken(token));
Expression expression = popForValue();
checkEmpty(token.charOffset);
return expression;
}
void finishConstructor(
KernelConstructorBuilder builder, AsyncMarker asyncModifier) {
/// Quotes below are from [Dart Programming Language Specification, 4th
/// Edition](
/// https://ecma-international.org/publications/files/ECMA-ST/ECMA-408.pdf).
assert(builder == member);
Constructor constructor = builder.constructor;
if (asyncModifier != AsyncMarker.Sync) {
// TODO(ahe): Change this to a null check.
int offset = builder.body?.fileOffset ?? builder.charOffset;
constructor.initializers.add(buildInvalidInitializer(
buildProblem(fasta.messageConstructorNotSync, offset, noLength),
offset));
}
if (needsImplicitSuperInitializer) {
/// >If no superinitializer is provided, an implicit superinitializer
/// >of the form super() is added at the end of k’s initializer list,
/// >unless the enclosing class is class Object.
Constructor superTarget = lookupConstructor(emptyName, isSuper: true);
Initializer initializer;
Arguments arguments = forest.argumentsEmpty(noLocation);
if (superTarget == null ||
checkArgumentsForFunction(superTarget.function, arguments,
builder.charOffset, const <TypeParameter>[]) !=
null) {
String superclass = classBuilder.supertype.fullNameForErrors;
int length = constructor.name.name.length;
if (length == 0) {
length = (constructor.parent as Class).name.length;
}
initializer = buildInvalidInitializer(
buildProblem(
fasta.templateSuperclassHasNoDefaultConstructor
.withArguments(superclass),
builder.charOffset,
length)
.desugared,
builder.charOffset);
} else {
initializer = buildSuperInitializer(
true, superTarget, arguments, builder.charOffset);
}
constructor.initializers.add(initializer);
}
setParents(constructor.initializers, constructor);
if (constructor.function.body == null) {
/// >If a generative constructor c is not a redirecting constructor
/// >and no body is provided, then c implicitly has an empty body {}.
/// We use an empty statement instead.
constructor.function.body = new EmptyStatement();
constructor.function.body.parent = constructor.function;
}
}
@override
void endExpressionStatement(Token token) {
debugEvent("ExpressionStatement");
push(forest.expressionStatement(popForEffect(), token));
}
@override
void endArguments(int count, Token beginToken, Token endToken) {
debugEvent("Arguments");
List<Object> arguments = count == 0
? <Object>[]
: const FixedNullableList<Object>().pop(stack, count);
if (arguments == null) {
push(new ParserRecovery(beginToken.charOffset));
return;
}
int firstNamedArgumentIndex = arguments.length;
for (int i = 0; i < arguments.length; i++) {
Object node = arguments[i];
if (node is NamedExpression) {
firstNamedArgumentIndex =
i < firstNamedArgumentIndex ? i : firstNamedArgumentIndex;
} else {
Expression argument = toValue(node);
arguments[i] = argument;
if (i > firstNamedArgumentIndex) {
arguments[i] = new NamedExpression(
"#$i",
buildProblem(fasta.messageExpectedNamedArgument,
forest.readOffset(argument), noLength))
..fileOffset = beginToken.charOffset;
}
}
}
if (firstNamedArgumentIndex < arguments.length) {
List<Expression> positional = new List<Expression>.from(
arguments.getRange(0, firstNamedArgumentIndex));
List<NamedExpression> named = new List<NamedExpression>.from(
arguments.getRange(firstNamedArgumentIndex, arguments.length));
push(forest.arguments(positional, beginToken, named: named));
} else {
// TODO(kmillikin): Find a way to avoid allocating a second list in the
// case where there were no named arguments, which is a common one.
push(forest.arguments(new List<Expression>.from(arguments), beginToken));
}
}
@override
void handleParenthesizedCondition(Token token) {
debugEvent("ParenthesizedCondition");
push(forest.parenthesizedCondition(token, popForValue(), token.endGroup));
}
@override
void handleParenthesizedExpression(Token token) {
debugEvent("ParenthesizedExpression");
Expression value = popForValue();
if (value is ShadowLargeIntLiteral) {
// We need to know that the expression was parenthesized because we will
// treat -n differently from -(n). If the expression occurs in a double
// context, -n is a double literal and -(n) is an application of unary- to
// an integer literal. And in any other context, '-' is part of the
// syntax of -n, i.e., -9223372036854775808 is OK and it is the minimum
// 64-bit integer, and '-' is an application of unary- in -(n), i.e.,
// -(9223372036854775808) is an error because the literal does not fit in
// 64-bits.
push(value..isParenthesized = true);
} else {
push(new ParenthesizedExpressionGenerator(this, token.endGroup, value));
}
}
@override
void handleSend(Token beginToken, Token endToken) {
debugEvent("Send");
Arguments arguments = pop();
List<UnresolvedType<KernelTypeBuilder>> typeArguments = pop();
Object receiver = pop();
if (arguments != null && typeArguments != null) {
assert(forest.argumentsTypeArguments(arguments).isEmpty);
forest.argumentsSetTypeArguments(
arguments, buildDartTypeArguments(typeArguments));
} else {
assert(typeArguments == null);
}
if (receiver is Identifier) {
Name name = new Name(receiver.name, library.library);
if (arguments == null) {
push(new IncompletePropertyAccessGenerator(this, beginToken, name));
} else {
push(new SendAccessGenerator(
this, beginToken, name, forest.castArguments(arguments)));
}
} else if (arguments == null) {
push(receiver);
} else {
push(finishSend(receiver, arguments, beginToken.charOffset));
}
}
@override
finishSend(Object receiver, Arguments arguments, int charOffset) {
if (receiver is Generator) {
return receiver.doInvocation(charOffset, arguments);
} else if (receiver is ParserRecovery) {
return new ParserErrorGenerator(this, null, fasta.messageSyntheticToken);
} else {
return buildMethodInvocation(
toValue(receiver), callName, arguments, charOffset,
isImplicitCall: true);
}
}
@override
void beginCascade(Token token) {
debugEvent("beginCascade");
Expression expression = popForValue();
if (expression is CascadeJudgment) {
push(expression);
push(new VariableUseGenerator(this, token, expression.variable));
expression.extend();
} else {
VariableDeclaration variable = new VariableDeclarationJudgment.forValue(
expression, functionNestingLevel)
..fileOffset = expression.fileOffset;
push(new CascadeJudgment(variable)..fileOffset = expression.fileOffset);
push(new VariableUseGenerator(this, token, variable));
}
}
@override
void endCascade() {
debugEvent("endCascade");
Expression expression = popForEffect();
CascadeJudgment cascadeReceiver = pop();
cascadeReceiver.finalize(expression);
push(cascadeReceiver);
}
@override
void beginCaseExpression(Token caseKeyword) {
debugEvent("beginCaseExpression");
super.push(constantContext);
constantContext = ConstantContext.inferred;
}
@override
void endCaseExpression(Token colon) {
debugEvent("endCaseExpression");
Expression expression = popForValue();
constantContext = pop();
super.push(expression);
}
@override
void beginBinaryExpression(Token token) {
if (optional("&&", token) || optional("||", token)) {
Expression lhs = popForValue();
typePromoter.enterLogicalExpression(lhs, token.stringValue);
push(lhs);
}
}
@override
void endBinaryExpression(Token token) {
debugEvent("BinaryExpression");
if (optional(".", token) || optional("..", token)) {
return doDotOrCascadeExpression(token);
}
if (optional("&&", token) || optional("||", token)) {
return doLogicalExpression(token);
}
if (optional("??", token)) return doIfNull(token);
if (optional("?.", token)) return doIfNotNull(token);
Expression argument = popForValue();
Object receiver = pop();
bool isSuper = false;
if (receiver is ThisAccessGenerator && receiver.isSuper) {
ThisAccessGenerator thisAccessorReceiver = receiver;
isSuper = true;
receiver = forest.thisExpression(thisAccessorReceiver.token);
}
push(buildBinaryOperator(toValue(receiver), token, argument, isSuper));
}
Expression buildBinaryOperator(
Expression a, Token token, Expression b, bool isSuper) {
bool negate = false;
String operator = token.stringValue;
if (identical("!=", operator)) {
operator = "==";
negate = true;
}
if (!isBinaryOperator(operator) && !isMinusOperator(operator)) {
return buildProblem(fasta.templateInvalidOperator.withArguments(token),
token.charOffset, token.length);
} else {
Expression result = buildMethodInvocation(a, new Name(operator),
forest.arguments(<Expression>[b], noLocation), token.charOffset,
// This *could* be a constant expression, we can't know without
// evaluating [a] and [b].
isConstantExpression: !isSuper,
isSuper: isSuper);
return negate ? forest.notExpression(result, null, true) : result;
}
}
void doLogicalExpression(Token token) {
Expression argument = popForValue();
Expression receiver = pop();
Expression logicalExpression =
forest.logicalExpression(receiver, token, argument);
typePromoter.exitLogicalExpression(argument, logicalExpression);
push(logicalExpression);
}
/// Handle `a ?? b`.
void doIfNull(Token token) {
Expression b = popForValue();
Expression a = popForValue();
VariableDeclaration variable = new VariableDeclaration.forValue(a);
push(new IfNullJudgment(
variable,
forest.conditionalExpression(
buildIsNull(new VariableGet(variable), offsetForToken(token), this),
token,
b,
null,
new VariableGet(variable)))
..fileOffset = offsetForToken(token));
}
/// Handle `a?.b(...)`.
void doIfNotNull(Token token) {
Object send = pop();
if (send is IncompleteSendGenerator) {
push(send.withReceiver(pop(), token.charOffset, isNullAware: true));
} else {
pop();
token = token.next;
push(buildProblem(fasta.templateExpectedIdentifier.withArguments(token),
offsetForToken(token), lengthForToken(token)));
}
}
void doDotOrCascadeExpression(Token token) {
Object send = pop();
if (send is IncompleteSendGenerator) {
Object receiver = optional(".", token) ? pop() : popForValue();
push(send.withReceiver(receiver, token.charOffset));
} else {
pop();
token = token.next;
push(buildProblem(fasta.templateExpectedIdentifier.withArguments(token),
offsetForToken(token), lengthForToken(token)));
}
}
bool areArgumentsCompatible(FunctionNode function, Arguments arguments) {
// TODO(ahe): Implement this.
return true;
}
@override
Expression throwNoSuchMethodError(
Expression receiver, String name, Arguments arguments, int charOffset,
{Member candidate,
bool isSuper: false,
bool isGetter: false,
bool isSetter: false,
bool isStatic: false,
LocatedMessage message}) {
int length = name.length;
int periodIndex = name.lastIndexOf(".");
if (periodIndex != -1) {
length -= periodIndex + 1;
}
Name kernelName = new Name(name, library.library);
List<LocatedMessage> context;
if (candidate != null) {
Uri uri = candidate.location.file;
int offset = candidate.fileOffset;
Message contextMessage;
int length = noLength;
if (offset == -1 && candidate is Constructor) {
offset = candidate.enclosingClass.fileOffset;
contextMessage = fasta.templateCandidateFoundIsDefaultConstructor
.withArguments(candidate.enclosingClass.name);
} else {
length = name.length;
contextMessage = fasta.messageCandidateFound;
}
context = [contextMessage.withLocation(uri, offset, length)];
}
if (message == null) {
if (isGetter) {
message = warnUnresolvedGet(kernelName, charOffset,
isSuper: isSuper, reportWarning: false, context: context)
.withLocation(uri, charOffset, length);
} else if (isSetter) {
message = warnUnresolvedSet(kernelName, charOffset,
isSuper: isSuper, reportWarning: false, context: context)
.withLocation(uri, charOffset, length);
} else {
message = warnUnresolvedMethod(kernelName, charOffset,
isSuper: isSuper, reportWarning: false, context: context)
.withLocation(uri, charOffset, length);
}
}
if (!library.loader.target.strongMode &&
constantContext == ConstantContext.none) {
addProblem(message.messageObject, message.charOffset, message.length,
wasHandled: true, context: context);
return new SyntheticExpressionJudgment(
forest.throwExpression(
null,
library.loader.instantiateNoSuchMethodError(
receiver, name, forest.castArguments(arguments), charOffset,
isMethod: !isGetter && !isSetter,
isGetter: isGetter,
isSetter: isSetter,
isStatic: isStatic,
isTopLevel: !isStatic && !isSuper))
..fileOffset = charOffset)
..fileOffset = charOffset;
}
return buildProblem(
message.messageObject, message.charOffset, message.length,
context: context)
.desugared;
}
@override
Message warnUnresolvedGet(Name name, int charOffset,
{bool isSuper: false,
bool reportWarning: true,
List<LocatedMessage> context}) {
Message message = isSuper
? fasta.templateSuperclassHasNoGetter.withArguments(name.name)
: fasta.templateGetterNotFound.withArguments(name.name);
if (reportWarning) {
addProblemErrorIfConst(message, charOffset, name.name.length,
context: context);
}
return message;
}
@override
Message warnUnresolvedSet(Name name, int charOffset,
{bool isSuper: false,
bool reportWarning: true,
List<LocatedMessage> context}) {
Message message = isSuper
? fasta.templateSuperclassHasNoSetter.withArguments(name.name)
: fasta.templateSetterNotFound.withArguments(name.name);
if (reportWarning) {
addProblemErrorIfConst(message, charOffset, name.name.length,
context: context);
}
return message;
}
@override
Message warnUnresolvedMethod(Name name, int charOffset,
{bool isSuper: false,
bool reportWarning: true,
List<LocatedMessage> context}) {
String plainName = name.name;
int dotIndex = plainName.lastIndexOf(".");
if (dotIndex != -1) {
plainName = plainName.substring(dotIndex + 1);
}
// TODO(ahe): This is rather brittle. We would probably be better off with
// more precise location information in this case.
int length = plainName.length;
if (plainName.startsWith("[")) {
length = 1;
}
Message message = isSuper
? fasta.templateSuperclassHasNoMethod.withArguments(name.name)
: fasta.templateMethodNotFound.withArguments(name.name);
if (reportWarning) {
addProblemErrorIfConst(message, charOffset, length, context: context);
}
return message;
}
@override
void warnTypeArgumentsMismatch(String name, int expected, int charOffset) {
addProblemErrorIfConst(
fasta.templateTypeArgumentMismatch.withArguments(expected),
charOffset,
name.length);
}
@override
Member lookupInstanceMember(Name name,
{bool isSetter: false, bool isSuper: false}) {
Class cls = classBuilder.cls;
if (classBuilder.isPatch) {
if (isSuper) {
// The super class is only correctly found through the origin class.
cls = classBuilder.origin.cls;
} else {
Member member =
hierarchy.getInterfaceMember(cls, name, setter: isSetter);
if (member?.parent == cls) {
// 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.
cls = classBuilder.origin.cls;
}
}
}
if (isSuper) {
cls = cls.superclass;
if (cls == null) return null;
}
Member target = isSuper
? hierarchy.getDispatchTarget(cls, name, setter: isSetter)
: hierarchy.getInterfaceMember(cls, name, setter: isSetter);
if (isSuper && target == null) {
if (classBuilder.cls.isMixinDeclaration ||
(library.loader.target.backendTarget.enableSuperMixins &&
classBuilder.isAbstract)) {
target = hierarchy.getInterfaceMember(cls, name, setter: isSetter);
}
}
return target;
}
@override
Constructor lookupConstructor(Name name, {bool isSuper}) {
Class cls = classBuilder.cls;
if (isSuper) {
cls = cls.superclass;
while (cls.isMixinApplication) {
cls = cls.superclass;
}
}
if (cls != null) {
for (Constructor constructor in cls.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<TypeBuilder, Object> builder = classBuilder.origin;
ClassBuilder<TypeBuilder, Object> getSuperclass(
ClassBuilder<TypeBuilder, Object> builder) {
// This way of computing the superclass is slower than using the kernel
// objects directly.
Object supertype = builder.supertype;
if (supertype is NamedTypeBuilder<TypeBuilder, Object>) {
Object builder = supertype.declaration;
if (builder is ClassBuilder<TypeBuilder, Object>) return builder;
}
return null;
}
if (isSuper) {
builder = getSuperclass(builder)?.origin;
while (builder?.isMixinApplication ?? false) {
builder = getSuperclass(builder)?.origin;
}
}
if (builder != null) {
Class target = builder.target;
for (Constructor constructor in target.constructors) {
if (constructor.name == name) return constructor;
}
}
return null;
}
return lookupConstructorWithPatches(name, isSuper);
}
@override
void handleIdentifier(Token token, IdentifierContext context) {
debugEvent("handleIdentifier");
String name = token.lexeme;
if (name.startsWith("deprecated") &&
// Note that the previous check is redundant, but faster in the common
// case (when [name] isn't deprecated).
(name == "deprecated" || name.startsWith("deprecated_"))) {
addProblem(fasta.templateUseOfDeprecatedIdentifier.withArguments(name),
offsetForToken(token), lengthForToken(token));
}
if (context.isScopeReference) {
assert(!inInitializer ||
this.scope == enclosingScope ||
this.scope.parent == enclosingScope);
// This deals with this kind of initializer: `C(a) : a = a;`
Scope scope = inInitializer ? enclosingScope : this.scope;
push(scopeLookup(scope, name, token));
return;
} else if (context.inDeclaration) {
if (context == IdentifierContext.topLevelVariableDeclaration ||
context == IdentifierContext.fieldDeclaration) {
constantContext =
member.isConst ? ConstantContext.inferred : ConstantContext.none;
}
} else if (constantContext != ConstantContext.none &&
!context.allowedInConstantExpression) {
addProblem(
fasta.messageNotAConstantExpression, token.charOffset, token.length);
}
if (token.isSynthetic) {
push(new ParserRecovery(offsetForToken(token)));
} else {
push(new Identifier.preserveToken(token));
}
}
/// Look up [name] in [scope] using [token] as location information (both to
/// report problems and as the file offset in the generated kernel code).
/// [isQualified] should be true if [name] is a qualified access (which
/// implies that it shouldn't be turned into a [ThisPropertyAccessGenerator]
/// if the name doesn't resolve in the scope).
@override
scopeLookup(Scope scope, String name, Token token,
{bool isQualified: false, PrefixBuilder prefix}) {
int charOffset = offsetForToken(token);
if (token.isSynthetic) {
return new ParserErrorGenerator(this, token, fasta.messageSyntheticToken);
}
Declaration declaration = scope.lookup(name, charOffset, uri);
if (declaration is UnlinkedDeclaration) {
return new UnlinkedGenerator(this, token, declaration);
}
if (declaration == null &&
prefix == null &&
(classBuilder?.isPatch ?? false)) {
// The scope of a patched method includes the origin class.
declaration =
classBuilder.origin.findStaticBuilder(name, charOffset, uri, library);
}
if (declaration != null &&
declaration.isInstanceMember &&
inFieldInitializer &&
!inInitializer) {
return new IncompleteErrorGenerator(this, token, declaration.target,
fasta.templateThisAccessInFieldInitializer.withArguments(name));
}
if (declaration == null ||
(!isInstanceContext && declaration.isInstanceMember)) {
Name n = new Name(name, library.library);
if (!isQualified && isInstanceContext) {
assert(declaration == null);
if (constantContext != ConstantContext.none || member.isField) {
return new UnresolvedNameGenerator(this, token, n);
}
return new ThisPropertyAccessGenerator(this, token, n,
lookupInstanceMember(n), lookupInstanceMember(n, isSetter: true));
} else if (ignoreMainInGetMainClosure &&
name == "main" &&
member?.name == "_getMainClosure") {
return forest.literalNull(null)..fileOffset = charOffset;
} else {
return new UnresolvedNameGenerator(this, token, n);
}
} else if (declaration.isTypeDeclaration) {
return new TypeUseGenerator(this, token, declaration, name);
} else if (declaration.isLocal) {
if (constantContext != ConstantContext.none &&
!declaration.isConst &&
!member.isConstructor) {
addProblem(
fasta.messageNotAConstantExpression, charOffset, token.length);
}
// An initializing formal parameter might be final without its
// VariableDeclaration being final. See
// [ProcedureBuilder.computeFormalParameterInitializerScope]. If that
// wasn't the case, we could always use [VariableUseGenerator].
if (declaration.isFinal) {
Object fact = typePromoter.getFactForAccess(
declaration.target, functionNestingLevel);
Object scope = typePromoter.currentScope;
return new ReadOnlyAccessGenerator(
this,
token,
new VariableGetJudgment(declaration.target, fact, scope)
..fileOffset = charOffset,
name);
} else {
return new VariableUseGenerator(this, token, declaration.target);
}
} else if (declaration.isInstanceMember) {
if (constantContext != ConstantContext.none &&
!inInitializer &&
// TODO(ahe): This is a hack because Fasta sets up the scope
// "this.field" parameters according to old semantics. Under the new
// semantics, such parameters introduces a new parameter with that
// name that should be resolved here.
!member.isConstructor) {
addProblem(
fasta.messageNotAConstantExpression, charOffset, token.length);
}
Name n = new Name(name, library.library);
Member getter;
Member setter;
if (declaration is AccessErrorBuilder) {
setter = declaration.parent.target;
getter = lookupInstanceMember(n);
} else {
getter = declaration.target;
setter = lookupInstanceMember(n, isSetter: true);
}
return new ThisPropertyAccessGenerator(this, token, n, getter, setter);
} else if (declaration.isRegularMethod) {
assert(declaration.isStatic || declaration.isTopLevel);
return new StaticAccessGenerator(this, token, declaration.target, null);
} else if (declaration is PrefixBuilder) {
assert(prefix == null);
return new PrefixUseGenerator(this, token, declaration);
} else if (declaration is LoadLibraryBuilder) {
return new LoadLibraryGenerator(this, token, declaration);
} else {
if (declaration.hasProblem && declaration is! AccessErrorBuilder)
return declaration;
Declaration setter;
if (declaration.isSetter) {
setter = declaration;
} else if (declaration.isGetter) {
setter = scope.lookupSetter(name, charOffset, uri);
} else if (declaration.isField && !declaration.isFinal) {
setter = declaration;
}
StaticAccessGenerator generator = new StaticAccessGenerator.fromBuilder(
this, declaration, token, setter);
if (constantContext != ConstantContext.none) {
Member readTarget = generator.readTarget;
if (!(readTarget is Field && readTarget.isConst ||
// Static tear-offs are also compile time constants.
readTarget is Procedure)) {
addProblem(
fasta.messageNotAConstantExpression, charOffset, token.length);
}
}
return generator;
}
}
@override
void handleQualified(Token period) {
debugEvent("Qualified");
Object node = pop();
Object qualifier = pop();
if (qualifier is ParserRecovery) {
push(qualifier);
} else if (node is ParserRecovery) {
push(node);
} else {
Identifier identifier = node;
push(identifier.withQualifier(qualifier));
}
}
@override
void beginLiteralString(Token token) {
debugEvent("beginLiteralString");
push(token);
}
@override
void handleStringPart(Token token) {
debugEvent("StringPart");
push(token);
}
@override
void endLiteralString(int interpolationCount, Token endToken) {
debugEvent("endLiteralString");
if (interpolationCount == 0) {
Token token = pop();
String value = unescapeString(token.lexeme, token, this);
push(forest.literalString(value, token));
} else {
int count = 1 + interpolationCount * 2;
List<Object> parts = const FixedNullableList<Object>().pop(stack, count);
if (parts == null) {
push(new ParserRecovery(endToken.charOffset));
return;
}
Token first = parts.first;
Token last = parts.last;
Quote quote = analyzeQuote(first.lexeme);
List<Expression> expressions = <Expression>[];
// Contains more than just \' or \".
if (first.lexeme.length > 1) {
String value =
unescapeFirstStringPart(first.lexeme, quote, first, this);
if (value.isNotEmpty) {
expressions.add(forest.literalString(value, first));
}
}
for (int i = 1; i < parts.length - 1; i++) {
Object part = parts[i];
if (part is Token) {
if (part.lexeme.length != 0) {
String value = unescape(part.lexeme, quote, part, this);
expressions.add(forest.literalString(value, part));
}
} else {
expressions.add(toValue(part));
}
}
// Contains more than just \' or \".
if (last.lexeme.length > 1) {
String value = unescapeLastStringPart(last.lexeme, quote, last, this);
if (value.isNotEmpty) {
expressions.add(forest.literalString(value, last));
}
}
push(forest.stringConcatenationExpression(expressions, endToken));
}
}
@override
void handleNativeClause(Token nativeToken, bool hasName) {
debugEvent("NativeClause");
if (hasName) {
forest.asLiteralString(pop());
}
}
@override
void handleScript(Token token) {
debugEvent("Script");
}
@override
void handleStringJuxtaposition(int literalCount) {
debugEvent("StringJuxtaposition");
List<Expression> parts = popListForValue(literalCount);
List<Expression> expressions;
// Flatten string juxtapositions of string interpolation.
for (int i = 0; i < parts.length; i++) {
Expression part = parts[i];
if (part is StringConcatenation) {
if (expressions == null) {
expressions = parts.sublist(0, i);
}
for (Expression expression in part.expressions) {
expressions.add(expression);
}
} else {
if (expressions != null) {
expressions.add(part);
}
}
}
push(forest.stringConcatenationExpression(expressions ?? parts, null));
}
@override
void handleLiteralInt(Token token) {
debugEvent("LiteralInt");
int value = int.tryParse(token.lexeme);
if (!library.loader.target.strongMode) {
if (value == null) {
push(unhandled(
'large integer', 'handleLiteralInt', token.charOffset, uri));
} else {
push(forest.literalInt(value, token));
}
return;
}
// Postpone parsing of literals resulting in a negative value
// (hex literals >= 2^63). These are only allowed when not negated.
if (value == null || value < 0) {
push(forest.literalLargeInt(token.lexeme, token));
} else {
push(forest.literalInt(value, token));
}
}
@override
void handleEmptyFunctionBody(Token semicolon) {
debugEvent("ExpressionFunctionBody");
endBlockFunctionBody(0, null, semicolon);
}
@override
void handleExpressionFunctionBody(Token arrowToken, Token endToken) {
debugEvent("ExpressionFunctionBody");
endReturnStatement(true, arrowToken.next, endToken);
}
@override
void endReturnStatement(
bool hasExpression, Token beginToken, Token endToken) {
debugEvent("ReturnStatement");
Expression expression = hasExpression ? popForValue() : null;
if (expression != null && inConstructor) {
push(buildProblemStatement(
fasta.messageConstructorWithReturnType, beginToken.charOffset));
} else {
push(forest.returnStatement(beginToken, expression, endToken));
}
}
@override
void beginThenStatement(Token token) {
Expression condition = popForValue();
enterThenForTypePromotion(condition);
push(condition);
super.beginThenStatement(token);
}
@override
void endThenStatement(Token token) {
typePromoter.enterElse();
super.endThenStatement(token);
}
@override
void endIfStatement(Token ifToken, Token elseToken) {
Statement elsePart = popStatementIfNotNull(elseToken);
Statement thenPart = popStatement();
Expression condition = pop();
typePromoter.exitConditional();
push(forest.ifStatement(ifToken, condition, thenPart, elseToken, elsePart));
}
@override
void endVariableInitializer(Token assignmentOperator) {
debugEvent("VariableInitializer");
assert(assignmentOperator.stringValue == "=");
pushNewLocalVariable(popForValue(), equalsToken: assignmentOperator);
}
@override
void handleNoVariableInitializer(Token token) {
debugEvent("NoVariableInitializer");
bool isConst = (currentLocalVariableModifiers & constMask) != 0;
bool isFinal = (currentLocalVariableModifiers & finalMask) != 0;
Expression initializer;
if (!optional("in", token)) {
// A for-in loop-variable can't have an initializer. So let's remain
// silent if the next token is `in`. Since a for-in loop can only have
// one variable it must be followed by `in`.
if (isConst) {
initializer = buildProblem(
fasta.templateConstFieldWithoutInitializer
.withArguments(token.lexeme),
token.charOffset,
token.length);
} else if (isFinal) {
initializer = buildProblem(
fasta.templateFinalFieldWithoutInitializer
.withArguments(token.lexeme),
token.charOffset,
token.length);
}
}
pushNewLocalVariable(initializer);
}
void pushNewLocalVariable(Expression initializer, {Token equalsToken}) {
Object node = pop();
if (node is ParserRecovery) {
push(node);
return;
}
Identifier identifier = node;
assert(currentLocalVariableModifiers != -1);
bool isConst = (currentLocalVariableModifiers & constMask) != 0;
bool isFinal = (currentLocalVariableModifiers & finalMask) != 0;
assert(isConst == (constantContext == ConstantContext.inferred));
VariableDeclaration variable = new VariableDeclarationJudgment(
identifier.name, functionNestingLevel,
forSyntheticToken: deprecated_extractToken(identifier).isSynthetic,
initializer: initializer,
type: buildDartType(currentLocalVariableType),
isFinal: isFinal,
isConst: isConst)
..fileOffset = identifier.charOffset
..fileEqualsOffset = offsetForToken(equalsToken);
library.checkBoundsInVariableDeclaration(variable, typeEnvironment);
push(variable);
}
@override
void beginFieldInitializer(Token token) {
inFieldInitializer = true;
}
@override
void endFieldInitializer(Token assignmentOperator, Token token) {
debugEvent("FieldInitializer");
inFieldInitializer = false;
assert(assignmentOperator.stringValue == "=");
push(popForValue());
}
@override
void handleNoFieldInitializer(Token token) {
debugEvent("NoFieldInitializer");
if (constantContext != ConstantContext.none) {
// Creating a null value to prevent the Dart VM from crashing.
push(forest.literalNull(token));
} else {
push(NullValue.FieldInitializer);
}
}
@override
void endInitializedIdentifier(Token nameToken) {
// TODO(ahe): Use [InitializedIdentifier] here?
debugEvent("InitializedIdentifier");
Object node = pop();
if (node is ParserRecovery) {
push(node);
return;
}
VariableDeclaration variable = node;
variable.fileOffset = nameToken.charOffset;
push(variable);
declareVariable(variable, scope);
}
@override
void beginVariablesDeclaration(Token token, Token varFinalOrConst) {
debugEvent("beginVariablesDeclaration");
UnresolvedType<KernelTypeBuilder> type = pop();
int modifiers = Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme);
super.push(currentLocalVariableModifiers);
super.push(currentLocalVariableType ?? NullValue.Type);
currentLocalVariableType = type;
currentLocalVariableModifiers = modifiers;
super.push(constantContext);
constantContext = ((modifiers & constMask) != 0)
? ConstantContext.inferred
: ConstantContext.none;
}
@override
void endVariablesDeclaration(int count, Token endToken) {
debugEvent("VariablesDeclaration");
if (count == 1) {
Object node = pop();
constantContext = pop();
currentLocalVariableType = pop();
currentLocalVariableModifiers = pop();
List<Expression> annotations = pop();
if (node is ParserRecovery) {
push(node);
return;
}
VariableDeclaration variable = node;
if (annotations != null) {
for (Expression annotation in annotations) {
variable.addAnnotation(annotation);
}
}
push(variable);
} else {
List<VariableDeclaration> variables =
const FixedNullableList<VariableDeclaration>().pop(stack, count);
constantContext = pop();
currentLocalVariableType = pop();
currentLocalVariableModifiers = pop();
List<Expression> annotations = pop();
if (variables == null) {
push(new ParserRecovery(offsetForToken(endToken)));
return;
}
if (annotations != null) {
bool isFirstVariable = true;
for (VariableDeclarationJudgment variable in variables) {
for (Expression annotation in annotations) {
variable.addAnnotation(annotation);
}
if (isFirstVariable) {
isFirstVariable = false;
} else {
variable.infersAnnotations = false;
}
}
}
push(forest.variablesDeclaration(variables, uri));
}
}
@override
void endBlock(int count, Token openBrace, Token closeBrace) {
debugEvent("Block");
Statement block = popBlock(count, openBrace, closeBrace);
exitLocalScope();
push(block);
}
void handleInvalidTopLevelBlock(Token token) {
// TODO(danrubel): Consider improved recovery by adding this block
// as part of a synthetic top level function.
pop(); // block
}
@override
void handleAssignmentExpression(Token token) {
debugEvent("AssignmentExpression");
Expression value = popForValue();
Object generator = pop();
if (generator is! Generator) {
push(buildProblem(fasta.messageNotAnLvalue, offsetForToken(token),
lengthForToken(token)));
} else {
push(new DelayedAssignment(
this, token, generator, value, token.stringValue));
}
}
@override
void enterLoop(int charOffset) {
if (peek() is LabelTarget) {
LabelTarget target = peek();
enterBreakTarget(charOffset, target.breakTarget);
enterContinueTarget(charOffset, target.continueTarget);
} else {
enterBreakTarget(charOffset);
enterContinueTarget(charOffset);
}
}
void exitLoopOrSwitch(Statement statement) {
if (problemInLoopOrSwitch != null) {
push(problemInLoopOrSwitch);
problemInLoopOrSwitch = null;
} else {
push(statement);
}
}
List<VariableDeclaration> buildForInitVariableDeclarations(
variableOrExpression) {
if (variableOrExpression is VariableDeclaration) {
return <VariableDeclaration>[variableOrExpression];
} else if (forest.isVariablesDeclaration(variableOrExpression)) {
return forest
.variablesDeclarationExtractDeclarations(variableOrExpression);
} else if (variableOrExpression is List<Object>) {
List<VariableDeclaration> variables = <VariableDeclaration>[];
for (Object v in variableOrExpression) {
variables.addAll(buildForInitVariableDeclarations(v));
}
return variables;
} else if (variableOrExpression == null) {
return <VariableDeclaration>[];
}
return null;
}
List<Expression> buildForInitExpressions(variableOrExpression) {
if (variableOrExpression is Expression) {
return <Expression>[variableOrExpression];
} else if (variableOrExpression is ExpressionStatementJudgment) {
return <Expression>[variableOrExpression.expression];
}
return null;
}
@override
void endForStatement(Token forKeyword, Token leftParen, Token leftSeparator,
int updateExpressionCount, Token endToken) {
debugEvent("ForStatement");
Statement body = popStatement();
List<Expression> updates = popListForEffect(updateExpressionCount);
Statement conditionStatement = popStatement();
Object variableOrExpression = pop();
variableOrExpression = variableOrExpression is Generator
? variableOrExpression.buildForEffect()
: variableOrExpression;
List<Expression> initializers =
buildForInitExpressions(variableOrExpression);
List<VariableDeclaration> variableList = initializers == null
? buildForInitVariableDeclarations(variableOrExpression)
: null;
exitLocalScope();
JumpTarget continueTarget = exitContinueTarget();
JumpTarget breakTarget = exitBreakTarget();
if (continueTarget.hasUsers) {
body = forest.syntheticLabeledStatement(body);
continueTarget.resolveContinues(forest, body);
}
Expression condition;
if (forest.isExpressionStatement(conditionStatement)) {
condition =
forest.getExpressionFromExpressionStatement(conditionStatement);
} else {
assert(forest.isEmptyStatement(conditionStatement));
}
Statement result = forest.forStatement(
forKeyword,
leftParen,
variableList,
initializers,
leftSeparator,
condition,
conditionStatement,
updates,
leftParen.endGroup,
body);
if (breakTarget.hasUsers) {
result = forest.syntheticLabeledStatement(result);
breakTarget.resolveBreaks(forest, result);
}
if (variableOrExpression is ParserRecovery) {
problemInLoopOrSwitch ??= buildProblemStatement(
fasta.messageSyntheticToken, variableOrExpression.charOffset,
suppressMessage: true);
}
exitLoopOrSwitch(result);
}
@override
void endAwaitExpression(Token keyword, Token endToken) {
debugEvent("AwaitExpression");
push(forest.awaitExpression(popForValue(), keyword));
}
@override
void handleAsyncModifier(Token asyncToken, Token starToken) {
debugEvent("AsyncModifier");
push(asyncMarkerFromTokens(asyncToken, starToken));
}
@override
void handleLiteralList(
int count, Token leftBracket, Token constKeyword, Token rightBracket) {
debugEvent("LiteralList");
List<Expression> expressions = popListForValue(count);
List<UnresolvedType<KernelTypeBuilder>> typeArguments = pop();
DartType typeArgument;
if (typeArguments != null) {
if (typeArguments.length > 1) {
addProblem(
fasta.messageListLiteralTooManyTypeArguments,
offsetForToken(leftBracket),
lengthOfSpan(leftBracket, leftBracket.endGroup));
} else {
typeArgument = buildDartType(typeArguments.single);
if (library.loader.target.strongMode) {
typeArgument =
instantiateToBounds(typeArgument, coreTypes.objectClass);
}
}
}
Expression node = forest.literalList(
constKeyword,
constKeyword != null || constantContext == ConstantContext.inferred,
typeArgument,
typeArguments,
leftBracket,
expressions,
rightBracket);
library.checkBoundsInListLiteral(node, typeEnvironment);
push(node);
}
@override
void handleLiteralBool(Token token) {
debugEvent("LiteralBool");
bool value = optional("true", token);
assert(value || optional("false", token));
push(forest.literalBool(value, token));
}
@override
void handleLiteralDouble(Token token) {
debugEvent("LiteralDouble");
push(forest.literalDouble(double.parse(token.lexeme), token));
}
@override
void handleLiteralNull(Token token) {
debugEvent("LiteralNull");
push(forest.literalNull(token));
}
@override
void handleLiteralMap(
int count, Token leftBrace, Token constKeyword, Token rightBrace) {
debugEvent("LiteralMap");
List<MapEntry> entries =
const GrowableList<MapEntry>().pop(stack, count) ?? <MapEntry>[];
List<UnresolvedType<KernelTypeBuilder>> typeArguments = pop();
DartType keyType;
DartType valueType;
if (typeArguments != null) {
if (typeArguments.length != 2) {
addProblem(
fasta.messageMapLiteralTypeArgumentMismatch,
offsetForToken(leftBrace),
lengthOfSpan(leftBrace, leftBrace.endGroup));
} else {
keyType = buildDartType(typeArguments[0]);
valueType = buildDartType(typeArguments[1]);
if (library.loader.target.strongMode) {
keyType = instantiateToBounds(keyType, coreTypes.objectClass);
valueType = instantiateToBounds(valueType, coreTypes.objectClass);
}
}
}
Expression node = forest.literalMap(
constKeyword,
constKeyword != null || constantContext == ConstantContext.inferred,
keyType,
valueType,
typeArguments,
leftBrace,
entries,
rightBrace);
library.checkBoundsInMapLiteral(node, typeEnvironment);
push(node);
}
@override
void endLiteralMapEntry(Token colon, Token endToken) {
debugEvent("LiteralMapEntry");
Expression value = popForValue();
Expression key = popForValue();
push(forest.mapEntry(key, colon, value));
}
String symbolPartToString(name) {
if (name is Identifier) {
return name.name;
} else if (name is Operator) {
return name.name;
} else {
return unhandled("${name.runtimeType}", "symbolPartToString", -1, uri);
}
}
@override
void endLiteralSymbol(Token hashToken, int identifierCount) {
debugEvent("LiteralSymbol");
if (identifierCount == 1) {
Object part = pop();
if (part is ParserRecovery) {
push(new ParserErrorGenerator(
this, hashToken, fasta.messageSyntheticToken));
} else {
push(forest.literalSymbolSingluar(
symbolPartToString(part), hashToken, part));
}
} else {
List<Identifier> parts =
const FixedNullableList<Identifier>().pop(stack, identifierCount);
if (parts == null) {
push(new ParserErrorGenerator(
this, hashToken, fasta.messageSyntheticToken));
return;
}
String value = symbolPartToString(parts.first);
for (int i = 1; i < parts.length; i++) {
value += ".${symbolPartToString(parts[i])}";
}
push(forest.literalSymbolMultiple(value, hashToken, parts));
}
}
@override
void handleType(Token beginToken) {
// TODO(ahe): The scope is wrong for return types of generic functions.
debugEvent("Type");
List<UnresolvedType<KernelTypeBuilder>> arguments = pop();
Object name = pop();
if (name is QualifiedName) {
QualifiedName qualified = name;
Object prefix = qualified.qualifier;
Token suffix = deprecated_extractToken(qualified);
if (prefix is Generator) {
name = prefix.qualifiedLookup(suffix);
} else {
String name = getNodeName(prefix);
String displayName = debugName(name, suffix.lexeme);
int offset = offsetForToken(beginToken);
push(new UnresolvedType<KernelTypeBuilder>(
new KernelNamedTypeBuilder(name, null)
..bind(new KernelInvalidTypeBuilder(
name,
fasta.templateNotAType
.withArguments(displayName)
.withLocation(
uri, offset, lengthOfSpan(beginToken, suffix)))),
offset,
uri));
return;
}
}
KernelTypeBuilder result;
if (name is Generator) {
result = name.buildTypeWithResolvedArguments(arguments);
if (result == null) {
unhandled("null", "result", beginToken.charOffset, uri);
}
} else if (name is TypeBuilder) {
result = name.build(library);
if (result == null) {
unhandled("null", "result", beginToken.charOffset, uri);
}
} else if (name is ProblemBuilder) {
// TODO(ahe): Arguments could be passed here.
result = new KernelNamedTypeBuilder(name.name, null)
..bind(new KernelInvalidTypeBuilder(
name.name,
name.message.withLocation(
name.fileUri, name.charOffset, name.name.length)));
} else {
unhandled(
"${name.runtimeType}", "handleType", beginToken.charOffset, uri);
}
push(new UnresolvedType<KernelTypeBuilder>(
result, beginToken.charOffset, uri));
}
@override
void beginFunctionType(Token beginToken) {
debugEvent("beginFunctionType");
}
void enterFunctionTypeScope(List<KernelTypeVariableBuilder> typeVariables) {
debugEvent("enterFunctionTypeScope");
enterLocalScope(null,
scope.createNestedScope("function-type scope", isModifiable: true));
if (typeVariables != null) {
ScopeBuilder scopeBuilder = new ScopeBuilder(scope);
for (KernelTypeVariableBuilder builder in typeVariables) {
String name = builder.name;
KernelTypeVariableBuilder existing = scopeBuilder[name];
if (existing == null) {
scopeBuilder.addMember(name, builder);
} else {
reportDuplicatedDeclaration(existing, name, builder.charOffset);
}
}
}
}
@override
void endFunctionType(Token functionToken) {
debugEvent("FunctionType");
FormalParameters formals = pop();
UnresolvedType<KernelTypeBuilder> returnType = pop();
List<KernelTypeVariableBuilder> typeVariables = pop();
UnresolvedType<KernelTypeBuilder> type =
formals.toFunctionType(returnType, typeVariables);
exitLocalScope();
push(type);
}
@override
void handleVoidKeyword(Token token) {
debugEvent("VoidKeyword");
int offset = offsetForToken(token);
push(new UnresolvedType<KernelTypeBuilder>(
new KernelNamedTypeBuilder("void", null)
..bind(new VoidTypeBuilder<KernelTypeBuilder, VoidType>(
const VoidType(), library, offset)),
offset,
uri));
}
@override
void handleAsOperator(Token operator) {
debugEvent("AsOperator");
DartType type = buildDartType(pop());
library.checkBoundsInType(type, typeEnvironment, operator.charOffset);
Expression expression = popForValue();
if (constantContext != ConstantContext.none) {
push(buildProblem(
fasta.templateNotConstantExpression
.withArguments('As expression'),
operator.charOffset,
operator.length)
.desugared);
} else {
Expression node = forest.asExpression(expression, type, operator);
push(node);
}
}
@override
void handleIsOperator(Token isOperator, Token not) {
debugEvent("IsOperator");
DartType type = buildDartType(pop());
Expression operand = popForValue();
bool isInverted = not != null;
Expression isExpression =
forest.isExpression(operand, isOperator, not, type);
library.checkBoundsInType(type, typeEnvironment, isOperator.charOffset);
if (operand is VariableGet) {
typePromoter.handleIsCheck(isExpression, isInverted, operand.variable,
type, functionNestingLevel);
}
if (constantContext != ConstantContext.none) {
push(buildProblem(
fasta.templateNotConstantExpression
.withArguments('Is expression'),
isOperator.charOffset,
isOperator.length)
.desugared);
} else {
push(isExpression);
}
}
@override
void beginConditionalExpression(Token question) {
Expression condition = popForValue();
typePromoter.enterThen(condition);
push(condition);
super.beginConditionalExpression(question);
}
@override
void handleConditionalExpressionColon() {
Expression then = popForValue();
typePromoter.enterElse();
push(then);
super.handleConditionalExpressionColon();
}
@override
void endConditionalExpression(Token question, Token colon) {
debugEvent("ConditionalExpression");
Expression elseExpression = popForValue();
Expression thenExpression = pop();
Expression condition = pop();
typePromoter.exitConditional();
push(forest.conditionalExpression(
condition, question, thenExpression, colon, elseExpression));
}
@override
void handleThrowExpression(Token throwToken, Token endToken) {
debugEvent("ThrowExpression");
Expression expression = popForValue();
if (constantContext != ConstantContext.none) {
push(buildProblem(
fasta.templateNotConstantExpression.withArguments('Throw'),
throwToken.offset,
throwToken.length));
} else {
push(forest.throwExpression(throwToken, expression));
}
}
@override
void beginFormalParameter(Token token, MemberKind kind, Token covariantToken,
Token varFinalOrConst) {
push((covariantToken != null ? covariantMask : 0) |
Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme));
}
@override
void endFormalParameter(Token thisKeyword, Token periodAfterThis,
Token nameToken, FormalParameterKind kind, MemberKind memberKind) {
debugEvent("FormalParameter");
if (thisKeyword != null) {
if (!inConstructor) {
handleRecoverableError(fasta.messageFieldInitializerOutsideConstructor,
thisKeyword, thisKeyword);
thisKeyword = null;
}
}
Object nameNode = pop();
UnresolvedType<KernelTypeBuilder> type = pop();
if (functionNestingLevel == 0) {
// TODO(ahe): The type we compute here may be different from what is
// computed in the outline phase. We should make sure that the outline
// phase computes the same type. See
// pkg/front_end/testcases/deferred_type_annotation.dart for an example
// where not calling [buildDartType] leads to a missing compile-time
// error. Also, notice that the type of the problematic parameter isn't
// `invalid-type`.
buildDartType(type);
}
int modifiers = pop();
if (inCatchClause) {
modifiers |= finalMask;
}
List<Expression> annotations = pop();
if (nameNode is ParserRecovery) {
push(nameNode);
return;
}
Identifier name = nameNode;
KernelFormalParameterBuilder parameter;
if (!inCatchClause &&
functionNestingLevel == 0 &&
memberKind != MemberKind.GeneralizedFunctionType) {
ProcedureBuilder<TypeBuilder> member = this.member;
parameter = member.getFormal(name.name);
if (parameter == null) {
push(new ParserRecovery(nameToken.charOffset));
return;
}
} else {
parameter = new KernelFormalParameterBuilder(null, modifiers,
type?.builder, name?.name, false, library, offsetForToken(nameToken));
}
VariableDeclaration variable =
parameter.build(library, functionNestingLevel);
Expression initializer = name?.initializer;
if (initializer != null) {
if (member is KernelRedirectingFactoryBuilder) {
KernelRedirectingFactoryBuilder factory = member;
addProblem(
fasta.templateDefaultValueInRedirectingFactoryConstructor
.withArguments(factory.redirectionTarget.fullNameForErrors),
initializer.fileOffset,
noLength);
} else {
variable.initializer = initializer..parent = variable;
}
}
if (annotations != null) {
if (functionNestingLevel == 0) {
_typeInferrer.inferMetadata(this, annotations);
}
for (Expression annotation in annotations) {
variable.addAnnotation(annotation);
}
}
push(parameter);
}
@override
void endOptionalFormalParameters(
int count, Token beginToken, Token endToken) {
debugEvent("OptionalFormalParameters");
FormalParameterKind kind = optional("{", beginToken)
? FormalParameterKind.optionalNamed
: FormalParameterKind.optionalPositional;
// When recovering from an empty list of optional arguments, count may be
// 0. It might be simpler if the parser didn't call this method in that
// case, however, then [beginOptionalFormalParameters] wouldn't always be
// matched by this method.
List<KernelFormalParameterBuilder> parameters =
const FixedNullableList<KernelFormalParameterBuilder>()
.pop(stack, count);
if (parameters == null) {
push(new ParserRecovery(offsetForToken(beginToken)));
} else {
for (KernelFormalParameterBuilder parameter in parameters) {
parameter.kind = kind;
}
push(parameters);
}
}
@override
void beginFunctionTypedFormalParameter(Token token) {
debugEvent("beginFunctionTypedFormalParameter");
functionNestingLevel++;
}
@override
void endFunctionTypedFormalParameter(Token nameToken) {
debugEvent("FunctionTypedFormalParameter");
if (inCatchClause || functionNestingLevel != 0) {
exitLocalScope();
}
FormalParameters formals = pop();
UnresolvedType<KernelTypeBuilder> returnType = pop();
List<KernelTypeVariableBuilder> typeVariables = pop();
UnresolvedType<KernelTypeBuilder> type =
formals.toFunctionType(returnType, typeVariables);
exitLocalScope();
push(type);
functionNestingLevel--;
}
@override
void beginFormalParameterDefaultValueExpression() {
super.push(constantContext);
constantContext = ConstantContext.none;
}
@override
void endFormalParameterDefaultValueExpression() {
debugEvent("FormalParameterDefaultValueExpression");
Object defaultValueExpression = pop();
constantContext = pop();
push(defaultValueExpression);
}
@override
void handleValuedFormalParameter(Token equals, Token token) {
debugEvent("ValuedFormalParameter");
Expression initializer = popForValue();
Identifier name = pop();
push(new InitializedIdentifier(name, initializer));
}
@override
void handleFormalParameterWithoutValue(Token token) {
debugEvent("FormalParameterWithoutValue");
}
@override
void beginFormalParameters(Token token, MemberKind kind) {
super.push(constantContext);
constantContext = ConstantContext.none;
}
@override
void endFormalParameters(
int count, Token beginToken, Token endToken, MemberKind kind) {
debugEvent("FormalParameters");
List<KernelFormalParameterBuilder> optionals;
int optionalsCount = 0;
if (count > 0 && peek() is List<KernelFormalParameterBuilder>) {
optionals = pop();
count--;
optionalsCount = optionals.length;
}
List<KernelFormalParameterBuilder> parameters =
const FixedNullableList<KernelFormalParameterBuilder>()
.popPadded(stack, count, optionalsCount);
if (optionals != null && parameters != null) {
parameters.setRange(count, count + optionalsCount, optionals);
}
assert(parameters?.isNotEmpty ?? true);
FormalParameters formals = new FormalParameters(parameters,
offsetForToken(beginToken), lengthOfSpan(beginToken, endToken), uri);
constantContext = pop();
push(formals);
if ((inCatchClause || functionNestingLevel != 0) &&
kind != MemberKind.GeneralizedFunctionType) {
enterLocalScope(
null,
formals.computeFormalParameterScope(
scope, member ?? classBuilder ?? library, this));
}
}
@override
void beginCatchClause(Token token) {
debugEvent("beginCatchClause");
inCatchClause = true;
}
@override
void endCatchClause(Token token) {
debugEvent("CatchClause");
inCatchClause = false;
push(inCatchBlock);
inCatchBlock = true;
}
@override
void handleCatchBlock(Token onKeyword, Token catchKeyword, Token comma) {
debugEvent("CatchBlock");
Statement body = pop();
inCatchBlock = pop();
if (catchKeyword != null) {
exitLocalScope();
}
FormalParameters catchParameters = popIfNotNull(catchKeyword);
DartType exceptionType =
buildDartType(popIfNotNull(onKeyword)) ?? const DynamicType();
KernelFormalParameterBuilder exception;
KernelFormalParameterBuilder stackTrace;
List<Statement> compileTimeErrors;
if (catchParameters?.parameters != null) {
int parameterCount = catchParameters.parameters.length;
if (parameterCount > 0) {
exception = catchParameters.parameters[0];
exception.build(library, functionNestingLevel).type = exceptionType;
if (parameterCount > 1) {
stackTrace = catchParameters.parameters[1];
stackTrace.build(library, functionNestingLevel).type =
coreTypes.stackTraceClass.rawType;
}
}
if (parameterCount > 2) {
// If parameterCount is 0, the parser reported an error already.
if (parameterCount != 0) {
for (int i = 2; i < parameterCount; i++) {
KernelFormalParameterBuilder parameter =
catchParameters.parameters[i];
compileTimeErrors ??= <Statement>[];
compileTimeErrors.add(buildProblemStatement(
fasta.messageCatchSyntaxExtraParameters, parameter.charOffset,
length: parameter.name.length));
}
}
}
}
push(forest.catchClause(
onKeyword,
exceptionType,
catchKeyword,
exception?.target,
stackTrace?.target,
coreTypes.stackTraceClass.rawType,
body));
if (compileTimeErrors == null) {
push(NullValue.Block);
} else {
push(forest.block(null, compileTimeErrors, null));
}
}
@override
void endTryStatement(int catchCount, Token tryKeyword, Token finallyKeyword) {
Statement finallyBlock = popStatementIfNotNull(finallyKeyword);
List<Catch> catchBlocks;
List<Statement> compileTimeErrors;
if (catchCount != 0) {
List<Object> catchBlocksAndErrors =
const FixedNullableList<Object>().pop(stack, catchCount * 2);
catchBlocks = new List<Catch>.filled(catchCount, null, growable: true);
for (int i = 0; i < catchCount; i++) {
catchBlocks[i] = catchBlocksAndErrors[i * 2];
Statement error = catchBlocksAndErrors[i * 2 + 1];
if (error != null) {
compileTimeErrors ??= <Statement>[];
compileTimeErrors.add(error);
}
}
}
Statement tryBlock = popStatement();
Statement tryStatement = forest.tryStatement(
tryKeyword, tryBlock, catchBlocks, finallyKeyword, finallyBlock);
if (compileTimeErrors != null) {
compileTimeErrors.add(tryStatement);
push(forest.block(null, compileTimeErrors, null));
} else {
push(tryStatement);
}
}
@override
void handleNoExpression(Token token) {
debugEvent("NoExpression");
push(NullValue.Expression);
}
@override
void handleIndexedExpression(
Token openSquareBracket, Token closeSquareBracket) {
debugEvent("IndexedExpression");
Expression index = popForValue();
Object receiver = pop();
if (receiver is ThisAccessGenerator && receiver.isSuper) {
push(new SuperIndexedAccessGenerator(
this,
openSquareBracket,
index,
lookupInstanceMember(indexGetName, isSuper: true),
lookupInstanceMember(indexSetName, isSuper: true)));
} else {
push(IndexedAccessGenerator.make(
this, openSquareBracket, toValue(receiver), index, null, null));
}
}
@override
void handleUnaryPrefixExpression(Token token) {
debugEvent("UnaryPrefixExpression");
Object receiver = pop();
if (optional("!", token)) {
push(forest.notExpression(toValue(receiver), token, false));
} else {
String operator = token.stringValue;
Expression receiverValue;
if (optional("-", token)) {
operator = "unary-";
}
bool isSuper = false;
if (receiver is ThisAccessGenerator && receiver.isSuper) {
isSuper = true;
receiverValue = forest.thisExpression(receiver.token);
} else {
receiverValue = toValue(receiver);
}
push(buildMethodInvocation(receiverValue, new Name(operator),
forest.argumentsEmpty(noLocation), token.charOffset,
// This *could* be a constant expression, we can't know without
// evaluating [receiver].
isConstantExpression: !isSuper,
isSuper: isSuper));
}
}
Name incrementOperator(Token token) {
if (optional("++", token)) return plusName;
if (optional("--", token)) return minusName;
return unhandled(token.lexeme, "incrementOperator", token.charOffset, u