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
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/front_end/src/fasta/crash.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.crash; import 'dart:async' show Future; import 'dart:convert' show jsonEncode; import 'dart:io' show ContentType, HttpClient, HttpClientRequest, SocketException, stderr; import 'problems.dart' show DebugAbort; const String defaultServerAddress = "http://127.0.0.1:59410/"; /// Tracks if there has been a crash reported through [reportCrash]. Should be /// reset between each compilation by calling [resetCrashReporting]. bool hasCrashed = false; /// Tracks the first source URI that has been read and is used as a fall-back /// for [reportCrash]. Should be reset between each compilation by calling /// [resetCrashReporting]. Uri firstSourceUri; class Crash { final Uri uri; final int charOffset; final Object error; final StackTrace trace; Crash(this.uri, this.charOffset, this.error, this.trace); String toString() { return """ Crash when compiling $uri, at character offset $charOffset: $error${trace == null ? '' : '\n$trace'} """; } } void resetCrashReporting() { firstSourceUri = null; hasCrashed = false; } Future<T> reportCrash<T>(error, StackTrace trace, [Uri uri, int charOffset]) async { note(String note) async { stderr.write(note); await stderr.flush(); } if (hasCrashed) return new Future<T>.error(error, trace); if (error is Crash) { trace = error.trace ?? trace; uri = error.uri ?? uri; charOffset = error.charOffset ?? charOffset; error = error.error; } uri ??= firstSourceUri; hasCrashed = true; Map<String, dynamic> data = <String, dynamic>{}; data["type"] = "crash"; data["client"] = "package:fasta"; if (uri != null) data["uri"] = "$uri"; if (charOffset != null) data["offset"] = charOffset; data["error"] = safeToString(error); data["trace"] = "$trace"; String json = jsonEncode(data); HttpClient client = new HttpClient(); try { Uri serverUri = Uri.parse(defaultServerAddress); HttpClientRequest request; try { request = await client.postUrl(serverUri); } on SocketException { // Assume the crash logger isn't running. client.close(force: true); return new Future<T>.error( new Crash(uri, charOffset, error, trace), trace); } if (request != null) { await note("\nSending crash report data"); request.persistentConnection = false; request.bufferOutput = false; String host = request?.connectionInfo?.remoteAddress?.host; int port = request?.connectionInfo?.remotePort; await note(" to $host:$port"); await request ..headers.contentType = ContentType.json ..write(json); await request.close(); await note("."); } } catch (e, s) { await note("\n${safeToString(e)}\n$s\n"); await note("\n\n\nFE::ERROR::$json\n\n\n"); } client.close(force: true); await note("\n"); return new Future<T>.error(error, trace); } String safeToString(Object object) { try { return "$object"; } catch (e) { return "Error when converting ${object.runtimeType} to string."; } } Future<T> withCrashReporting<T>( Future<T> Function() action, Uri Function() currentUri) async { resetCrashReporting(); try { return await action(); } on Crash { rethrow; } on DebugAbort { rethrow; } catch (e, s) { return reportCrash(e, s, currentUri()); } }
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/fasta/scanner.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; import 'dart:convert' show unicodeReplacementCharacterRune, utf8; import '../scanner/token.dart' show Token; import 'scanner/abstract_scanner.dart' show LanguageVersionChanged, ScannerConfiguration; import 'scanner/string_scanner.dart' show StringScanner; import 'scanner/utf8_bytes_scanner.dart' show Utf8BytesScanner; import 'scanner/recover.dart' show scannerRecovery; export 'scanner/abstract_scanner.dart' show LanguageVersionChanged, ScannerConfiguration; export 'scanner/token.dart' show LanguageVersionToken, StringToken, isBinaryOperator, isMinusOperator, isTernaryOperator, isUnaryOperator, isUserDefinableOperator; export 'scanner/error_token.dart' show ErrorToken, buildUnexpectedCharacterToken; export 'scanner/token.dart' show LanguageVersionToken; export 'scanner/token_constants.dart' show EOF_TOKEN; export 'scanner/utf8_bytes_scanner.dart' show Utf8BytesScanner; export 'scanner/string_scanner.dart' show StringScanner; export '../scanner/token.dart' show Keyword, Token; const int unicodeReplacementCharacter = unicodeReplacementCharacterRune; typedef Token Recover(List<int> bytes, Token tokens, List<int> lineStarts); abstract class Scanner { /// Returns true if an error occurred during [tokenize]. bool get hasErrors; List<int> get lineStarts; /// Configure which tokens are produced. set configuration(ScannerConfiguration config); Token tokenize(); } class ScannerResult { final Token tokens; final List<int> lineStarts; final bool hasErrors; ScannerResult(this.tokens, this.lineStarts, this.hasErrors); } /// Scan/tokenize the given UTF8 [bytes]. ScannerResult scan(List<int> bytes, {ScannerConfiguration configuration, bool includeComments: false, LanguageVersionChanged languageVersionChanged}) { if (bytes.last != 0) { throw new ArgumentError("[bytes]: the last byte must be null."); } Scanner scanner = new Utf8BytesScanner(bytes, configuration: configuration, includeComments: includeComments, languageVersionChanged: languageVersionChanged); return _tokenizeAndRecover(scanner, bytes: bytes); } /// Scan/tokenize the given [source]. ScannerResult scanString(String source, {ScannerConfiguration configuration, bool includeComments: false, LanguageVersionChanged languageVersionChanged}) { assert(source != null, 'source must not be null'); StringScanner scanner = new StringScanner(source, configuration: configuration, includeComments: includeComments, languageVersionChanged: languageVersionChanged); return _tokenizeAndRecover(scanner, source: source); } ScannerResult _tokenizeAndRecover(Scanner scanner, {List<int> bytes, String source}) { Token tokens = scanner.tokenize(); if (scanner.hasErrors) { if (bytes == null) bytes = utf8.encode(source); tokens = scannerRecovery(bytes, tokens, scanner.lineStarts); } return new ScannerResult(tokens, scanner.lineStarts, scanner.hasErrors); }
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/fasta/operator.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.operators; /// The user-definable operators in Dart. /// /// The names have been chosen to represent their normal semantic meaning. enum Operator { add, bitwiseAnd, bitwiseNot, bitwiseOr, bitwiseXor, divide, equals, greaterThan, greaterThanEquals, indexGet, indexSet, leftShift, lessThan, lessThanEquals, modulo, multiply, rightShift, tripleShift, subtract, truncatingDivide, unaryMinus, } Operator operatorFromString(String string) { if (identical("+", string)) return Operator.add; if (identical("&", string)) return Operator.bitwiseAnd; if (identical("~", string)) return Operator.bitwiseNot; if (identical("|", string)) return Operator.bitwiseOr; if (identical("^", string)) return Operator.bitwiseXor; if (identical("/", string)) return Operator.divide; if (identical("==", string)) return Operator.equals; if (identical(">", string)) return Operator.greaterThan; if (identical(">=", string)) return Operator.greaterThanEquals; if (identical("[]", string)) return Operator.indexGet; if (identical("[]=", string)) return Operator.indexSet; if (identical("<<", string)) return Operator.leftShift; if (identical("<", string)) return Operator.lessThan; if (identical("<=", string)) return Operator.lessThanEquals; if (identical("%", string)) return Operator.modulo; if (identical("*", string)) return Operator.multiply; if (identical(">>", string)) return Operator.rightShift; if (identical(">>>", string)) return Operator.tripleShift; if (identical("-", string)) return Operator.subtract; if (identical("~/", string)) return Operator.truncatingDivide; if (identical("unary-", string)) return Operator.unaryMinus; return null; } String operatorToString(Operator operator) { switch (operator) { case Operator.add: return "+"; case Operator.bitwiseAnd: return "&"; case Operator.bitwiseNot: return "~"; case Operator.bitwiseOr: return "|"; case Operator.bitwiseXor: return "^"; case Operator.divide: return "/"; case Operator.equals: return "=="; case Operator.greaterThan: return ">"; case Operator.greaterThanEquals: return ">="; case Operator.indexGet: return "[]"; case Operator.indexSet: return "[]="; case Operator.leftShift: return "<<"; case Operator.lessThan: return "<"; case Operator.lessThanEquals: return "<="; case Operator.modulo: return "%"; case Operator.multiply: return "*"; case Operator.rightShift: return ">>"; case Operator.tripleShift: return ">>>"; case Operator.subtract: return "-"; case Operator.truncatingDivide: return "~/"; case Operator.unaryMinus: return "unary-"; } return null; } int operatorRequiredArgumentCount(Operator operator) { switch (operator) { case Operator.bitwiseNot: case Operator.unaryMinus: return 0; case Operator.add: case Operator.bitwiseAnd: case Operator.bitwiseOr: case Operator.bitwiseXor: case Operator.divide: case Operator.equals: case Operator.greaterThan: case Operator.greaterThanEquals: case Operator.indexGet: case Operator.leftShift: case Operator.lessThan: case Operator.lessThanEquals: case Operator.modulo: case Operator.multiply: case Operator.rightShift: case Operator.tripleShift: case Operator.subtract: case Operator.truncatingDivide: return 1; case Operator.indexSet: return 2; } return -1; }
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/fasta/messages.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.messages; import 'package:kernel/ast.dart' show Library, Location, Component, TreeNode; import 'compiler_context.dart' show CompilerContext; export 'fasta_codes.dart'; bool get isVerbose => CompilerContext.current.options.verbose; Location getLocation(Uri uri, int charOffset) { return CompilerContext.current.uriToSource[uri]?.getLocation(uri, charOffset); } Location getLocationFromUri(Uri uri, int charOffset) { if (charOffset == -1) return null; return getLocation(uri, charOffset); } String getSourceLine(Location location) { if (location == null) return null; return CompilerContext.current.uriToSource[location.file] ?.getTextLine(location.line); } Location getLocationFromNode(TreeNode node) { if (node.enclosingComponent == null) { TreeNode parent = node; while (parent != null && parent is! Library) { parent = parent.parent; } if (parent is Library) { Component component = CompilerContext.current.options.target .configureComponent( new Component(uriToSource: CompilerContext.current.uriToSource)); component.libraries.add(parent); parent.parent = component; Location result = node.location; component.libraries.clear(); parent.parent = null; return result; } else { return null; } } else { return node.location; } }
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/fasta/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.loader; import 'dart:async' show Future; import 'dart:collection' show Queue; import 'package:kernel/ast.dart' show Class, DartType, Library; import 'builder/builder.dart' show Builder, ClassBuilder, LibraryBuilder, Scope, TypeBuilder; import 'builder/declaration_builder.dart' show DeclarationBuilder; import 'builder/modifier_builder.dart' show ModifierBuilder; import 'crash.dart' show firstSourceUri; import 'kernel/body_builder.dart' show BodyBuilder; import 'messages.dart' show FormattedMessage, LocatedMessage, Message, noLength, SummaryTemplate, Template, messagePlatformPrivateLibraryAccess, templateInternalProblemContextSeverity, templateSourceBodySummary; import 'problems.dart' show internalProblem, unhandled; import 'severity.dart' show Severity; import 'target_implementation.dart' show TargetImplementation; import 'ticker.dart' show Ticker; const String untranslatableUriScheme = "org-dartlang-untranslatable-uri"; abstract class Loader { final Map<Uri, LibraryBuilder> builders = <Uri, LibraryBuilder>{}; final Queue<LibraryBuilder> unparsedLibraries = new Queue<LibraryBuilder>(); final List<Library> libraries = <Library>[]; final TargetImplementation target; /// List of all handled compile-time errors seen so far by libraries loaded /// by this loader. /// /// A handled error is an error that has been added to the generated AST /// already, for example, as a throw expression. final List<LocatedMessage> handledErrors = <LocatedMessage>[]; /// List of all unhandled compile-time errors seen so far by libraries loaded /// by this loader. /// /// An unhandled error is an error that hasn't been handled, see /// [handledErrors]. final List<LocatedMessage> unhandledErrors = <LocatedMessage>[]; /// List of all problems seen so far by libraries loaded by this loader that /// does not belong directly to a library. final List<FormattedMessage> allComponentProblems = <FormattedMessage>[]; final Set<String> seenMessages = new Set<String>(); LibraryBuilder coreLibrary; /// The first library that we've been asked to compile. When compiling a /// program (aka script), this is the library that should have a main method. LibraryBuilder first; int byteCount = 0; Uri currentUriForCrashReporting; Loader(this.target); Ticker get ticker => target.ticker; Template<SummaryTemplate> get outlineSummaryTemplate; bool get isSourceLoader => false; /// Look up a library builder by the name [uri], or if such doesn't /// exist, create one. The canonical URI of the library is [uri], and its /// actual location is [fileUri]. /// /// Canonical URIs have schemes like "dart", or "package", and the actual /// location is often a file URI. /// /// The [accessor] is the library that's trying to import, export, or include /// as part [uri], and [charOffset] is the location of the corresponding /// directive. If [accessor] isn't allowed to access [uri], it's a /// compile-time error. LibraryBuilder read(Uri uri, int charOffset, {Uri fileUri, LibraryBuilder accessor, LibraryBuilder origin}) { LibraryBuilder builder = builders.putIfAbsent(uri, () { if (fileUri != null && (fileUri.scheme == "dart" || fileUri.scheme == "package" || fileUri.scheme == "dart-ext")) { fileUri = null; } String packageFragment; if (fileUri == null) { switch (uri.scheme) { case "package": case "dart": fileUri = target.translateUri(uri) ?? new Uri( scheme: untranslatableUriScheme, path: Uri.encodeComponent("$uri")); packageFragment = target.uriTranslator.getPackageFragment(uri); break; default: fileUri = uri; // Check for empty package name entry (redirecting to package name // from which we should get the fragment part). packageFragment = target.uriTranslator?.getDefaultPackageFragment(); break; } } bool hasPackageSpecifiedLanguageVersion = false; int packageSpecifiedLanguageVersionMajor; int packageSpecifiedLanguageVersionMinor; if (packageFragment != null) { List<String> properties = packageFragment.split("&"); int foundEntries = 0; for (int i = 0; i < properties.length; ++i) { String property = properties[i]; if (property.startsWith("dart=")) { if (++foundEntries > 1) { // Force error to be issued if more than one "dart=" entry. // (The error will be issued in library.setLanguageVersion below // when giving it `null` version numbers.) packageSpecifiedLanguageVersionMajor = null; packageSpecifiedLanguageVersionMinor = null; break; } hasPackageSpecifiedLanguageVersion = true; String langaugeVersionString = property.substring(5); // Verify that the version is x.y[whatever] List<String> dotSeparatedParts = langaugeVersionString.split("."); if (dotSeparatedParts.length >= 2) { packageSpecifiedLanguageVersionMajor = int.tryParse(dotSeparatedParts[0]); packageSpecifiedLanguageVersionMinor = int.tryParse(dotSeparatedParts[1]); } } } } LibraryBuilder library = target.createLibraryBuilder(uri, fileUri, origin); if (library == null) { throw new StateError("createLibraryBuilder for uri $uri, " "fileUri $fileUri returned null."); } if (hasPackageSpecifiedLanguageVersion) { library.setLanguageVersion(packageSpecifiedLanguageVersionMajor, packageSpecifiedLanguageVersionMinor, explicit: false); } if (uri.scheme == "dart" && uri.path == "core") { coreLibrary = library; } if (library.loader != this) { if (coreLibrary == library) { target.loadExtraRequiredLibraries(this); } // This library isn't owned by this loader, so not further processing // should be attempted. return library; } { // Add any additional logic after this block. Setting the // firstSourceUri and first library should be done as early as // possible. firstSourceUri ??= uri; first ??= library; } if (coreLibrary == library) { target.loadExtraRequiredLibraries(this); } if (target.backendTarget.mayDefineRestrictedType(origin?.uri ?? uri)) { library.mayImplementRestrictedTypes = true; } if (uri.scheme == "dart") { target.readPatchFiles(library); } unparsedLibraries.addLast(library); return library; }); if (accessor == null) { if (builder.loader == this && first != builder && isSourceLoader) { unhandled("null", "accessor", charOffset, uri); } } else { builder.recordAccess(charOffset, noLength, accessor.fileUri); if (!accessor.isPatch && !accessor.isPart && !target.backendTarget .allowPlatformPrivateLibraryAccess(accessor.uri, uri)) { accessor.addProblem(messagePlatformPrivateLibraryAccess, charOffset, noLength, accessor.fileUri); } } return builder; } void ensureCoreLibrary() { if (coreLibrary == null) { read(Uri.parse("dart:core"), 0, accessor: first); // TODO(askesc): When all backends support set literals, we no longer // need to index dart:collection, as it is only needed for desugaring of // const sets. We can remove it from this list at that time. read(Uri.parse("dart:collection"), 0, accessor: first); assert(coreLibrary != null); } } Future<Null> buildBodies() async { assert(coreLibrary != null); for (LibraryBuilder library in builders.values) { if (library.loader == this) { currentUriForCrashReporting = library.uri; await buildBody(library); } } currentUriForCrashReporting = null; logSummary(templateSourceBodySummary); } Future<Null> buildOutlines() async { ensureCoreLibrary(); while (unparsedLibraries.isNotEmpty) { LibraryBuilder library = unparsedLibraries.removeFirst(); currentUriForCrashReporting = library.uri; await buildOutline(library); } currentUriForCrashReporting = null; logSummary(outlineSummaryTemplate); } void logSummary(Template<SummaryTemplate> template) { ticker.log((Duration elapsed, Duration sinceStart) { int libraryCount = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) libraryCount++; }); double ms = elapsed.inMicroseconds / Duration.microsecondsPerMillisecond; Message message = template.withArguments( libraryCount, byteCount, ms, byteCount / ms, ms / libraryCount); print("$sinceStart: ${message.message}"); }); } Future<Null> buildOutline(covariant LibraryBuilder library); /// Builds all the method bodies found in the given [library]. Future<Null> buildBody(covariant LibraryBuilder library); /// Register [message] as a problem with a severity determined by the /// intrinsic severity of the message. FormattedMessage addProblem( Message message, int charOffset, int length, Uri fileUri, {bool wasHandled: false, List<LocatedMessage> context, Severity severity, bool problemOnLibrary: false}) { return addMessage(message, charOffset, length, fileUri, severity, wasHandled: wasHandled, context: context, problemOnLibrary: problemOnLibrary); } /// All messages reported by the compiler (errors, warnings, etc.) are routed /// through this method. /// /// Returns a FormattedMessage if the message is new, that is, not previously /// reported. This is important as some parser errors may be reported up to /// three times by `OutlineBuilder`, `DietListener`, and `BodyBuilder`. /// If the message is not new, [null] is reported. /// /// If [severity] is `Severity.error`, the message is added to /// [handledErrors] if [wasHandled] is true or to [unhandledErrors] if /// [wasHandled] is false. FormattedMessage addMessage(Message message, int charOffset, int length, Uri fileUri, Severity severity, {bool wasHandled: false, List<LocatedMessage> context, bool problemOnLibrary: false}) { severity = target.fixSeverity(severity, message, fileUri); if (severity == Severity.ignored) return null; String trace = """ message: ${message.message} charOffset: $charOffset fileUri: $fileUri severity: $severity """; // TODO(askesc): Swap message and context around for interface checks // and mixin overrides to make comparing context here unnecessary. if (context != null) { for (LocatedMessage contextMessage in context) { trace += """ message: ${contextMessage.message} charOffset: ${contextMessage.charOffset} fileUri: ${contextMessage.uri} """; } } if (!seenMessages.add(trace)) return null; if (message.code.severity == Severity.context) { internalProblem( templateInternalProblemContextSeverity .withArguments(message.code.name), charOffset, fileUri); } target.context.report( message.withLocation(fileUri, charOffset, length), severity, context: context); if (severity == Severity.error) { (wasHandled ? handledErrors : unhandledErrors) .add(message.withLocation(fileUri, charOffset, length)); } FormattedMessage formattedMessage = target.createFormattedMessage( message, charOffset, length, fileUri, context, severity); if (!problemOnLibrary) { allComponentProblems.add(formattedMessage); } return formattedMessage; } Builder getAbstractClassInstantiationError() { return target.getAbstractClassInstantiationError(this); } Builder getCompileTimeError() => target.getCompileTimeError(this); Builder getDuplicatedFieldInitializerError() { return target.getDuplicatedFieldInitializerError(this); } Builder getNativeAnnotation() => target.getNativeAnnotation(this); ClassBuilder computeClassBuilderFromTargetClass(Class cls); TypeBuilder computeTypeBuilder(DartType type); BodyBuilder createBodyBuilderForOutlineExpression( LibraryBuilder library, DeclarationBuilder declarationBuilder, ModifierBuilder member, Scope scope, Uri fileUri) { return new BodyBuilder.forOutlineExpression( library, declarationBuilder, member, scope, fileUri); } }
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/fasta/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.target; import 'dart:async' show Future; import 'package:kernel/ast.dart' show Component; import 'ticker.dart' show Ticker; /// A compilation target. /// /// A target reads source files with [read], builds outlines when /// [buildOutlines] is called and builds the full component when /// [buildComponent] is called. abstract class Target { final Ticker ticker; Target(this.ticker); /// Build and return outlines for all libraries. Future<Component> buildOutlines(); /// Build and return the full component for all libraries. Future<Component> buildComponent(); }
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/fasta/names.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 front_end.src.fasta.names; import 'package:kernel/ast.dart' show Name; final Name ampersandName = new Name("&"); final Name barName = new Name("|"); final Name callName = new Name("call"); final Name caretName = new Name("^"); final Name divisionName = new Name("/"); final Name doubleAmpersandName = new Name("&&"); final Name doubleBarName = new Name("||"); final Name doubleQuestionName = new Name("??"); final Name emptyName = new Name(""); final Name equalsName = new Name('=='); final Name greaterThanName = new Name(">"); final Name greaterThanOrEqualsName = new Name(">="); final Name identicalName = new Name("identical"); final Name indexGetName = new Name("[]"); final Name indexSetName = new Name("[]="); final Name leftShiftName = new Name("<<"); final Name lengthName = new Name("length"); final Name lessThanName = new Name("<"); final Name lessThanOrEqualsName = new Name("<="); final Name minusName = new Name("-"); final Name multiplyName = new Name("*"); final Name mustacheName = new Name("~/"); final Name negationName = new Name("!"); final Name noSuchMethodName = new Name("noSuchMethod"); final Name percentName = new Name("%"); final Name plusName = new Name("+"); final Name rightShiftName = new Name(">>"); final Name tripleShiftName = new Name(">>>"); final Name tildeName = new Name("~"); final Name unaryMinusName = new Name("unary-");
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/fasta/configuration.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.configuration; class Configuration { final int charOffset; final String dottedName; final String condition; final String importUri; Configuration( this.charOffset, this.dottedName, this.condition, this.importUri); }
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/fasta/resolve_input_uri.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. /// Detect if we're on Windows without importing `dart:io`. bool isWindows = new Uri.directory("C:\\").path == new Uri.directory("C:\\", windows: true).path; Uri resolveInputUri(String path) { Uri uri; if (path.indexOf(":") == -1) { uri = new Uri.file(path, windows: isWindows); } else if (!isWindows) { uri = parseUri(path); } else { uri = resolveAmbiguousWindowsPath(path); } return Uri.base.resolveUri(uri); } Uri parseUri(String path) { if (path.startsWith("file:")) { if (Uri.base.scheme == "file") { // The Uri class doesn't handle relative file URIs correctly, the // following works around that issue. return new Uri(path: Uri.parse("x-$path").path); } } return Uri.parse(path); } Uri resolveAmbiguousWindowsPath(String path) { try { return new Uri.file(path, windows: isWindows); } on ArgumentError catch (_) { return parseUri(path); } }
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/fasta/colors.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. // TODO(ahe): Originally copied from sdk/pkg/compiler/lib/src/colors.dart, // merge these two packages. library colors; import 'dart:convert' show jsonEncode; import 'dart:io' show Platform, Process, ProcessResult, stderr, stdout; import 'compiler_context.dart' show CompilerContext; /// ANSI/xterm termcap for setting default colors. Output from Unix /// command-line program `tput op`. const String DEFAULT_COLOR = "\x1b[39;49m"; /// ANSI/xterm termcap for setting black text color. Output from Unix /// command-line program `tput setaf 0`. const String BLACK_COLOR = "\x1b[30m"; /// ANSI/xterm termcap for setting red text color. Output from Unix /// command-line program `tput setaf 1`. const String RED_COLOR = "\x1b[31m"; /// ANSI/xterm termcap for setting green text color. Output from Unix /// command-line program `tput setaf 2`. const String GREEN_COLOR = "\x1b[32m"; /// ANSI/xterm termcap for setting yellow text color. Output from Unix /// command-line program `tput setaf 3`. const String YELLOW_COLOR = "\x1b[33m"; /// ANSI/xterm termcap for setting blue text color. Output from Unix /// command-line program `tput setaf 4`. const String BLUE_COLOR = "\x1b[34m"; /// ANSI/xterm termcap for setting magenta text color. Output from Unix /// command-line program `tput setaf 5`. const String MAGENTA_COLOR = "\x1b[35m"; /// ANSI/xterm termcap for setting cyan text color. Output from Unix /// command-line program `tput setaf 6`. const String CYAN_COLOR = "\x1b[36m"; /// ANSI/xterm termcap for setting white text color. Output from Unix /// command-line program `tput setaf 7`. const String WHITE_COLOR = "\x1b[37m"; /// All the above codes. This is used to compare the above codes to the /// terminal's. Printing this string should have the same effect as just /// printing [DEFAULT_COLOR]. const String ALL_CODES = BLACK_COLOR + RED_COLOR + GREEN_COLOR + YELLOW_COLOR + BLUE_COLOR + MAGENTA_COLOR + CYAN_COLOR + WHITE_COLOR + DEFAULT_COLOR; const String TERMINAL_CAPABILITIES = """ colors setaf 0 setaf 1 setaf 2 setaf 3 setaf 4 setaf 5 setaf 6 setaf 7 op """; String wrap(String string, String color) { return CompilerContext.enableColors ? "${color}$string${DEFAULT_COLOR}" : string; } String black(String string) => wrap(string, BLACK_COLOR); String red(String string) => wrap(string, RED_COLOR); String green(String string) => wrap(string, GREEN_COLOR); String yellow(String string) => wrap(string, YELLOW_COLOR); String blue(String string) => wrap(string, BLUE_COLOR); String magenta(String string) => wrap(string, MAGENTA_COLOR); String cyan(String string) => wrap(string, CYAN_COLOR); String white(String string) => wrap(string, WHITE_COLOR); /// Returns whether [sink] supports ANSI escapes or `null` if it could not be /// determined. bool _supportsAnsiEscapes(sink) { try { // ignore: undefined_getter return sink.supportsAnsiEscapes; } on NoSuchMethodError { // Ignored: We're running on an older version of the Dart VM which doesn't // implement `supportsAnsiEscapes`. return null; } } /// True if we should enable colors in output. /// /// We enable colors when both `stdout` and `stderr` support ANSI escapes. /// /// On non-Windows platforms, this functions checks the terminal capabilities, /// on Windows we only enable colors if the VM getters are present and returned /// `true`. /// /// Note: do not call this method directly, as it is expensive to /// compute. Instead, use [CompilerContext.enableColors]. bool computeEnableColors(CompilerContext context) { // TODO(ahe): Remove this method. bool stderrSupportsColors = _supportsAnsiEscapes(stdout); bool stdoutSupportsColors = _supportsAnsiEscapes(stderr); if (stdoutSupportsColors == false) { if (context.options.verbose) { print("Not enabling colors, stdout does not support ANSI colors."); } return false; } if (stderrSupportsColors == false) { if (context.options.verbose) { print("Not enabling colors, stderr does not support ANSI colors."); } return false; } if (Platform.isWindows) { if (stderrSupportsColors != true || stdoutSupportsColors != true) { // 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 (context.options.verbose) { print("Not enabling colors as ANSI is not supported."); } return false; } if (context.options.verbose) { 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")`. // The `-S` option of `tput` allows us to query multiple capabilities at // once. ProcessResult result = Process.runSync( "/bin/sh", ["-c", "printf '%s' '$TERMINAL_CAPABILITIES' | tput -S"]); if (result.exitCode != 0) { if (context.options.verbose) { print("Not enabling colors, running tput failed."); } return false; } List<String> lines = result.stdout.split("\n"); if (lines.length != 2) { if (context.options.verbose) { print("Not enabling colors, unexpected output from tput: " "${jsonEncode(result.stdout)}."); } return false; } String numberOfColors = lines[0]; if ((int.tryParse(numberOfColors) ?? -1) < 8) { if (context.options.verbose) { print("Not enabling colors, less than 8 colors supported: " "${jsonEncode(numberOfColors)}."); } return false; } String allCodes = lines[1].trim(); if (ALL_CODES != allCodes) { if (context.options.verbose) { print("Not enabling colors, color codes don't match: " "${jsonEncode(ALL_CODES)} != ${jsonEncode(allCodes)}."); } return false; } if (context.options.verbose) { 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/fasta/import.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.import; import 'package:kernel/ast.dart' show LibraryDependency; import 'builder/builder.dart' show Builder, LibraryBuilder; import 'builder/prefix_builder.dart' show PrefixBuilder; import 'kernel/kernel_builder.dart' show toKernelCombinators; import 'combinator.dart' show Combinator; import 'configuration.dart' show Configuration; class Import { /// The library that is importing [imported]; final LibraryBuilder importer; /// The library being imported. final LibraryBuilder imported; final PrefixBuilder prefixBuilder; final bool deferred; final String prefix; final List<Combinator> combinators; final List<Configuration> configurations; final int charOffset; final int prefixCharOffset; // The LibraryBuilder for the imported library ('imported') may be null when // this field is set. final String nativeImportPath; Import( this.importer, this.imported, this.deferred, this.prefix, this.combinators, this.configurations, this.charOffset, this.prefixCharOffset, int importIndex, {this.nativeImportPath}) : prefixBuilder = createPrefixBuilder(prefix, importer, imported, combinators, deferred, charOffset, prefixCharOffset, importIndex); Uri get fileUri => importer.fileUri; void finalizeImports(LibraryBuilder importer) { if (nativeImportPath != null) return; void Function(String, Builder) add; if (prefixBuilder == null) { add = (String name, Builder member) { importer.addToScope(name, member, charOffset, true); }; } else { add = (String name, Builder member) { prefixBuilder.addToExportScope(name, member, charOffset); }; } imported.exportScope.forEach((String name, Builder member) { if (combinators != null) { for (Combinator combinator in combinators) { if (combinator.isShow && !combinator.names.contains(name)) return; if (combinator.isHide && combinator.names.contains(name)) return; } } add(name, member); }); if (prefixBuilder != null) { Builder existing = importer.addBuilder(prefix, prefixBuilder, prefixCharOffset); if (existing == prefixBuilder) { importer.addToScope(prefix, prefixBuilder, prefixCharOffset, true); } } } } PrefixBuilder createPrefixBuilder( String prefix, LibraryBuilder importer, LibraryBuilder imported, List<Combinator> combinators, bool deferred, int charOffset, int prefixCharOffset, int importIndex) { if (prefix == null) return null; LibraryDependency dependency = null; if (deferred) { dependency = new LibraryDependency.deferredImport(imported.library, prefix, combinators: toKernelCombinators(combinators)) ..fileOffset = charOffset; } return new PrefixBuilder( prefix, deferred, importer, dependency, prefixCharOffset, importIndex); }
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/fasta/rewrite_severity.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'severity.dart' show Severity; import 'messages.dart' as msg; Severity rewriteSeverity( Severity severity, msg.Code<Object> code, Uri fileUri) { if (severity != Severity.ignored) { return severity; } String path = fileUri.path; String fastaPath = "/pkg/front_end/lib/src/fasta/"; int index = path.indexOf(fastaPath); if (index == -1) { fastaPath = "/pkg/front_end/tool/_fasta/"; index = path.indexOf(fastaPath); if (index == -1) return severity; } if (code == msg.codeUseOfDeprecatedIdentifier) { // TODO(ahe): Remove the exceptions below. // We plan to remove all uses of deprecated identifiers from Fasta. The // strategy is to remove files from the list below one by one. To get // started on cleaning up a given file, simply remove it from the list // below and compile Fasta with itself to get a list of remaining call // sites. switch (path.substring(fastaPath.length + index)) { case "command_line.dart": case "kernel/body_builder.dart": return severity; } } return Severity.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/fasta/combinator.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.combinator; class Combinator { final bool isShow; final Set<String> names; Combinator(this.isShow, this.names, int charOffset, Uri fileUri); Combinator.show(Iterable<String> names, int charOffset, Uri fileUri) : this(true, new Set<String>.from(names), charOffset, fileUri); Combinator.hide(Iterable<String> names, int charOffset, Uri fileUri) : this(false, new Set<String>.from(names), charOffset, fileUri); bool get isHide => !isShow; }
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/fasta/fasta_codes_generated.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 'pkg/front_end/messages.yaml' and run // 'pkg/front_end/tool/fasta generate-messages' to update. // ignore_for_file: lines_longer_than_80_chars part of fasta.codes; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateAbstractClassInstantiation = const Template<Message Function(String name)>( messageTemplate: r"""The class '#name' is abstract and can't be instantiated.""", withArguments: _withArgumentsAbstractClassInstantiation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeAbstractClassInstantiation = const Code<Message Function(String name)>( "AbstractClassInstantiation", templateAbstractClassInstantiation, analyzerCodes: <String>["NEW_WITH_ABSTRACT_CLASS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsAbstractClassInstantiation(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeAbstractClassInstantiation, message: """The class '${name}' is abstract and can't be instantiated.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAbstractClassMember = messageAbstractClassMember; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAbstractClassMember = const MessageCode( "AbstractClassMember", index: 51, message: r"""Members of classes can't be declared to be 'abstract'.""", tip: r"""Try removing the 'abstract' keyword. You can add the 'abstract' keyword before the class declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAbstractNotSync = messageAbstractNotSync; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAbstractNotSync = const MessageCode("AbstractNotSync", analyzerCodes: <String>["NON_SYNC_ABSTRACT_METHOD"], message: r"""Abstract methods can't use 'async', 'async*', or 'sync*'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateAbstractRedirectedClassInstantiation = const Template< Message Function(String name)>( messageTemplate: r"""Factory redirects to class '#name', which is abstract and can't be instantiated.""", withArguments: _withArgumentsAbstractRedirectedClassInstantiation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeAbstractRedirectedClassInstantiation = const Code<Message Function(String name)>( "AbstractRedirectedClassInstantiation", templateAbstractRedirectedClassInstantiation, analyzerCodes: <String>["FACTORY_REDIRECTS_TO_ABSTRACT_CLASS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsAbstractRedirectedClassInstantiation(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeAbstractRedirectedClassInstantiation, message: """Factory redirects to class '${name}', which is abstract and can't be instantiated.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateAccessError = const Template<Message Function(String name)>( messageTemplate: r"""Access error: '#name'.""", withArguments: _withArgumentsAccessError); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeAccessError = const Code<Message Function(String name)>( "AccessError", templateAccessError, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsAccessError(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeAccessError, message: """Access error: '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, DartType _type, DartType _type2)> templateAmbiguousSupertypes = const Template< Message Function(String name, DartType _type, DartType _type2)>( messageTemplate: r"""'#name' can't implement both '#type' and '#type2'""", withArguments: _withArgumentsAmbiguousSupertypes); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, DartType _type, DartType _type2)> codeAmbiguousSupertypes = const Code<Message Function(String name, DartType _type, DartType _type2)>( "AmbiguousSupertypes", templateAmbiguousSupertypes, analyzerCodes: <String>["AMBIGUOUS_SUPERTYPES"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsAmbiguousSupertypes( String name, DartType _type, DartType _type2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeAmbiguousSupertypes, message: """'${name}' can't implement both '${type}' and '${type2}'""" + labeler.originMessages, arguments: {'name': name, 'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAnonymousBreakTargetOutsideFunction = messageAnonymousBreakTargetOutsideFunction; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAnonymousBreakTargetOutsideFunction = const MessageCode("AnonymousBreakTargetOutsideFunction", analyzerCodes: <String>["LABEL_IN_OUTER_SCOPE"], message: r"""Can't break to a target in a different function."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAnonymousContinueTargetOutsideFunction = messageAnonymousContinueTargetOutsideFunction; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAnonymousContinueTargetOutsideFunction = const MessageCode("AnonymousContinueTargetOutsideFunction", analyzerCodes: <String>["LABEL_IN_OUTER_SCOPE"], message: r"""Can't continue at a target in a different function."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateArgumentTypeNotAssignable = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The argument type '#type' can't be assigned to the parameter type '#type2'.""", withArguments: _withArgumentsArgumentTypeNotAssignable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeArgumentTypeNotAssignable = const Code<Message Function(DartType _type, DartType _type2)>( "ArgumentTypeNotAssignable", templateArgumentTypeNotAssignable, analyzerCodes: <String>["ARGUMENT_TYPE_NOT_ASSIGNABLE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsArgumentTypeNotAssignable( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeArgumentTypeNotAssignable, message: """The argument type '${type}' can't be assigned to the parameter type '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int codePoint)> templateAsciiControlCharacter = const Template< Message Function(int codePoint)>( messageTemplate: r"""The control character #unicode can only be used in strings and comments.""", withArguments: _withArgumentsAsciiControlCharacter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(int codePoint)> codeAsciiControlCharacter = const Code<Message Function(int codePoint)>( "AsciiControlCharacter", templateAsciiControlCharacter, analyzerCodes: <String>["ILLEGAL_CHARACTER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsAsciiControlCharacter(int codePoint) { String unicode = "U+${codePoint.toRadixString(16).toUpperCase().padLeft(4, '0')}"; return new Message(codeAsciiControlCharacter, message: """The control character ${unicode} can only be used in strings and comments.""", arguments: {'codePoint': codePoint}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAssertAsExpression = messageAssertAsExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAssertAsExpression = const MessageCode( "AssertAsExpression", message: r"""`assert` can't be used as an expression."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAssertExtraneousArgument = messageAssertExtraneousArgument; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAssertExtraneousArgument = const MessageCode( "AssertExtraneousArgument", message: r"""`assert` can't have more than two arguments."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAwaitAsIdentifier = messageAwaitAsIdentifier; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAwaitAsIdentifier = const MessageCode( "AwaitAsIdentifier", analyzerCodes: <String>["ASYNC_KEYWORD_USED_AS_IDENTIFIER"], message: r"""'await' can't be used as an identifier in 'async', 'async*', or 'sync*' methods."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAwaitForNotAsync = messageAwaitForNotAsync; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAwaitForNotAsync = const MessageCode( "AwaitForNotAsync", analyzerCodes: <String>["ASYNC_FOR_IN_WRONG_CONTEXT"], message: r"""The asynchronous for-in can only be used in functions marked with 'async' or 'async*'.""", tip: r"""Try marking the function body with either 'async' or 'async*', or removing the 'await' before the for loop."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeAwaitNotAsync = messageAwaitNotAsync; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageAwaitNotAsync = const MessageCode("AwaitNotAsync", analyzerCodes: <String>["AWAIT_IN_WRONG_CONTEXT"], message: r"""'await' can only be used in 'async' or 'async*' methods."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, String name2)> templateBadTypeVariableInSupertype = const Template<Message Function(String name, String name2)>( messageTemplate: r"""Found unsupported uses of '#name' in supertype '#name2'.""", withArguments: _withArgumentsBadTypeVariableInSupertype); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeBadTypeVariableInSupertype = const Code<Message Function(String name, String name2)>( "BadTypeVariableInSupertype", templateBadTypeVariableInSupertype, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsBadTypeVariableInSupertype(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeBadTypeVariableInSupertype, message: """Found unsupported uses of '${name}' in supertype '${name2}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateBoundIssueViaCycleNonSimplicity = const Template< Message Function(String name, String name2)>( messageTemplate: r"""Generic type '#name' can't be used without type arguments in the bounds of its own type variables. It is referenced indirectly through '#name2'.""", tipTemplate: r"""Try providing type arguments to '#name2' here or to some other raw types in the bounds along the reference chain.""", withArguments: _withArgumentsBoundIssueViaCycleNonSimplicity); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeBoundIssueViaCycleNonSimplicity = const Code<Message Function(String name, String name2)>( "BoundIssueViaCycleNonSimplicity", templateBoundIssueViaCycleNonSimplicity, analyzerCodes: <String>["NOT_INSTANTIATED_BOUND"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsBoundIssueViaCycleNonSimplicity( String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeBoundIssueViaCycleNonSimplicity, message: """Generic type '${name}' can't be used without type arguments in the bounds of its own type variables. It is referenced indirectly through '${name2}'.""", tip: """Try providing type arguments to '${name2}' here or to some other raw types in the bounds along the reference chain.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateBoundIssueViaLoopNonSimplicity = const Template< Message Function(String name)>( messageTemplate: r"""Generic type '#name' can't be used without type arguments in the bounds of its own type variables.""", tipTemplate: r"""Try providing type arguments to '#name' here.""", withArguments: _withArgumentsBoundIssueViaLoopNonSimplicity); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeBoundIssueViaLoopNonSimplicity = const Code<Message Function(String name)>("BoundIssueViaLoopNonSimplicity", templateBoundIssueViaLoopNonSimplicity, analyzerCodes: <String>["NOT_INSTANTIATED_BOUND"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsBoundIssueViaLoopNonSimplicity(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeBoundIssueViaLoopNonSimplicity, message: """Generic type '${name}' can't be used without type arguments in the bounds of its own type variables.""", tip: """Try providing type arguments to '${name}' here.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateBoundIssueViaRawTypeWithNonSimpleBounds = const Template<Message Function(String name)>( messageTemplate: r"""Generic type '#name' can't be used without type arguments in a type variable bound.""", tipTemplate: r"""Try providing type arguments to '#name' here.""", withArguments: _withArgumentsBoundIssueViaRawTypeWithNonSimpleBounds); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeBoundIssueViaRawTypeWithNonSimpleBounds = const Code<Message Function(String name)>( "BoundIssueViaRawTypeWithNonSimpleBounds", templateBoundIssueViaRawTypeWithNonSimpleBounds, analyzerCodes: <String>["NOT_INSTANTIATED_BOUND"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsBoundIssueViaRawTypeWithNonSimpleBounds(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeBoundIssueViaRawTypeWithNonSimpleBounds, message: """Generic type '${name}' can't be used without type arguments in a type variable bound.""", tip: """Try providing type arguments to '${name}' here.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeBreakOutsideOfLoop = messageBreakOutsideOfLoop; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageBreakOutsideOfLoop = const MessageCode( "BreakOutsideOfLoop", index: 52, message: r"""A break statement can't be used outside of a loop or switch statement.""", tip: r"""Try removing the break statement."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateBreakTargetOutsideFunction = const Template<Message Function(String name)>( messageTemplate: r"""Can't break to '#name' in a different function.""", withArguments: _withArgumentsBreakTargetOutsideFunction); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeBreakTargetOutsideFunction = const Code<Message Function(String name)>( "BreakTargetOutsideFunction", templateBreakTargetOutsideFunction, analyzerCodes: <String>["LABEL_IN_OUTER_SCOPE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsBreakTargetOutsideFunction(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeBreakTargetOutsideFunction, message: """Can't break to '${name}' in a different function.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateBuiltInIdentifierAsType = const Template<Message Function(Token token)>( messageTemplate: r"""The built-in identifier '#lexeme' can't be used as a type.""", withArguments: _withArgumentsBuiltInIdentifierAsType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeBuiltInIdentifierAsType = const Code<Message Function(Token token)>( "BuiltInIdentifierAsType", templateBuiltInIdentifierAsType, analyzerCodes: <String>["BUILT_IN_IDENTIFIER_AS_TYPE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsBuiltInIdentifierAsType(Token token) { String lexeme = token.lexeme; return new Message(codeBuiltInIdentifierAsType, message: """The built-in identifier '${lexeme}' can't be used as a type.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateBuiltInIdentifierInDeclaration = const Template<Message Function(Token token)>( messageTemplate: r"""Can't use '#lexeme' as a name here.""", withArguments: _withArgumentsBuiltInIdentifierInDeclaration); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeBuiltInIdentifierInDeclaration = const Code<Message Function(Token token)>("BuiltInIdentifierInDeclaration", templateBuiltInIdentifierInDeclaration, analyzerCodes: <String>["BUILT_IN_IDENTIFIER_IN_DECLARATION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsBuiltInIdentifierInDeclaration(Token token) { String lexeme = token.lexeme; return new Message(codeBuiltInIdentifierInDeclaration, message: """Can't use '${lexeme}' as a name here.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeBytecodeLimitExceededTooManyArguments = messageBytecodeLimitExceededTooManyArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageBytecodeLimitExceededTooManyArguments = const MessageCode("BytecodeLimitExceededTooManyArguments", message: r"""Dart bytecode limit exceeded: too many arguments."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCandidateFound = messageCandidateFound; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCandidateFound = const MessageCode("CandidateFound", severity: Severity.context, message: r"""Found this candidate, but the arguments don't match."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateCandidateFoundIsDefaultConstructor = const Template<Message Function(String name)>( messageTemplate: r"""The class '#name' has a constructor that takes no arguments.""", withArguments: _withArgumentsCandidateFoundIsDefaultConstructor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeCandidateFoundIsDefaultConstructor = const Code<Message Function(String name)>( "CandidateFoundIsDefaultConstructor", templateCandidateFoundIsDefaultConstructor, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCandidateFoundIsDefaultConstructor(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeCandidateFoundIsDefaultConstructor, message: """The class '${name}' has a constructor that takes no arguments.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCannotAssignToParenthesizedExpression = messageCannotAssignToParenthesizedExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCannotAssignToParenthesizedExpression = const MessageCode("CannotAssignToParenthesizedExpression", analyzerCodes: <String>["ASSIGNMENT_TO_PARENTHESIZED_EXPRESSION"], message: r"""Can't assign to a parenthesized expression."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCannotAssignToSuper = messageCannotAssignToSuper; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCannotAssignToSuper = const MessageCode( "CannotAssignToSuper", analyzerCodes: <String>["NOT_AN_LVALUE"], message: r"""Can't assign to super."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateCannotReadSdkSpecification = const Template<Message Function(String string)>( messageTemplate: r"""Unable to read the 'libraries.json' specification file: #string.""", withArguments: _withArgumentsCannotReadSdkSpecification); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeCannotReadSdkSpecification = const Code<Message Function(String string)>( "CannotReadSdkSpecification", templateCannotReadSdkSpecification, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCannotReadSdkSpecification(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeCannotReadSdkSpecification, message: """Unable to read the 'libraries.json' specification file: ${string}.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCantDisambiguateAmbiguousInformation = messageCantDisambiguateAmbiguousInformation; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCantDisambiguateAmbiguousInformation = const MessageCode( "CantDisambiguateAmbiguousInformation", message: r"""Both Iterable and Map spread elements encountered in ambiguous literal."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCantDisambiguateNotEnoughInformation = messageCantDisambiguateNotEnoughInformation; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCantDisambiguateNotEnoughInformation = const MessageCode( "CantDisambiguateNotEnoughInformation", message: r"""Not enough type information to disambiguate between literal set and literal map.""", tip: r"""Try providing type arguments for the literal explicitly to disambiguate it."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCantInferPackagesFromManyInputs = messageCantInferPackagesFromManyInputs; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCantInferPackagesFromManyInputs = const MessageCode( "CantInferPackagesFromManyInputs", message: r"""Can't infer a .packages file when compiling multiple inputs.""", tip: r"""Try specifying the file explicitly with the --packages option."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCantInferPackagesFromPackageUri = messageCantInferPackagesFromPackageUri; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCantInferPackagesFromPackageUri = const MessageCode( "CantInferPackagesFromPackageUri", message: r"""Can't infer a .packages file from an input 'package:*' URI.""", tip: r"""Try specifying the file explicitly with the --packages option."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateCantInferReturnTypeDueToInconsistentOverrides = const Template<Message Function(String name)>( messageTemplate: r"""Can't infer a return type for '#name' as some of the inherited members have different types.""", tipTemplate: r"""Try adding an explicit type.""", withArguments: _withArgumentsCantInferReturnTypeDueToInconsistentOverrides); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeCantInferReturnTypeDueToInconsistentOverrides = const Code<Message Function(String name)>( "CantInferReturnTypeDueToInconsistentOverrides", templateCantInferReturnTypeDueToInconsistentOverrides, analyzerCodes: <String>["INVALID_METHOD_OVERRIDE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCantInferReturnTypeDueToInconsistentOverrides( String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeCantInferReturnTypeDueToInconsistentOverrides, message: """Can't infer a return type for '${name}' as some of the inherited members have different types.""", tip: """Try adding an explicit type.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string)> templateCantInferTypeDueToCircularity = const Template< Message Function(String string)>( messageTemplate: r"""Can't infer the type of '#string': circularity found during type inference.""", tipTemplate: r"""Specify the type explicitly.""", withArguments: _withArgumentsCantInferTypeDueToCircularity); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeCantInferTypeDueToCircularity = const Code<Message Function(String string)>( "CantInferTypeDueToCircularity", templateCantInferTypeDueToCircularity, analyzerCodes: <String>["RECURSIVE_COMPILE_TIME_CONSTANT"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCantInferTypeDueToCircularity(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeCantInferTypeDueToCircularity, message: """Can't infer the type of '${string}': circularity found during type inference.""", tip: """Specify the type explicitly.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateCantInferTypeDueToInconsistentOverrides = const Template<Message Function(String name)>( messageTemplate: r"""Can't infer a type for '#name' as some of the inherited members have different types.""", tipTemplate: r"""Try adding an explicit type.""", withArguments: _withArgumentsCantInferTypeDueToInconsistentOverrides); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeCantInferTypeDueToInconsistentOverrides = const Code<Message Function(String name)>( "CantInferTypeDueToInconsistentOverrides", templateCantInferTypeDueToInconsistentOverrides, analyzerCodes: <String>["INVALID_METHOD_OVERRIDE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCantInferTypeDueToInconsistentOverrides(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeCantInferTypeDueToInconsistentOverrides, message: """Can't infer a type for '${name}' as some of the inherited members have different types.""", tip: """Try adding an explicit type.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_, String string)> templateCantReadFile = const Template<Message Function(Uri uri_, String string)>( messageTemplate: r"""Error when reading '#uri': #string""", withArguments: _withArgumentsCantReadFile); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_, String string)> codeCantReadFile = const Code<Message Function(Uri uri_, String string)>( "CantReadFile", templateCantReadFile, analyzerCodes: <String>["URI_DOES_NOT_EXIST"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCantReadFile(Uri uri_, String string) { String uri = relativizeUri(uri_); if (string.isEmpty) throw 'No string provided'; return new Message(codeCantReadFile, message: """Error when reading '${uri}': ${string}""", arguments: {'uri': uri_, 'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateCantUseControlFlowOrSpreadAsConstant = const Template<Message Function(Token token)>( messageTemplate: r"""'#lexeme' is not supported in constant expressions.""", withArguments: _withArgumentsCantUseControlFlowOrSpreadAsConstant); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeCantUseControlFlowOrSpreadAsConstant = const Code<Message Function(Token token)>( "CantUseControlFlowOrSpreadAsConstant", templateCantUseControlFlowOrSpreadAsConstant, analyzerCodes: <String>["NOT_CONSTANT_EXPRESSION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCantUseControlFlowOrSpreadAsConstant(Token token) { String lexeme = token.lexeme; return new Message(codeCantUseControlFlowOrSpreadAsConstant, message: """'${lexeme}' is not supported in constant expressions.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Token token)> templateCantUseDeferredPrefixAsConstant = const Template< Message Function(Token token)>( messageTemplate: r"""'#lexeme' can't be used in a constant expression because it's marked as 'deferred' which means it isn't available until loaded.""", tipTemplate: r"""Try moving the constant from the deferred library, or removing 'deferred' from the import. """, withArguments: _withArgumentsCantUseDeferredPrefixAsConstant); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeCantUseDeferredPrefixAsConstant = const Code<Message Function(Token token)>("CantUseDeferredPrefixAsConstant", templateCantUseDeferredPrefixAsConstant, analyzerCodes: <String>["CONST_DEFERRED_CLASS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCantUseDeferredPrefixAsConstant(Token token) { String lexeme = token.lexeme; return new Message(codeCantUseDeferredPrefixAsConstant, message: """'${lexeme}' can't be used in a constant expression because it's marked as 'deferred' which means it isn't available until loaded.""", tip: """Try moving the constant from the deferred library, or removing 'deferred' from the import. """, arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCantUsePrefixAsExpression = messageCantUsePrefixAsExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCantUsePrefixAsExpression = const MessageCode( "CantUsePrefixAsExpression", analyzerCodes: <String>["PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT"], message: r"""A prefix can't be used as an expression."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCantUsePrefixWithNullAware = messageCantUsePrefixWithNullAware; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCantUsePrefixWithNullAware = const MessageCode( "CantUsePrefixWithNullAware", analyzerCodes: <String>["PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT"], message: r"""A prefix can't be used with null-aware operators.""", tip: r"""Try replacing '?.' with '.'"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCatchSyntax = messageCatchSyntax; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCatchSyntax = const MessageCode("CatchSyntax", index: 84, message: r"""'catch' must be followed by '(identifier)' or '(identifier, identifier)'.""", tip: r"""No types are needed, the first is given by 'on', the second is always 'StackTrace'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCatchSyntaxExtraParameters = messageCatchSyntaxExtraParameters; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCatchSyntaxExtraParameters = const MessageCode( "CatchSyntaxExtraParameters", index: 83, message: r"""'catch' must be followed by '(identifier)' or '(identifier, identifier)'.""", tip: r"""No types are needed, the first is given by 'on', the second is always 'StackTrace'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeClassInClass = messageClassInClass; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageClassInClass = const MessageCode("ClassInClass", index: 53, message: r"""Classes can't be declared inside other classes.""", tip: r"""Try moving the class to the top-level."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeColonInPlaceOfIn = messageColonInPlaceOfIn; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageColonInPlaceOfIn = const MessageCode( "ColonInPlaceOfIn", index: 54, message: r"""For-in loops use 'in' rather than a colon.""", tip: r"""Try replacing the colon with the keyword 'in'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateCombinedMemberSignatureFailed = const Template< Message Function(String name, String name2)>( messageTemplate: r"""Class '#name' inherits multiple members named '#name2' with incompatible signatures.""", tipTemplate: r"""Try adding a declaration of '#name2' to '#name'.""", withArguments: _withArgumentsCombinedMemberSignatureFailed); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeCombinedMemberSignatureFailed = const Code<Message Function(String name, String name2)>( "CombinedMemberSignatureFailed", templateCombinedMemberSignatureFailed, analyzerCodes: <String>["INCONSISTENT_INHERITANCE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCombinedMemberSignatureFailed(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeCombinedMemberSignatureFailed, message: """Class '${name}' inherits multiple members named '${name2}' with incompatible signatures.""", tip: """Try adding a declaration of '${name2}' to '${name}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, String string2)> templateConflictingModifiers = const Template< Message Function(String string, String string2)>( messageTemplate: r"""Members can't be declared to be both '#string' and '#string2'.""", tipTemplate: r"""Try removing one of the keywords.""", withArguments: _withArgumentsConflictingModifiers); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeConflictingModifiers = const Code<Message Function(String string, String string2)>( "ConflictingModifiers", templateConflictingModifiers, index: 59); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictingModifiers(String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeConflictingModifiers, message: """Members can't be declared to be both '${string}' and '${string2}'.""", tip: """Try removing one of the keywords.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConflictsWithConstructor = const Template<Message Function(String name)>( messageTemplate: r"""Conflicts with constructor '#name'.""", withArguments: _withArgumentsConflictsWithConstructor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConflictsWithConstructor = const Code<Message Function(String name)>( "ConflictsWithConstructor", templateConflictsWithConstructor, analyzerCodes: <String>["CONFLICTS_WITH_CONSTRUCTOR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictsWithConstructor(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConflictsWithConstructor, message: """Conflicts with constructor '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConflictsWithFactory = const Template<Message Function(String name)>( messageTemplate: r"""Conflicts with factory '#name'.""", withArguments: _withArgumentsConflictsWithFactory); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConflictsWithFactory = const Code<Message Function(String name)>( "ConflictsWithFactory", templateConflictsWithFactory, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictsWithFactory(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConflictsWithFactory, message: """Conflicts with factory '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConflictsWithMember = const Template<Message Function(String name)>( messageTemplate: r"""Conflicts with member '#name'.""", withArguments: _withArgumentsConflictsWithMember); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConflictsWithMember = const Code<Message Function(String name)>( "ConflictsWithMember", templateConflictsWithMember, analyzerCodes: <String>["CONFLICTS_WITH_MEMBER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictsWithMember(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConflictsWithMember, message: """Conflicts with member '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConflictsWithMemberWarning = const Template<Message Function(String name)>( messageTemplate: r"""Conflicts with member '#name'.""", withArguments: _withArgumentsConflictsWithMemberWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConflictsWithMemberWarning = const Code<Message Function(String name)>( "ConflictsWithMemberWarning", templateConflictsWithMemberWarning, analyzerCodes: <String>["CONFLICTS_WITH_MEMBER"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictsWithMemberWarning(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConflictsWithMemberWarning, message: """Conflicts with member '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConflictsWithSetter = const Template<Message Function(String name)>( messageTemplate: r"""Conflicts with setter '#name'.""", withArguments: _withArgumentsConflictsWithSetter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConflictsWithSetter = const Code<Message Function(String name)>( "ConflictsWithSetter", templateConflictsWithSetter, analyzerCodes: <String>["CONFLICTS_WITH_MEMBER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictsWithSetter(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConflictsWithSetter, message: """Conflicts with setter '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConflictsWithSetterWarning = const Template<Message Function(String name)>( messageTemplate: r"""Conflicts with setter '#name'.""", withArguments: _withArgumentsConflictsWithSetterWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConflictsWithSetterWarning = const Code<Message Function(String name)>( "ConflictsWithSetterWarning", templateConflictsWithSetterWarning, analyzerCodes: <String>["CONFLICTS_WITH_MEMBER"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictsWithSetterWarning(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConflictsWithSetterWarning, message: """Conflicts with setter '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConflictsWithTypeVariable = const Template<Message Function(String name)>( messageTemplate: r"""Conflicts with type variable '#name'.""", withArguments: _withArgumentsConflictsWithTypeVariable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConflictsWithTypeVariable = const Code<Message Function(String name)>( "ConflictsWithTypeVariable", templateConflictsWithTypeVariable, analyzerCodes: <String>["CONFLICTING_TYPE_VARIABLE_AND_MEMBER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConflictsWithTypeVariable(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConflictsWithTypeVariable, message: """Conflicts with type variable '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConflictsWithTypeVariableCause = messageConflictsWithTypeVariableCause; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConflictsWithTypeVariableCause = const MessageCode( "ConflictsWithTypeVariableCause", severity: Severity.context, message: r"""This is the type variable."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstAndFinal = messageConstAndFinal; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstAndFinal = const MessageCode("ConstAndFinal", index: 58, message: r"""Members can't be declared to be both 'const' and 'final'.""", tip: r"""Try removing either the 'const' or 'final' keyword."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstClass = messageConstClass; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstClass = const MessageCode("ConstClass", index: 60, message: r"""Classes can't be declared to be 'const'.""", tip: r"""Try removing the 'const' keyword. If you're trying to indicate that instances of the class can be constants, place the 'const' keyword on the class' constructor(s)."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstConstructorNonFinalField = messageConstConstructorNonFinalField; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstConstructorNonFinalField = const MessageCode( "ConstConstructorNonFinalField", analyzerCodes: <String>["CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD"], message: r"""Constructor is marked 'const' so all fields must be final."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstConstructorNonFinalFieldCause = messageConstConstructorNonFinalFieldCause; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstConstructorNonFinalFieldCause = const MessageCode( "ConstConstructorNonFinalFieldCause", severity: Severity.context, message: r"""Field isn't final, but constructor is 'const'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstConstructorRedirectionToNonConst = messageConstConstructorRedirectionToNonConst; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstConstructorRedirectionToNonConst = const MessageCode("ConstConstructorRedirectionToNonConst", message: r"""A constant constructor can't call a non-constant constructor."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstConstructorWithBody = messageConstConstructorWithBody; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstConstructorWithBody = const MessageCode( "ConstConstructorWithBody", analyzerCodes: <String>["CONST_CONSTRUCTOR_WITH_BODY"], message: r"""A const constructor can't have a body.""", tip: r"""Try removing either the 'const' keyword or the body."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstConstructorWithNonConstSuper = messageConstConstructorWithNonConstSuper; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstConstructorWithNonConstSuper = const MessageCode( "ConstConstructorWithNonConstSuper", analyzerCodes: <String>["CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER"], message: r"""Constant constructor can't call non-constant super constructors."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalCircularity = messageConstEvalCircularity; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalCircularity = const MessageCode( "ConstEvalCircularity", analyzerCodes: <String>["RECURSIVE_COMPILE_TIME_CONSTANT"], message: r"""Constant expression depends on itself."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalContext = messageConstEvalContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalContext = const MessageCode("ConstEvalContext", message: r"""While analyzing:"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateConstEvalDeferredLibrary = const Template< Message Function(String name)>( messageTemplate: r"""'#name' can't be used in a constant expression because it's marked as 'deferred' which means it isn't available until loaded.""", tipTemplate: r"""Try moving the constant from the deferred library, or removing 'deferred' from the import. """, withArguments: _withArgumentsConstEvalDeferredLibrary); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConstEvalDeferredLibrary = const Code<Message Function(String name)>( "ConstEvalDeferredLibrary", templateConstEvalDeferredLibrary, analyzerCodes: <String>[ "NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY" ]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalDeferredLibrary(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConstEvalDeferredLibrary, message: """'${name}' can't be used in a constant expression because it's marked as 'deferred' which means it isn't available until loaded.""", tip: """Try moving the constant from the deferred library, or removing 'deferred' from the import. """, arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Constant _constant)> templateConstEvalDuplicateElement = const Template< Message Function(Constant _constant)>( messageTemplate: r"""The element '#constant' conflicts with another existing element in the set.""", withArguments: _withArgumentsConstEvalDuplicateElement); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Constant _constant)> codeConstEvalDuplicateElement = const Code<Message Function(Constant _constant)>( "ConstEvalDuplicateElement", templateConstEvalDuplicateElement, analyzerCodes: <String>["EQUAL_ELEMENTS_IN_CONST_SET"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalDuplicateElement(Constant _constant) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalDuplicateElement, message: """The element '${constant}' conflicts with another existing element in the set.""" + labeler.originMessages, arguments: {'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Constant _constant)> templateConstEvalDuplicateKey = const Template< Message Function(Constant _constant)>( messageTemplate: r"""The key '#constant' conflicts with another existing key in the map.""", withArguments: _withArgumentsConstEvalDuplicateKey); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Constant _constant)> codeConstEvalDuplicateKey = const Code<Message Function(Constant _constant)>( "ConstEvalDuplicateKey", templateConstEvalDuplicateKey, analyzerCodes: <String>["EQUAL_KEYS_IN_CONST_MAP"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalDuplicateKey(Constant _constant) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalDuplicateKey, message: """The key '${constant}' conflicts with another existing key in the map.""" + labeler.originMessages, arguments: {'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Constant _constant)> templateConstEvalElementImplementsEqual = const Template< Message Function(Constant _constant)>( messageTemplate: r"""The element '#constant' does not have a primitive operator '=='.""", withArguments: _withArgumentsConstEvalElementImplementsEqual); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Constant _constant)> codeConstEvalElementImplementsEqual = const Code<Message Function(Constant _constant)>( "ConstEvalElementImplementsEqual", templateConstEvalElementImplementsEqual, analyzerCodes: <String>["CONST_SET_ELEMENT_TYPE_IMPLEMENTS_EQUALS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalElementImplementsEqual(Constant _constant) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalElementImplementsEqual, message: """The element '${constant}' does not have a primitive operator '=='.""" + labeler.originMessages, arguments: {'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalFailedAssertion = messageConstEvalFailedAssertion; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalFailedAssertion = const MessageCode( "ConstEvalFailedAssertion", analyzerCodes: <String>["CONST_EVAL_THROWS_EXCEPTION"], message: r"""This assertion failed."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateConstEvalFailedAssertionWithMessage = const Template<Message Function(String string)>( messageTemplate: r"""This assertion failed with message: #string""", withArguments: _withArgumentsConstEvalFailedAssertionWithMessage); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeConstEvalFailedAssertionWithMessage = const Code<Message Function(String string)>( "ConstEvalFailedAssertionWithMessage", templateConstEvalFailedAssertionWithMessage, analyzerCodes: <String>["CONST_EVAL_THROWS_EXCEPTION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalFailedAssertionWithMessage(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeConstEvalFailedAssertionWithMessage, message: """This assertion failed with message: ${string}""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type)> templateConstEvalFreeTypeParameter = const Template< Message Function(DartType _type)>( messageTemplate: r"""The type '#type' is not a constant because it depends on a type parameter, only instantiated types are allowed.""", withArguments: _withArgumentsConstEvalFreeTypeParameter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeConstEvalFreeTypeParameter = const Code<Message Function(DartType _type)>( "ConstEvalFreeTypeParameter", templateConstEvalFreeTypeParameter, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalFreeTypeParameter(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeConstEvalFreeTypeParameter, message: """The type '${type}' is not a constant because it depends on a type parameter, only instantiated types are allowed.""" + labeler.originMessages, arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, Constant _constant, DartType _type, DartType _type2)> templateConstEvalInvalidBinaryOperandType = const Template< Message Function(String string, Constant _constant, DartType _type, DartType _type2)>( messageTemplate: r"""Binary operator '#string' on '#constant' requires operand of type '#type', but was of type '#type2'.""", withArguments: _withArgumentsConstEvalInvalidBinaryOperandType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(String string, Constant _constant, DartType _type, DartType _type2)> codeConstEvalInvalidBinaryOperandType = const Code< Message Function( String string, Constant _constant, DartType _type, DartType _type2)>( "ConstEvalInvalidBinaryOperandType", templateConstEvalInvalidBinaryOperandType, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidBinaryOperandType( String string, Constant _constant, DartType _type, DartType _type2) { if (string.isEmpty) throw 'No string provided'; TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String constant = constantParts.join(); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeConstEvalInvalidBinaryOperandType, message: """Binary operator '${string}' on '${constant}' requires operand of type '${type}', but was of type '${type2}'.""" + labeler.originMessages, arguments: { 'string': string, 'constant': _constant, 'type': _type, 'type2': _type2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Constant _constant, DartType _type)> templateConstEvalInvalidEqualsOperandType = const Template< Message Function(Constant _constant, DartType _type)>( messageTemplate: r"""Binary operator '==' requires receiver constant '#constant' of type 'Null', 'bool', 'int', 'double', or 'String', but was of type '#type'.""", withArguments: _withArgumentsConstEvalInvalidEqualsOperandType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Constant _constant, DartType _type)> codeConstEvalInvalidEqualsOperandType = const Code<Message Function(Constant _constant, DartType _type)>( "ConstEvalInvalidEqualsOperandType", templateConstEvalInvalidEqualsOperandType, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidEqualsOperandType( Constant _constant, DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); List<Object> typeParts = labeler.labelType(_type); String constant = constantParts.join(); String type = typeParts.join(); return new Message(codeConstEvalInvalidEqualsOperandType, message: """Binary operator '==' requires receiver constant '${constant}' of type 'Null', 'bool', 'int', 'double', or 'String', but was of type '${type}'.""" + labeler.originMessages, arguments: {'constant': _constant, 'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, Constant _constant)> templateConstEvalInvalidMethodInvocation = const Template< Message Function(String string, Constant _constant)>( messageTemplate: r"""The method '#string' can't be invoked on '#constant' in a constant expression.""", withArguments: _withArgumentsConstEvalInvalidMethodInvocation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, Constant _constant)> codeConstEvalInvalidMethodInvocation = const Code<Message Function(String string, Constant _constant)>( "ConstEvalInvalidMethodInvocation", templateConstEvalInvalidMethodInvocation, analyzerCodes: <String>["UNDEFINED_OPERATOR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidMethodInvocation( String string, Constant _constant) { if (string.isEmpty) throw 'No string provided'; TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalInvalidMethodInvocation, message: """The method '${string}' can't be invoked on '${constant}' in a constant expression.""" + labeler.originMessages, arguments: {'string': string, 'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, Constant _constant)> templateConstEvalInvalidPropertyGet = const Template< Message Function(String string, Constant _constant)>( messageTemplate: r"""The property '#string' can't be accessed on '#constant' in a constant expression.""", withArguments: _withArgumentsConstEvalInvalidPropertyGet); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, Constant _constant)> codeConstEvalInvalidPropertyGet = const Code<Message Function(String string, Constant _constant)>( "ConstEvalInvalidPropertyGet", templateConstEvalInvalidPropertyGet, analyzerCodes: <String>["CONST_EVAL_THROWS_EXCEPTION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidPropertyGet( String string, Constant _constant) { if (string.isEmpty) throw 'No string provided'; TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalInvalidPropertyGet, message: """The property '${string}' can't be accessed on '${constant}' in a constant expression.""" + labeler.originMessages, arguments: {'string': string, 'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateConstEvalInvalidStaticInvocation = const Template< Message Function(String name)>( messageTemplate: r"""The invocation of '#name' is not allowed in a constant expression.""", withArguments: _withArgumentsConstEvalInvalidStaticInvocation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConstEvalInvalidStaticInvocation = const Code<Message Function(String name)>( "ConstEvalInvalidStaticInvocation", templateConstEvalInvalidStaticInvocation, analyzerCodes: <String>["CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidStaticInvocation(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConstEvalInvalidStaticInvocation, message: """The invocation of '${name}' is not allowed in a constant expression.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Constant _constant)> templateConstEvalInvalidStringInterpolationOperand = const Template<Message Function(Constant _constant)>( messageTemplate: r"""The constant value '#constant' can't be used as part of a string interpolation in a constant expression. Only values of type 'null', 'bool', 'int', 'double', or 'String' can be used.""", withArguments: _withArgumentsConstEvalInvalidStringInterpolationOperand); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Constant _constant)> codeConstEvalInvalidStringInterpolationOperand = const Code<Message Function(Constant _constant)>( "ConstEvalInvalidStringInterpolationOperand", templateConstEvalInvalidStringInterpolationOperand, analyzerCodes: <String>["CONST_EVAL_TYPE_BOOL_NUM_STRING"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidStringInterpolationOperand( Constant _constant) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalInvalidStringInterpolationOperand, message: """The constant value '${constant}' can't be used as part of a string interpolation in a constant expression. Only values of type 'null', 'bool', 'int', 'double', or 'String' can be used.""" + labeler.originMessages, arguments: {'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Constant _constant)> templateConstEvalInvalidSymbolName = const Template< Message Function(Constant _constant)>( messageTemplate: r"""The symbol name must be a valid public Dart member name, public constructor name, or library name, optionally qualified, but was '#constant'.""", withArguments: _withArgumentsConstEvalInvalidSymbolName); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Constant _constant)> codeConstEvalInvalidSymbolName = const Code<Message Function(Constant _constant)>( "ConstEvalInvalidSymbolName", templateConstEvalInvalidSymbolName, analyzerCodes: <String>["CONST_EVAL_THROWS_EXCEPTION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidSymbolName(Constant _constant) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalInvalidSymbolName, message: """The symbol name must be a valid public Dart member name, public constructor name, or library name, optionally qualified, but was '${constant}'.""" + labeler.originMessages, arguments: {'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Constant _constant, DartType _type, DartType _type2)> templateConstEvalInvalidType = const Template< Message Function(Constant _constant, DartType _type, DartType _type2)>( messageTemplate: r"""Expected constant '#constant' to be of type '#type', but was of type '#type2'.""", withArguments: _withArgumentsConstEvalInvalidType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(Constant _constant, DartType _type, DartType _type2)> codeConstEvalInvalidType = const Code< Message Function(Constant _constant, DartType _type, DartType _type2)>( "ConstEvalInvalidType", templateConstEvalInvalidType, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalInvalidType( Constant _constant, DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String constant = constantParts.join(); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeConstEvalInvalidType, message: """Expected constant '${constant}' to be of type '${type}', but was of type '${type2}'.""" + labeler.originMessages, arguments: {'constant': _constant, 'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Constant _constant)> templateConstEvalKeyImplementsEqual = const Template<Message Function(Constant _constant)>( messageTemplate: r"""The key '#constant' does not have a primitive operator '=='.""", withArguments: _withArgumentsConstEvalKeyImplementsEqual); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Constant _constant)> codeConstEvalKeyImplementsEqual = const Code<Message Function(Constant _constant)>( "ConstEvalKeyImplementsEqual", templateConstEvalKeyImplementsEqual, analyzerCodes: <String>[ "CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS" ]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalKeyImplementsEqual(Constant _constant) { TypeLabeler labeler = new TypeLabeler(); List<Object> constantParts = labeler.labelConstant(_constant); String constant = constantParts.join(); return new Message(codeConstEvalKeyImplementsEqual, message: """The key '${constant}' does not have a primitive operator '=='.""" + labeler.originMessages, arguments: {'constant': _constant}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, String string2, String string3)> templateConstEvalNegativeShift = const Template< Message Function(String string, String string2, String string3)>( messageTemplate: r"""Binary operator '#string' on '#string2' requires non-negative operand, but was '#string3'.""", withArguments: _withArgumentsConstEvalNegativeShift); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2, String string3)> codeConstEvalNegativeShift = const Code<Message Function(String string, String string2, String string3)>( "ConstEvalNegativeShift", templateConstEvalNegativeShift, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalNegativeShift( String string, String string2, String string3) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; if (string3.isEmpty) throw 'No string provided'; return new Message(codeConstEvalNegativeShift, message: """Binary operator '${string}' on '${string2}' requires non-negative operand, but was '${string3}'.""", arguments: {'string': string, 'string2': string2, 'string3': string3}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string)> templateConstEvalNonConstantVariableGet = const Template< Message Function(String string)>( messageTemplate: r"""The variable '#string' is not a constant, only constant expressions are allowed.""", withArguments: _withArgumentsConstEvalNonConstantVariableGet); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeConstEvalNonConstantVariableGet = const Code<Message Function(String string)>( "ConstEvalNonConstantVariableGet", templateConstEvalNonConstantVariableGet, analyzerCodes: <String>["NON_CONSTANT_VALUE_IN_INITIALIZER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalNonConstantVariableGet(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeConstEvalNonConstantVariableGet, message: """The variable '${string}' is not a constant, only constant expressions are allowed.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalNotListOrSetInSpread = messageConstEvalNotListOrSetInSpread; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalNotListOrSetInSpread = const MessageCode( "ConstEvalNotListOrSetInSpread", analyzerCodes: <String>["CONST_SPREAD_EXPECTED_LIST_OR_SET"], message: r"""Only lists and sets can be used in spreads in constant lists and sets."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalNotMapInSpread = messageConstEvalNotMapInSpread; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalNotMapInSpread = const MessageCode( "ConstEvalNotMapInSpread", analyzerCodes: <String>["CONST_SPREAD_EXPECTED_MAP"], message: r"""Only maps can be used in spreads in constant maps."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalNullValue = messageConstEvalNullValue; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalNullValue = const MessageCode( "ConstEvalNullValue", analyzerCodes: <String>["CONST_EVAL_THROWS_EXCEPTION"], message: r"""Null value during constant evaluation."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalStartingPoint = messageConstEvalStartingPoint; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalStartingPoint = const MessageCode( "ConstEvalStartingPoint", message: r"""Constant evaluation error:"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstEvalUnevaluated = messageConstEvalUnevaluated; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstEvalUnevaluated = const MessageCode( "ConstEvalUnevaluated", message: r"""Could not evaluate constant expression."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, String string2)> templateConstEvalZeroDivisor = const Template< Message Function(String string, String string2)>( messageTemplate: r"""Binary operator '#string' on '#string2' requires non-zero divisor, but divisor was '0'.""", withArguments: _withArgumentsConstEvalZeroDivisor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeConstEvalZeroDivisor = const Code<Message Function(String string, String string2)>( "ConstEvalZeroDivisor", templateConstEvalZeroDivisor, analyzerCodes: <String>["CONST_EVAL_THROWS_IDBZE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstEvalZeroDivisor(String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeConstEvalZeroDivisor, message: """Binary operator '${string}' on '${string2}' requires non-zero divisor, but divisor was '0'.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstFactory = messageConstFactory; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstFactory = const MessageCode("ConstFactory", index: 62, message: r"""Only redirecting factory constructors can be declared to be 'const'.""", tip: r"""Try removing the 'const' keyword, or replacing the body with '=' followed by a valid target."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstFactoryRedirectionToNonConst = messageConstFactoryRedirectionToNonConst; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstFactoryRedirectionToNonConst = const MessageCode( "ConstFactoryRedirectionToNonConst", analyzerCodes: <String>["REDIRECT_TO_NON_CONST_CONSTRUCTOR"], message: r"""Constant factory constructor can't delegate to a non-constant constructor.""", tip: r"""Try redirecting to a different constructor or marking the target constructor 'const'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateConstFieldWithoutInitializer = const Template< Message Function(String name)>( messageTemplate: r"""The const variable '#name' must be initialized.""", tipTemplate: r"""Try adding an initializer ('= expression') to the declaration.""", withArguments: _withArgumentsConstFieldWithoutInitializer); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConstFieldWithoutInitializer = const Code<Message Function(String name)>( "ConstFieldWithoutInitializer", templateConstFieldWithoutInitializer, analyzerCodes: <String>["CONST_NOT_INITIALIZED"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstFieldWithoutInitializer(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConstFieldWithoutInitializer, message: """The const variable '${name}' must be initialized.""", tip: """Try adding an initializer ('= expression') to the declaration.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstInstanceField = messageConstInstanceField; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstInstanceField = const MessageCode( "ConstInstanceField", analyzerCodes: <String>["CONST_INSTANCE_FIELD"], message: r"""Only static fields can be declared as const.""", tip: r"""Try using 'final' instead of 'const', or adding the keyword 'static'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstMethod = messageConstMethod; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstMethod = const MessageCode("ConstMethod", index: 63, message: r"""Getters, setters and methods can't be declared to be 'const'.""", tip: r"""Try removing the 'const' keyword."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstructorCyclic = messageConstructorCyclic; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstructorCyclic = const MessageCode( "ConstructorCyclic", analyzerCodes: <String>["RECURSIVE_CONSTRUCTOR_REDIRECT"], message: r"""Redirecting constructors can't be cyclic.""", tip: r"""Try to have all constructors eventually redirect to a non-redirecting constructor."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConstructorNotFound = const Template<Message Function(String name)>( messageTemplate: r"""Couldn't find constructor '#name'.""", withArguments: _withArgumentsConstructorNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConstructorNotFound = const Code<Message Function(String name)>( "ConstructorNotFound", templateConstructorNotFound, analyzerCodes: <String>["CONSTRUCTOR_NOT_FOUND"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstructorNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConstructorNotFound, message: """Couldn't find constructor '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstructorNotSync = messageConstructorNotSync; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstructorNotSync = const MessageCode( "ConstructorNotSync", analyzerCodes: <String>["NON_SYNC_CONSTRUCTOR"], message: r"""Constructor bodies can't use 'async', 'async*', or 'sync*'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstructorWithReturnType = messageConstructorWithReturnType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstructorWithReturnType = const MessageCode( "ConstructorWithReturnType", index: 55, message: r"""Constructors can't have a return type.""", tip: r"""Try removing the return type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstructorWithTypeArguments = messageConstructorWithTypeArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstructorWithTypeArguments = const MessageCode( "ConstructorWithTypeArguments", analyzerCodes: <String>["WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR"], message: r"""A constructor invocation can't have type arguments on the constructor name.""", tip: r"""Try to place the type arguments on the class name."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstructorWithTypeParameters = messageConstructorWithTypeParameters; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstructorWithTypeParameters = const MessageCode( "ConstructorWithTypeParameters", analyzerCodes: <String>["TYPE_PARAMETER_ON_CONSTRUCTOR"], message: r"""Constructors can't have type parameters."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeConstructorWithWrongName = messageConstructorWithWrongName; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageConstructorWithWrongName = const MessageCode( "ConstructorWithWrongName", analyzerCodes: <String>["INVALID_CONSTRUCTOR_NAME"], message: r"""The name of a constructor must match the name of the enclosing class."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateConstructorWithWrongNameContext = const Template<Message Function(String name)>( messageTemplate: r"""The name of the enclosing class is '#name'.""", withArguments: _withArgumentsConstructorWithWrongNameContext); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeConstructorWithWrongNameContext = const Code<Message Function(String name)>("ConstructorWithWrongNameContext", templateConstructorWithWrongNameContext, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsConstructorWithWrongNameContext(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeConstructorWithWrongNameContext, message: """The name of the enclosing class is '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeContinueLabelNotTarget = messageContinueLabelNotTarget; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageContinueLabelNotTarget = const MessageCode( "ContinueLabelNotTarget", analyzerCodes: <String>["LABEL_UNDEFINED"], message: r"""Target of continue must be a label."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeContinueOutsideOfLoop = messageContinueOutsideOfLoop; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageContinueOutsideOfLoop = const MessageCode( "ContinueOutsideOfLoop", index: 2, message: r"""A continue statement can't be used outside of a loop or switch statement.""", tip: r"""Try removing the continue statement."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateContinueTargetOutsideFunction = const Template<Message Function(String name)>( messageTemplate: r"""Can't continue at '#name' in a different function.""", withArguments: _withArgumentsContinueTargetOutsideFunction); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeContinueTargetOutsideFunction = const Code<Message Function(String name)>( "ContinueTargetOutsideFunction", templateContinueTargetOutsideFunction, analyzerCodes: <String>["LABEL_IN_OUTER_SCOPE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsContinueTargetOutsideFunction(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeContinueTargetOutsideFunction, message: """Can't continue at '${name}' in a different function.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeContinueWithoutLabelInCase = messageContinueWithoutLabelInCase; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageContinueWithoutLabelInCase = const MessageCode( "ContinueWithoutLabelInCase", index: 64, message: r"""A continue statement in a switch statement must have a label as a target.""", tip: r"""Try adding a label associated with one of the case clauses to the continue statement."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string, String string2)> templateCouldNotParseUri = const Template<Message Function(String string, String string2)>( messageTemplate: r"""Couldn't parse URI '#string': #string2.""", withArguments: _withArgumentsCouldNotParseUri); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeCouldNotParseUri = const Code<Message Function(String string, String string2)>( "CouldNotParseUri", templateCouldNotParseUri, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCouldNotParseUri(String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeCouldNotParseUri, message: """Couldn't parse URI '${string}': ${string2}.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCovariantAndStatic = messageCovariantAndStatic; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCovariantAndStatic = const MessageCode( "CovariantAndStatic", index: 66, message: r"""Members can't be declared to be both 'covariant' and 'static'.""", tip: r"""Try removing either the 'covariant' or 'static' keyword."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeCovariantMember = messageCovariantMember; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageCovariantMember = const MessageCode("CovariantMember", index: 67, message: r"""Getters, setters and methods can't be declared to be 'covariant'.""", tip: r"""Try removing the 'covariant' keyword."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String string)> templateCycleInTypeVariables = const Template< Message Function(String name, String string)>( messageTemplate: r"""Type '#name' is a bound of itself via '#string'.""", tipTemplate: r"""Try breaking the cycle by removing at least on of the 'extends' clauses in the cycle.""", withArguments: _withArgumentsCycleInTypeVariables); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String string)> codeCycleInTypeVariables = const Code<Message Function(String name, String string)>( "CycleInTypeVariables", templateCycleInTypeVariables, analyzerCodes: <String>["TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCycleInTypeVariables(String name, String string) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (string.isEmpty) throw 'No string provided'; return new Message(codeCycleInTypeVariables, message: """Type '${name}' is a bound of itself via '${string}'.""", tip: """Try breaking the cycle by removing at least on of the 'extends' clauses in the cycle.""", arguments: {'name': name, 'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateCyclicClassHierarchy = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is a supertype of itself.""", withArguments: _withArgumentsCyclicClassHierarchy); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeCyclicClassHierarchy = const Code<Message Function(String name)>( "CyclicClassHierarchy", templateCyclicClassHierarchy, analyzerCodes: <String>["RECURSIVE_INTERFACE_INHERITANCE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCyclicClassHierarchy(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeCyclicClassHierarchy, message: """'${name}' is a supertype of itself.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateCyclicRedirectingFactoryConstructors = const Template<Message Function(String name)>( messageTemplate: r"""Cyclic definition of factory '#name'.""", withArguments: _withArgumentsCyclicRedirectingFactoryConstructors); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeCyclicRedirectingFactoryConstructors = const Code<Message Function(String name)>( "CyclicRedirectingFactoryConstructors", templateCyclicRedirectingFactoryConstructors, analyzerCodes: <String>["RECURSIVE_FACTORY_REDIRECT"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCyclicRedirectingFactoryConstructors(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeCyclicRedirectingFactoryConstructors, message: """Cyclic definition of factory '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateCyclicTypedef = const Template<Message Function(String name)>( messageTemplate: r"""The typedef '#name' has a reference to itself.""", withArguments: _withArgumentsCyclicTypedef); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeCyclicTypedef = const Code<Message Function(String name)>( "CyclicTypedef", templateCyclicTypedef, analyzerCodes: <String>["TYPE_ALIAS_CANNOT_REFERENCE_ITSELF"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsCyclicTypedef(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeCyclicTypedef, message: """The typedef '${name}' has a reference to itself.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeDeclaredMemberConflictsWithInheritedMember = messageDeclaredMemberConflictsWithInheritedMember; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageDeclaredMemberConflictsWithInheritedMember = const MessageCode("DeclaredMemberConflictsWithInheritedMember", analyzerCodes: <String>["DECLARED_MEMBER_CONFLICTS_WITH_INHERITED"], message: r"""Can't declare a member that conflicts with an inherited one."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeDeclaredMemberConflictsWithInheritedMemberCause = messageDeclaredMemberConflictsWithInheritedMemberCause; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageDeclaredMemberConflictsWithInheritedMemberCause = const MessageCode("DeclaredMemberConflictsWithInheritedMemberCause", severity: Severity.context, message: r"""This is the inherited member."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDefaultValueInRedirectingFactoryConstructor = const Template<Message Function(String name)>( messageTemplate: r"""Can't have a default value here because any default values of '#name' would be used instead.""", tipTemplate: r"""Try removing the default value.""", withArguments: _withArgumentsDefaultValueInRedirectingFactoryConstructor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDefaultValueInRedirectingFactoryConstructor = const Code<Message Function(String name)>( "DefaultValueInRedirectingFactoryConstructor", templateDefaultValueInRedirectingFactoryConstructor, analyzerCodes: <String>[ "DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR" ]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDefaultValueInRedirectingFactoryConstructor(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDefaultValueInRedirectingFactoryConstructor, message: """Can't have a default value here because any default values of '${name}' would be used instead.""", tip: """Try removing the default value.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeDeferredAfterPrefix = messageDeferredAfterPrefix; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageDeferredAfterPrefix = const MessageCode( "DeferredAfterPrefix", index: 68, message: r"""The deferred keyword should come immediately before the prefix ('as' clause).""", tip: r"""Try moving the deferred keyword before the prefix."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateDeferredPrefixDuplicated = const Template< Message Function(String name)>( messageTemplate: r"""Can't use the name '#name' for a deferred library, as the name is used elsewhere.""", withArguments: _withArgumentsDeferredPrefixDuplicated); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDeferredPrefixDuplicated = const Code<Message Function(String name)>( "DeferredPrefixDuplicated", templateDeferredPrefixDuplicated, analyzerCodes: <String>["SHARED_DEFERRED_PREFIX"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDeferredPrefixDuplicated(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDeferredPrefixDuplicated, message: """Can't use the name '${name}' for a deferred library, as the name is used elsewhere.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDeferredPrefixDuplicatedCause = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is used here.""", withArguments: _withArgumentsDeferredPrefixDuplicatedCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDeferredPrefixDuplicatedCause = const Code<Message Function(String name)>( "DeferredPrefixDuplicatedCause", templateDeferredPrefixDuplicatedCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDeferredPrefixDuplicatedCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDeferredPrefixDuplicatedCause, message: """'${name}' is used here.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, String name)> templateDeferredTypeAnnotation = const Template< Message Function(DartType _type, String name)>( messageTemplate: r"""The type '#type' is deferred loaded via prefix '#name' and can't be used as a type annotation.""", tipTemplate: r"""Try removing 'deferred' from the import of '#name' or use a supertype of '#type' that isn't deferred.""", withArguments: _withArgumentsDeferredTypeAnnotation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, String name)> codeDeferredTypeAnnotation = const Code<Message Function(DartType _type, String name)>( "DeferredTypeAnnotation", templateDeferredTypeAnnotation, analyzerCodes: <String>["TYPE_ANNOTATION_DEFERRED_CLASS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDeferredTypeAnnotation(DartType _type, String name) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String type = typeParts.join(); return new Message(codeDeferredTypeAnnotation, message: """The type '${type}' is deferred loaded via prefix '${name}' and can't be used as a type annotation.""" + labeler.originMessages, tip: """Try removing 'deferred' from the import of '${name}' or use a supertype of '${type}' that isn't deferred.""", arguments: {'type': _type, 'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int count, int count2, num _num1, num _num2, num _num3)> templateDillOutlineSummary = const Template< Message Function( int count, int count2, num _num1, num _num2, num _num3)>( messageTemplate: r"""Indexed #count libraries (#count2 bytes) in #num1%.3ms, that is, #num2%12.3 bytes/ms, and #num3%12.3 ms/libraries.""", withArguments: _withArgumentsDillOutlineSummary); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(int count, int count2, num _num1, num _num2, num _num3)> codeDillOutlineSummary = const Code< Message Function(int count, int count2, num _num1, num _num2, num _num3)>( "DillOutlineSummary", templateDillOutlineSummary, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDillOutlineSummary( int count, int count2, num _num1, num _num2, num _num3) { if (count == null) throw 'No count provided'; if (count2 == null) throw 'No count provided'; if (_num1 == null) throw 'No number provided'; String num1 = _num1.toStringAsFixed(3); if (_num2 == null) throw 'No number provided'; String num2 = _num2.toStringAsFixed(3).padLeft(12); if (_num3 == null) throw 'No number provided'; String num3 = _num3.toStringAsFixed(3).padLeft(12); return new Message(codeDillOutlineSummary, message: """Indexed ${count} libraries (${count2} bytes) in ${num1}ms, that is, ${num2} bytes/ms, and ${num3} ms/libraries.""", arguments: { 'count': count, 'count2': count2, 'num1': _num1, 'num2': _num2, 'num3': _num3 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateDirectCycleInTypeVariables = const Template< Message Function(String name)>( messageTemplate: r"""Type '#name' can't use itself as a bound.""", tipTemplate: r"""Try breaking the cycle by removing at least on of the 'extends' clauses in the cycle.""", withArguments: _withArgumentsDirectCycleInTypeVariables); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDirectCycleInTypeVariables = const Code<Message Function(String name)>( "DirectCycleInTypeVariables", templateDirectCycleInTypeVariables, analyzerCodes: <String>["TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDirectCycleInTypeVariables(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDirectCycleInTypeVariables, message: """Type '${name}' can't use itself as a bound.""", tip: """Try breaking the cycle by removing at least on of the 'extends' clauses in the cycle.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeDirectiveAfterDeclaration = messageDirectiveAfterDeclaration; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageDirectiveAfterDeclaration = const MessageCode( "DirectiveAfterDeclaration", index: 69, message: r"""Directives must appear before any declarations.""", tip: r"""Try moving the directive before any declarations."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeDuplicateDeferred = messageDuplicateDeferred; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageDuplicateDeferred = const MessageCode( "DuplicateDeferred", index: 71, message: r"""An import directive can only have one 'deferred' keyword.""", tip: r"""Try removing all but one 'deferred' keyword."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicateLabelInSwitchStatement = const Template<Message Function(String name)>( messageTemplate: r"""The label '#name' was already used in this switch statement.""", tipTemplate: r"""Try choosing a different name for this label.""", withArguments: _withArgumentsDuplicateLabelInSwitchStatement); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicateLabelInSwitchStatement = const Code<Message Function(String name)>("DuplicateLabelInSwitchStatement", templateDuplicateLabelInSwitchStatement, index: 72); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicateLabelInSwitchStatement(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicateLabelInSwitchStatement, message: """The label '${name}' was already used in this switch statement.""", tip: """Try choosing a different name for this label.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeDuplicatePrefix = messageDuplicatePrefix; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageDuplicatePrefix = const MessageCode("DuplicatePrefix", index: 73, message: r"""An import directive can only have one prefix ('as' clause).""", tip: r"""Try removing all but one prefix."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedDeclaration = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is already declared in this scope.""", withArguments: _withArgumentsDuplicatedDeclaration); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedDeclaration = const Code<Message Function(String name)>( "DuplicatedDeclaration", templateDuplicatedDeclaration, analyzerCodes: <String>["DUPLICATE_DEFINITION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedDeclaration(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedDeclaration, message: """'${name}' is already declared in this scope.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedDeclarationCause = const Template<Message Function(String name)>( messageTemplate: r"""Previous declaration of '#name'.""", withArguments: _withArgumentsDuplicatedDeclarationCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedDeclarationCause = const Code<Message Function(String name)>( "DuplicatedDeclarationCause", templateDuplicatedDeclarationCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedDeclarationCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedDeclarationCause, message: """Previous declaration of '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateDuplicatedDeclarationSyntheticCause = const Template< Message Function(String name)>( messageTemplate: r"""Previous declaration of '#name' is implied by this definition.""", withArguments: _withArgumentsDuplicatedDeclarationSyntheticCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedDeclarationSyntheticCause = const Code<Message Function(String name)>( "DuplicatedDeclarationSyntheticCause", templateDuplicatedDeclarationSyntheticCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedDeclarationSyntheticCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedDeclarationSyntheticCause, message: """Previous declaration of '${name}' is implied by this definition.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedDeclarationUse = const Template<Message Function(String name)>( messageTemplate: r"""Can't use '#name' because it is declared more than once.""", withArguments: _withArgumentsDuplicatedDeclarationUse); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedDeclarationUse = const Code<Message Function(String name)>( "DuplicatedDeclarationUse", templateDuplicatedDeclarationUse, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedDeclarationUse(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedDeclarationUse, message: """Can't use '${name}' because it is declared more than once.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_, Uri uri2_)> templateDuplicatedExport = const Template<Message Function(String name, Uri uri_, Uri uri2_)>( messageTemplate: r"""'#name' is exported from both '#uri' and '#uri2'.""", withArguments: _withArgumentsDuplicatedExport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_, Uri uri2_)> codeDuplicatedExport = const Code<Message Function(String name, Uri uri_, Uri uri2_)>( "DuplicatedExport", templateDuplicatedExport, analyzerCodes: <String>["AMBIGUOUS_EXPORT"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedExport(String name, Uri uri_, Uri uri2_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); return new Message(codeDuplicatedExport, message: """'${name}' is exported from both '${uri}' and '${uri2}'.""", arguments: {'name': name, 'uri': uri_, 'uri2': uri2_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_, Uri uri2_)> templateDuplicatedExportInType = const Template<Message Function(String name, Uri uri_, Uri uri2_)>( messageTemplate: r"""'#name' is exported from both '#uri' and '#uri2'.""", withArguments: _withArgumentsDuplicatedExportInType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_, Uri uri2_)> codeDuplicatedExportInType = const Code<Message Function(String name, Uri uri_, Uri uri2_)>( "DuplicatedExportInType", templateDuplicatedExportInType, severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedExportInType(String name, Uri uri_, Uri uri2_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); return new Message(codeDuplicatedExportInType, message: """'${name}' is exported from both '${uri}' and '${uri2}'.""", arguments: {'name': name, 'uri': uri_, 'uri2': uri2_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_, Uri uri2_)> templateDuplicatedImport = const Template<Message Function(String name, Uri uri_, Uri uri2_)>( messageTemplate: r"""'#name' is imported from both '#uri' and '#uri2'.""", withArguments: _withArgumentsDuplicatedImport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_, Uri uri2_)> codeDuplicatedImport = const Code<Message Function(String name, Uri uri_, Uri uri2_)>( "DuplicatedImport", templateDuplicatedImport, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedImport(String name, Uri uri_, Uri uri2_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); return new Message(codeDuplicatedImport, message: """'${name}' is imported from both '${uri}' and '${uri2}'.""", arguments: {'name': name, 'uri': uri_, 'uri2': uri2_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_, Uri uri2_)> templateDuplicatedImportInType = const Template<Message Function(String name, Uri uri_, Uri uri2_)>( messageTemplate: r"""'#name' is imported from both '#uri' and '#uri2'.""", withArguments: _withArgumentsDuplicatedImportInType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_, Uri uri2_)> codeDuplicatedImportInType = const Code<Message Function(String name, Uri uri_, Uri uri2_)>( "DuplicatedImportInType", templateDuplicatedImportInType, analyzerCodes: <String>["AMBIGUOUS_IMPORT"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedImportInType(String name, Uri uri_, Uri uri2_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); return new Message(codeDuplicatedImportInType, message: """'${name}' is imported from both '${uri}' and '${uri2}'.""", arguments: {'name': name, 'uri': uri_, 'uri2': uri2_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedLibraryExport = const Template<Message Function(String name)>( messageTemplate: r"""A library with name '#name' is exported more than once.""", withArguments: _withArgumentsDuplicatedLibraryExport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedLibraryExport = const Code<Message Function(String name)>( "DuplicatedLibraryExport", templateDuplicatedLibraryExport, analyzerCodes: <String>["EXPORT_DUPLICATED_LIBRARY_NAMED"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedLibraryExport(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedLibraryExport, message: """A library with name '${name}' is exported more than once.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedLibraryExportContext = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is also exported here.""", withArguments: _withArgumentsDuplicatedLibraryExportContext); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedLibraryExportContext = const Code<Message Function(String name)>("DuplicatedLibraryExportContext", templateDuplicatedLibraryExportContext, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedLibraryExportContext(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedLibraryExportContext, message: """'${name}' is also exported here.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedLibraryImport = const Template<Message Function(String name)>( messageTemplate: r"""A library with name '#name' is imported more than once.""", withArguments: _withArgumentsDuplicatedLibraryImport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedLibraryImport = const Code<Message Function(String name)>( "DuplicatedLibraryImport", templateDuplicatedLibraryImport, analyzerCodes: <String>["IMPORT_DUPLICATED_LIBRARY_NAMED"], severity: Severity.warning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedLibraryImport(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedLibraryImport, message: """A library with name '${name}' is imported more than once.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedLibraryImportContext = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is also imported here.""", withArguments: _withArgumentsDuplicatedLibraryImportContext); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedLibraryImportContext = const Code<Message Function(String name)>("DuplicatedLibraryImportContext", templateDuplicatedLibraryImportContext, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedLibraryImportContext(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedLibraryImportContext, message: """'${name}' is also imported here.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateDuplicatedModifier = const Template<Message Function(Token token)>( messageTemplate: r"""The modifier '#lexeme' was already specified.""", tipTemplate: r"""Try removing all but one occurrence of the modifier.""", withArguments: _withArgumentsDuplicatedModifier); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeDuplicatedModifier = const Code<Message Function(Token token)>( "DuplicatedModifier", templateDuplicatedModifier, index: 70); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedModifier(Token token) { String lexeme = token.lexeme; return new Message(codeDuplicatedModifier, message: """The modifier '${lexeme}' was already specified.""", tip: """Try removing all but one occurrence of the modifier.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateDuplicatedNamePreviouslyUsed = const Template< Message Function(String name)>( messageTemplate: r"""Can't declare '#name' because it was already used in this scope.""", withArguments: _withArgumentsDuplicatedNamePreviouslyUsed); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedNamePreviouslyUsed = const Code<Message Function(String name)>( "DuplicatedNamePreviouslyUsed", templateDuplicatedNamePreviouslyUsed, analyzerCodes: <String>["REFERENCED_BEFORE_DECLARATION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedNamePreviouslyUsed(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedNamePreviouslyUsed, message: """Can't declare '${name}' because it was already used in this scope.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedNamePreviouslyUsedCause = const Template<Message Function(String name)>( messageTemplate: r"""Previous use of '#name'.""", withArguments: _withArgumentsDuplicatedNamePreviouslyUsedCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedNamePreviouslyUsedCause = const Code<Message Function(String name)>( "DuplicatedNamePreviouslyUsedCause", templateDuplicatedNamePreviouslyUsedCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedNamePreviouslyUsedCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedNamePreviouslyUsedCause, message: """Previous use of '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedNamedArgument = const Template<Message Function(String name)>( messageTemplate: r"""Duplicated named argument '#name'.""", withArguments: _withArgumentsDuplicatedNamedArgument); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedNamedArgument = const Code<Message Function(String name)>( "DuplicatedNamedArgument", templateDuplicatedNamedArgument, analyzerCodes: <String>["DUPLICATE_NAMED_ARGUMENT"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedNamedArgument(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedNamedArgument, message: """Duplicated named argument '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedParameterName = const Template<Message Function(String name)>( messageTemplate: r"""Duplicated parameter name '#name'.""", withArguments: _withArgumentsDuplicatedParameterName); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedParameterName = const Code<Message Function(String name)>( "DuplicatedParameterName", templateDuplicatedParameterName, analyzerCodes: <String>["DUPLICATE_DEFINITION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedParameterName(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedParameterName, message: """Duplicated parameter name '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateDuplicatedParameterNameCause = const Template<Message Function(String name)>( messageTemplate: r"""Other parameter named '#name'.""", withArguments: _withArgumentsDuplicatedParameterNameCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeDuplicatedParameterNameCause = const Code<Message Function(String name)>( "DuplicatedParameterNameCause", templateDuplicatedParameterNameCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsDuplicatedParameterNameCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeDuplicatedParameterNameCause, message: """Other parameter named '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeEmptyNamedParameterList = messageEmptyNamedParameterList; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageEmptyNamedParameterList = const MessageCode( "EmptyNamedParameterList", analyzerCodes: <String>["MISSING_IDENTIFIER"], message: r"""Named parameter lists cannot be empty.""", tip: r"""Try adding a named parameter to the list."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeEmptyOptionalParameterList = messageEmptyOptionalParameterList; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageEmptyOptionalParameterList = const MessageCode( "EmptyOptionalParameterList", analyzerCodes: <String>["MISSING_IDENTIFIER"], message: r"""Optional parameter lists cannot be empty.""", tip: r"""Try adding an optional parameter to the list."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeEncoding = messageEncoding; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageEncoding = const MessageCode("Encoding", message: r"""Unable to decode bytes as UTF-8."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateEnumConstantSameNameAsEnclosing = const Template< Message Function(String name)>( messageTemplate: r"""Name of enum constant '#name' can't be the same as the enum's own name.""", withArguments: _withArgumentsEnumConstantSameNameAsEnclosing); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeEnumConstantSameNameAsEnclosing = const Code<Message Function(String name)>("EnumConstantSameNameAsEnclosing", templateEnumConstantSameNameAsEnclosing, analyzerCodes: <String>["ENUM_CONSTANT_WITH_ENUM_NAME"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsEnumConstantSameNameAsEnclosing(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeEnumConstantSameNameAsEnclosing, message: """Name of enum constant '${name}' can't be the same as the enum's own name.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeEnumDeclarationEmpty = messageEnumDeclarationEmpty; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageEnumDeclarationEmpty = const MessageCode( "EnumDeclarationEmpty", analyzerCodes: <String>["EMPTY_ENUM_BODY"], message: r"""An enum declaration can't be empty."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeEnumInClass = messageEnumInClass; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageEnumInClass = const MessageCode("EnumInClass", index: 74, message: r"""Enums can't be declared inside classes.""", tip: r"""Try moving the enum to the top-level."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeEnumInstantiation = messageEnumInstantiation; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageEnumInstantiation = const MessageCode( "EnumInstantiation", analyzerCodes: <String>["INSTANTIATE_ENUM"], message: r"""Enums can't be instantiated."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeEqualityCannotBeEqualityOperand = messageEqualityCannotBeEqualityOperand; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageEqualityCannotBeEqualityOperand = const MessageCode( "EqualityCannotBeEqualityOperand", index: 1, message: r"""A comparison expression can't be an operand of another comparison expression.""", tip: r"""Try putting parentheses around one of the comparisons."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateExpectedAfterButGot = const Template<Message Function(String string)>( messageTemplate: r"""Expected '#string' after this.""", withArguments: _withArgumentsExpectedAfterButGot); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeExpectedAfterButGot = const Code<Message Function(String string)>( "ExpectedAfterButGot", templateExpectedAfterButGot, analyzerCodes: <String>["EXPECTED_TOKEN"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedAfterButGot(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeExpectedAfterButGot, message: """Expected '${string}' after this.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedAnInitializer = messageExpectedAnInitializer; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedAnInitializer = const MessageCode( "ExpectedAnInitializer", index: 36, message: r"""Expected an initializer."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedBlock = messageExpectedBlock; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedBlock = const MessageCode("ExpectedBlock", analyzerCodes: <String>["EXPECTED_TOKEN"], message: r"""Expected a block.""", tip: r"""Try adding {}."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedBlockToSkip = messageExpectedBlockToSkip; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedBlockToSkip = const MessageCode( "ExpectedBlockToSkip", analyzerCodes: <String>["MISSING_FUNCTION_BODY"], message: r"""Expected a function body or '=>'.""", tip: r"""Try adding {}."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedBody = messageExpectedBody; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedBody = const MessageCode("ExpectedBody", analyzerCodes: <String>["MISSING_FUNCTION_BODY"], message: r"""Expected a function body or '=>'.""", tip: r"""Try adding {}."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateExpectedButGot = const Template<Message Function(String string)>( messageTemplate: r"""Expected '#string' before this.""", withArguments: _withArgumentsExpectedButGot); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeExpectedButGot = const Code<Message Function(String string)>( "ExpectedButGot", templateExpectedButGot, analyzerCodes: <String>["EXPECTED_TOKEN"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedButGot(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeExpectedButGot, message: """Expected '${string}' before this.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateExpectedClassMember = const Template<Message Function(Token token)>( messageTemplate: r"""Expected a class member, but got '#lexeme'.""", withArguments: _withArgumentsExpectedClassMember); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExpectedClassMember = const Code<Message Function(Token token)>( "ExpectedClassMember", templateExpectedClassMember, analyzerCodes: <String>["EXPECTED_CLASS_MEMBER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedClassMember(Token token) { String lexeme = token.lexeme; return new Message(codeExpectedClassMember, message: """Expected a class member, but got '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateExpectedClassOrMixinBody = const Template<Message Function(String string)>( messageTemplate: r"""A #string must have a body, even if it is empty.""", tipTemplate: r"""Try adding an empty body.""", withArguments: _withArgumentsExpectedClassOrMixinBody); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeExpectedClassOrMixinBody = const Code<Message Function(String string)>( "ExpectedClassOrMixinBody", templateExpectedClassOrMixinBody, index: 8); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedClassOrMixinBody(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeExpectedClassOrMixinBody, message: """A ${string} must have a body, even if it is empty.""", tip: """Try adding an empty body.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateExpectedDeclaration = const Template<Message Function(Token token)>( messageTemplate: r"""Expected a declaration, but got '#lexeme'.""", withArguments: _withArgumentsExpectedDeclaration); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExpectedDeclaration = const Code<Message Function(Token token)>( "ExpectedDeclaration", templateExpectedDeclaration, analyzerCodes: <String>["EXPECTED_EXECUTABLE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedDeclaration(Token token) { String lexeme = token.lexeme; return new Message(codeExpectedDeclaration, message: """Expected a declaration, but got '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedElseOrComma = messageExpectedElseOrComma; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedElseOrComma = const MessageCode( "ExpectedElseOrComma", index: 46, message: r"""Expected 'else' or comma."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(Token token)> templateExpectedEnumBody = const Template< Message Function(Token token)>( messageTemplate: r"""Expected a enum body, but got '#lexeme'.""", tipTemplate: r"""An enum definition must have a body with at least one constant name.""", withArguments: _withArgumentsExpectedEnumBody); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExpectedEnumBody = const Code<Message Function(Token token)>( "ExpectedEnumBody", templateExpectedEnumBody, analyzerCodes: <String>["MISSING_ENUM_BODY"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedEnumBody(Token token) { String lexeme = token.lexeme; return new Message(codeExpectedEnumBody, message: """Expected a enum body, but got '${lexeme}'.""", tip: """An enum definition must have a body with at least one constant name.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateExpectedFunctionBody = const Template<Message Function(Token token)>( messageTemplate: r"""Expected a function body, but got '#lexeme'.""", withArguments: _withArgumentsExpectedFunctionBody); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExpectedFunctionBody = const Code<Message Function(Token token)>( "ExpectedFunctionBody", templateExpectedFunctionBody, analyzerCodes: <String>["MISSING_FUNCTION_BODY"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedFunctionBody(Token token) { String lexeme = token.lexeme; return new Message(codeExpectedFunctionBody, message: """Expected a function body, but got '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedHexDigit = messageExpectedHexDigit; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedHexDigit = const MessageCode( "ExpectedHexDigit", analyzerCodes: <String>["MISSING_HEX_DIGIT"], message: r"""A hex digit (0-9 or A-F) must follow '0x'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateExpectedIdentifier = const Template<Message Function(Token token)>( messageTemplate: r"""Expected an identifier, but got '#lexeme'.""", withArguments: _withArgumentsExpectedIdentifier); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExpectedIdentifier = const Code<Message Function(Token token)>( "ExpectedIdentifier", templateExpectedIdentifier, analyzerCodes: <String>["MISSING_IDENTIFIER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedIdentifier(Token token) { String lexeme = token.lexeme; return new Message(codeExpectedIdentifier, message: """Expected an identifier, but got '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateExpectedInstead = const Template<Message Function(String string)>( messageTemplate: r"""Expected '#string' instead of this.""", withArguments: _withArgumentsExpectedInstead); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeExpectedInstead = const Code<Message Function(String string)>( "ExpectedInstead", templateExpectedInstead, index: 41); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedInstead(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeExpectedInstead, message: """Expected '${string}' instead of this.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedNamedArgument = messageExpectedNamedArgument; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedNamedArgument = const MessageCode( "ExpectedNamedArgument", analyzerCodes: <String>["EXTRA_POSITIONAL_ARGUMENTS"], message: r"""Expected named argument."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedOneExpression = messageExpectedOneExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedOneExpression = const MessageCode( "ExpectedOneExpression", message: r"""Expected one expression, but found additional input."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedOpenParens = messageExpectedOpenParens; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedOpenParens = const MessageCode("ExpectedOpenParens", message: r"""Expected '('."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedStatement = messageExpectedStatement; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedStatement = const MessageCode( "ExpectedStatement", index: 29, message: r"""Expected a statement."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateExpectedString = const Template<Message Function(Token token)>( messageTemplate: r"""Expected a String, but got '#lexeme'.""", withArguments: _withArgumentsExpectedString); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExpectedString = const Code<Message Function(Token token)>( "ExpectedString", templateExpectedString, analyzerCodes: <String>["EXPECTED_STRING_LITERAL"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedString(Token token) { String lexeme = token.lexeme; return new Message(codeExpectedString, message: """Expected a String, but got '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateExpectedToken = const Template<Message Function(String string)>( messageTemplate: r"""Expected to find '#string'.""", withArguments: _withArgumentsExpectedToken); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeExpectedToken = const Code<Message Function(String string)>( "ExpectedToken", templateExpectedToken, analyzerCodes: <String>["EXPECTED_TOKEN"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedToken(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeExpectedToken, message: """Expected to find '${string}'.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateExpectedType = const Template<Message Function(Token token)>( messageTemplate: r"""Expected a type, but got '#lexeme'.""", withArguments: _withArgumentsExpectedType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExpectedType = const Code<Message Function(Token token)>( "ExpectedType", templateExpectedType, analyzerCodes: <String>["EXPECTED_TYPE_NAME"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExpectedType(Token token) { String lexeme = token.lexeme; return new Message(codeExpectedType, message: """Expected a type, but got '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpectedUri = messageExpectedUri; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpectedUri = const MessageCode("ExpectedUri", message: r"""Expected a URI."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string)> templateExperimentNotEnabled = const Template< Message Function(String string)>( messageTemplate: r"""This requires the '#string' experiment to be enabled.""", tipTemplate: r"""Try enabling this experiment by adding it to the command line when compiling and running.""", withArguments: _withArgumentsExperimentNotEnabled); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeExperimentNotEnabled = const Code<Message Function(String string)>( "ExperimentNotEnabled", templateExperimentNotEnabled, index: 48); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExperimentNotEnabled(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeExperimentNotEnabled, message: """This requires the '${string}' experiment to be enabled.""", tip: """Try enabling this experiment by adding it to the command line when compiling and running.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExplicitExtensionArgumentMismatch = messageExplicitExtensionArgumentMismatch; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExplicitExtensionArgumentMismatch = const MessageCode( "ExplicitExtensionArgumentMismatch", message: r"""Explicit extension application requires exactly 1 positional argument."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExplicitExtensionAsExpression = messageExplicitExtensionAsExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExplicitExtensionAsExpression = const MessageCode( "ExplicitExtensionAsExpression", message: r"""Explicit extension application cannot be used as an expression."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExplicitExtensionAsLvalue = messageExplicitExtensionAsLvalue; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExplicitExtensionAsLvalue = const MessageCode( "ExplicitExtensionAsLvalue", message: r"""Explicit extension application cannot be a target for assignment."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, int count)> templateExplicitExtensionTypeArgumentMismatch = const Template< Message Function(String name, int count)>( messageTemplate: r"""Explicit extension application of extension '#name' takes '#count' type argument(s).""", withArguments: _withArgumentsExplicitExtensionTypeArgumentMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, int count)> codeExplicitExtensionTypeArgumentMismatch = const Code<Message Function(String name, int count)>( "ExplicitExtensionTypeArgumentMismatch", templateExplicitExtensionTypeArgumentMismatch, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExplicitExtensionTypeArgumentMismatch( String name, int count) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (count == null) throw 'No count provided'; return new Message(codeExplicitExtensionTypeArgumentMismatch, message: """Explicit extension application of extension '${name}' takes '${count}' type argument(s).""", arguments: {'name': name, 'count': count}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExportAfterPart = messageExportAfterPart; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExportAfterPart = const MessageCode("ExportAfterPart", index: 75, message: r"""Export directives must precede part directives.""", tip: r"""Try moving the export directives before the part directives."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_, Uri uri2_)> templateExportHidesExport = const Template<Message Function(String name, Uri uri_, Uri uri2_)>( messageTemplate: r"""Export of '#name' (from '#uri') hides export from '#uri2'.""", withArguments: _withArgumentsExportHidesExport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_, Uri uri2_)> codeExportHidesExport = const Code<Message Function(String name, Uri uri_, Uri uri2_)>( "ExportHidesExport", templateExportHidesExport, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExportHidesExport(String name, Uri uri_, Uri uri2_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); return new Message(codeExportHidesExport, message: """Export of '${name}' (from '${uri}') hides export from '${uri2}'.""", arguments: {'name': name, 'uri': uri_, 'uri2': uri2_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExpressionNotMetadata = messageExpressionNotMetadata; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExpressionNotMetadata = const MessageCode( "ExpressionNotMetadata", message: r"""This can't be used as metadata; metadata should be a reference to a compile-time constant variable, or a call to a constant constructor."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateExtendingEnum = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is an enum and can't be extended or implemented.""", withArguments: _withArgumentsExtendingEnum); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeExtendingEnum = const Code<Message Function(String name)>( "ExtendingEnum", templateExtendingEnum, analyzerCodes: <String>["EXTENDS_ENUM"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExtendingEnum(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeExtendingEnum, message: """'${name}' is an enum and can't be extended or implemented.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateExtendingRestricted = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is restricted and can't be extended or implemented.""", withArguments: _withArgumentsExtendingRestricted); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeExtendingRestricted = const Code<Message Function(String name)>( "ExtendingRestricted", templateExtendingRestricted, analyzerCodes: <String>["EXTENDS_DISALLOWED_CLASS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExtendingRestricted(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeExtendingRestricted, message: """'${name}' is restricted and can't be extended or implemented.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExtensionDeclaresAbstractMember = messageExtensionDeclaresAbstractMember; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExtensionDeclaresAbstractMember = const MessageCode( "ExtensionDeclaresAbstractMember", index: 94, message: r"""Extensions can't declare abstract members.""", tip: r"""Try providing an implementation for the member."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExtensionDeclaresConstructor = messageExtensionDeclaresConstructor; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExtensionDeclaresConstructor = const MessageCode( "ExtensionDeclaresConstructor", index: 92, message: r"""Extensions can't declare constructors.""", tip: r"""Try removing the constructor declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExtensionDeclaresInstanceField = messageExtensionDeclaresInstanceField; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExtensionDeclaresInstanceField = const MessageCode( "ExtensionDeclaresInstanceField", index: 93, message: r"""Extensions can't declare instance fields""", tip: r"""Try removing the field declaration or making it a static field"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateExtensionMemberConflictsWithObjectMember = const Template<Message Function(String name)>( messageTemplate: r"""This extension member conflicts with Object member '#name'.""", withArguments: _withArgumentsExtensionMemberConflictsWithObjectMember); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeExtensionMemberConflictsWithObjectMember = const Code<Message Function(String name)>( "ExtensionMemberConflictsWithObjectMember", templateExtensionMemberConflictsWithObjectMember, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExtensionMemberConflictsWithObjectMember(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeExtensionMemberConflictsWithObjectMember, message: """This extension member conflicts with Object member '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalClass = messageExternalClass; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalClass = const MessageCode("ExternalClass", index: 3, message: r"""Classes can't be declared to be 'external'.""", tip: r"""Try removing the keyword 'external'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalConstructorWithBody = messageExternalConstructorWithBody; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalConstructorWithBody = const MessageCode( "ExternalConstructorWithBody", index: 87, message: r"""External constructors can't have a body.""", tip: r"""Try removing the body of the constructor, or removing the keyword 'external'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalConstructorWithFieldInitializers = messageExternalConstructorWithFieldInitializers; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalConstructorWithFieldInitializers = const MessageCode("ExternalConstructorWithFieldInitializers", analyzerCodes: <String>["EXTERNAL_CONSTRUCTOR_WITH_FIELD_INITIALIZERS"], message: r"""An external constructor can't initialize fields.""", tip: r"""Try removing the field initializers, or removing the keyword 'external'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalEnum = messageExternalEnum; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalEnum = const MessageCode("ExternalEnum", index: 5, message: r"""Enums can't be declared to be 'external'.""", tip: r"""Try removing the keyword 'external'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalFactoryRedirection = messageExternalFactoryRedirection; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalFactoryRedirection = const MessageCode( "ExternalFactoryRedirection", index: 85, message: r"""A redirecting factory can't be external.""", tip: r"""Try removing the 'external' modifier."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalFactoryWithBody = messageExternalFactoryWithBody; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalFactoryWithBody = const MessageCode( "ExternalFactoryWithBody", index: 86, message: r"""External factories can't have a body.""", tip: r"""Try removing the body of the factory, or removing the keyword 'external'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalField = messageExternalField; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalField = const MessageCode("ExternalField", index: 50, message: r"""Fields can't be declared to be 'external'.""", tip: r"""Try removing the keyword 'external', or replacing the field by an external getter and/or setter."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalMethodWithBody = messageExternalMethodWithBody; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalMethodWithBody = const MessageCode( "ExternalMethodWithBody", index: 49, message: r"""An external or native method can't have a body."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeExternalTypedef = messageExternalTypedef; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageExternalTypedef = const MessageCode("ExternalTypedef", index: 76, message: r"""Typedefs can't be declared to be 'external'.""", tip: r"""Try removing the keyword 'external'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateExtraneousModifier = const Template<Message Function(Token token)>( messageTemplate: r"""Can't have modifier '#lexeme' here.""", tipTemplate: r"""Try removing '#lexeme'.""", withArguments: _withArgumentsExtraneousModifier); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeExtraneousModifier = const Code<Message Function(Token token)>( "ExtraneousModifier", templateExtraneousModifier, index: 77); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsExtraneousModifier(Token token) { String lexeme = token.lexeme; return new Message(codeExtraneousModifier, message: """Can't have modifier '${lexeme}' here.""", tip: """Try removing '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFactoryNotSync = messageFactoryNotSync; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFactoryNotSync = const MessageCode("FactoryNotSync", analyzerCodes: <String>["NON_SYNC_FACTORY"], message: r"""Factory bodies can't use 'async', 'async*', or 'sync*'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFactoryTopLevelDeclaration = messageFactoryTopLevelDeclaration; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFactoryTopLevelDeclaration = const MessageCode( "FactoryTopLevelDeclaration", index: 78, message: r"""Top-level declarations can't be declared to be 'factory'.""", tip: r"""Try removing the keyword 'factory'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateFastaCLIArgumentRequired = const Template<Message Function(String name)>( messageTemplate: r"""Expected value after '#name'.""", withArguments: _withArgumentsFastaCLIArgumentRequired); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFastaCLIArgumentRequired = const Code<Message Function(String name)>( "FastaCLIArgumentRequired", templateFastaCLIArgumentRequired, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFastaCLIArgumentRequired(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFastaCLIArgumentRequired, message: """Expected value after '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFastaUsageLong = messageFastaUsageLong; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFastaUsageLong = const MessageCode("FastaUsageLong", message: r"""Supported options: -o <file>, --output=<file> Generate the output into <file>. -h, /h, /?, --help Display this message (add -v for information about all options). -v, --verbose Display verbose information. -Dname -Dname=value Define an environment variable in the compile-time environment. --no-defines Ignore all -D options and leave environment constants unevaluated. -- Stop option parsing, the rest of the command line is assumed to be file names or arguments to the Dart program. --packages=<file> Use package resolution configuration <file>, which should contain a mapping of package names to paths. --platform=<file> Read the SDK platform from <file>, which should be in Dill/Kernel IR format and contain the Dart SDK. --target=dart2js|dart2js_server|dart_runner|dartdevc|flutter|flutter_runner|none|vm Specify the target configuration. --enable-asserts Check asserts in initializers during constant evaluation. --verify Check that the generated output is free of various problems. This is mostly useful for developers of this compiler or Kernel transformations. --dump-ir Print compiled libraries in Kernel source notation. --omit-platform Exclude the platform from the serialized dill file. --bytecode Generate bytecode. Supported only for SDK platform compilation. --exclude-source Do not include source code in the dill file. --compile-sdk=<sdk> Compile the SDK from scratch instead of reading it from a .dill file (see --platform). --sdk=<sdk> Location of the SDK sources for use when compiling additional platform libraries. --supermixin Ignored for now. --single-root-scheme=String --single-root-base=<dir> Specify a custom URI scheme and a location on disk where such URIs are mapped to. When specified, the compiler can be invoked with inputs using the custom URI scheme. The compiler can ignore the exact location of files on disk and as a result to produce output that is independent of the absolute location of files on disk. This is mostly useful for integrating with build systems. --fatal=errors --fatal=warnings Makes messages of the given kinds fatal, that is, immediately stop the compiler with a non-zero exit-code. In --verbose mode, also display an internal stack trace from the compiler. Multiple kinds can be separated by commas, for example, --fatal=errors,warnings. --enable-experiment=<flag> Enable or disable an experimental flag, used to guard features currently in development. Prefix an experiment name with 'no-' to disable it. Multiple experiments can be separated by commas."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFastaUsageShort = messageFastaUsageShort; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFastaUsageShort = const MessageCode("FastaUsageShort", message: r"""Frequently used options: -o <file> Generate the output into <file>. -h Display this message (add -v for information about all options)."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(DartType _type, DartType _type2)> templateFfiDartTypeMismatch = const Template<Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""Expected '#type' to be a subtype of '#type2'.""", withArguments: _withArgumentsFfiDartTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeFfiDartTypeMismatch = const Code<Message Function(DartType _type, DartType _type2)>( "FfiDartTypeMismatch", templateFfiDartTypeMismatch, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiDartTypeMismatch(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeFfiDartTypeMismatch, message: """Expected '${type}' to be a subtype of '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFfiExceptionalReturnNull = messageFfiExceptionalReturnNull; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFfiExceptionalReturnNull = const MessageCode( "FfiExceptionalReturnNull", message: r"""Exceptional return value must not be null."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFfiExpectedConstant = messageFfiExpectedConstant; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFfiExpectedConstant = const MessageCode( "FfiExpectedConstant", message: r"""Exceptional return value must be a constant."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type)> templateFfiExpectedExceptionalReturn = const Template< Message Function(DartType _type)>( messageTemplate: r"""Expected an exceptional return value for a native callback returning '#type'.""", withArguments: _withArgumentsFfiExpectedExceptionalReturn); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeFfiExpectedExceptionalReturn = const Code<Message Function(DartType _type)>( "FfiExpectedExceptionalReturn", templateFfiExpectedExceptionalReturn, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiExpectedExceptionalReturn(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeFfiExpectedExceptionalReturn, message: """Expected an exceptional return value for a native callback returning '${type}'.""" + labeler.originMessages, arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type)> templateFfiExpectedNoExceptionalReturn = const Template< Message Function(DartType _type)>( messageTemplate: r"""Exceptional return value cannot be provided for a native callback returning '#type'.""", withArguments: _withArgumentsFfiExpectedNoExceptionalReturn); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeFfiExpectedNoExceptionalReturn = const Code<Message Function(DartType _type)>( "FfiExpectedNoExceptionalReturn", templateFfiExpectedNoExceptionalReturn, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiExpectedNoExceptionalReturn(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeFfiExpectedNoExceptionalReturn, message: """Exceptional return value cannot be provided for a native callback returning '${type}'.""" + labeler.originMessages, arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateFfiExtendsOrImplementsSealedClass = const Template<Message Function(String name)>( messageTemplate: r"""Class '#name' cannot be extended or implemented.""", withArguments: _withArgumentsFfiExtendsOrImplementsSealedClass); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFfiExtendsOrImplementsSealedClass = const Code<Message Function(String name)>( "FfiExtendsOrImplementsSealedClass", templateFfiExtendsOrImplementsSealedClass, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiExtendsOrImplementsSealedClass(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFfiExtendsOrImplementsSealedClass, message: """Class '${name}' cannot be extended or implemented.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(String name)> templateFfiFieldAnnotation = const Template< Message Function(String name)>( messageTemplate: r"""Field '#name' requires exactly one annotation to declare its native type, which cannot be Void. dart:ffi Structs cannot have regular Dart fields.""", withArguments: _withArgumentsFfiFieldAnnotation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFfiFieldAnnotation = const Code<Message Function(String name)>( "FfiFieldAnnotation", templateFfiFieldAnnotation, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiFieldAnnotation(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFfiFieldAnnotation, message: """Field '${name}' requires exactly one annotation to declare its native type, which cannot be Void. dart:ffi Structs cannot have regular Dart fields.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(String name)> templateFfiFieldInitializer = const Template< Message Function(String name)>( messageTemplate: r"""Field '#name' is a dart:ffi Pointer to a struct field and therefore cannot be initialized before constructor execution.""", withArguments: _withArgumentsFfiFieldInitializer); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFfiFieldInitializer = const Code<Message Function(String name)>( "FfiFieldInitializer", templateFfiFieldInitializer, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiFieldInitializer(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFfiFieldInitializer, message: """Field '${name}' is a dart:ffi Pointer to a struct field and therefore cannot be initialized before constructor execution.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateFfiFieldNoAnnotation = const Template< Message Function(String name)>( messageTemplate: r"""Field '#name' requires no annotation to declare its native type, it is a Pointer which is represented by the same type in Dart and native code.""", withArguments: _withArgumentsFfiFieldNoAnnotation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFfiFieldNoAnnotation = const Code<Message Function(String name)>( "FfiFieldNoAnnotation", templateFfiFieldNoAnnotation, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiFieldNoAnnotation(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFfiFieldNoAnnotation, message: """Field '${name}' requires no annotation to declare its native type, it is a Pointer which is represented by the same type in Dart and native code.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(String name)> templateFfiNotStatic = const Template< Message Function(String name)>( messageTemplate: r"""#name expects a static function as parameter. dart:ffi only supports calling static Dart functions from native code.""", withArguments: _withArgumentsFfiNotStatic); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFfiNotStatic = const Code<Message Function(String name)>( "FfiNotStatic", templateFfiNotStatic, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiNotStatic(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFfiNotStatic, message: """${name} expects a static function as parameter. dart:ffi only supports calling static Dart functions from native code.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateFfiStructGeneric = const Template<Message Function(String name)>( messageTemplate: r"""Struct '#name' should not be generic.""", withArguments: _withArgumentsFfiStructGeneric); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFfiStructGeneric = const Code<Message Function(String name)>( "FfiStructGeneric", templateFfiStructGeneric, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiStructGeneric(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFfiStructGeneric, message: """Struct '${name}' should not be generic.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(DartType _type)> templateFfiTypeInvalid = const Template< Message Function(DartType _type)>( messageTemplate: r"""Expected type '#type' to be a valid and instantiated subtype of 'NativeType'.""", withArguments: _withArgumentsFfiTypeInvalid); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeFfiTypeInvalid = const Code<Message Function(DartType _type)>( "FfiTypeInvalid", templateFfiTypeInvalid, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiTypeInvalid(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeFfiTypeInvalid, message: """Expected type '${type}' to be a valid and instantiated subtype of 'NativeType'.""" + labeler.originMessages, arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, DartType _type3)> templateFfiTypeMismatch = const Template< Message Function(DartType _type, DartType _type2, DartType _type3)>( messageTemplate: r"""Expected type '#type' to be '#type2', which is the Dart type corresponding to '#type3'.""", withArguments: _withArgumentsFfiTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2, DartType _type3)> codeFfiTypeMismatch = const Code< Message Function(DartType _type, DartType _type2, DartType _type3)>( "FfiTypeMismatch", templateFfiTypeMismatch, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiTypeMismatch( DartType _type, DartType _type2, DartType _type3) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); List<Object> type3Parts = labeler.labelType(_type3); String type = typeParts.join(); String type2 = type2Parts.join(); String type3 = type3Parts.join(); return new Message(codeFfiTypeMismatch, message: """Expected type '${type}' to be '${type2}', which is the Dart type corresponding to '${type3}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2, 'type3': _type3}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type)> templateFfiTypeUnsized = const Template< Message Function(String name, DartType _type)>( messageTemplate: r"""Method '#name' cannot be called on something of type '#type' as this type is unsized.""", withArguments: _withArgumentsFfiTypeUnsized); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, DartType _type)> codeFfiTypeUnsized = const Code<Message Function(String name, DartType _type)>( "FfiTypeUnsized", templateFfiTypeUnsized, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiTypeUnsized(String name, DartType _type) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeFfiTypeUnsized, message: """Method '${name}' cannot be called on something of type '${type}' as this type is unsized.""" + labeler.originMessages, arguments: {'name': name, 'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateFfiWrongStructInheritance = const Template<Message Function(String name)>( messageTemplate: r"""Struct '#name' must inherit from 'Struct<#name>'.""", withArguments: _withArgumentsFfiWrongStructInheritance); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFfiWrongStructInheritance = const Code<Message Function(String name)>( "FfiWrongStructInheritance", templateFfiWrongStructInheritance, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFfiWrongStructInheritance(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFfiWrongStructInheritance, message: """Struct '${name}' must inherit from 'Struct<${name}>'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFieldInitializedOutsideDeclaringClass = messageFieldInitializedOutsideDeclaringClass; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFieldInitializedOutsideDeclaringClass = const MessageCode( "FieldInitializedOutsideDeclaringClass", index: 88, message: r"""A field can only be initialized in its declaring class""", tip: r"""Try passing a value into the superclass constructor, or moving the initialization into the constructor body."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFieldInitializerOutsideConstructor = messageFieldInitializerOutsideConstructor; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFieldInitializerOutsideConstructor = const MessageCode( "FieldInitializerOutsideConstructor", index: 79, message: r"""Field formal parameters can only be used in a constructor.""", tip: r"""Try removing 'this.'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFinalAndCovariant = messageFinalAndCovariant; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFinalAndCovariant = const MessageCode( "FinalAndCovariant", index: 80, message: r"""Members can't be declared to be both 'final' and 'covariant'.""", tip: r"""Try removing either the 'final' or 'covariant' keyword."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFinalAndVar = messageFinalAndVar; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFinalAndVar = const MessageCode("FinalAndVar", index: 81, message: r"""Members can't be declared to be both 'final' and 'var'.""", tip: r"""Try removing the keyword 'var'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateFinalFieldNotInitialized = const Template< Message Function(String name)>( messageTemplate: r"""Final field '#name' is not initialized.""", tipTemplate: r"""Try to initialize the field in the declaration or in every constructor.""", withArguments: _withArgumentsFinalFieldNotInitialized); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFinalFieldNotInitialized = const Code<Message Function(String name)>( "FinalFieldNotInitialized", templateFinalFieldNotInitialized, analyzerCodes: <String>["FINAL_NOT_INITIALIZED"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFinalFieldNotInitialized(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFinalFieldNotInitialized, message: """Final field '${name}' is not initialized.""", tip: """Try to initialize the field in the declaration or in every constructor.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateFinalFieldNotInitializedByConstructor = const Template< Message Function(String name)>( messageTemplate: r"""Final field '#name' is not initialized by this constructor.""", tipTemplate: r"""Try to initialize the field using an initializing formal or a field initializer.""", withArguments: _withArgumentsFinalFieldNotInitializedByConstructor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFinalFieldNotInitializedByConstructor = const Code<Message Function(String name)>( "FinalFieldNotInitializedByConstructor", templateFinalFieldNotInitializedByConstructor, analyzerCodes: <String>["FINAL_NOT_INITIALIZED_CONSTRUCTOR_1"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFinalFieldNotInitializedByConstructor(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFinalFieldNotInitializedByConstructor, message: """Final field '${name}' is not initialized by this constructor.""", tip: """Try to initialize the field using an initializing formal or a field initializer.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateFinalFieldWithoutInitializer = const Template< Message Function(String name)>( messageTemplate: r"""The final variable '#name' must be initialized.""", tipTemplate: r"""Try adding an initializer ('= expression') to the declaration.""", withArguments: _withArgumentsFinalFieldWithoutInitializer); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFinalFieldWithoutInitializer = const Code<Message Function(String name)>( "FinalFieldWithoutInitializer", templateFinalFieldWithoutInitializer, analyzerCodes: <String>["FINAL_NOT_INITIALIZED"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFinalFieldWithoutInitializer(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFinalFieldWithoutInitializer, message: """The final variable '${name}' must be initialized.""", tip: """Try adding an initializer ('= expression') to the declaration.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateFinalInstanceVariableAlreadyInitialized = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is a final instance variable that has already been initialized.""", withArguments: _withArgumentsFinalInstanceVariableAlreadyInitialized); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFinalInstanceVariableAlreadyInitialized = const Code<Message Function(String name)>( "FinalInstanceVariableAlreadyInitialized", templateFinalInstanceVariableAlreadyInitialized, analyzerCodes: <String>["FINAL_INITIALIZED_MULTIPLE_TIMES"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFinalInstanceVariableAlreadyInitialized(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFinalInstanceVariableAlreadyInitialized, message: """'${name}' is a final instance variable that has already been initialized.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateFinalInstanceVariableAlreadyInitializedCause = const Template<Message Function(String name)>( messageTemplate: r"""'#name' was initialized here.""", withArguments: _withArgumentsFinalInstanceVariableAlreadyInitializedCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeFinalInstanceVariableAlreadyInitializedCause = const Code<Message Function(String name)>( "FinalInstanceVariableAlreadyInitializedCause", templateFinalInstanceVariableAlreadyInitializedCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsFinalInstanceVariableAlreadyInitializedCause( String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeFinalInstanceVariableAlreadyInitializedCause, message: """'${name}' was initialized here.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateForInLoopElementTypeNotAssignable = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""A value of type '#type' can't be assigned to a variable of type '#type2'.""", tipTemplate: r"""Try changing the type of the variable.""", withArguments: _withArgumentsForInLoopElementTypeNotAssignable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeForInLoopElementTypeNotAssignable = const Code<Message Function(DartType _type, DartType _type2)>( "ForInLoopElementTypeNotAssignable", templateForInLoopElementTypeNotAssignable, analyzerCodes: <String>["FOR_IN_OF_INVALID_ELEMENT_TYPE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsForInLoopElementTypeNotAssignable( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeForInLoopElementTypeNotAssignable, message: """A value of type '${type}' can't be assigned to a variable of type '${type2}'.""" + labeler.originMessages, tip: """Try changing the type of the variable.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeForInLoopExactlyOneVariable = messageForInLoopExactlyOneVariable; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageForInLoopExactlyOneVariable = const MessageCode( "ForInLoopExactlyOneVariable", message: r"""A for-in loop can't have more than one loop variable."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeForInLoopNotAssignable = messageForInLoopNotAssignable; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageForInLoopNotAssignable = const MessageCode( "ForInLoopNotAssignable", message: r"""Can't assign to this, so it can't be used in a for-in loop."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateForInLoopTypeNotIterable = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The type '#type' used in the 'for' loop must implement '#type2'.""", withArguments: _withArgumentsForInLoopTypeNotIterable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeForInLoopTypeNotIterable = const Code<Message Function(DartType _type, DartType _type2)>( "ForInLoopTypeNotIterable", templateForInLoopTypeNotIterable, analyzerCodes: <String>["FOR_IN_OF_INVALID_TYPE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsForInLoopTypeNotIterable( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeForInLoopTypeNotIterable, message: """The type '${type}' used in the 'for' loop must implement '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeForInLoopWithConstVariable = messageForInLoopWithConstVariable; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageForInLoopWithConstVariable = const MessageCode( "ForInLoopWithConstVariable", analyzerCodes: <String>["FOR_IN_WITH_CONST_VARIABLE"], message: r"""A for-in loop-variable can't be 'const'.""", tip: r"""Try removing the 'const' modifier."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFunctionTypeDefaultValue = messageFunctionTypeDefaultValue; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFunctionTypeDefaultValue = const MessageCode( "FunctionTypeDefaultValue", analyzerCodes: <String>["DEFAULT_VALUE_IN_FUNCTION_TYPE"], message: r"""Can't have a default value in a function type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeFunctionTypedParameterVar = messageFunctionTypedParameterVar; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageFunctionTypedParameterVar = const MessageCode( "FunctionTypedParameterVar", analyzerCodes: <String>["FUNCTION_TYPED_PARAMETER_VAR"], message: r"""Function-typed parameters can't specify 'const', 'final' or 'var' in place of a return type.""", tip: r"""Try replacing the keyword with a return type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeGeneratorReturnsValue = messageGeneratorReturnsValue; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageGeneratorReturnsValue = const MessageCode( "GeneratorReturnsValue", analyzerCodes: <String>["RETURN_IN_GENERATOR"], message: r"""'sync*' and 'async*' can't return a value."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeGenericFunctionTypeInBound = messageGenericFunctionTypeInBound; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageGenericFunctionTypeInBound = const MessageCode( "GenericFunctionTypeInBound", analyzerCodes: <String>["GENERIC_FUNCTION_TYPE_CANNOT_BE_BOUND"], message: r"""Type variables can't have generic function types in their bounds."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(DartType _type)> templateGenericFunctionTypeInferredAsActualTypeArgument = const Template<Message Function(DartType _type)>( messageTemplate: r"""Generic function type '#type' inferred as a type argument.""", tipTemplate: r"""Try providing a non-generic function type explicitly.""", withArguments: _withArgumentsGenericFunctionTypeInferredAsActualTypeArgument); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeGenericFunctionTypeInferredAsActualTypeArgument = const Code<Message Function(DartType _type)>( "GenericFunctionTypeInferredAsActualTypeArgument", templateGenericFunctionTypeInferredAsActualTypeArgument, analyzerCodes: <String>["GENERIC_FUNCTION_CANNOT_BE_TYPE_ARGUMENT"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsGenericFunctionTypeInferredAsActualTypeArgument( DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeGenericFunctionTypeInferredAsActualTypeArgument, message: """Generic function type '${type}' inferred as a type argument.""" + labeler.originMessages, tip: """Try providing a non-generic function type explicitly.""", arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeGenericFunctionTypeUsedAsActualTypeArgument = messageGenericFunctionTypeUsedAsActualTypeArgument; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageGenericFunctionTypeUsedAsActualTypeArgument = const MessageCode("GenericFunctionTypeUsedAsActualTypeArgument", analyzerCodes: <String>["GENERIC_FUNCTION_CANNOT_BE_TYPE_ARGUMENT"], message: r"""A generic function type can't be used as a type argument.""", tip: r"""Try using a non-generic function type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateGetterNotFound = const Template<Message Function(String name)>( messageTemplate: r"""Getter not found: '#name'.""", withArguments: _withArgumentsGetterNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeGetterNotFound = const Code<Message Function(String name)>( "GetterNotFound", templateGetterNotFound, analyzerCodes: <String>["UNDEFINED_GETTER"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsGetterNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeGetterNotFound, message: """Getter not found: '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeGetterWithFormals = messageGetterWithFormals; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageGetterWithFormals = const MessageCode( "GetterWithFormals", analyzerCodes: <String>["GETTER_WITH_PARAMETERS"], message: r"""A getter can't have formal parameters.""", tip: r"""Try removing '(...)'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeIllegalAssignmentToNonAssignable = messageIllegalAssignmentToNonAssignable; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageIllegalAssignmentToNonAssignable = const MessageCode( "IllegalAssignmentToNonAssignable", index: 45, message: r"""Illegal assignment to non-assignable expression."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeIllegalAsyncGeneratorReturnType = messageIllegalAsyncGeneratorReturnType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageIllegalAsyncGeneratorReturnType = const MessageCode( "IllegalAsyncGeneratorReturnType", analyzerCodes: <String>["ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE"], message: r"""Functions marked 'async*' must have a return type assignable to 'Stream'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeIllegalAsyncGeneratorVoidReturnType = messageIllegalAsyncGeneratorVoidReturnType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageIllegalAsyncGeneratorVoidReturnType = const MessageCode("IllegalAsyncGeneratorVoidReturnType", message: r"""Functions marked 'async*' can't have return type 'void'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeIllegalAsyncReturnType = messageIllegalAsyncReturnType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageIllegalAsyncReturnType = const MessageCode( "IllegalAsyncReturnType", analyzerCodes: <String>["ILLEGAL_ASYNC_RETURN_TYPE"], message: r"""Functions marked 'async' must have a return type assignable to 'Future'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateIllegalMixin = const Template<Message Function(String name)>( messageTemplate: r"""The type '#name' can't be mixed in.""", withArguments: _withArgumentsIllegalMixin); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeIllegalMixin = const Code<Message Function(String name)>( "IllegalMixin", templateIllegalMixin, analyzerCodes: <String>["ILLEGAL_MIXIN"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIllegalMixin(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeIllegalMixin, message: """The type '${name}' can't be mixed in.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateIllegalMixinDueToConstructors = const Template<Message Function(String name)>( messageTemplate: r"""Can't use '#name' as a mixin because it has constructors.""", withArguments: _withArgumentsIllegalMixinDueToConstructors); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeIllegalMixinDueToConstructors = const Code<Message Function(String name)>( "IllegalMixinDueToConstructors", templateIllegalMixinDueToConstructors, analyzerCodes: <String>["MIXIN_DECLARES_CONSTRUCTOR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIllegalMixinDueToConstructors(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeIllegalMixinDueToConstructors, message: """Can't use '${name}' as a mixin because it has constructors.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateIllegalMixinDueToConstructorsCause = const Template<Message Function(String name)>( messageTemplate: r"""This constructor prevents using '#name' as a mixin.""", withArguments: _withArgumentsIllegalMixinDueToConstructorsCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeIllegalMixinDueToConstructorsCause = const Code<Message Function(String name)>( "IllegalMixinDueToConstructorsCause", templateIllegalMixinDueToConstructorsCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIllegalMixinDueToConstructorsCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeIllegalMixinDueToConstructorsCause, message: """This constructor prevents using '${name}' as a mixin.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(DartType _type)> templateIllegalRecursiveType = const Template<Message Function(DartType _type)>( messageTemplate: r"""Illegal recursive type '#type'.""", withArguments: _withArgumentsIllegalRecursiveType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeIllegalRecursiveType = const Code<Message Function(DartType _type)>( "IllegalRecursiveType", templateIllegalRecursiveType, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIllegalRecursiveType(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeIllegalRecursiveType, message: """Illegal recursive type '${type}'.""" + labeler.originMessages, arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeIllegalSyncGeneratorReturnType = messageIllegalSyncGeneratorReturnType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageIllegalSyncGeneratorReturnType = const MessageCode( "IllegalSyncGeneratorReturnType", analyzerCodes: <String>["ILLEGAL_SYNC_GENERATOR_RETURN_TYPE"], message: r"""Functions marked 'sync*' must have a return type assignable to 'Iterable'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeIllegalSyncGeneratorVoidReturnType = messageIllegalSyncGeneratorVoidReturnType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageIllegalSyncGeneratorVoidReturnType = const MessageCode( "IllegalSyncGeneratorVoidReturnType", message: r"""Functions marked 'sync*' can't have return type 'void'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeImplementsBeforeExtends = messageImplementsBeforeExtends; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageImplementsBeforeExtends = const MessageCode( "ImplementsBeforeExtends", index: 44, message: r"""The extends clause must be before the implements clause.""", tip: r"""Try moving the extends clause before the implements clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeImplementsBeforeOn = messageImplementsBeforeOn; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageImplementsBeforeOn = const MessageCode( "ImplementsBeforeOn", index: 43, message: r"""The on clause must be before the implements clause.""", tip: r"""Try moving the on clause before the implements clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeImplementsBeforeWith = messageImplementsBeforeWith; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageImplementsBeforeWith = const MessageCode( "ImplementsBeforeWith", index: 42, message: r"""The with clause must be before the implements clause.""", tip: r"""Try moving the with clause before the implements clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeImplementsFutureOr = messageImplementsFutureOr; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageImplementsFutureOr = const MessageCode( "ImplementsFutureOr", message: r"""'FutureOr' can't be used in an 'implements' clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, int count)> templateImplementsRepeated = const Template<Message Function(String name, int count)>( messageTemplate: r"""'#name' can only be implemented once.""", tipTemplate: r"""Try removing #count of the occurrences.""", withArguments: _withArgumentsImplementsRepeated); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, int count)> codeImplementsRepeated = const Code<Message Function(String name, int count)>( "ImplementsRepeated", templateImplementsRepeated, analyzerCodes: <String>["IMPLEMENTS_REPEATED"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsImplementsRepeated(String name, int count) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (count == null) throw 'No count provided'; return new Message(codeImplementsRepeated, message: """'${name}' can only be implemented once.""", tip: """Try removing ${count} of the occurrences.""", arguments: {'name': name, 'count': count}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateImplementsSuperClass = const Template< Message Function(String name)>( messageTemplate: r"""'#name' can't be used in both 'extends' and 'implements' clauses.""", tipTemplate: r"""Try removing one of the occurrences.""", withArguments: _withArgumentsImplementsSuperClass); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeImplementsSuperClass = const Code<Message Function(String name)>( "ImplementsSuperClass", templateImplementsSuperClass, analyzerCodes: <String>["IMPLEMENTS_SUPER_CLASS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsImplementsSuperClass(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeImplementsSuperClass, message: """'${name}' can't be used in both 'extends' and 'implements' clauses.""", tip: """Try removing one of the occurrences.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type)> templateImplicitCallOfNonMethod = const Template< Message Function(DartType _type)>( messageTemplate: r"""Cannot invoke an instance of '#type' because it declares 'call' to be something other than a method.""", tipTemplate: r"""Try changing 'call' to a method or explicitly invoke 'call'.""", withArguments: _withArgumentsImplicitCallOfNonMethod); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeImplicitCallOfNonMethod = const Code<Message Function(DartType _type)>( "ImplicitCallOfNonMethod", templateImplicitCallOfNonMethod, analyzerCodes: <String>["IMPLICIT_CALL_OF_NON_METHOD"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsImplicitCallOfNonMethod(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeImplicitCallOfNonMethod, message: """Cannot invoke an instance of '${type}' because it declares 'call' to be something other than a method.""" + labeler.originMessages, tip: """Try changing 'call' to a method or explicitly invoke 'call'.""", arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2, String name3)> templateImplicitMixinOverride = const Template< Message Function(String name, String name2, String name3)>( messageTemplate: r"""Applying the mixin '#name' to '#name2' introduces an erroneous override of '#name3'.""", withArguments: _withArgumentsImplicitMixinOverride); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2, String name3)> codeImplicitMixinOverride = const Code<Message Function(String name, String name2, String name3)>( "ImplicitMixinOverride", templateImplicitMixinOverride, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsImplicitMixinOverride( String name, String name2, String name3) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); if (name3.isEmpty) throw 'No name provided'; name3 = demangleMixinApplicationName(name3); return new Message(codeImplicitMixinOverride, message: """Applying the mixin '${name}' to '${name2}' introduces an erroneous override of '${name3}'.""", arguments: {'name': name, 'name2': name2, 'name3': name3}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeImportAfterPart = messageImportAfterPart; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageImportAfterPart = const MessageCode("ImportAfterPart", index: 10, message: r"""Import directives must precede part directives.""", tip: r"""Try moving the import directives before the part directives."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_, Uri uri2_)> templateImportHidesImport = const Template<Message Function(String name, Uri uri_, Uri uri2_)>( messageTemplate: r"""Import of '#name' (from '#uri') hides import from '#uri2'.""", withArguments: _withArgumentsImportHidesImport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_, Uri uri2_)> codeImportHidesImport = const Code<Message Function(String name, Uri uri_, Uri uri2_)>( "ImportHidesImport", templateImportHidesImport, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsImportHidesImport(String name, Uri uri_, Uri uri2_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); return new Message(codeImportHidesImport, message: """Import of '${name}' (from '${uri}') hides import from '${uri2}'.""", arguments: {'name': name, 'uri': uri_, 'uri2': uri2_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateIncompatibleRedirecteeFunctionType = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The constructor function type '#type' isn't a subtype of '#type2'.""", withArguments: _withArgumentsIncompatibleRedirecteeFunctionType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeIncompatibleRedirecteeFunctionType = const Code<Message Function(DartType _type, DartType _type2)>( "IncompatibleRedirecteeFunctionType", templateIncompatibleRedirecteeFunctionType, analyzerCodes: <String>["REDIRECT_TO_INVALID_TYPE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncompatibleRedirecteeFunctionType( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeIncompatibleRedirecteeFunctionType, message: """The constructor function type '${type}' isn't a subtype of '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, String name, String name2)> templateIncorrectTypeArgument = const Template< Message Function( DartType _type, DartType _type2, String name, String name2)>( messageTemplate: r"""Type argument '#type' doesn't conform to the bound '#type2' of the type variable '#name' on '#name2'.""", tipTemplate: r"""Try changing type arguments so that they conform to the bounds.""", withArguments: _withArgumentsIncorrectTypeArgument); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function( DartType _type, DartType _type2, String name, String name2)> codeIncorrectTypeArgument = const Code< Message Function( DartType _type, DartType _type2, String name, String name2)>( "IncorrectTypeArgument", templateIncorrectTypeArgument, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncorrectTypeArgument( DartType _type, DartType _type2, String name, String name2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeIncorrectTypeArgument, message: """Type argument '${type}' doesn't conform to the bound '${type2}' of the type variable '${name}' on '${name2}'.""" + labeler.originMessages, tip: """Try changing type arguments so that they conform to the bounds.""", arguments: { 'type': _type, 'type2': _type2, 'name': name, 'name2': name2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, String name, String name2)> templateIncorrectTypeArgumentInReturnType = const Template< Message Function( DartType _type, DartType _type2, String name, String name2)>( messageTemplate: r"""Type argument '#type' doesn't conform to the bound '#type2' of the type variable '#name' on '#name2' in the return type.""", tipTemplate: r"""Try changing type arguments so that they conform to the bounds.""", withArguments: _withArgumentsIncorrectTypeArgumentInReturnType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function( DartType _type, DartType _type2, String name, String name2)> codeIncorrectTypeArgumentInReturnType = const Code< Message Function( DartType _type, DartType _type2, String name, String name2)>( "IncorrectTypeArgumentInReturnType", templateIncorrectTypeArgumentInReturnType, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncorrectTypeArgumentInReturnType( DartType _type, DartType _type2, String name, String name2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeIncorrectTypeArgumentInReturnType, message: """Type argument '${type}' doesn't conform to the bound '${type2}' of the type variable '${name}' on '${name2}' in the return type.""" + labeler.originMessages, tip: """Try changing type arguments so that they conform to the bounds.""", arguments: { 'type': _type, 'type2': _type2, 'name': name, 'name2': name2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, String name, String name2, String name3, String name4)> templateIncorrectTypeArgumentInSupertype = const Template< Message Function(DartType _type, DartType _type2, String name, String name2, String name3, String name4)>( messageTemplate: r"""Type argument '#type' doesn't conform to the bound '#type2' of the type variable '#name' on '#name2' in the supertype '#name3' of class '#name4'.""", tipTemplate: r"""Try changing type arguments so that they conform to the bounds.""", withArguments: _withArgumentsIncorrectTypeArgumentInSupertype); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(DartType _type, DartType _type2, String name, String name2, String name3, String name4)> codeIncorrectTypeArgumentInSupertype = const Code< Message Function(DartType _type, DartType _type2, String name, String name2, String name3, String name4)>( "IncorrectTypeArgumentInSupertype", templateIncorrectTypeArgumentInSupertype, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncorrectTypeArgumentInSupertype(DartType _type, DartType _type2, String name, String name2, String name3, String name4) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); if (name3.isEmpty) throw 'No name provided'; name3 = demangleMixinApplicationName(name3); if (name4.isEmpty) throw 'No name provided'; name4 = demangleMixinApplicationName(name4); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeIncorrectTypeArgumentInSupertype, message: """Type argument '${type}' doesn't conform to the bound '${type2}' of the type variable '${name}' on '${name2}' in the supertype '${name3}' of class '${name4}'.""" + labeler.originMessages, tip: """Try changing type arguments so that they conform to the bounds.""", arguments: { 'type': _type, 'type2': _type2, 'name': name, 'name2': name2, 'name3': name3, 'name4': name4 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, String name, String name2, String name3, String name4)> templateIncorrectTypeArgumentInSupertypeInferred = const Template< Message Function( DartType _type, DartType _type2, String name, String name2, String name3, String name4)>( messageTemplate: r"""Inferred type argument '#type' doesn't conform to the bound '#type2' of the type variable '#name' on '#name2' in the supertype '#name3' of class '#name4'.""", tipTemplate: r"""Try specifying type arguments explicitly so that they conform to the bounds.""", withArguments: _withArgumentsIncorrectTypeArgumentInSupertypeInferred); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(DartType _type, DartType _type2, String name, String name2, String name3, String name4)> codeIncorrectTypeArgumentInSupertypeInferred = const Code< Message Function(DartType _type, DartType _type2, String name, String name2, String name3, String name4)>( "IncorrectTypeArgumentInSupertypeInferred", templateIncorrectTypeArgumentInSupertypeInferred, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncorrectTypeArgumentInSupertypeInferred(DartType _type, DartType _type2, String name, String name2, String name3, String name4) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); if (name3.isEmpty) throw 'No name provided'; name3 = demangleMixinApplicationName(name3); if (name4.isEmpty) throw 'No name provided'; name4 = demangleMixinApplicationName(name4); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeIncorrectTypeArgumentInSupertypeInferred, message: """Inferred type argument '${type}' doesn't conform to the bound '${type2}' of the type variable '${name}' on '${name2}' in the supertype '${name3}' of class '${name4}'.""" + labeler.originMessages, tip: """Try specifying type arguments explicitly so that they conform to the bounds.""", arguments: { 'type': _type, 'type2': _type2, 'name': name, 'name2': name2, 'name3': name3, 'name4': name4 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, String name, String name2)> templateIncorrectTypeArgumentInferred = const Template< Message Function( DartType _type, DartType _type2, String name, String name2)>( messageTemplate: r"""Inferred type argument '#type' doesn't conform to the bound '#type2' of the type variable '#name' on '#name2'.""", tipTemplate: r"""Try specifying type arguments explicitly so that they conform to the bounds.""", withArguments: _withArgumentsIncorrectTypeArgumentInferred); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function( DartType _type, DartType _type2, String name, String name2)> codeIncorrectTypeArgumentInferred = const Code< Message Function( DartType _type, DartType _type2, String name, String name2)>( "IncorrectTypeArgumentInferred", templateIncorrectTypeArgumentInferred, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncorrectTypeArgumentInferred( DartType _type, DartType _type2, String name, String name2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeIncorrectTypeArgumentInferred, message: """Inferred type argument '${type}' doesn't conform to the bound '${type2}' of the type variable '${name}' on '${name2}'.""" + labeler.originMessages, tip: """Try specifying type arguments explicitly so that they conform to the bounds.""", arguments: { 'type': _type, 'type2': _type2, 'name': name, 'name2': name2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, String name, DartType _type3, String name2)> templateIncorrectTypeArgumentQualified = const Template< Message Function( DartType _type, DartType _type2, String name, DartType _type3, String name2)>( messageTemplate: r"""Type argument '#type' doesn't conform to the bound '#type2' of the type variable '#name' on '#type3.#name2'.""", tipTemplate: r"""Try changing type arguments so that they conform to the bounds.""", withArguments: _withArgumentsIncorrectTypeArgumentQualified); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(DartType _type, DartType _type2, String name, DartType _type3, String name2)> codeIncorrectTypeArgumentQualified = const Code< Message Function(DartType _type, DartType _type2, String name, DartType _type3, String name2)>( "IncorrectTypeArgumentQualified", templateIncorrectTypeArgumentQualified, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncorrectTypeArgumentQualified(DartType _type, DartType _type2, String name, DartType _type3, String name2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); List<Object> type3Parts = labeler.labelType(_type3); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); String type = typeParts.join(); String type2 = type2Parts.join(); String type3 = type3Parts.join(); return new Message(codeIncorrectTypeArgumentQualified, message: """Type argument '${type}' doesn't conform to the bound '${type2}' of the type variable '${name}' on '${type3}.${name2}'.""" + labeler.originMessages, tip: """Try changing type arguments so that they conform to the bounds.""", arguments: { 'type': _type, 'type2': _type2, 'name': name, 'type3': _type3, 'name2': name2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2, String name, DartType _type3, String name2)> templateIncorrectTypeArgumentQualifiedInferred = const Template< Message Function(DartType _type, DartType _type2, String name, DartType _type3, String name2)>( messageTemplate: r"""Inferred type argument '#type' doesn't conform to the bound '#type2' of the type variable '#name' on '#type3.#name2'.""", tipTemplate: r"""Try specifying type arguments explicitly so that they conform to the bounds.""", withArguments: _withArgumentsIncorrectTypeArgumentQualifiedInferred); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(DartType _type, DartType _type2, String name, DartType _type3, String name2)> codeIncorrectTypeArgumentQualifiedInferred = const Code< Message Function(DartType _type, DartType _type2, String name, DartType _type3, String name2)>( "IncorrectTypeArgumentQualifiedInferred", templateIncorrectTypeArgumentQualifiedInferred, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIncorrectTypeArgumentQualifiedInferred(DartType _type, DartType _type2, String name, DartType _type3, String name2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); List<Object> type3Parts = labeler.labelType(_type3); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); String type = typeParts.join(); String type2 = type2Parts.join(); String type3 = type3Parts.join(); return new Message(codeIncorrectTypeArgumentQualifiedInferred, message: """Inferred type argument '${type}' doesn't conform to the bound '${type2}' of the type variable '${name}' on '${type3}.${name2}'.""" + labeler.originMessages, tip: """Try specifying type arguments explicitly so that they conform to the bounds.""", arguments: { 'type': _type, 'type2': _type2, 'name': name, 'type3': _type3, 'name2': name2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeIncorrectTypeArgumentVariable = messageIncorrectTypeArgumentVariable; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageIncorrectTypeArgumentVariable = const MessageCode( "IncorrectTypeArgumentVariable", severity: Severity.context, message: r"""This is the type variable whose bound isn't conformed to."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_)> templateInferredPackageUri = const Template<Message Function(Uri uri_)>( messageTemplate: r"""Interpreting this as package URI, '#uri'.""", withArguments: _withArgumentsInferredPackageUri); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeInferredPackageUri = const Code<Message Function(Uri uri_)>( "InferredPackageUri", templateInferredPackageUri, severity: Severity.warning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInferredPackageUri(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeInferredPackageUri, message: """Interpreting this as package URI, '${uri}'.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInheritedMembersConflict = messageInheritedMembersConflict; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInheritedMembersConflict = const MessageCode( "InheritedMembersConflict", analyzerCodes: <String>["CONFLICTS_WITH_INHERITED_MEMBER"], message: r"""Can't inherit members that conflict with each other."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInheritedMembersConflictCause1 = messageInheritedMembersConflictCause1; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInheritedMembersConflictCause1 = const MessageCode( "InheritedMembersConflictCause1", severity: Severity.context, message: r"""This is one inherited member."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInheritedMembersConflictCause2 = messageInheritedMembersConflictCause2; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInheritedMembersConflictCause2 = const MessageCode( "InheritedMembersConflictCause2", severity: Severity.context, message: r"""This is the other inherited member."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, Uri uri_)> templateInitializeFromDillNotSelfContained = const Template< Message Function(String string, Uri uri_)>( messageTemplate: r"""Tried to initialize from a previous compilation (#string), but the file was not self-contained. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new. If you are comfortable with it, it would improve the chances of fixing any bug if you included the file #uri in your error report, but be aware that this file includes your source code. Either way, you should probably delete the file so it doesn't use unnecessary disk space.""", withArguments: _withArgumentsInitializeFromDillNotSelfContained); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, Uri uri_)> codeInitializeFromDillNotSelfContained = const Code<Message Function(String string, Uri uri_)>( "InitializeFromDillNotSelfContained", templateInitializeFromDillNotSelfContained, severity: Severity.warning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInitializeFromDillNotSelfContained( String string, Uri uri_) { if (string.isEmpty) throw 'No string provided'; String uri = relativizeUri(uri_); return new Message(codeInitializeFromDillNotSelfContained, message: """Tried to initialize from a previous compilation (${string}), but the file was not self-contained. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new. If you are comfortable with it, it would improve the chances of fixing any bug if you included the file ${uri} in your error report, but be aware that this file includes your source code. Either way, you should probably delete the file so it doesn't use unnecessary disk space.""", arguments: {'string': string, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateInitializeFromDillNotSelfContainedNoDump = const Template<Message Function(String string)>( messageTemplate: r"""Tried to initialize from a previous compilation (#string), but the file was not self-contained. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new.""", withArguments: _withArgumentsInitializeFromDillNotSelfContainedNoDump); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeInitializeFromDillNotSelfContainedNoDump = const Code<Message Function(String string)>( "InitializeFromDillNotSelfContainedNoDump", templateInitializeFromDillNotSelfContainedNoDump, severity: Severity.warning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInitializeFromDillNotSelfContainedNoDump(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeInitializeFromDillNotSelfContainedNoDump, message: """Tried to initialize from a previous compilation (${string}), but the file was not self-contained. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, String string2, String string3, Uri uri_)> templateInitializeFromDillUnknownProblem = const Template< Message Function( String string, String string2, String string3, Uri uri_)>( messageTemplate: r"""Tried to initialize from a previous compilation (#string), but couldn't. Error message was '#string2'. Stacktrace included '#string3'. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new. If you are comfortable with it, it would improve the chances of fixing any bug if you included the file #uri in your error report, but be aware that this file includes your source code. Either way, you should probably delete the file so it doesn't use unnecessary disk space.""", withArguments: _withArgumentsInitializeFromDillUnknownProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function( String string, String string2, String string3, Uri uri_)> codeInitializeFromDillUnknownProblem = const Code< Message Function( String string, String string2, String string3, Uri uri_)>( "InitializeFromDillUnknownProblem", templateInitializeFromDillUnknownProblem, severity: Severity.warning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInitializeFromDillUnknownProblem( String string, String string2, String string3, Uri uri_) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; if (string3.isEmpty) throw 'No string provided'; String uri = relativizeUri(uri_); return new Message(codeInitializeFromDillUnknownProblem, message: """Tried to initialize from a previous compilation (${string}), but couldn't. Error message was '${string2}'. Stacktrace included '${string3}'. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new. If you are comfortable with it, it would improve the chances of fixing any bug if you included the file ${uri} in your error report, but be aware that this file includes your source code. Either way, you should probably delete the file so it doesn't use unnecessary disk space.""", arguments: { 'string': string, 'string2': string2, 'string3': string3, 'uri': uri_ }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string, String string2, String string3)> templateInitializeFromDillUnknownProblemNoDump = const Template< Message Function(String string, String string2, String string3)>( messageTemplate: r"""Tried to initialize from a previous compilation (#string), but couldn't. Error message was '#string2'. Stacktrace included '#string3'. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new.""", withArguments: _withArgumentsInitializeFromDillUnknownProblemNoDump); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2, String string3)> codeInitializeFromDillUnknownProblemNoDump = const Code<Message Function(String string, String string2, String string3)>( "InitializeFromDillUnknownProblemNoDump", templateInitializeFromDillUnknownProblemNoDump, severity: Severity.warning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInitializeFromDillUnknownProblemNoDump( String string, String string2, String string3) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; if (string3.isEmpty) throw 'No string provided'; return new Message(codeInitializeFromDillUnknownProblemNoDump, message: """Tried to initialize from a previous compilation (${string}), but couldn't. Error message was '${string2}'. Stacktrace included '${string3}'. This might be a bug. The Dart team would greatly appreciate it if you would take a moment to report this problem at http://dartbug.com/new.""", arguments: {'string': string, 'string2': string2, 'string3': string3}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInitializedVariableInForEach = messageInitializedVariableInForEach; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInitializedVariableInForEach = const MessageCode( "InitializedVariableInForEach", index: 82, message: r"""The loop variable in a for-each loop can't be initialized.""", tip: r"""Try removing the initializer, or using a different kind of loop."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateInitializerForStaticField = const Template<Message Function(String name)>( messageTemplate: r"""'#name' isn't an instance field of this class.""", withArguments: _withArgumentsInitializerForStaticField); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInitializerForStaticField = const Code<Message Function(String name)>( "InitializerForStaticField", templateInitializerForStaticField, analyzerCodes: <String>["INITIALIZER_FOR_STATIC_FIELD"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInitializerForStaticField(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInitializerForStaticField, message: """'${name}' isn't an instance field of this class.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateInitializerOutsideConstructor = const Template< Message Function(String name)>( messageTemplate: r"""Only constructors can have initializers, and '#name' is not a constructor.""", withArguments: _withArgumentsInitializerOutsideConstructor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInitializerOutsideConstructor = const Code<Message Function(String name)>( "InitializerOutsideConstructor", templateInitializerOutsideConstructor, analyzerCodes: <String>["INITIALIZER_OUTSIDE_CONSTRUCTOR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInitializerOutsideConstructor(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInitializerOutsideConstructor, message: """Only constructors can have initializers, and '${name}' is not a constructor.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type, DartType _type2)> templateInitializingFormalTypeMismatch = const Template< Message Function(String name, DartType _type, DartType _type2)>( messageTemplate: r"""The type of parameter '#name', '#type' is not a subtype of the corresponding field's type, '#type2'.""", tipTemplate: r"""Try changing the type of parameter '#name' to a subtype of '#type2'.""", withArguments: _withArgumentsInitializingFormalTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, DartType _type, DartType _type2)> codeInitializingFormalTypeMismatch = const Code<Message Function(String name, DartType _type, DartType _type2)>( "InitializingFormalTypeMismatch", templateInitializingFormalTypeMismatch, analyzerCodes: <String>["INVALID_PARAMETER_DECLARATION"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInitializingFormalTypeMismatch( String name, DartType _type, DartType _type2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInitializingFormalTypeMismatch, message: """The type of parameter '${name}', '${type}' is not a subtype of the corresponding field's type, '${type2}'.""" + labeler.originMessages, tip: """Try changing the type of parameter '${name}' to a subtype of '${type2}'.""", arguments: {'name': name, 'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInitializingFormalTypeMismatchField = messageInitializingFormalTypeMismatchField; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInitializingFormalTypeMismatchField = const MessageCode("InitializingFormalTypeMismatchField", severity: Severity.context, message: r"""The field that corresponds to the parameter."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_)> templateInputFileNotFound = const Template<Message Function(Uri uri_)>( messageTemplate: r"""Input file not found: #uri.""", withArguments: _withArgumentsInputFileNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeInputFileNotFound = const Code<Message Function(Uri uri_)>( "InputFileNotFound", templateInputFileNotFound, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInputFileNotFound(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeInputFileNotFound, message: """Input file not found: ${uri}.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string)> templateIntegerLiteralIsOutOfRange = const Template< Message Function(String string)>( messageTemplate: r"""The integer literal #string can't be represented in 64 bits.""", tipTemplate: r"""Try using the BigInt class if you need an integer larger than 9,223,372,036,854,775,807 or less than -9,223,372,036,854,775,808.""", withArguments: _withArgumentsIntegerLiteralIsOutOfRange); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeIntegerLiteralIsOutOfRange = const Code<Message Function(String string)>( "IntegerLiteralIsOutOfRange", templateIntegerLiteralIsOutOfRange, analyzerCodes: <String>["INTEGER_LITERAL_OUT_OF_RANGE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIntegerLiteralIsOutOfRange(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeIntegerLiteralIsOutOfRange, message: """The integer literal ${string} can't be represented in 64 bits.""", tip: """Try using the BigInt class if you need an integer larger than 9,223,372,036,854,775,807 or less than -9,223,372,036,854,775,808.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateInterfaceCheck = const Template< Message Function(String name, String name2)>( messageTemplate: r"""The implementation of '#name' in the non-abstract class '#name2' does not conform to its interface.""", withArguments: _withArgumentsInterfaceCheck); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeInterfaceCheck = const Code<Message Function(String name, String name2)>( "InterfaceCheck", templateInterfaceCheck, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInterfaceCheck(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeInterfaceCheck, message: """The implementation of '${name}' in the non-abstract class '${name2}' does not conform to its interface.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInternalProblemAlreadyInitialized = messageInternalProblemAlreadyInitialized; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInternalProblemAlreadyInitialized = const MessageCode( "InternalProblemAlreadyInitialized", severity: Severity.internalProblem, message: r"""Attempt to set initializer on field without initializer."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInternalProblemBodyOnAbstractMethod = messageInternalProblemBodyOnAbstractMethod; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInternalProblemBodyOnAbstractMethod = const MessageCode("InternalProblemBodyOnAbstractMethod", severity: Severity.internalProblem, message: r"""Attempting to set body on abstract method."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_)> templateInternalProblemConstructorNotFound = const Template<Message Function(String name, Uri uri_)>( messageTemplate: r"""No constructor named '#name' in '#uri'.""", withArguments: _withArgumentsInternalProblemConstructorNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_)> codeInternalProblemConstructorNotFound = const Code<Message Function(String name, Uri uri_)>( "InternalProblemConstructorNotFound", templateInternalProblemConstructorNotFound, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemConstructorNotFound( String name, Uri uri_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); return new Message(codeInternalProblemConstructorNotFound, message: """No constructor named '${name}' in '${uri}'.""", arguments: {'name': name, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateInternalProblemContextSeverity = const Template<Message Function(String string)>( messageTemplate: r"""Non-context message has context severity: #string""", withArguments: _withArgumentsInternalProblemContextSeverity); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeInternalProblemContextSeverity = const Code<Message Function(String string)>( "InternalProblemContextSeverity", templateInternalProblemContextSeverity, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemContextSeverity(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeInternalProblemContextSeverity, message: """Non-context message has context severity: ${string}""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, String string)> templateInternalProblemDebugAbort = const Template<Message Function(String name, String string)>( messageTemplate: r"""Compilation aborted due to fatal '#name' at: #string""", withArguments: _withArgumentsInternalProblemDebugAbort); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String string)> codeInternalProblemDebugAbort = const Code<Message Function(String name, String string)>( "InternalProblemDebugAbort", templateInternalProblemDebugAbort, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemDebugAbort(String name, String string) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (string.isEmpty) throw 'No string provided'; return new Message(codeInternalProblemDebugAbort, message: """Compilation aborted due to fatal '${name}' at: ${string}""", arguments: {'name': name, 'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInternalProblemExtendingUnmodifiableScope = messageInternalProblemExtendingUnmodifiableScope; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInternalProblemExtendingUnmodifiableScope = const MessageCode("InternalProblemExtendingUnmodifiableScope", severity: Severity.internalProblem, message: r"""Can't extend an unmodifiable scope."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInternalProblemLabelUsageInVariablesDeclaration = messageInternalProblemLabelUsageInVariablesDeclaration; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInternalProblemLabelUsageInVariablesDeclaration = const MessageCode("InternalProblemLabelUsageInVariablesDeclaration", severity: Severity.internalProblem, message: r"""Unexpected usage of label inside declaration of variables."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInternalProblemMissingContext = messageInternalProblemMissingContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInternalProblemMissingContext = const MessageCode( "InternalProblemMissingContext", severity: Severity.internalProblem, message: r"""Compiler cannot run without a compiler context.""", tip: r"""Are calls to the compiler wrapped in CompilerContext.runInContext?"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateInternalProblemNotFound = const Template<Message Function(String name)>( messageTemplate: r"""Couldn't find '#name'.""", withArguments: _withArgumentsInternalProblemNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInternalProblemNotFound = const Code<Message Function(String name)>( "InternalProblemNotFound", templateInternalProblemNotFound, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInternalProblemNotFound, message: """Couldn't find '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, String name2)> templateInternalProblemNotFoundIn = const Template<Message Function(String name, String name2)>( messageTemplate: r"""Couldn't find '#name' in '#name2'.""", withArguments: _withArgumentsInternalProblemNotFoundIn); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeInternalProblemNotFoundIn = const Code<Message Function(String name, String name2)>( "InternalProblemNotFoundIn", templateInternalProblemNotFoundIn, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemNotFoundIn(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeInternalProblemNotFoundIn, message: """Couldn't find '${name}' in '${name2}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInternalProblemPreviousTokenNotFound = messageInternalProblemPreviousTokenNotFound; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInternalProblemPreviousTokenNotFound = const MessageCode("InternalProblemPreviousTokenNotFound", severity: Severity.internalProblem, message: r"""Couldn't find previous token."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateInternalProblemPrivateConstructorAccess = const Template<Message Function(String name)>( messageTemplate: r"""Can't access private constructor '#name'.""", withArguments: _withArgumentsInternalProblemPrivateConstructorAccess); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInternalProblemPrivateConstructorAccess = const Code<Message Function(String name)>( "InternalProblemPrivateConstructorAccess", templateInternalProblemPrivateConstructorAccess, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemPrivateConstructorAccess(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInternalProblemPrivateConstructorAccess, message: """Can't access private constructor '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInternalProblemProvidedBothCompileSdkAndSdkSummary = messageInternalProblemProvidedBothCompileSdkAndSdkSummary; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInternalProblemProvidedBothCompileSdkAndSdkSummary = const MessageCode("InternalProblemProvidedBothCompileSdkAndSdkSummary", severity: Severity.internalProblem, message: r"""The compileSdk and sdkSummary options are mutually exclusive"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, String string)> templateInternalProblemStackNotEmpty = const Template<Message Function(String name, String string)>( messageTemplate: r"""#name.stack isn't empty: #string""", withArguments: _withArgumentsInternalProblemStackNotEmpty); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String string)> codeInternalProblemStackNotEmpty = const Code<Message Function(String name, String string)>( "InternalProblemStackNotEmpty", templateInternalProblemStackNotEmpty, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemStackNotEmpty(String name, String string) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (string.isEmpty) throw 'No string provided'; return new Message(codeInternalProblemStackNotEmpty, message: """${name}.stack isn't empty: ${string}""", arguments: {'name': name, 'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string, String string2)> templateInternalProblemUnexpected = const Template<Message Function(String string, String string2)>( messageTemplate: r"""Expected '#string', but got '#string2'.""", withArguments: _withArgumentsInternalProblemUnexpected); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeInternalProblemUnexpected = const Code<Message Function(String string, String string2)>( "InternalProblemUnexpected", templateInternalProblemUnexpected, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemUnexpected(String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeInternalProblemUnexpected, message: """Expected '${string}', but got '${string2}'.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, Uri uri_)> templateInternalProblemUnfinishedTypeVariable = const Template< Message Function(String name, Uri uri_)>( messageTemplate: r"""Unfinished type variable '#name' found in non-source library '#uri'.""", withArguments: _withArgumentsInternalProblemUnfinishedTypeVariable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_)> codeInternalProblemUnfinishedTypeVariable = const Code<Message Function(String name, Uri uri_)>( "InternalProblemUnfinishedTypeVariable", templateInternalProblemUnfinishedTypeVariable, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemUnfinishedTypeVariable( String name, Uri uri_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); return new Message(codeInternalProblemUnfinishedTypeVariable, message: """Unfinished type variable '${name}' found in non-source library '${uri}'.""", arguments: {'name': name, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string, String string2)> templateInternalProblemUnhandled = const Template<Message Function(String string, String string2)>( messageTemplate: r"""Unhandled #string in #string2.""", withArguments: _withArgumentsInternalProblemUnhandled); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeInternalProblemUnhandled = const Code<Message Function(String string, String string2)>( "InternalProblemUnhandled", templateInternalProblemUnhandled, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemUnhandled(String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeInternalProblemUnhandled, message: """Unhandled ${string} in ${string2}.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateInternalProblemUnimplemented = const Template<Message Function(String string)>( messageTemplate: r"""Unimplemented #string.""", withArguments: _withArgumentsInternalProblemUnimplemented); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeInternalProblemUnimplemented = const Code<Message Function(String string)>( "InternalProblemUnimplemented", templateInternalProblemUnimplemented, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemUnimplemented(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeInternalProblemUnimplemented, message: """Unimplemented ${string}.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateInternalProblemUnsupported = const Template<Message Function(String name)>( messageTemplate: r"""Unsupported operation: '#name'.""", withArguments: _withArgumentsInternalProblemUnsupported); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInternalProblemUnsupported = const Code<Message Function(String name)>( "InternalProblemUnsupported", templateInternalProblemUnsupported, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemUnsupported(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInternalProblemUnsupported, message: """Unsupported operation: '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_)> templateInternalProblemUriMissingScheme = const Template<Message Function(Uri uri_)>( messageTemplate: r"""The URI '#uri' has no scheme.""", withArguments: _withArgumentsInternalProblemUriMissingScheme); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeInternalProblemUriMissingScheme = const Code<Message Function(Uri uri_)>("InternalProblemUriMissingScheme", templateInternalProblemUriMissingScheme, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemUriMissingScheme(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeInternalProblemUriMissingScheme, message: """The URI '${uri}' has no scheme.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateInternalProblemVerificationError = const Template<Message Function(String string)>( messageTemplate: r"""Verification of the generated program failed: #string""", withArguments: _withArgumentsInternalProblemVerificationError); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeInternalProblemVerificationError = const Code<Message Function(String string)>( "InternalProblemVerificationError", templateInternalProblemVerificationError, severity: Severity.internalProblem); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInternalProblemVerificationError(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeInternalProblemVerificationError, message: """Verification of the generated program failed: ${string}""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInterpolationInUri = messageInterpolationInUri; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInterpolationInUri = const MessageCode( "InterpolationInUri", analyzerCodes: <String>["INVALID_LITERAL_IN_CONFIGURATION"], message: r"""Can't use string interpolation in a URI."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type, DartType _type2)> templateIntersectionTypeAsTypeArgument = const Template< Message Function(String name, DartType _type, DartType _type2)>( messageTemplate: r"""Can't infer a type for '#name', it can be either '#type' or '#type2'.""", tipTemplate: r"""Try adding a type argument selecting one of the options.""", withArguments: _withArgumentsIntersectionTypeAsTypeArgument); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, DartType _type, DartType _type2)> codeIntersectionTypeAsTypeArgument = const Code<Message Function(String name, DartType _type, DartType _type2)>( "IntersectionTypeAsTypeArgument", templateIntersectionTypeAsTypeArgument, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsIntersectionTypeAsTypeArgument( String name, DartType _type, DartType _type2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeIntersectionTypeAsTypeArgument, message: """Can't infer a type for '${name}', it can be either '${type}' or '${type2}'.""" + labeler.originMessages, tip: """Try adding a type argument selecting one of the options.""", arguments: {'name': name, 'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidAssignment = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""A value of type '#type' can't be assigned to a variable of type '#type2'.""", withArguments: _withArgumentsInvalidAssignment); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidAssignment = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidAssignment", templateInvalidAssignment, analyzerCodes: <String>["INVALID_ASSIGNMENT"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidAssignment(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidAssignment, message: """A value of type '${type}' can't be assigned to a variable of type '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidAwaitFor = messageInvalidAwaitFor; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidAwaitFor = const MessageCode("InvalidAwaitFor", index: 9, message: r"""The keyword 'await' isn't allowed for a normal 'for' statement.""", tip: r"""Try removing the keyword, or use a for-each statement."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateInvalidBreakTarget = const Template<Message Function(String name)>( messageTemplate: r"""Can't break to '#name'.""", withArguments: _withArgumentsInvalidBreakTarget); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInvalidBreakTarget = const Code<Message Function(String name)>( "InvalidBreakTarget", templateInvalidBreakTarget, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidBreakTarget(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInvalidBreakTarget, message: """Can't break to '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastFunctionExpr = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The function expression type '#type' isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the function expression or the context in which it is used.""", withArguments: _withArgumentsInvalidCastFunctionExpr); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastFunctionExpr = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastFunctionExpr", templateInvalidCastFunctionExpr, analyzerCodes: <String>["INVALID_CAST_FUNCTION_EXPR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastFunctionExpr(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastFunctionExpr, message: """The function expression type '${type}' isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the function expression or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastLiteralList = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The list literal type '#type' isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the list literal or the context in which it is used.""", withArguments: _withArgumentsInvalidCastLiteralList); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastLiteralList = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastLiteralList", templateInvalidCastLiteralList, analyzerCodes: <String>["INVALID_CAST_LITERAL_LIST"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastLiteralList(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastLiteralList, message: """The list literal type '${type}' isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the list literal or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastLiteralMap = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The map literal type '#type' isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the map literal or the context in which it is used.""", withArguments: _withArgumentsInvalidCastLiteralMap); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastLiteralMap = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastLiteralMap", templateInvalidCastLiteralMap, analyzerCodes: <String>["INVALID_CAST_LITERAL_MAP"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastLiteralMap(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastLiteralMap, message: """The map literal type '${type}' isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the map literal or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastLiteralSet = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The set literal type '#type' isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the set literal or the context in which it is used.""", withArguments: _withArgumentsInvalidCastLiteralSet); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastLiteralSet = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastLiteralSet", templateInvalidCastLiteralSet, analyzerCodes: <String>["INVALID_CAST_LITERAL_SET"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastLiteralSet(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastLiteralSet, message: """The set literal type '${type}' isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the set literal or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastLocalFunction = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The local function has type '#type' that isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the function or the context in which it is used.""", withArguments: _withArgumentsInvalidCastLocalFunction); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastLocalFunction = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastLocalFunction", templateInvalidCastLocalFunction, analyzerCodes: <String>["INVALID_CAST_FUNCTION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastLocalFunction( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastLocalFunction, message: """The local function has type '${type}' that isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the function or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastNewExpr = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The constructor returns type '#type' that isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the object being constructed or the context in which it is used.""", withArguments: _withArgumentsInvalidCastNewExpr); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastNewExpr = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastNewExpr", templateInvalidCastNewExpr, analyzerCodes: <String>["INVALID_CAST_NEW_EXPR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastNewExpr(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastNewExpr, message: """The constructor returns type '${type}' that isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the object being constructed or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastStaticMethod = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The static method has type '#type' that isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the method or the context in which it is used.""", withArguments: _withArgumentsInvalidCastStaticMethod); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastStaticMethod = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastStaticMethod", templateInvalidCastStaticMethod, analyzerCodes: <String>["INVALID_CAST_METHOD"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastStaticMethod(DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastStaticMethod, message: """The static method has type '${type}' that isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the method or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateInvalidCastTopLevelFunction = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The top level function has type '#type' that isn't of expected type '#type2'.""", tipTemplate: r"""Change the type of the function or the context in which it is used.""", withArguments: _withArgumentsInvalidCastTopLevelFunction); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeInvalidCastTopLevelFunction = const Code<Message Function(DartType _type, DartType _type2)>( "InvalidCastTopLevelFunction", templateInvalidCastTopLevelFunction, analyzerCodes: <String>["INVALID_CAST_FUNCTION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidCastTopLevelFunction( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeInvalidCastTopLevelFunction, message: """The top level function has type '${type}' that isn't of expected type '${type2}'.""" + labeler.originMessages, tip: """Change the type of the function or the context in which it is used.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidCatchArguments = messageInvalidCatchArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidCatchArguments = const MessageCode( "InvalidCatchArguments", analyzerCodes: <String>["INVALID_CATCH_ARGUMENTS"], message: r"""Invalid catch arguments."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidCodePoint = messageInvalidCodePoint; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidCodePoint = const MessageCode( "InvalidCodePoint", analyzerCodes: <String>["INVALID_CODE_POINT"], message: r"""The escape sequence starting with '\u' isn't a valid code point."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateInvalidContinueTarget = const Template<Message Function(String name)>( messageTemplate: r"""Can't continue at '#name'.""", withArguments: _withArgumentsInvalidContinueTarget); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInvalidContinueTarget = const Code<Message Function(String name)>( "InvalidContinueTarget", templateInvalidContinueTarget, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidContinueTarget(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInvalidContinueTarget, message: """Can't continue at '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidHexEscape = messageInvalidHexEscape; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidHexEscape = const MessageCode( "InvalidHexEscape", index: 40, message: r"""An escape sequence starting with '\x' must be followed by 2 hexadecimal digits."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidInitializer = messageInvalidInitializer; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidInitializer = const MessageCode( "InvalidInitializer", index: 90, message: r"""Not a valid initializer.""", tip: r"""To initialize a field, use the syntax 'name = value'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidInlineFunctionType = messageInvalidInlineFunctionType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidInlineFunctionType = const MessageCode( "InvalidInlineFunctionType", analyzerCodes: <String>["INVALID_INLINE_FUNCTION_TYPE"], message: r"""Inline function types cannot be used for parameters in a generic function type.""", tip: r"""Try changing the inline function type (as in 'int f()') to a prefixed function type using the `Function` keyword (as in 'int Function() f')."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateInvalidOperator = const Template<Message Function(Token token)>( messageTemplate: r"""The string '#lexeme' isn't a user-definable operator.""", withArguments: _withArgumentsInvalidOperator); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeInvalidOperator = const Code<Message Function(Token token)>( "InvalidOperator", templateInvalidOperator, index: 39); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidOperator(Token token) { String lexeme = token.lexeme; return new Message(codeInvalidOperator, message: """The string '${lexeme}' isn't a user-definable operator.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_, String string)> templateInvalidPackageUri = const Template<Message Function(Uri uri_, String string)>( messageTemplate: r"""Invalid package URI '#uri': #string.""", withArguments: _withArgumentsInvalidPackageUri); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_, String string)> codeInvalidPackageUri = const Code<Message Function(Uri uri_, String string)>( "InvalidPackageUri", templateInvalidPackageUri, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvalidPackageUri(Uri uri_, String string) { String uri = relativizeUri(uri_); if (string.isEmpty) throw 'No string provided'; return new Message(codeInvalidPackageUri, message: """Invalid package URI '${uri}': ${string}.""", arguments: {'uri': uri_, 'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidSuperInInitializer = messageInvalidSuperInInitializer; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidSuperInInitializer = const MessageCode( "InvalidSuperInInitializer", index: 47, message: r"""Can only use 'super' in an initializer for calling the superclass constructor (e.g. 'super()' or 'super.namedConstructor()')"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidSyncModifier = messageInvalidSyncModifier; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidSyncModifier = const MessageCode( "InvalidSyncModifier", analyzerCodes: <String>["MISSING_STAR_AFTER_SYNC"], message: r"""Invalid modifier 'sync'.""", tip: r"""Try replacing 'sync' with 'sync*'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidThisInInitializer = messageInvalidThisInInitializer; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidThisInInitializer = const MessageCode( "InvalidThisInInitializer", index: 65, message: r"""Can only use 'this' in an initializer for field initialization (e.g. 'this.x = something') and constructor redirection (e.g. 'this()' or 'this.namedConstructor())"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidUnicodeEscape = messageInvalidUnicodeEscape; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidUnicodeEscape = const MessageCode( "InvalidUnicodeEscape", index: 38, message: r"""An escape sequence starting with '\u' must be followed by 4 hexadecimal digits or from 1 to 6 digits between '{' and '}'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidUseOfNullAwareAccess = messageInvalidUseOfNullAwareAccess; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidUseOfNullAwareAccess = const MessageCode( "InvalidUseOfNullAwareAccess", analyzerCodes: <String>["INVALID_USE_OF_NULL_AWARE_ACCESS"], message: r"""Cannot use '?.' here.""", tip: r"""Try using '.'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeInvalidVoid = messageInvalidVoid; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageInvalidVoid = const MessageCode("InvalidVoid", analyzerCodes: <String>["EXPECTED_TYPE_NAME"], message: r"""Type 'void' can't be used here.""", tip: r"""Try removing 'void' keyword or replace it with 'var', 'final', or a type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateInvokeNonFunction = const Template<Message Function(String name)>( messageTemplate: r"""'#name' isn't a function or method and can't be invoked.""", withArguments: _withArgumentsInvokeNonFunction); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeInvokeNonFunction = const Code<Message Function(String name)>( "InvokeNonFunction", templateInvokeNonFunction, analyzerCodes: <String>["INVOCATION_OF_NON_FUNCTION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsInvokeNonFunction(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeInvokeNonFunction, message: """'${name}' isn't a function or method and can't be invoked.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(String name)> templateLabelNotFound = const Template< Message Function(String name)>( messageTemplate: r"""Can't find label '#name'.""", tipTemplate: r"""Try defining the label, or correcting the name to match an existing label.""", withArguments: _withArgumentsLabelNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeLabelNotFound = const Code<Message Function(String name)>( "LabelNotFound", templateLabelNotFound, analyzerCodes: <String>["LABEL_UNDEFINED"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsLabelNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeLabelNotFound, message: """Can't find label '${name}'.""", tip: """Try defining the label, or correcting the name to match an existing label.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeLanguageVersionInvalidInDotPackages = messageLanguageVersionInvalidInDotPackages; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageLanguageVersionInvalidInDotPackages = const MessageCode( "LanguageVersionInvalidInDotPackages", message: r"""The language version is not specified correctly in the .packages file."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeLanguageVersionMismatchInPart = messageLanguageVersionMismatchInPart; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageLanguageVersionMismatchInPart = const MessageCode( "LanguageVersionMismatchInPart", message: r"""The language version override has to be the same in the library and its part(s)."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int count, int count2)> templateLanguageVersionTooHigh = const Template< Message Function(int count, int count2)>( messageTemplate: r"""The specified language version is too high. The highest supported language version is #count.#count2.""", withArguments: _withArgumentsLanguageVersionTooHigh); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(int count, int count2)> codeLanguageVersionTooHigh = const Code<Message Function(int count, int count2)>( "LanguageVersionTooHigh", templateLanguageVersionTooHigh, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsLanguageVersionTooHigh(int count, int count2) { if (count == null) throw 'No count provided'; if (count2 == null) throw 'No count provided'; return new Message(codeLanguageVersionTooHigh, message: """The specified language version is too high. The highest supported language version is ${count}.${count2}.""", arguments: {'count': count, 'count2': count2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeLibraryDirectiveNotFirst = messageLibraryDirectiveNotFirst; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageLibraryDirectiveNotFirst = const MessageCode( "LibraryDirectiveNotFirst", index: 37, message: r"""The library directive must appear before all other directives.""", tip: r"""Try moving the library directive before any other directives."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeListLiteralTooManyTypeArguments = messageListLiteralTooManyTypeArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageListLiteralTooManyTypeArguments = const MessageCode( "ListLiteralTooManyTypeArguments", analyzerCodes: <String>["EXPECTED_ONE_LIST_TYPE_ARGUMENTS"], severity: Severity.errorLegacyWarning, message: r"""List literal requires exactly one type argument."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(Uri uri_)> templateLoadLibraryHidesMember = const Template< Message Function(Uri uri_)>( messageTemplate: r"""The library '#uri' defines a top-level member named 'loadLibrary'. This member is hidden by the special member 'loadLibrary' that the language adds to support deferred loading.""", tipTemplate: r"""Try to rename or hide the member.""", withArguments: _withArgumentsLoadLibraryHidesMember); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeLoadLibraryHidesMember = const Code<Message Function(Uri uri_)>( "LoadLibraryHidesMember", templateLoadLibraryHidesMember, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsLoadLibraryHidesMember(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeLoadLibraryHidesMember, message: """The library '${uri}' defines a top-level member named 'loadLibrary'. This member is hidden by the special member 'loadLibrary' that the language adds to support deferred loading.""", tip: """Try to rename or hide the member.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeLoadLibraryTakesNoArguments = messageLoadLibraryTakesNoArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageLoadLibraryTakesNoArguments = const MessageCode( "LoadLibraryTakesNoArguments", analyzerCodes: <String>["LOAD_LIBRARY_TAKES_NO_ARGUMENTS"], severity: Severity.errorLegacyWarning, message: r"""'loadLibrary' takes no arguments."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_)> templateLocalDefinitionHidesExport = const Template<Message Function(String name, Uri uri_)>( messageTemplate: r"""Local definition of '#name' hides export from '#uri'.""", withArguments: _withArgumentsLocalDefinitionHidesExport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_)> codeLocalDefinitionHidesExport = const Code<Message Function(String name, Uri uri_)>( "LocalDefinitionHidesExport", templateLocalDefinitionHidesExport, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsLocalDefinitionHidesExport(String name, Uri uri_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); return new Message(codeLocalDefinitionHidesExport, message: """Local definition of '${name}' hides export from '${uri}'.""", arguments: {'name': name, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_)> templateLocalDefinitionHidesImport = const Template<Message Function(String name, Uri uri_)>( messageTemplate: r"""Local definition of '#name' hides import from '#uri'.""", withArguments: _withArgumentsLocalDefinitionHidesImport); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_)> codeLocalDefinitionHidesImport = const Code<Message Function(String name, Uri uri_)>( "LocalDefinitionHidesImport", templateLocalDefinitionHidesImport, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsLocalDefinitionHidesImport(String name, Uri uri_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); return new Message(codeLocalDefinitionHidesImport, message: """Local definition of '${name}' hides import from '${uri}'.""", arguments: {'name': name, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMapLiteralTypeArgumentMismatch = messageMapLiteralTypeArgumentMismatch; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMapLiteralTypeArgumentMismatch = const MessageCode( "MapLiteralTypeArgumentMismatch", analyzerCodes: <String>["EXPECTED_TWO_MAP_TYPE_ARGUMENTS"], severity: Severity.errorLegacyWarning, message: r"""A map literal requires exactly two type arguments."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMemberWithSameNameAsClass = messageMemberWithSameNameAsClass; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMemberWithSameNameAsClass = const MessageCode( "MemberWithSameNameAsClass", message: r"""A class member can't have the same name as the enclosing class."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMetadataTypeArguments = messageMetadataTypeArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMetadataTypeArguments = const MessageCode( "MetadataTypeArguments", index: 91, message: r"""An annotation (metadata) can't use type arguments."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateMethodNotFound = const Template<Message Function(String name)>( messageTemplate: r"""Method not found: '#name'.""", withArguments: _withArgumentsMethodNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeMethodNotFound = const Code<Message Function(String name)>( "MethodNotFound", templateMethodNotFound, analyzerCodes: <String>["UNDEFINED_METHOD"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsMethodNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeMethodNotFound, message: """Method not found: '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingArgumentList = messageMissingArgumentList; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingArgumentList = const MessageCode( "MissingArgumentList", message: r"""Constructor invocations must have an argument list."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingAssignableSelector = messageMissingAssignableSelector; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingAssignableSelector = const MessageCode( "MissingAssignableSelector", index: 35, message: r"""Missing selector such as '.identifier' or '[0]'.""", tip: r"""Try adding a selector."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingAssignmentInInitializer = messageMissingAssignmentInInitializer; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingAssignmentInInitializer = const MessageCode( "MissingAssignmentInInitializer", index: 34, message: r"""Expected an assignment after the field name.""", tip: r"""To initialize a field, use the syntax 'name = value'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingConstFinalVarOrType = messageMissingConstFinalVarOrType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingConstFinalVarOrType = const MessageCode( "MissingConstFinalVarOrType", index: 33, message: r"""Variables must be declared using the keywords 'const', 'final', 'var' or a type name.""", tip: r"""Try adding the name of the type of the variable or the keyword 'var'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingExplicitConst = messageMissingExplicitConst; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingExplicitConst = const MessageCode( "MissingExplicitConst", analyzerCodes: <String>["NOT_CONSTANT_EXPRESSION"], message: r"""Constant expression expected.""", tip: r"""Try inserting 'const'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(int count)> templateMissingExplicitTypeArguments = const Template<Message Function(int count)>( messageTemplate: r"""No type arguments provided, #count possible.""", withArguments: _withArgumentsMissingExplicitTypeArguments); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(int count)> codeMissingExplicitTypeArguments = const Code<Message Function(int count)>( "MissingExplicitTypeArguments", templateMissingExplicitTypeArguments, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsMissingExplicitTypeArguments(int count) { if (count == null) throw 'No count provided'; return new Message(codeMissingExplicitTypeArguments, message: """No type arguments provided, ${count} possible.""", arguments: {'count': count}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingExponent = messageMissingExponent; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingExponent = const MessageCode("MissingExponent", analyzerCodes: <String>["MISSING_DIGIT"], message: r"""Numbers in exponential notation should always contain an exponent (an integer number with an optional sign).""", tip: r"""Make sure there is an exponent, and remove any whitespace before it."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingExpressionInThrow = messageMissingExpressionInThrow; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingExpressionInThrow = const MessageCode( "MissingExpressionInThrow", index: 32, message: r"""Missing expression after 'throw'.""", tip: r"""Add an expression after 'throw' or use 'rethrow' to throw a caught exception"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingFunctionParameters = messageMissingFunctionParameters; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingFunctionParameters = const MessageCode( "MissingFunctionParameters", analyzerCodes: <String>["MISSING_FUNCTION_PARAMETERS"], message: r"""A function declaration needs an explicit list of parameters.""", tip: r"""Try adding a parameter list to the function declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateMissingImplementationCause = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is defined here.""", withArguments: _withArgumentsMissingImplementationCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeMissingImplementationCause = const Code<Message Function(String name)>( "MissingImplementationCause", templateMissingImplementationCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsMissingImplementationCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeMissingImplementationCause, message: """'${name}' is defined here.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, List<String> _names)> templateMissingImplementationNotAbstract = const Template< Message Function(String name, List<String> _names)>( messageTemplate: r"""The non-abstract class '#name' is missing implementations for these members: #names""", tipTemplate: r"""Try to either - provide an implementation, - inherit an implementation from a superclass or mixin, - mark the class as abstract, or - provide a 'noSuchMethod' implementation. """, withArguments: _withArgumentsMissingImplementationNotAbstract); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, List<String> _names)> codeMissingImplementationNotAbstract = const Code<Message Function(String name, List<String> _names)>( "MissingImplementationNotAbstract", templateMissingImplementationNotAbstract, analyzerCodes: <String>["CONCRETE_CLASS_WITH_ABSTRACT_MEMBER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsMissingImplementationNotAbstract( String name, List<String> _names) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (_names.isEmpty) throw 'No names provided'; String names = itemizeNames(_names); return new Message(codeMissingImplementationNotAbstract, message: """The non-abstract class '${name}' is missing implementations for these members: ${names}""", tip: """Try to either - provide an implementation, - inherit an implementation from a superclass or mixin, - mark the class as abstract, or - provide a 'noSuchMethod' implementation. """, arguments: {'name': name, 'names': _names}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingInput = messageMissingInput; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingInput = const MessageCode("MissingInput", message: r"""No input file provided to the compiler."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingMain = messageMissingMain; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingMain = const MessageCode("MissingMain", message: r"""No 'main' method found.""", tip: r"""Try adding a method named 'main' to your program."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingMethodParameters = messageMissingMethodParameters; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingMethodParameters = const MessageCode( "MissingMethodParameters", analyzerCodes: <String>["MISSING_METHOD_PARAMETERS"], message: r"""A method declaration needs an explicit list of parameters.""", tip: r"""Try adding a parameter list to the method declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingOperatorKeyword = messageMissingOperatorKeyword; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingOperatorKeyword = const MessageCode( "MissingOperatorKeyword", index: 31, message: r"""Operator declarations must be preceded by the keyword 'operator'.""", tip: r"""Try adding the keyword 'operator'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(Uri uri_)> templateMissingPartOf = const Template< Message Function(Uri uri_)>( messageTemplate: r"""Can't use '#uri' as a part, because it has no 'part of' declaration.""", withArguments: _withArgumentsMissingPartOf); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeMissingPartOf = const Code<Message Function(Uri uri_)>( "MissingPartOf", templateMissingPartOf, analyzerCodes: <String>["PART_OF_NON_PART"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsMissingPartOf(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeMissingPartOf, message: """Can't use '${uri}' as a part, because it has no 'part of' declaration.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingPrefixInDeferredImport = messageMissingPrefixInDeferredImport; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingPrefixInDeferredImport = const MessageCode( "MissingPrefixInDeferredImport", index: 30, message: r"""Deferred imports should have a prefix.""", tip: r"""Try adding a prefix to the import by adding an 'as' clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMissingTypedefParameters = messageMissingTypedefParameters; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMissingTypedefParameters = const MessageCode( "MissingTypedefParameters", analyzerCodes: <String>["MISSING_TYPEDEF_PARAMETERS"], message: r"""A typedef needs an explicit list of parameters.""", tip: r"""Try adding a parameter list to the typedef."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(DartType _type, DartType _type2, DartType _type3)> templateMixinApplicationIncompatibleSupertype = const Template< Message Function(DartType _type, DartType _type2, DartType _type3)>( messageTemplate: r"""'#type' doesn't implement '#type2' so it can't be used with '#type3'.""", withArguments: _withArgumentsMixinApplicationIncompatibleSupertype); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2, DartType _type3)> codeMixinApplicationIncompatibleSupertype = const Code< Message Function(DartType _type, DartType _type2, DartType _type3)>( "MixinApplicationIncompatibleSupertype", templateMixinApplicationIncompatibleSupertype, analyzerCodes: <String>["MIXIN_APPLICATION_NOT_IMPLEMENTED_INTERFACE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsMixinApplicationIncompatibleSupertype( DartType _type, DartType _type2, DartType _type3) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); List<Object> type3Parts = labeler.labelType(_type3); String type = typeParts.join(); String type2 = type2Parts.join(); String type3 = type3Parts.join(); return new Message(codeMixinApplicationIncompatibleSupertype, message: """'${type}' doesn't implement '${type2}' so it can't be used with '${type3}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2, 'type3': _type3}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMixinDeclaresConstructor = messageMixinDeclaresConstructor; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMixinDeclaresConstructor = const MessageCode( "MixinDeclaresConstructor", index: 95, message: r"""Mixins can't declare constructors."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2, DartType _type)> templateMixinInferenceNoMatchingClass = const Template< Message Function(String name, String name2, DartType _type)>( messageTemplate: r"""Type parameters could not be inferred for the mixin '#name' because '#name2' does not implement the mixin's supertype constraint '#type'.""", withArguments: _withArgumentsMixinInferenceNoMatchingClass); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2, DartType _type)> codeMixinInferenceNoMatchingClass = const Code<Message Function(String name, String name2, DartType _type)>( "MixinInferenceNoMatchingClass", templateMixinInferenceNoMatchingClass, analyzerCodes: <String>["MIXIN_INFERENCE_NO_POSSIBLE_SUBSTITUTION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsMixinInferenceNoMatchingClass( String name, String name2, DartType _type) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeMixinInferenceNoMatchingClass, message: """Type parameters could not be inferred for the mixin '${name}' because '${name2}' does not implement the mixin's supertype constraint '${type}'.""" + labeler.originMessages, arguments: {'name': name, 'name2': name2, 'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, String string2)> templateModifierOutOfOrder = const Template< Message Function(String string, String string2)>( messageTemplate: r"""The modifier '#string' should be before the modifier '#string2'.""", tipTemplate: r"""Try re-ordering the modifiers.""", withArguments: _withArgumentsModifierOutOfOrder); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeModifierOutOfOrder = const Code<Message Function(String string, String string2)>( "ModifierOutOfOrder", templateModifierOutOfOrder, index: 56); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsModifierOutOfOrder(String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeModifierOutOfOrder, message: """The modifier '${string}' should be before the modifier '${string2}'.""", tip: """Try re-ordering the modifiers.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMoreThanOneSuperOrThisInitializer = messageMoreThanOneSuperOrThisInitializer; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMoreThanOneSuperOrThisInitializer = const MessageCode( "MoreThanOneSuperOrThisInitializer", analyzerCodes: <String>["SUPER_IN_REDIRECTING_CONSTRUCTOR"], message: r"""Can't have more than one 'super' or 'this' initializer."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMultipleExtends = messageMultipleExtends; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMultipleExtends = const MessageCode("MultipleExtends", index: 28, message: r"""Each class definition can have at most one extends clause.""", tip: r"""Try choosing one superclass and define your class to implement (or mix in) the others."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMultipleImplements = messageMultipleImplements; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMultipleImplements = const MessageCode( "MultipleImplements", analyzerCodes: <String>["MULTIPLE_IMPLEMENTS_CLAUSES"], message: r"""Each class definition can have at most one implements clause.""", tip: r"""Try combining all of the implements clauses into a single clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMultipleLibraryDirectives = messageMultipleLibraryDirectives; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMultipleLibraryDirectives = const MessageCode( "MultipleLibraryDirectives", index: 27, message: r"""Only one library directive may be declared in a file.""", tip: r"""Try removing all but one of the library directives."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMultipleOnClauses = messageMultipleOnClauses; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMultipleOnClauses = const MessageCode( "MultipleOnClauses", index: 26, message: r"""Each mixin definition can have at most one on clause.""", tip: r"""Try combining all of the on clauses into a single clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMultipleVarianceModifiers = messageMultipleVarianceModifiers; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMultipleVarianceModifiers = const MessageCode( "MultipleVarianceModifiers", index: 97, message: r"""Each type parameter can have at most one variance modifier.""", tip: r"""Use at most one of the 'in', 'out', or 'inout' modifiers."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeMultipleWith = messageMultipleWith; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageMultipleWith = const MessageCode("MultipleWith", index: 24, message: r"""Each class definition can have at most one with clause.""", tip: r"""Try combining all of the with clauses into a single clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNamedFunctionExpression = messageNamedFunctionExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNamedFunctionExpression = const MessageCode( "NamedFunctionExpression", analyzerCodes: <String>["NAMED_FUNCTION_EXPRESSION"], message: r"""A function expression can't have a name."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateNamedMixinOverride = const Template< Message Function(String name, String name2)>( messageTemplate: r"""The mixin application class '#name' introduces an erroneous override of '#name2'.""", withArguments: _withArgumentsNamedMixinOverride); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeNamedMixinOverride = const Code<Message Function(String name, String name2)>( "NamedMixinOverride", templateNamedMixinOverride, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNamedMixinOverride(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeNamedMixinOverride, message: """The mixin application class '${name}' introduces an erroneous override of '${name2}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNativeClauseShouldBeAnnotation = messageNativeClauseShouldBeAnnotation; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNativeClauseShouldBeAnnotation = const MessageCode( "NativeClauseShouldBeAnnotation", index: 23, message: r"""Native clause in this form is deprecated.""", tip: r"""Try removing this native clause and adding @native() or @native('native-name') before the declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(Token token)> templateNoFormals = const Template< Message Function(Token token)>( messageTemplate: r"""A function should have formal parameters.""", tipTemplate: r"""Try adding '()' after '#lexeme', or add 'get' before '#lexeme' to declare a getter.""", withArguments: _withArgumentsNoFormals); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeNoFormals = const Code<Message Function(Token token)>("NoFormals", templateNoFormals, analyzerCodes: <String>["MISSING_FUNCTION_PARAMETERS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNoFormals(Token token) { String lexeme = token.lexeme; return new Message(codeNoFormals, message: """A function should have formal parameters.""", tip: """Try adding '()' after '${lexeme}', or add 'get' before '${lexeme}' to declare a getter.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateNoSuchNamedParameter = const Template<Message Function(String name)>( messageTemplate: r"""No named parameter with the name '#name'.""", withArguments: _withArgumentsNoSuchNamedParameter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeNoSuchNamedParameter = const Code<Message Function(String name)>( "NoSuchNamedParameter", templateNoSuchNamedParameter, analyzerCodes: <String>["UNDEFINED_NAMED_PARAMETER"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNoSuchNamedParameter(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeNoSuchNamedParameter, message: """No named parameter with the name '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNoUnnamedConstructorInObject = messageNoUnnamedConstructorInObject; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNoUnnamedConstructorInObject = const MessageCode( "NoUnnamedConstructorInObject", message: r"""'Object' has no unnamed constructor."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String character, int codePoint)> templateNonAsciiIdentifier = const Template< Message Function(String character, int codePoint)>( messageTemplate: r"""The non-ASCII character '#character' (#unicode) can't be used in identifiers, only in strings and comments.""", tipTemplate: r"""Try using an US-ASCII letter, a digit, '_' (an underscore), or '$' (a dollar sign).""", withArguments: _withArgumentsNonAsciiIdentifier); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String character, int codePoint)> codeNonAsciiIdentifier = const Code<Message Function(String character, int codePoint)>( "NonAsciiIdentifier", templateNonAsciiIdentifier, analyzerCodes: <String>["ILLEGAL_CHARACTER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNonAsciiIdentifier(String character, int codePoint) { if (character.runes.length != 1) throw "Not a character '${character}'"; String unicode = "U+${codePoint.toRadixString(16).toUpperCase().padLeft(4, '0')}"; return new Message(codeNonAsciiIdentifier, message: """The non-ASCII character '${character}' (${unicode}) can't be used in identifiers, only in strings and comments.""", tip: """Try using an US-ASCII letter, a digit, '_' (an underscore), or '\$' (a dollar sign).""", arguments: {'character': character, 'codePoint': codePoint}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int codePoint)> templateNonAsciiWhitespace = const Template< Message Function(int codePoint)>( messageTemplate: r"""The non-ASCII space character #unicode can only be used in strings and comments.""", withArguments: _withArgumentsNonAsciiWhitespace); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(int codePoint)> codeNonAsciiWhitespace = const Code<Message Function(int codePoint)>( "NonAsciiWhitespace", templateNonAsciiWhitespace, analyzerCodes: <String>["ILLEGAL_CHARACTER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNonAsciiWhitespace(int codePoint) { String unicode = "U+${codePoint.toRadixString(16).toUpperCase().padLeft(4, '0')}"; return new Message(codeNonAsciiWhitespace, message: """The non-ASCII space character ${unicode} can only be used in strings and comments.""", arguments: {'codePoint': codePoint}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNonConstConstructor = messageNonConstConstructor; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNonConstConstructor = const MessageCode( "NonConstConstructor", analyzerCodes: <String>["NOT_CONSTANT_EXPRESSION"], message: r"""Cannot invoke a non-'const' constructor where a const expression is expected.""", tip: r"""Try using a constructor or factory that is 'const'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNonConstFactory = messageNonConstFactory; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNonConstFactory = const MessageCode("NonConstFactory", analyzerCodes: <String>["NOT_CONSTANT_EXPRESSION"], message: r"""Cannot invoke a non-'const' factory where a const expression is expected.""", tip: r"""Try using a constructor or factory that is 'const'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNonInstanceTypeVariableUse = messageNonInstanceTypeVariableUse; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNonInstanceTypeVariableUse = const MessageCode( "NonInstanceTypeVariableUse", analyzerCodes: <String>["TYPE_PARAMETER_REFERENCED_BY_STATIC"], severity: Severity.errorLegacyWarning, message: r"""Can only use type variables in instance methods."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNonNullAwareSpreadIsNull = messageNonNullAwareSpreadIsNull; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNonNullAwareSpreadIsNull = const MessageCode( "NonNullAwareSpreadIsNull", message: r"""Can't spread a value with static type Null."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNonPartOfDirectiveInPart = messageNonPartOfDirectiveInPart; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNonPartOfDirectiveInPart = const MessageCode( "NonPartOfDirectiveInPart", analyzerCodes: <String>["NON_PART_OF_DIRECTIVE_IN_PART"], message: r"""The part-of directive must be the only directive in a part.""", tip: r"""Try removing the other directives, or moving them to the library for which this is a part."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateNonSimpleBoundViaReference = const Template<Message Function(String name)>( messageTemplate: r"""Bound of this variable references raw type '#name'.""", withArguments: _withArgumentsNonSimpleBoundViaReference); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeNonSimpleBoundViaReference = const Code<Message Function(String name)>( "NonSimpleBoundViaReference", templateNonSimpleBoundViaReference, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNonSimpleBoundViaReference(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeNonSimpleBoundViaReference, message: """Bound of this variable references raw type '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateNonSimpleBoundViaVariable = const Template< Message Function(String name)>( messageTemplate: r"""Bound of this variable references variable '#name' from the same declaration.""", withArguments: _withArgumentsNonSimpleBoundViaVariable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeNonSimpleBoundViaVariable = const Code<Message Function(String name)>( "NonSimpleBoundViaVariable", templateNonSimpleBoundViaVariable, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNonSimpleBoundViaVariable(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeNonSimpleBoundViaVariable, message: """Bound of this variable references variable '${name}' from the same declaration.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNotAConstantExpression = messageNotAConstantExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNotAConstantExpression = const MessageCode( "NotAConstantExpression", analyzerCodes: <String>["NOT_CONSTANT_EXPRESSION"], message: r"""Not a constant expression."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateNotAPrefixInTypeAnnotation = const Template< Message Function(String name, String name2)>( messageTemplate: r"""'#name.#name2' can't be used as a type because '#name' doesn't refer to an import prefix.""", withArguments: _withArgumentsNotAPrefixInTypeAnnotation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeNotAPrefixInTypeAnnotation = const Code<Message Function(String name, String name2)>( "NotAPrefixInTypeAnnotation", templateNotAPrefixInTypeAnnotation, analyzerCodes: <String>["NOT_A_TYPE"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNotAPrefixInTypeAnnotation(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeNotAPrefixInTypeAnnotation, message: """'${name}.${name2}' can't be used as a type because '${name}' doesn't refer to an import prefix.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateNotAType = const Template<Message Function(String name)>( messageTemplate: r"""'#name' isn't a type.""", withArguments: _withArgumentsNotAType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeNotAType = const Code<Message Function(String name)>("NotAType", templateNotAType, analyzerCodes: <String>["NOT_A_TYPE"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNotAType(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeNotAType, message: """'${name}' isn't a type.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNotATypeContext = messageNotATypeContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNotATypeContext = const MessageCode("NotATypeContext", severity: Severity.context, message: r"""This isn't a type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNotAnLvalue = messageNotAnLvalue; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNotAnLvalue = const MessageCode("NotAnLvalue", analyzerCodes: <String>["NOT_AN_LVALUE"], message: r"""Can't assign to this."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateNotBinaryOperator = const Template<Message Function(Token token)>( messageTemplate: r"""'#lexeme' isn't a binary operator.""", withArguments: _withArgumentsNotBinaryOperator); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeNotBinaryOperator = const Code<Message Function(Token token)>( "NotBinaryOperator", templateNotBinaryOperator, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNotBinaryOperator(Token token) { String lexeme = token.lexeme; return new Message(codeNotBinaryOperator, message: """'${lexeme}' isn't a binary operator.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateNotConstantExpression = const Template<Message Function(String string)>( messageTemplate: r"""#string is not a constant expression.""", withArguments: _withArgumentsNotConstantExpression); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeNotConstantExpression = const Code<Message Function(String string)>( "NotConstantExpression", templateNotConstantExpression, analyzerCodes: <String>["NOT_CONSTANT_EXPRESSION"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsNotConstantExpression(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeNotConstantExpression, message: """${string} is not a constant expression.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeNullAwareCascadeOutOfOrder = messageNullAwareCascadeOutOfOrder; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageNullAwareCascadeOutOfOrder = const MessageCode( "NullAwareCascadeOutOfOrder", index: 96, message: r"""The '?..' cascade operator must be first in the cascade sequence.""", tip: r"""Try moving the '?..' operator to be the first cascade operator in the sequence."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeObjectExtends = messageObjectExtends; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageObjectExtends = const MessageCode("ObjectExtends", message: r"""The class 'Object' can't have a superclass."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeObjectImplements = messageObjectImplements; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageObjectImplements = const MessageCode( "ObjectImplements", message: r"""The class 'Object' can't implement anything."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeObjectMixesIn = messageObjectMixesIn; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageObjectMixesIn = const MessageCode("ObjectMixesIn", message: r"""The class 'Object' can't use mixins."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeOnlyTry = messageOnlyTry; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageOnlyTry = const MessageCode("OnlyTry", index: 20, message: r"""A try block must be followed by an 'on', 'catch', or 'finally' clause.""", tip: r"""Try adding either a catch or finally clause, or remove the try statement."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateOperatorMinusParameterMismatch = const Template< Message Function(String name)>( messageTemplate: r"""Operator '#name' should have zero or one parameter.""", tipTemplate: r"""With zero parameters, it has the syntactic form '-a', formally known as 'unary-'. With one parameter, it has the syntactic form 'a - b', formally known as '-'.""", withArguments: _withArgumentsOperatorMinusParameterMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeOperatorMinusParameterMismatch = const Code<Message Function(String name)>("OperatorMinusParameterMismatch", templateOperatorMinusParameterMismatch, analyzerCodes: <String>[ "WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS" ]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOperatorMinusParameterMismatch(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeOperatorMinusParameterMismatch, message: """Operator '${name}' should have zero or one parameter.""", tip: """With zero parameters, it has the syntactic form '-a', formally known as 'unary-'. With one parameter, it has the syntactic form 'a - b', formally known as '-'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateOperatorParameterMismatch0 = const Template<Message Function(String name)>( messageTemplate: r"""Operator '#name' shouldn't have any parameters.""", withArguments: _withArgumentsOperatorParameterMismatch0); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeOperatorParameterMismatch0 = const Code<Message Function(String name)>( "OperatorParameterMismatch0", templateOperatorParameterMismatch0, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOperatorParameterMismatch0(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeOperatorParameterMismatch0, message: """Operator '${name}' shouldn't have any parameters.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateOperatorParameterMismatch1 = const Template<Message Function(String name)>( messageTemplate: r"""Operator '#name' should have exactly one parameter.""", withArguments: _withArgumentsOperatorParameterMismatch1); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeOperatorParameterMismatch1 = const Code<Message Function(String name)>( "OperatorParameterMismatch1", templateOperatorParameterMismatch1, analyzerCodes: <String>["WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOperatorParameterMismatch1(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeOperatorParameterMismatch1, message: """Operator '${name}' should have exactly one parameter.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateOperatorParameterMismatch2 = const Template<Message Function(String name)>( messageTemplate: r"""Operator '#name' should have exactly two parameters.""", withArguments: _withArgumentsOperatorParameterMismatch2); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeOperatorParameterMismatch2 = const Code<Message Function(String name)>( "OperatorParameterMismatch2", templateOperatorParameterMismatch2, analyzerCodes: <String>["WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOperatorParameterMismatch2(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeOperatorParameterMismatch2, message: """Operator '${name}' should have exactly two parameters.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeOperatorWithOptionalFormals = messageOperatorWithOptionalFormals; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageOperatorWithOptionalFormals = const MessageCode( "OperatorWithOptionalFormals", message: r"""An operator can't have optional parameters."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateOverriddenMethodCause = const Template<Message Function(String name)>( messageTemplate: r"""This is the overridden method ('#name').""", withArguments: _withArgumentsOverriddenMethodCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeOverriddenMethodCause = const Code<Message Function(String name)>( "OverriddenMethodCause", templateOverriddenMethodCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverriddenMethodCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeOverriddenMethodCause, message: """This is the overridden method ('${name}').""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateOverrideFewerNamedArguments = const Template< Message Function(String name, String name2)>( messageTemplate: r"""The method '#name' has fewer named arguments than those of overridden method '#name2'.""", withArguments: _withArgumentsOverrideFewerNamedArguments); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeOverrideFewerNamedArguments = const Code<Message Function(String name, String name2)>( "OverrideFewerNamedArguments", templateOverrideFewerNamedArguments, analyzerCodes: <String>["INVALID_OVERRIDE_NAMED"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideFewerNamedArguments(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeOverrideFewerNamedArguments, message: """The method '${name}' has fewer named arguments than those of overridden method '${name2}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateOverrideFewerPositionalArguments = const Template< Message Function(String name, String name2)>( messageTemplate: r"""The method '#name' has fewer positional arguments than those of overridden method '#name2'.""", withArguments: _withArgumentsOverrideFewerPositionalArguments); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeOverrideFewerPositionalArguments = const Code<Message Function(String name, String name2)>( "OverrideFewerPositionalArguments", templateOverrideFewerPositionalArguments, analyzerCodes: <String>["INVALID_OVERRIDE_POSITIONAL"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideFewerPositionalArguments( String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeOverrideFewerPositionalArguments, message: """The method '${name}' has fewer positional arguments than those of overridden method '${name2}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2, String name3)> templateOverrideMismatchNamedParameter = const Template< Message Function(String name, String name2, String name3)>( messageTemplate: r"""The method '#name' doesn't have the named parameter '#name2' of overridden method '#name3'.""", withArguments: _withArgumentsOverrideMismatchNamedParameter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2, String name3)> codeOverrideMismatchNamedParameter = const Code<Message Function(String name, String name2, String name3)>( "OverrideMismatchNamedParameter", templateOverrideMismatchNamedParameter, analyzerCodes: <String>["INVALID_OVERRIDE_NAMED"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideMismatchNamedParameter( String name, String name2, String name3) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); if (name3.isEmpty) throw 'No name provided'; name3 = demangleMixinApplicationName(name3); return new Message(codeOverrideMismatchNamedParameter, message: """The method '${name}' doesn't have the named parameter '${name2}' of overridden method '${name3}'.""", arguments: {'name': name, 'name2': name2, 'name3': name3}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateOverrideMoreRequiredArguments = const Template< Message Function(String name, String name2)>( messageTemplate: r"""The method '#name' has more required arguments than those of overridden method '#name2'.""", withArguments: _withArgumentsOverrideMoreRequiredArguments); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeOverrideMoreRequiredArguments = const Code<Message Function(String name, String name2)>( "OverrideMoreRequiredArguments", templateOverrideMoreRequiredArguments, analyzerCodes: <String>["INVALID_OVERRIDE_REQUIRED"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideMoreRequiredArguments(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeOverrideMoreRequiredArguments, message: """The method '${name}' has more required arguments than those of overridden method '${name2}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2, DartType _type, DartType _type2, String name3)> templateOverrideTypeMismatchParameter = const Template< Message Function( String name, String name2, DartType _type, DartType _type2, String name3)>( messageTemplate: r"""The parameter '#name' of the method '#name2' has type '#type', which does not match the corresponding type, '#type2', in the overridden method, '#name3'.""", tipTemplate: r"""Change to a supertype of '#type2', or, for a covariant parameter, a subtype.""", withArguments: _withArgumentsOverrideTypeMismatchParameter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(String name, String name2, DartType _type, DartType _type2, String name3)> codeOverrideTypeMismatchParameter = const Code< Message Function(String name, String name2, DartType _type, DartType _type2, String name3)>( "OverrideTypeMismatchParameter", templateOverrideTypeMismatchParameter, analyzerCodes: <String>["INVALID_METHOD_OVERRIDE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideTypeMismatchParameter( String name, String name2, DartType _type, DartType _type2, String name3) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name3.isEmpty) throw 'No name provided'; name3 = demangleMixinApplicationName(name3); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeOverrideTypeMismatchParameter, message: """The parameter '${name}' of the method '${name2}' has type '${type}', which does not match the corresponding type, '${type2}', in the overridden method, '${name3}'.""" + labeler.originMessages, tip: """Change to a supertype of '${type2}', or, for a covariant parameter, a subtype.""", arguments: { 'name': name, 'name2': name2, 'type': _type, 'type2': _type2, 'name3': name3 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type, DartType _type2, String name2)> templateOverrideTypeMismatchReturnType = const Template< Message Function( String name, DartType _type, DartType _type2, String name2)>( messageTemplate: r"""The return type of the method '#name' is '#type', which does not match the return type, '#type2', of the overridden method, '#name2'.""", tipTemplate: r"""Change to a subtype of '#type2'.""", withArguments: _withArgumentsOverrideTypeMismatchReturnType); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function( String name, DartType _type, DartType _type2, String name2)> codeOverrideTypeMismatchReturnType = const Code< Message Function( String name, DartType _type, DartType _type2, String name2)>( "OverrideTypeMismatchReturnType", templateOverrideTypeMismatchReturnType, analyzerCodes: <String>["INVALID_METHOD_OVERRIDE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideTypeMismatchReturnType( String name, DartType _type, DartType _type2, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeOverrideTypeMismatchReturnType, message: """The return type of the method '${name}' is '${type}', which does not match the return type, '${type2}', of the overridden method, '${name2}'.""" + labeler.originMessages, tip: """Change to a subtype of '${type2}'.""", arguments: { 'name': name, 'type': _type, 'type2': _type2, 'name2': name2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type, DartType _type2, String name2)> templateOverrideTypeMismatchSetter = const Template< Message Function( String name, DartType _type, DartType _type2, String name2)>( messageTemplate: r"""The field '#name' has type '#type', which does not match the corresponding type, '#type2', in the overridden setter, '#name2'.""", withArguments: _withArgumentsOverrideTypeMismatchSetter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function( String name, DartType _type, DartType _type2, String name2)> codeOverrideTypeMismatchSetter = const Code< Message Function( String name, DartType _type, DartType _type2, String name2)>( "OverrideTypeMismatchSetter", templateOverrideTypeMismatchSetter, analyzerCodes: <String>["INVALID_METHOD_OVERRIDE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideTypeMismatchSetter( String name, DartType _type, DartType _type2, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeOverrideTypeMismatchSetter, message: """The field '${name}' has type '${type}', which does not match the corresponding type, '${type2}', in the overridden setter, '${name2}'.""" + labeler.originMessages, arguments: { 'name': name, 'type': _type, 'type2': _type2, 'name2': name2 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateOverrideTypeVariablesMismatch = const Template< Message Function(String name, String name2)>( messageTemplate: r"""Declared type variables of '#name' doesn't match those on overridden method '#name2'.""", withArguments: _withArgumentsOverrideTypeVariablesMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeOverrideTypeVariablesMismatch = const Code<Message Function(String name, String name2)>( "OverrideTypeVariablesMismatch", templateOverrideTypeVariablesMismatch, analyzerCodes: <String>["INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsOverrideTypeVariablesMismatch(String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeOverrideTypeVariablesMismatch, message: """Declared type variables of '${name}' doesn't match those on overridden method '${name2}'.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(String name, Uri uri_)> templatePackageNotFound = const Template<Message Function(String name, Uri uri_)>( messageTemplate: r"""Could not resolve the package '#name' in '#uri'.""", withArguments: _withArgumentsPackageNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_)> codePackageNotFound = const Code<Message Function(String name, Uri uri_)>( "PackageNotFound", templatePackageNotFound, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPackageNotFound(String name, Uri uri_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); return new Message(codePackageNotFound, message: """Could not resolve the package '${name}' in '${uri}'.""", arguments: {'name': name, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templatePackagesFileFormat = const Template<Message Function(String string)>( messageTemplate: r"""Problem in packages configuration file: #string""", withArguments: _withArgumentsPackagesFileFormat); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codePackagesFileFormat = const Code<Message Function(String string)>( "PackagesFileFormat", templatePackagesFileFormat, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPackagesFileFormat(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codePackagesFileFormat, message: """Problem in packages configuration file: ${string}""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartExport = messagePartExport; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartExport = const MessageCode("PartExport", analyzerCodes: <String>["EXPORT_OF_NON_LIBRARY"], message: r"""Can't export this file because it contains a 'part of' declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartExportContext = messagePartExportContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartExportContext = const MessageCode( "PartExportContext", severity: Severity.context, message: r"""This is the file that can't be exported."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartInPart = messagePartInPart; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartInPart = const MessageCode("PartInPart", analyzerCodes: <String>["NON_PART_OF_DIRECTIVE_IN_PART"], message: r"""A file that's a part of a library can't have parts itself.""", tip: r"""Try moving the 'part' declaration to the containing library."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartInPartLibraryContext = messagePartInPartLibraryContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartInPartLibraryContext = const MessageCode( "PartInPartLibraryContext", severity: Severity.context, message: r"""This is the containing library."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function(Uri uri_)> templatePartOfInLibrary = const Template< Message Function(Uri uri_)>( messageTemplate: r"""Can't import '#uri', because it has a 'part of' declaration.""", tipTemplate: r"""Try removing the 'part of' declaration, or using '#uri' as a part.""", withArguments: _withArgumentsPartOfInLibrary); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codePartOfInLibrary = const Code<Message Function(Uri uri_)>( "PartOfInLibrary", templatePartOfInLibrary, analyzerCodes: <String>["IMPORT_OF_NON_LIBRARY"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPartOfInLibrary(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codePartOfInLibrary, message: """Can't import '${uri}', because it has a 'part of' declaration.""", tip: """Try removing the 'part of' declaration, or using '${uri}' as a part.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Uri uri_, String name, String name2)> templatePartOfLibraryNameMismatch = const Template< Message Function(Uri uri_, String name, String name2)>( messageTemplate: r"""Using '#uri' as part of '#name' but its 'part of' declaration says '#name2'.""", withArguments: _withArgumentsPartOfLibraryNameMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_, String name, String name2)> codePartOfLibraryNameMismatch = const Code<Message Function(Uri uri_, String name, String name2)>( "PartOfLibraryNameMismatch", templatePartOfLibraryNameMismatch, analyzerCodes: <String>["PART_OF_DIFFERENT_LIBRARY"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPartOfLibraryNameMismatch( Uri uri_, String name, String name2) { String uri = relativizeUri(uri_); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codePartOfLibraryNameMismatch, message: """Using '${uri}' as part of '${name}' but its 'part of' declaration says '${name2}'.""", arguments: {'uri': uri_, 'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartOfSelf = messagePartOfSelf; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartOfSelf = const MessageCode("PartOfSelf", analyzerCodes: <String>["PART_OF_NON_PART"], message: r"""A file can't be a part of itself."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartOfTwice = messagePartOfTwice; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartOfTwice = const MessageCode("PartOfTwice", index: 25, message: r"""Only one part-of directive may be declared in a file.""", tip: r"""Try removing all but one of the part-of directives."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartOfTwoLibraries = messagePartOfTwoLibraries; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartOfTwoLibraries = const MessageCode( "PartOfTwoLibraries", analyzerCodes: <String>["PART_OF_DIFFERENT_LIBRARY"], message: r"""A file can't be part of more than one library.""", tip: r"""Try moving the shared declarations into the libraries, or into a new library."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartOfTwoLibrariesContext = messagePartOfTwoLibrariesContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartOfTwoLibrariesContext = const MessageCode( "PartOfTwoLibrariesContext", severity: Severity.context, message: r"""Used as a part in this library."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Uri uri_, Uri uri2_, Uri uri3_)> templatePartOfUriMismatch = const Template< Message Function(Uri uri_, Uri uri2_, Uri uri3_)>( messageTemplate: r"""Using '#uri' as part of '#uri2' but its 'part of' declaration says '#uri3'.""", withArguments: _withArgumentsPartOfUriMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_, Uri uri2_, Uri uri3_)> codePartOfUriMismatch = const Code<Message Function(Uri uri_, Uri uri2_, Uri uri3_)>( "PartOfUriMismatch", templatePartOfUriMismatch, analyzerCodes: <String>["PART_OF_DIFFERENT_LIBRARY"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPartOfUriMismatch(Uri uri_, Uri uri2_, Uri uri3_) { String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); String uri3 = relativizeUri(uri3_); return new Message(codePartOfUriMismatch, message: """Using '${uri}' as part of '${uri2}' but its 'part of' declaration says '${uri3}'.""", arguments: {'uri': uri_, 'uri2': uri2_, 'uri3': uri3_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Uri uri_, Uri uri2_, String name)> templatePartOfUseUri = const Template< Message Function(Uri uri_, Uri uri2_, String name)>( messageTemplate: r"""Using '#uri' as part of '#uri2' but its 'part of' declaration says '#name'.""", tipTemplate: r"""Try changing the 'part of' declaration to use a relative file name.""", withArguments: _withArgumentsPartOfUseUri); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_, Uri uri2_, String name)> codePartOfUseUri = const Code<Message Function(Uri uri_, Uri uri2_, String name)>( "PartOfUseUri", templatePartOfUseUri, analyzerCodes: <String>["PART_OF_UNNAMED_LIBRARY"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPartOfUseUri(Uri uri_, Uri uri2_, String name) { String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codePartOfUseUri, message: """Using '${uri}' as part of '${uri2}' but its 'part of' declaration says '${name}'.""", tip: """Try changing the 'part of' declaration to use a relative file name.""", arguments: {'uri': uri_, 'uri2': uri2_, 'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePartOrphan = messagePartOrphan; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePartOrphan = const MessageCode("PartOrphan", message: r"""This part doesn't have a containing library.""", tip: r"""Try removing the 'part of' declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_)> templatePartTwice = const Template<Message Function(Uri uri_)>( messageTemplate: r"""Can't use '#uri' as a part more than once.""", withArguments: _withArgumentsPartTwice); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codePartTwice = const Code<Message Function(Uri uri_)>("PartTwice", templatePartTwice, analyzerCodes: <String>["DUPLICATE_PART"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPartTwice(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codePartTwice, message: """Can't use '${uri}' as a part more than once.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePatchClassOrigin = messagePatchClassOrigin; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePatchClassOrigin = const MessageCode( "PatchClassOrigin", severity: Severity.context, message: r"""This is the origin class."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePatchClassTypeVariablesMismatch = messagePatchClassTypeVariablesMismatch; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePatchClassTypeVariablesMismatch = const MessageCode( "PatchClassTypeVariablesMismatch", message: r"""A patch class must have the same number of type variables as its origin class."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePatchDeclarationMismatch = messagePatchDeclarationMismatch; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePatchDeclarationMismatch = const MessageCode( "PatchDeclarationMismatch", message: r"""This patch doesn't match origin declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePatchDeclarationOrigin = messagePatchDeclarationOrigin; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePatchDeclarationOrigin = const MessageCode( "PatchDeclarationOrigin", severity: Severity.context, message: r"""This is the origin declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_)> templatePatchInjectionFailed = const Template<Message Function(String name, Uri uri_)>( messageTemplate: r"""Can't inject '#name' into '#uri'.""", tipTemplate: r"""Try adding '@patch'.""", withArguments: _withArgumentsPatchInjectionFailed); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_)> codePatchInjectionFailed = const Code<Message Function(String name, Uri uri_)>( "PatchInjectionFailed", templatePatchInjectionFailed, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsPatchInjectionFailed(String name, Uri uri_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); return new Message(codePatchInjectionFailed, message: """Can't inject '${name}' into '${uri}'.""", tip: """Try adding '@patch'.""", arguments: {'name': name, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePatchNonExternal = messagePatchNonExternal; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePatchNonExternal = const MessageCode( "PatchNonExternal", message: r"""Can't apply this patch as its origin declaration isn't external.""", tip: r"""Try adding 'external' to the origin declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePlatformPrivateLibraryAccess = messagePlatformPrivateLibraryAccess; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePlatformPrivateLibraryAccess = const MessageCode( "PlatformPrivateLibraryAccess", analyzerCodes: <String>["IMPORT_INTERNAL_LIBRARY"], message: r"""Can't access platform private library."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePositionalAfterNamedArgument = messagePositionalAfterNamedArgument; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePositionalAfterNamedArgument = const MessageCode( "PositionalAfterNamedArgument", analyzerCodes: <String>["POSITIONAL_AFTER_NAMED_ARGUMENT"], message: r"""Place positional arguments before named arguments.""", tip: r"""Try moving the positional argument before the named arguments, or add a name to the argument."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePositionalParameterWithEquals = messagePositionalParameterWithEquals; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePositionalParameterWithEquals = const MessageCode( "PositionalParameterWithEquals", analyzerCodes: <String>["WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER"], message: r"""Positional optional parameters can't use ':' to specify a default value.""", tip: r"""Try replacing ':' with '='."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePrefixAfterCombinator = messagePrefixAfterCombinator; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePrefixAfterCombinator = const MessageCode( "PrefixAfterCombinator", index: 6, message: r"""The prefix ('as' clause) should come before any show/hide combinators.""", tip: r"""Try moving the prefix before the combinators."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codePrivateNamedParameter = messagePrivateNamedParameter; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messagePrivateNamedParameter = const MessageCode( "PrivateNamedParameter", analyzerCodes: <String>["PRIVATE_OPTIONAL_PARAMETER"], message: r"""An optional named parameter can't start with '_'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeRedirectingConstructorWithBody = messageRedirectingConstructorWithBody; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageRedirectingConstructorWithBody = const MessageCode( "RedirectingConstructorWithBody", index: 22, message: r"""Redirecting constructors can't have a body.""", tip: r"""Try removing the body, or not making this a redirecting constructor."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(DartType _type, DartType _type2)> templateRedirectingFactoryIncompatibleTypeArgument = const Template<Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""The type '#type' doesn't extend '#type2'.""", tipTemplate: r"""Try using a different type as argument.""", withArguments: _withArgumentsRedirectingFactoryIncompatibleTypeArgument); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeRedirectingFactoryIncompatibleTypeArgument = const Code<Message Function(DartType _type, DartType _type2)>( "RedirectingFactoryIncompatibleTypeArgument", templateRedirectingFactoryIncompatibleTypeArgument, analyzerCodes: <String>["TYPE_ARGUMENT_NOT_MATCHING_BOUNDS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsRedirectingFactoryIncompatibleTypeArgument( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeRedirectingFactoryIncompatibleTypeArgument, message: """The type '${type}' doesn't extend '${type2}'.""" + labeler.originMessages, tip: """Try using a different type as argument.""", arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeRedirectionInNonFactory = messageRedirectionInNonFactory; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageRedirectionInNonFactory = const MessageCode( "RedirectionInNonFactory", index: 21, message: r"""Only factory constructor can specify '=' redirection.""", tip: r"""Try making this a factory constructor, or remove the redirection."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateRedirectionTargetNotFound = const Template<Message Function(String name)>( messageTemplate: r"""Redirection constructor target not found: '#name'""", withArguments: _withArgumentsRedirectionTargetNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeRedirectionTargetNotFound = const Code<Message Function(String name)>( "RedirectionTargetNotFound", templateRedirectionTargetNotFound, analyzerCodes: <String>["REDIRECT_TO_MISSING_CONSTRUCTOR"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsRedirectionTargetNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeRedirectionTargetNotFound, message: """Redirection constructor target not found: '${name}'""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeRequiredParameterWithDefault = messageRequiredParameterWithDefault; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageRequiredParameterWithDefault = const MessageCode( "RequiredParameterWithDefault", analyzerCodes: <String>["NAMED_PARAMETER_OUTSIDE_GROUP"], message: r"""Non-optional parameters can't have a default value.""", tip: r"""Try removing the default value or making the parameter optional."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeRethrowNotCatch = messageRethrowNotCatch; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageRethrowNotCatch = const MessageCode("RethrowNotCatch", analyzerCodes: <String>["RETHROW_OUTSIDE_CATCH"], message: r"""'rethrow' can only be used in catch clauses."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeReturnFromVoidFunction = messageReturnFromVoidFunction; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageReturnFromVoidFunction = const MessageCode( "ReturnFromVoidFunction", analyzerCodes: <String>["RETURN_OF_INVALID_TYPE"], message: r"""Can't return a value from a void function."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeReturnTypeFunctionExpression = messageReturnTypeFunctionExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageReturnTypeFunctionExpression = const MessageCode( "ReturnTypeFunctionExpression", severity: Severity.errorLegacyWarning, message: r"""A function expression can't have a return type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeReturnWithoutExpression = messageReturnWithoutExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageReturnWithoutExpression = const MessageCode( "ReturnWithoutExpression", analyzerCodes: <String>["RETURN_WITHOUT_VALUE"], severity: Severity.warning, message: r"""Must explicitly return a value from a non-void function."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_)> templateSdkRootNotFound = const Template<Message Function(Uri uri_)>( messageTemplate: r"""SDK root directory not found: #uri.""", withArguments: _withArgumentsSdkRootNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeSdkRootNotFound = const Code<Message Function(Uri uri_)>( "SdkRootNotFound", templateSdkRootNotFound, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSdkRootNotFound(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeSdkRootNotFound, message: """SDK root directory not found: ${uri}.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( Uri uri_)> templateSdkSpecificationNotFound = const Template< Message Function(Uri uri_)>( messageTemplate: r"""SDK libraries specification not found: #uri.""", tipTemplate: r"""Normally, the specification is a file named 'libraries.json' in the Dart SDK install location.""", withArguments: _withArgumentsSdkSpecificationNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeSdkSpecificationNotFound = const Code<Message Function(Uri uri_)>( "SdkSpecificationNotFound", templateSdkSpecificationNotFound, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSdkSpecificationNotFound(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeSdkSpecificationNotFound, message: """SDK libraries specification not found: ${uri}.""", tip: """Normally, the specification is a file named 'libraries.json' in the Dart SDK install location.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_)> templateSdkSummaryNotFound = const Template<Message Function(Uri uri_)>( messageTemplate: r"""SDK summary not found: #uri.""", withArguments: _withArgumentsSdkSummaryNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeSdkSummaryNotFound = const Code<Message Function(Uri uri_)>( "SdkSummaryNotFound", templateSdkSummaryNotFound, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSdkSummaryNotFound(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeSdkSummaryNotFound, message: """SDK summary not found: ${uri}.""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSetLiteralTooManyTypeArguments = messageSetLiteralTooManyTypeArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSetLiteralTooManyTypeArguments = const MessageCode( "SetLiteralTooManyTypeArguments", severity: Severity.errorLegacyWarning, message: r"""A set literal requires exactly one type argument."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSetOrMapLiteralTooManyTypeArguments = messageSetOrMapLiteralTooManyTypeArguments; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSetOrMapLiteralTooManyTypeArguments = const MessageCode( "SetOrMapLiteralTooManyTypeArguments", severity: Severity.errorLegacyWarning, message: r"""A set or map literal requires exactly one or two type arguments, respectively."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateSetterNotFound = const Template<Message Function(String name)>( messageTemplate: r"""Setter not found: '#name'.""", withArguments: _withArgumentsSetterNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSetterNotFound = const Code<Message Function(String name)>( "SetterNotFound", templateSetterNotFound, analyzerCodes: <String>["UNDEFINED_SETTER"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSetterNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSetterNotFound, message: """Setter not found: '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSetterNotSync = messageSetterNotSync; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSetterNotSync = const MessageCode("SetterNotSync", analyzerCodes: <String>["INVALID_MODIFIER_ON_SETTER"], message: r"""Setters can't use 'async', 'async*', or 'sync*'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSetterWithWrongNumberOfFormals = messageSetterWithWrongNumberOfFormals; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSetterWithWrongNumberOfFormals = const MessageCode( "SetterWithWrongNumberOfFormals", analyzerCodes: <String>["WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER"], message: r"""A setter should have exactly one formal parameter."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int count, int count2, num _num1, num _num2, num _num3)> templateSourceBodySummary = const Template< Message Function( int count, int count2, num _num1, num _num2, num _num3)>( messageTemplate: r"""Built bodies for #count compilation units (#count2 bytes) in #num1%.3ms, that is, #num2%12.3 bytes/ms, and #num3%12.3 ms/compilation unit.""", withArguments: _withArgumentsSourceBodySummary); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(int count, int count2, num _num1, num _num2, num _num3)> codeSourceBodySummary = const Code< Message Function(int count, int count2, num _num1, num _num2, num _num3)>( "SourceBodySummary", templateSourceBodySummary, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSourceBodySummary( int count, int count2, num _num1, num _num2, num _num3) { if (count == null) throw 'No count provided'; if (count2 == null) throw 'No count provided'; if (_num1 == null) throw 'No number provided'; String num1 = _num1.toStringAsFixed(3); if (_num2 == null) throw 'No number provided'; String num2 = _num2.toStringAsFixed(3).padLeft(12); if (_num3 == null) throw 'No number provided'; String num3 = _num3.toStringAsFixed(3).padLeft(12); return new Message(codeSourceBodySummary, message: """Built bodies for ${count} compilation units (${count2} bytes) in ${num1}ms, that is, ${num2} bytes/ms, and ${num3} ms/compilation unit.""", arguments: { 'count': count, 'count2': count2, 'num1': _num1, 'num2': _num2, 'num3': _num3 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int count, int count2, num _num1, num _num2, num _num3)> templateSourceOutlineSummary = const Template< Message Function( int count, int count2, num _num1, num _num2, num _num3)>( messageTemplate: r"""Built outlines for #count compilation units (#count2 bytes) in #num1%.3ms, that is, #num2%12.3 bytes/ms, and #num3%12.3 ms/compilation unit.""", withArguments: _withArgumentsSourceOutlineSummary); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code< Message Function(int count, int count2, num _num1, num _num2, num _num3)> codeSourceOutlineSummary = const Code< Message Function(int count, int count2, num _num1, num _num2, num _num3)>( "SourceOutlineSummary", templateSourceOutlineSummary, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSourceOutlineSummary( int count, int count2, num _num1, num _num2, num _num3) { if (count == null) throw 'No count provided'; if (count2 == null) throw 'No count provided'; if (_num1 == null) throw 'No number provided'; String num1 = _num1.toStringAsFixed(3); if (_num2 == null) throw 'No number provided'; String num2 = _num2.toStringAsFixed(3).padLeft(12); if (_num3 == null) throw 'No number provided'; String num3 = _num3.toStringAsFixed(3).padLeft(12); return new Message(codeSourceOutlineSummary, message: """Built outlines for ${count} compilation units (${count2} bytes) in ${num1}ms, that is, ${num2} bytes/ms, and ${num3} ms/compilation unit.""", arguments: { 'count': count, 'count2': count2, 'num1': _num1, 'num2': _num2, 'num3': _num3 }); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSpreadElement = messageSpreadElement; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSpreadElement = const MessageCode("SpreadElement", severity: Severity.context, message: r"""Iterable spread."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateSpreadElementTypeMismatch = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""Can't assign spread elements of type '#type' to collection elements of type '#type2'.""", withArguments: _withArgumentsSpreadElementTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeSpreadElementTypeMismatch = const Code<Message Function(DartType _type, DartType _type2)>( "SpreadElementTypeMismatch", templateSpreadElementTypeMismatch, analyzerCodes: <String>["LIST_ELEMENT_TYPE_NOT_ASSIGNABLE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSpreadElementTypeMismatch( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeSpreadElementTypeMismatch, message: """Can't assign spread elements of type '${type}' to collection elements of type '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSpreadMapElement = messageSpreadMapElement; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSpreadMapElement = const MessageCode( "SpreadMapElement", severity: Severity.context, message: r"""Map spread."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateSpreadMapEntryElementKeyTypeMismatch = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""Can't assign spread entry keys of type '#type' to map entry keys of type '#type2'.""", withArguments: _withArgumentsSpreadMapEntryElementKeyTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeSpreadMapEntryElementKeyTypeMismatch = const Code<Message Function(DartType _type, DartType _type2)>( "SpreadMapEntryElementKeyTypeMismatch", templateSpreadMapEntryElementKeyTypeMismatch, analyzerCodes: <String>["MAP_KEY_TYPE_NOT_ASSIGNABLE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSpreadMapEntryElementKeyTypeMismatch( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeSpreadMapEntryElementKeyTypeMismatch, message: """Can't assign spread entry keys of type '${type}' to map entry keys of type '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(DartType _type, DartType _type2)> templateSpreadMapEntryElementValueTypeMismatch = const Template<Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""Can't assign spread entry values of type '#type' to map entry values of type '#type2'.""", withArguments: _withArgumentsSpreadMapEntryElementValueTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeSpreadMapEntryElementValueTypeMismatch = const Code<Message Function(DartType _type, DartType _type2)>( "SpreadMapEntryElementValueTypeMismatch", templateSpreadMapEntryElementValueTypeMismatch, analyzerCodes: <String>["MAP_VALUE_TYPE_NOT_ASSIGNABLE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSpreadMapEntryElementValueTypeMismatch( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeSpreadMapEntryElementValueTypeMismatch, message: """Can't assign spread entry values of type '${type}' to map entry values of type '${type2}'.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type)> templateSpreadMapEntryTypeMismatch = const Template< Message Function(DartType _type)>( messageTemplate: r"""Unexpected type '#type' of a map spread entry. Expected 'dynamic' or a Map.""", withArguments: _withArgumentsSpreadMapEntryTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeSpreadMapEntryTypeMismatch = const Code<Message Function(DartType _type)>( "SpreadMapEntryTypeMismatch", templateSpreadMapEntryTypeMismatch, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSpreadMapEntryTypeMismatch(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeSpreadMapEntryTypeMismatch, message: """Unexpected type '${type}' of a map spread entry. Expected 'dynamic' or a Map.""" + labeler.originMessages, arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type)> templateSpreadTypeMismatch = const Template< Message Function(DartType _type)>( messageTemplate: r"""Unexpected type '#type' of a spread. Expected 'dynamic' or an Iterable.""", withArguments: _withArgumentsSpreadTypeMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type)> codeSpreadTypeMismatch = const Code<Message Function(DartType _type)>( "SpreadTypeMismatch", templateSpreadTypeMismatch, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSpreadTypeMismatch(DartType _type) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeSpreadTypeMismatch, message: """Unexpected type '${type}' of a spread. Expected 'dynamic' or an Iterable.""" + labeler.originMessages, arguments: {'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeStackOverflow = messageStackOverflow; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageStackOverflow = const MessageCode("StackOverflow", index: 19, message: r"""The file has too many nested expressions or statements.""", tip: r"""Try simplifying the code."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeStaticAndInstanceConflict = messageStaticAndInstanceConflict; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageStaticAndInstanceConflict = const MessageCode( "StaticAndInstanceConflict", analyzerCodes: <String>["CONFLICTING_STATIC_AND_INSTANCE"], message: r"""This static member conflicts with an instance member."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeStaticAndInstanceConflictCause = messageStaticAndInstanceConflictCause; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageStaticAndInstanceConflictCause = const MessageCode( "StaticAndInstanceConflictCause", severity: Severity.context, message: r"""This is the instance member."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeStaticConstructor = messageStaticConstructor; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageStaticConstructor = const MessageCode( "StaticConstructor", index: 4, message: r"""Constructors can't be static.""", tip: r"""Try removing the keyword 'static'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeStaticOperator = messageStaticOperator; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageStaticOperator = const MessageCode("StaticOperator", index: 17, message: r"""Operators can't be static.""", tip: r"""Try removing the keyword 'static'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSuperAsExpression = messageSuperAsExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSuperAsExpression = const MessageCode( "SuperAsExpression", analyzerCodes: <String>["SUPER_AS_EXPRESSION"], message: r"""Can't use 'super' as an expression.""", tip: r"""To delegate a constructor to a super constructor, put the super call as an initializer."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSuperAsIdentifier = messageSuperAsIdentifier; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSuperAsIdentifier = const MessageCode( "SuperAsIdentifier", analyzerCodes: <String>["SUPER_AS_EXPRESSION"], message: r"""Expected identifier, but got 'super'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSuperInitializerNotLast = messageSuperInitializerNotLast; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSuperInitializerNotLast = const MessageCode( "SuperInitializerNotLast", analyzerCodes: <String>["INVALID_SUPER_INVOCATION"], message: r"""Can't have initializers after 'super'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSuperNullAware = messageSuperNullAware; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSuperNullAware = const MessageCode("SuperNullAware", index: 18, message: r"""The operator '?.' cannot be used with 'super' because 'super' cannot be null.""", tip: r"""Try replacing '?.' with '.'"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateSuperclassHasNoConstructor = const Template<Message Function(String name)>( messageTemplate: r"""Superclass has no constructor named '#name'.""", withArguments: _withArgumentsSuperclassHasNoConstructor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSuperclassHasNoConstructor = const Code<Message Function(String name)>( "SuperclassHasNoConstructor", templateSuperclassHasNoConstructor, analyzerCodes: <String>[ "UNDEFINED_CONSTRUCTOR_IN_INITIALIZER", "UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT" ], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSuperclassHasNoConstructor(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSuperclassHasNoConstructor, message: """Superclass has no constructor named '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateSuperclassHasNoDefaultConstructor = const Template< Message Function(String name)>( messageTemplate: r"""The superclass, '#name', has no unnamed constructor that takes no arguments.""", withArguments: _withArgumentsSuperclassHasNoDefaultConstructor); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSuperclassHasNoDefaultConstructor = const Code<Message Function(String name)>( "SuperclassHasNoDefaultConstructor", templateSuperclassHasNoDefaultConstructor, analyzerCodes: <String>["NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSuperclassHasNoDefaultConstructor(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSuperclassHasNoDefaultConstructor, message: """The superclass, '${name}', has no unnamed constructor that takes no arguments.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateSuperclassHasNoGetter = const Template<Message Function(String name)>( messageTemplate: r"""Superclass has no getter named '#name'.""", withArguments: _withArgumentsSuperclassHasNoGetter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSuperclassHasNoGetter = const Code<Message Function(String name)>( "SuperclassHasNoGetter", templateSuperclassHasNoGetter, analyzerCodes: <String>["UNDEFINED_SUPER_GETTER"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSuperclassHasNoGetter(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSuperclassHasNoGetter, message: """Superclass has no getter named '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateSuperclassHasNoMethod = const Template<Message Function(String name)>( messageTemplate: r"""Superclass has no method named '#name'.""", withArguments: _withArgumentsSuperclassHasNoMethod); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSuperclassHasNoMethod = const Code<Message Function(String name)>( "SuperclassHasNoMethod", templateSuperclassHasNoMethod, analyzerCodes: <String>["UNDEFINED_SUPER_METHOD"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSuperclassHasNoMethod(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSuperclassHasNoMethod, message: """Superclass has no method named '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateSuperclassHasNoSetter = const Template<Message Function(String name)>( messageTemplate: r"""Superclass has no setter named '#name'.""", withArguments: _withArgumentsSuperclassHasNoSetter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSuperclassHasNoSetter = const Code<Message Function(String name)>( "SuperclassHasNoSetter", templateSuperclassHasNoSetter, analyzerCodes: <String>["UNDEFINED_SUPER_SETTER"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSuperclassHasNoSetter(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSuperclassHasNoSetter, message: """Superclass has no setter named '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name)> templateSuperclassMethodArgumentMismatch = const Template< Message Function(String name)>( messageTemplate: r"""Superclass doesn't have a method named '#name' with matching arguments.""", withArguments: _withArgumentsSuperclassMethodArgumentMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSuperclassMethodArgumentMismatch = const Code<Message Function(String name)>( "SuperclassMethodArgumentMismatch", templateSuperclassMethodArgumentMismatch, severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSuperclassMethodArgumentMismatch(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSuperclassMethodArgumentMismatch, message: """Superclass doesn't have a method named '${name}' with matching arguments.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSupertypeIsFunction = messageSupertypeIsFunction; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSupertypeIsFunction = const MessageCode( "SupertypeIsFunction", message: r"""Can't use a function type as supertype."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateSupertypeIsIllegal = const Template<Message Function(String name)>( messageTemplate: r"""The type '#name' can't be used as supertype.""", withArguments: _withArgumentsSupertypeIsIllegal); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSupertypeIsIllegal = const Code<Message Function(String name)>( "SupertypeIsIllegal", templateSupertypeIsIllegal, analyzerCodes: <String>["EXTENDS_NON_CLASS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSupertypeIsIllegal(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSupertypeIsIllegal, message: """The type '${name}' can't be used as supertype.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateSupertypeIsTypeVariable = const Template<Message Function(String name)>( messageTemplate: r"""The type variable '#name' can't be used as supertype.""", withArguments: _withArgumentsSupertypeIsTypeVariable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeSupertypeIsTypeVariable = const Code<Message Function(String name)>( "SupertypeIsTypeVariable", templateSupertypeIsTypeVariable, analyzerCodes: <String>["EXTENDS_NON_CLASS"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSupertypeIsTypeVariable(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeSupertypeIsTypeVariable, message: """The type variable '${name}' can't be used as supertype.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSwitchCaseFallThrough = messageSwitchCaseFallThrough; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSwitchCaseFallThrough = const MessageCode( "SwitchCaseFallThrough", analyzerCodes: <String>["CASE_BLOCK_NOT_TERMINATED"], severity: Severity.errorLegacyWarning, message: r"""Switch case may fall through to the next case."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( DartType _type, DartType _type2)> templateSwitchExpressionNotAssignable = const Template< Message Function(DartType _type, DartType _type2)>( messageTemplate: r"""Type '#type' of the switch expression isn't assignable to the type '#type2' of this case expression.""", withArguments: _withArgumentsSwitchExpressionNotAssignable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(DartType _type, DartType _type2)> codeSwitchExpressionNotAssignable = const Code<Message Function(DartType _type, DartType _type2)>( "SwitchExpressionNotAssignable", templateSwitchExpressionNotAssignable, analyzerCodes: <String>["SWITCH_EXPRESSION_NOT_ASSIGNABLE"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsSwitchExpressionNotAssignable( DartType _type, DartType _type2) { TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); List<Object> type2Parts = labeler.labelType(_type2); String type = typeParts.join(); String type2 = type2Parts.join(); return new Message(codeSwitchExpressionNotAssignable, message: """Type '${type}' of the switch expression isn't assignable to the type '${type2}' of this case expression.""" + labeler.originMessages, arguments: {'type': _type, 'type2': _type2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSwitchExpressionNotAssignableCause = messageSwitchExpressionNotAssignableCause; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSwitchExpressionNotAssignableCause = const MessageCode( "SwitchExpressionNotAssignableCause", severity: Severity.context, message: r"""The switch expression is here."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSwitchHasCaseAfterDefault = messageSwitchHasCaseAfterDefault; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSwitchHasCaseAfterDefault = const MessageCode( "SwitchHasCaseAfterDefault", index: 16, message: r"""The default case should be the last case in a switch statement.""", tip: r"""Try moving the default case after the other case clauses."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSwitchHasMultipleDefaults = messageSwitchHasMultipleDefaults; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSwitchHasMultipleDefaults = const MessageCode( "SwitchHasMultipleDefaults", index: 15, message: r"""The 'default' case can only be declared once.""", tip: r"""Try removing all but one default case."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeSyntheticToken = messageSyntheticToken; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageSyntheticToken = const MessageCode("SyntheticToken", message: r"""This couldn't be parsed."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateThisAccessInFieldInitializer = const Template<Message Function(String name)>( messageTemplate: r"""Can't access 'this' in a field initializer to read '#name'.""", withArguments: _withArgumentsThisAccessInFieldInitializer); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeThisAccessInFieldInitializer = const Code<Message Function(String name)>( "ThisAccessInFieldInitializer", templateThisAccessInFieldInitializer, analyzerCodes: <String>["THIS_ACCESS_FROM_FIELD_INITIALIZER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsThisAccessInFieldInitializer(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeThisAccessInFieldInitializer, message: """Can't access 'this' in a field initializer to read '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeThisAsIdentifier = messageThisAsIdentifier; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageThisAsIdentifier = const MessageCode( "ThisAsIdentifier", analyzerCodes: <String>["INVALID_REFERENCE_TO_THIS"], message: r"""Expected identifier, but got 'this'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeThisInitializerNotAlone = messageThisInitializerNotAlone; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageThisInitializerNotAlone = const MessageCode( "ThisInitializerNotAlone", analyzerCodes: <String>["FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR"], message: r"""Can't have other initializers together with 'this'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateThisOrSuperAccessInFieldInitializer = const Template<Message Function(String string)>( messageTemplate: r"""Can't access '#string' in a field initializer.""", withArguments: _withArgumentsThisOrSuperAccessInFieldInitializer); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeThisOrSuperAccessInFieldInitializer = const Code<Message Function(String string)>( "ThisOrSuperAccessInFieldInitializer", templateThisOrSuperAccessInFieldInitializer, analyzerCodes: <String>["THIS_ACCESS_FROM_INITIALIZER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsThisOrSuperAccessInFieldInitializer(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeThisOrSuperAccessInFieldInitializer, message: """Can't access '${string}' in a field initializer.""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int count, int count2)> templateTooFewArguments = const Template< Message Function(int count, int count2)>( messageTemplate: r"""Too few positional arguments: #count required, #count2 given.""", withArguments: _withArgumentsTooFewArguments); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(int count, int count2)> codeTooFewArguments = const Code<Message Function(int count, int count2)>( "TooFewArguments", templateTooFewArguments, analyzerCodes: <String>["NOT_ENOUGH_REQUIRED_ARGUMENTS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTooFewArguments(int count, int count2) { if (count == null) throw 'No count provided'; if (count2 == null) throw 'No count provided'; return new Message(codeTooFewArguments, message: """Too few positional arguments: ${count} required, ${count2} given.""", arguments: {'count': count, 'count2': count2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( int count, int count2)> templateTooManyArguments = const Template< Message Function(int count, int count2)>( messageTemplate: r"""Too many positional arguments: #count allowed, but #count2 found.""", tipTemplate: r"""Try removing the extra positional arguments.""", withArguments: _withArgumentsTooManyArguments); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(int count, int count2)> codeTooManyArguments = const Code<Message Function(int count, int count2)>( "TooManyArguments", templateTooManyArguments, analyzerCodes: <String>["EXTRA_POSITIONAL_ARGUMENTS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTooManyArguments(int count, int count2) { if (count == null) throw 'No count provided'; if (count2 == null) throw 'No count provided'; return new Message(codeTooManyArguments, message: """Too many positional arguments: ${count} allowed, but ${count2} found.""", tip: """Try removing the extra positional arguments.""", arguments: {'count': count, 'count2': count2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTopLevelOperator = messageTopLevelOperator; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTopLevelOperator = const MessageCode( "TopLevelOperator", index: 14, message: r"""Operators must be declared within a class.""", tip: r"""Try removing the operator, moving it to a class, or converting it to be a function."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypeAfterVar = messageTypeAfterVar; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypeAfterVar = const MessageCode("TypeAfterVar", index: 89, message: r"""Variables can't be declared using both 'var' and a type name.""", tip: r"""Try removing 'var.'"""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(int count)> templateTypeArgumentMismatch = const Template<Message Function(int count)>( messageTemplate: r"""Expected #count type arguments.""", withArguments: _withArgumentsTypeArgumentMismatch); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(int count)> codeTypeArgumentMismatch = const Code<Message Function(int count)>( "TypeArgumentMismatch", templateTypeArgumentMismatch, analyzerCodes: <String>["WRONG_NUMBER_OF_TYPE_ARGUMENTS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTypeArgumentMismatch(int count) { if (count == null) throw 'No count provided'; return new Message(codeTypeArgumentMismatch, message: """Expected ${count} type arguments.""", arguments: {'count': count}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateTypeArgumentsOnTypeVariable = const Template<Message Function(String name)>( messageTemplate: r"""Can't use type arguments with type variable '#name'.""", tipTemplate: r"""Try removing the type arguments.""", withArguments: _withArgumentsTypeArgumentsOnTypeVariable); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeTypeArgumentsOnTypeVariable = const Code<Message Function(String name)>( "TypeArgumentsOnTypeVariable", templateTypeArgumentsOnTypeVariable, index: 13, severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTypeArgumentsOnTypeVariable(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeTypeArgumentsOnTypeVariable, message: """Can't use type arguments with type variable '${name}'.""", tip: """Try removing the type arguments.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypeBeforeFactory = messageTypeBeforeFactory; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypeBeforeFactory = const MessageCode( "TypeBeforeFactory", index: 57, message: r"""Factory constructors cannot have a return type.""", tip: r"""Try removing the type appearing before 'factory'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateTypeNotFound = const Template<Message Function(String name)>( messageTemplate: r"""Type '#name' not found.""", withArguments: _withArgumentsTypeNotFound); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeTypeNotFound = const Code<Message Function(String name)>( "TypeNotFound", templateTypeNotFound, analyzerCodes: <String>["UNDEFINED_CLASS"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTypeNotFound(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeTypeNotFound, message: """Type '${name}' not found.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_)> templateTypeOrigin = const Template<Message Function(String name, Uri uri_)>( messageTemplate: r"""'#name' is from '#uri'.""", withArguments: _withArgumentsTypeOrigin); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_)> codeTypeOrigin = const Code<Message Function(String name, Uri uri_)>( "TypeOrigin", templateTypeOrigin, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTypeOrigin(String name, Uri uri_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); return new Message(codeTypeOrigin, message: """'${name}' is from '${uri}'.""", arguments: {'name': name, 'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name, Uri uri_, Uri uri2_)> templateTypeOriginWithFileUri = const Template<Message Function(String name, Uri uri_, Uri uri2_)>( messageTemplate: r"""'#name' is from '#uri' ('#uri2').""", withArguments: _withArgumentsTypeOriginWithFileUri); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, Uri uri_, Uri uri2_)> codeTypeOriginWithFileUri = const Code<Message Function(String name, Uri uri_, Uri uri2_)>( "TypeOriginWithFileUri", templateTypeOriginWithFileUri, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTypeOriginWithFileUri(String name, Uri uri_, Uri uri2_) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); String uri = relativizeUri(uri_); String uri2 = relativizeUri(uri2_); return new Message(codeTypeOriginWithFileUri, message: """'${name}' is from '${uri}' ('${uri2}').""", arguments: {'name': name, 'uri': uri_, 'uri2': uri2_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypeVariableDuplicatedName = messageTypeVariableDuplicatedName; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypeVariableDuplicatedName = const MessageCode( "TypeVariableDuplicatedName", analyzerCodes: <String>["DUPLICATE_DEFINITION"], message: r"""A type variable can't have the same name as another."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateTypeVariableDuplicatedNameCause = const Template<Message Function(String name)>( messageTemplate: r"""The other type variable named '#name'.""", withArguments: _withArgumentsTypeVariableDuplicatedNameCause); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeTypeVariableDuplicatedNameCause = const Code<Message Function(String name)>("TypeVariableDuplicatedNameCause", templateTypeVariableDuplicatedNameCause, severity: Severity.context); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsTypeVariableDuplicatedNameCause(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeTypeVariableDuplicatedNameCause, message: """The other type variable named '${name}'.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypeVariableInConstantContext = messageTypeVariableInConstantContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypeVariableInConstantContext = const MessageCode( "TypeVariableInConstantContext", analyzerCodes: <String>["TYPE_PARAMETER_IN_CONST_EXPRESSION"], message: r"""Type variables can't be used as constants."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypeVariableInStaticContext = messageTypeVariableInStaticContext; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypeVariableInStaticContext = const MessageCode( "TypeVariableInStaticContext", analyzerCodes: <String>["TYPE_PARAMETER_REFERENCED_BY_STATIC"], severity: Severity.errorLegacyWarning, message: r"""Type variables can't be used in static members."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypeVariableSameNameAsEnclosing = messageTypeVariableSameNameAsEnclosing; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypeVariableSameNameAsEnclosing = const MessageCode( "TypeVariableSameNameAsEnclosing", analyzerCodes: <String>["CONFLICTING_TYPE_VARIABLE_AND_CLASS"], message: r"""A type variable can't have the same name as its enclosing declaration."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypedefInClass = messageTypedefInClass; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypedefInClass = const MessageCode("TypedefInClass", index: 7, message: r"""Typedefs can't be declared inside classes.""", tip: r"""Try moving the typedef to the top-level."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeTypedefNotFunction = messageTypedefNotFunction; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageTypedefNotFunction = const MessageCode( "TypedefNotFunction", analyzerCodes: <String>["INVALID_GENERIC_FUNCTION_TYPE"], message: r"""Can't create typedef from non-function type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type)> templateUndefinedGetter = const Template< Message Function(String name, DartType _type)>( messageTemplate: r"""The getter '#name' isn't defined for the class '#type'.""", tipTemplate: r"""Try correcting the name to the name of an existing getter, or defining a getter or field named '#name'.""", withArguments: _withArgumentsUndefinedGetter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, DartType _type)> codeUndefinedGetter = const Code<Message Function(String name, DartType _type)>( "UndefinedGetter", templateUndefinedGetter, analyzerCodes: <String>["UNDEFINED_GETTER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUndefinedGetter(String name, DartType _type) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeUndefinedGetter, message: """The getter '${name}' isn't defined for the class '${type}'.""" + labeler.originMessages, tip: """Try correcting the name to the name of an existing getter, or defining a getter or field named '${name}'.""", arguments: {'name': name, 'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type)> templateUndefinedMethod = const Template< Message Function(String name, DartType _type)>( messageTemplate: r"""The method '#name' isn't defined for the class '#type'.""", tipTemplate: r"""Try correcting the name to the name of an existing method, or defining a method named '#name'.""", withArguments: _withArgumentsUndefinedMethod); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, DartType _type)> codeUndefinedMethod = const Code<Message Function(String name, DartType _type)>( "UndefinedMethod", templateUndefinedMethod, analyzerCodes: <String>["UNDEFINED_METHOD"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUndefinedMethod(String name, DartType _type) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeUndefinedMethod, message: """The method '${name}' isn't defined for the class '${type}'.""" + labeler.originMessages, tip: """Try correcting the name to the name of an existing method, or defining a method named '${name}'.""", arguments: {'name': name, 'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, DartType _type)> templateUndefinedSetter = const Template< Message Function(String name, DartType _type)>( messageTemplate: r"""The setter '#name' isn't defined for the class '#type'.""", tipTemplate: r"""Try correcting the name to the name of an existing setter, or defining a setter or field named '#name'.""", withArguments: _withArgumentsUndefinedSetter); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, DartType _type)> codeUndefinedSetter = const Code<Message Function(String name, DartType _type)>( "UndefinedSetter", templateUndefinedSetter, analyzerCodes: <String>["UNDEFINED_SETTER"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUndefinedSetter(String name, DartType _type) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); TypeLabeler labeler = new TypeLabeler(); List<Object> typeParts = labeler.labelType(_type); String type = typeParts.join(); return new Message(codeUndefinedSetter, message: """The setter '${name}' isn't defined for the class '${type}'.""" + labeler.originMessages, tip: """Try correcting the name to the name of an existing setter, or defining a setter or field named '${name}'.""", arguments: {'name': name, 'type': _type}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeUnexpectedDollarInString = messageUnexpectedDollarInString; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageUnexpectedDollarInString = const MessageCode( "UnexpectedDollarInString", analyzerCodes: <String>["UNEXPECTED_DOLLAR_IN_STRING"], message: r"""A '$' has special meaning inside a string, and must be followed by an identifier or an expression in curly braces ({}).""", tip: r"""Try adding a backslash (\) to escape the '$'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateUnexpectedToken = const Template<Message Function(Token token)>( messageTemplate: r"""Unexpected token '#lexeme'.""", withArguments: _withArgumentsUnexpectedToken); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeUnexpectedToken = const Code<Message Function(Token token)>( "UnexpectedToken", templateUnexpectedToken, analyzerCodes: <String>["UNEXPECTED_TOKEN"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUnexpectedToken(Token token) { String lexeme = token.lexeme; return new Message(codeUnexpectedToken, message: """Unexpected token '${lexeme}'.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string, Token token)> templateUnmatchedToken = const Template<Message Function(String string, Token token)>( messageTemplate: r"""Can't find '#string' to match '#lexeme'.""", withArguments: _withArgumentsUnmatchedToken); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, Token token)> codeUnmatchedToken = const Code<Message Function(String string, Token token)>( "UnmatchedToken", templateUnmatchedToken, analyzerCodes: <String>["EXPECTED_TOKEN"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUnmatchedToken(String string, Token token) { if (string.isEmpty) throw 'No string provided'; String lexeme = token.lexeme; return new Message(codeUnmatchedToken, message: """Can't find '${string}' to match '${lexeme}'.""", arguments: {'string': string, 'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String name, String name2)> templateUnresolvedPrefixInTypeAnnotation = const Template< Message Function(String name, String name2)>( messageTemplate: r"""'#name.#name2' can't be used as a type because '#name' isn't defined.""", withArguments: _withArgumentsUnresolvedPrefixInTypeAnnotation); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name, String name2)> codeUnresolvedPrefixInTypeAnnotation = const Code<Message Function(String name, String name2)>( "UnresolvedPrefixInTypeAnnotation", templateUnresolvedPrefixInTypeAnnotation, analyzerCodes: <String>["NOT_A_TYPE"], severity: Severity.errorLegacyWarning); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUnresolvedPrefixInTypeAnnotation( String name, String name2) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); if (name2.isEmpty) throw 'No name provided'; name2 = demangleMixinApplicationName(name2); return new Message(codeUnresolvedPrefixInTypeAnnotation, message: """'${name}.${name2}' can't be used as a type because '${name}' isn't defined.""", arguments: {'name': name, 'name2': name2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string)> templateUnspecified = const Template<Message Function(String string)>( messageTemplate: r"""#string""", withArguments: _withArgumentsUnspecified); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string)> codeUnspecified = const Code<Message Function(String string)>( "Unspecified", templateUnspecified, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUnspecified(String string) { if (string.isEmpty) throw 'No string provided'; return new Message(codeUnspecified, message: """${string}""", arguments: {'string': string}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Token token)> templateUnsupportedOperator = const Template<Message Function(Token token)>( messageTemplate: r"""The '#lexeme' operator is not supported.""", withArguments: _withArgumentsUnsupportedOperator); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Token token)> codeUnsupportedOperator = const Code<Message Function(Token token)>( "UnsupportedOperator", templateUnsupportedOperator, analyzerCodes: <String>["UNSUPPORTED_OPERATOR"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUnsupportedOperator(Token token) { String lexeme = token.lexeme; return new Message(codeUnsupportedOperator, message: """The '${lexeme}' operator is not supported.""", arguments: {'token': token}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeUnsupportedPrefixPlus = messageUnsupportedPrefixPlus; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageUnsupportedPrefixPlus = const MessageCode( "UnsupportedPrefixPlus", analyzerCodes: <String>["MISSING_IDENTIFIER"], message: r"""'+' is not a prefix operator.""", tip: r"""Try removing '+'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeUnterminatedComment = messageUnterminatedComment; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageUnterminatedComment = const MessageCode( "UnterminatedComment", analyzerCodes: <String>["UNTERMINATED_MULTI_LINE_COMMENT"], message: r"""Comment starting with '/*' must end with '*/'."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String string, String string2)> templateUnterminatedString = const Template<Message Function(String string, String string2)>( messageTemplate: r"""String starting with #string must end with #string2.""", withArguments: _withArgumentsUnterminatedString); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeUnterminatedString = const Code<Message Function(String string, String string2)>( "UnterminatedString", templateUnterminatedString, analyzerCodes: <String>["UNTERMINATED_STRING_LITERAL"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUnterminatedString(String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeUnterminatedString, message: """String starting with ${string} must end with ${string2}.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeUnterminatedToken = messageUnterminatedToken; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageUnterminatedToken = const MessageCode("UnterminatedToken", message: r"""Incomplete token."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(Uri uri_)> templateUntranslatableUri = const Template<Message Function(Uri uri_)>( messageTemplate: r"""Not found: '#uri'""", withArguments: _withArgumentsUntranslatableUri); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(Uri uri_)> codeUntranslatableUri = const Code<Message Function(Uri uri_)>( "UntranslatableUri", templateUntranslatableUri, analyzerCodes: <String>["URI_DOES_NOT_EXIST"]); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUntranslatableUri(Uri uri_) { String uri = relativizeUri(uri_); return new Message(codeUntranslatableUri, message: """Not found: '${uri}'""", arguments: {'uri': uri_}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template<Message Function(String name)> templateUseOfDeprecatedIdentifier = const Template<Message Function(String name)>( messageTemplate: r"""'#name' is deprecated.""", withArguments: _withArgumentsUseOfDeprecatedIdentifier); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String name)> codeUseOfDeprecatedIdentifier = const Code<Message Function(String name)>( "UseOfDeprecatedIdentifier", templateUseOfDeprecatedIdentifier, severity: Severity.ignored); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsUseOfDeprecatedIdentifier(String name) { if (name.isEmpty) throw 'No name provided'; name = demangleMixinApplicationName(name); return new Message(codeUseOfDeprecatedIdentifier, message: """'${name}' is deprecated.""", arguments: {'name': name}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeVarAsTypeName = messageVarAsTypeName; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageVarAsTypeName = const MessageCode("VarAsTypeName", index: 61, message: r"""The keyword 'var' can't be used as a type name."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeVarReturnType = messageVarReturnType; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageVarReturnType = const MessageCode("VarReturnType", index: 12, message: r"""The return type can't be 'var'.""", tip: r"""Try removing the keyword 'var', or replacing it with the name of the return type."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeVoidExpression = messageVoidExpression; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageVoidExpression = const MessageCode("VoidExpression", analyzerCodes: <String>["USE_OF_VOID_RESULT"], message: r"""This expression has type 'void' and can't be used."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Template< Message Function( String string, String string2)> templateWebLiteralCannotBeRepresentedExactly = const Template< Message Function(String string, String string2)>( messageTemplate: r"""The integer literal #string can't be represented exactly in JavaScript.""", tipTemplate: r"""Try changing the literal to something that can be represented in Javascript. In Javascript #string2 is the nearest value that can be represented exactly.""", withArguments: _withArgumentsWebLiteralCannotBeRepresentedExactly); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Message Function(String string, String string2)> codeWebLiteralCannotBeRepresentedExactly = const Code<Message Function(String string, String string2)>( "WebLiteralCannotBeRepresentedExactly", templateWebLiteralCannotBeRepresentedExactly, ); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. Message _withArgumentsWebLiteralCannotBeRepresentedExactly( String string, String string2) { if (string.isEmpty) throw 'No string provided'; if (string2.isEmpty) throw 'No string provided'; return new Message(codeWebLiteralCannotBeRepresentedExactly, message: """The integer literal ${string} can't be represented exactly in JavaScript.""", tip: """Try changing the literal to something that can be represented in Javascript. In Javascript ${string2} is the nearest value that can be represented exactly.""", arguments: {'string': string, 'string2': string2}); } // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeWithBeforeExtends = messageWithBeforeExtends; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageWithBeforeExtends = const MessageCode( "WithBeforeExtends", index: 11, message: r"""The extends clause must be before the with clause.""", tip: r"""Try moving the extends clause before the with clause."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeYieldAsIdentifier = messageYieldAsIdentifier; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageYieldAsIdentifier = const MessageCode( "YieldAsIdentifier", analyzerCodes: <String>["ASYNC_KEYWORD_USED_AS_IDENTIFIER"], message: r"""'yield' can't be used as an identifier in 'async', 'async*', or 'sync*' methods."""); // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const Code<Null> codeYieldNotGenerator = messageYieldNotGenerator; // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE. const MessageCode messageYieldNotGenerator = const MessageCode( "YieldNotGenerator", analyzerCodes: <String>["YIELD_IN_NON_GENERATOR"], message: r"""'yield' can only be used in 'sync*' or 'async*' methods.""");
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/fasta/scope.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.scope; import 'builder/builder.dart' show NameIterator, TypeVariableBuilder; import 'builder/declaration.dart'; import 'builder/extension_builder.dart'; import 'fasta_codes.dart' show LocatedMessage, Message, messageInternalProblemExtendingUnmodifiableScope, templateAccessError, templateDuplicatedDeclarationUse, templateDuplicatedNamePreviouslyUsedCause; import 'problems.dart' show internalProblem, unsupported; class MutableScope { /// Names declared in this scope. Map<String, Builder> local; /// Setters declared in this scope. Map<String, Builder> setters; /// The extensions declared in this scope. /// /// This includes all available extensions even if the extensions are not /// accessible by name because of duplicate imports. /// /// For instance: /// /// lib1.dart: /// extension Extension on String { /// method1() {} /// staticMethod1() {} /// } /// lib2.dart: /// extension Extension on String { /// method2() {} /// staticMethod2() {} /// } /// main.dart: /// import 'lib1.dart'; /// import 'lib2.dart'; /// /// main() { /// 'foo'.method1(); // This method is available. /// 'foo'.method2(); // This method is available. /// // These methods are not available because Extension is ambiguous: /// Extension.staticMethod1(); /// Extension.staticMethod2(); /// } /// List<ExtensionBuilder> _extensions; /// The scope that this scope is nested within, or `null` if this is the top /// level scope. Scope parent; final String classNameOrDebugName; MutableScope(this.local, this.setters, this._extensions, this.parent, this.classNameOrDebugName) { assert(classNameOrDebugName != null); } String toString() => "Scope($classNameOrDebugName, ${local.keys})"; } class Scope extends MutableScope { /// Indicates whether an attempt to declare new names in this scope should /// succeed. final bool isModifiable; Map<String, Builder> labels; Map<String, Builder> forwardDeclaredLabels; Map<String, int> usedNames; Scope( {Map<String, Builder> local, Map<String, Builder> setters, List<ExtensionBuilder> extensions, Scope parent, String debugName, this.isModifiable: true}) : super(local, setters = setters ?? const <String, Builder>{}, extensions, parent, debugName); Scope.top({bool isModifiable: false}) : this( local: <String, Builder>{}, setters: <String, Builder>{}, debugName: "top", isModifiable: isModifiable); Scope.immutable() : this( local: const <String, Builder>{}, setters: const <String, Builder>{}, debugName: "immutable", isModifiable: false); Scope.nested(Scope parent, String debugName, {bool isModifiable: true}) : this( local: <String, Builder>{}, setters: <String, Builder>{}, parent: parent, debugName: debugName, isModifiable: isModifiable); Iterator<Builder> get iterator { return new ScopeLocalDeclarationIterator(this); } NameIterator get nameIterator { return new ScopeLocalDeclarationNameIterator(this); } Scope copyWithParent(Scope parent, String debugName) { return new Scope( local: super.local, setters: super.setters, extensions: _extensions, parent: parent, debugName: debugName, isModifiable: isModifiable); } /// Don't use this. Use [becomePartOf] instead. void set local(_) => unsupported("local=", -1, null); /// Don't use this. Use [becomePartOf] instead. void set setters(_) => unsupported("setters=", -1, null); /// Don't use this. Use [becomePartOf] instead. void set parent(_) => unsupported("parent=", -1, null); /// This scope becomes equivalent to [scope]. This is used for parts to /// become part of their library's scope. void becomePartOf(Scope scope) { assert(parent.parent == null); assert(scope.parent.parent == null); super.local = scope.local; super.setters = scope.setters; super.parent = scope.parent; super._extensions = scope._extensions; } Scope createNestedScope(String debugName, {bool isModifiable: true}) { return new Scope.nested(this, debugName, isModifiable: isModifiable); } Scope withTypeVariables(List<TypeVariableBuilder> typeVariables) { if (typeVariables == null) return this; Scope newScope = new Scope.nested(this, "type variables", isModifiable: false); for (TypeVariableBuilder t in typeVariables) { newScope.local[t.name] = t; } return newScope; } /// Create a special scope for use by labeled statements. This scope doesn't /// introduce a new scope for local variables, only for labels. This deals /// with corner cases like this: /// /// L: var x; /// x = 42; /// print("The answer is $x."); Scope createNestedLabelScope() { return new Scope( local: local, setters: setters, extensions: _extensions, parent: parent, debugName: "label", isModifiable: true); } void recordUse(String name, int charOffset, Uri fileUri) { if (isModifiable) { usedNames ??= <String, int>{}; usedNames.putIfAbsent(name, () => charOffset); } } Builder lookupIn(String name, int charOffset, Uri fileUri, Map<String, Builder> map, bool isInstanceScope) { Builder builder = map[name]; if (builder == null) return null; if (builder.next != null) { return new AmbiguousBuilder(name.isEmpty ? classNameOrDebugName : name, builder, charOffset, fileUri); } else if (!isInstanceScope && builder.isDeclarationInstanceMember) { return null; } else { return builder; } } Builder lookup(String name, int charOffset, Uri fileUri, {bool isInstanceScope: true}) { recordUse(name, charOffset, fileUri); Builder builder = lookupIn(name, charOffset, fileUri, local, isInstanceScope); if (builder != null) return builder; builder = lookupIn(name, charOffset, fileUri, setters, isInstanceScope); if (builder != null && !builder.hasProblem) { return new AccessErrorBuilder(name, builder, charOffset, fileUri); } if (!isInstanceScope) { // For static lookup, do not search the parent scope. return builder; } return builder ?? parent?.lookup(name, charOffset, fileUri); } Builder lookupSetter(String name, int charOffset, Uri fileUri, {bool isInstanceScope: true}) { recordUse(name, charOffset, fileUri); Builder builder = lookupIn(name, charOffset, fileUri, setters, isInstanceScope); if (builder != null) return builder; builder = lookupIn(name, charOffset, fileUri, local, isInstanceScope); if (builder != null && !builder.hasProblem) { return new AccessErrorBuilder(name, builder, charOffset, fileUri); } if (!isInstanceScope) { // For static lookup, do not search the parent scope. return builder; } return builder ?? parent?.lookupSetter(name, charOffset, fileUri); } bool hasLocalLabel(String name) => labels != null && labels.containsKey(name); void declareLabel(String name, Builder target) { if (isModifiable) { labels ??= <String, Builder>{}; labels[name] = target; } else { internalProblem( messageInternalProblemExtendingUnmodifiableScope, -1, null); } } void forwardDeclareLabel(String name, Builder target) { declareLabel(name, target); forwardDeclaredLabels ??= <String, Builder>{}; forwardDeclaredLabels[name] = target; } bool claimLabel(String name) { if (forwardDeclaredLabels == null || forwardDeclaredLabels.remove(name) == null) return false; if (forwardDeclaredLabels.length == 0) { forwardDeclaredLabels = null; } return true; } Map<String, Builder> get unclaimedForwardDeclarations { return forwardDeclaredLabels; } Builder lookupLabel(String name) { return (labels == null ? null : labels[name]) ?? parent?.lookupLabel(name); } /// Declares that the meaning of [name] in this scope is [builder]. /// /// If name was used previously in this scope, this method returns a message /// that can be used as context for reporting a compile-time error about /// [name] being used before its declared. [fileUri] is used to bind the /// location of this message. LocatedMessage declare(String name, Builder builder, Uri fileUri) { if (isModifiable) { if (usedNames?.containsKey(name) ?? false) { return templateDuplicatedNamePreviouslyUsedCause .withArguments(name) .withLocation(fileUri, usedNames[name], name.length); } local[name] = builder; } else { internalProblem( messageInternalProblemExtendingUnmodifiableScope, -1, null); } return null; } /// Adds [builder] to the extensions in this scope. void addExtension(ExtensionBuilder builder) { _extensions ??= []; _extensions.add(builder); } /// Calls [f] for each extension in this scope and parent scopes. void forEachExtension(void Function(ExtensionBuilder) f) { _extensions?.forEach(f); parent?.forEachExtension(f); } void merge( Scope scope, Builder computeAmbiguousDeclaration( String name, Builder existing, Builder member)) { Map<String, Builder> map = local; void mergeMember(String name, Builder member) { Builder existing = map[name]; if (existing != null) { if (existing != member) { member = computeAmbiguousDeclaration(name, existing, member); } } map[name] = member; } scope.local.forEach(mergeMember); map = setters; scope.setters.forEach(mergeMember); } void forEach(f(String name, Builder member)) { local.forEach(f); setters.forEach(f); } String get debugString { StringBuffer buffer = new StringBuffer(); int nestingLevel = writeOn(buffer); for (int i = nestingLevel; i >= 0; i--) { buffer.writeln("${' ' * i}}"); } return "$buffer"; } int writeOn(StringSink sink) { int nestingLevel = (parent?.writeOn(sink) ?? -1) + 1; String indent = " " * nestingLevel; sink.writeln("$indent{"); local.forEach((String name, Builder member) { sink.writeln("$indent $name"); }); setters.forEach((String name, Builder member) { sink.writeln("$indent $name="); }); return nestingLevel; } Scope computeMixinScope() { List<String> names = this.local.keys.toList(); Map<String, Builder> local = <String, Builder>{}; bool needsCopy = false; for (int i = 0; i < names.length; i++) { String name = names[i]; Builder declaration = this.local[name]; if (declaration.isStatic) { needsCopy = true; } else { local[name] = declaration; } } names = this.setters.keys.toList(); Map<String, Builder> setters = <String, Builder>{}; for (int i = 0; i < names.length; i++) { String name = names[i]; Builder declaration = this.setters[name]; if (declaration.isStatic) { needsCopy = true; } else { setters[name] = declaration; } } return needsCopy ? new Scope( local: local, setters: setters, extensions: _extensions, parent: parent, debugName: classNameOrDebugName, isModifiable: isModifiable) : this; } } class ScopeBuilder { final Scope scope; ScopeBuilder(this.scope); void addMember(String name, Builder builder) { scope.local[name] = builder; } void addSetter(String name, Builder builder) { scope.setters[name] = builder; } void addExtension(ExtensionBuilder builder) { scope.addExtension(builder); } Builder operator [](String name) => scope.local[name]; } abstract class ProblemBuilder extends BuilderImpl { final String name; final Builder builder; final int charOffset; final Uri fileUri; ProblemBuilder(this.name, this.builder, this.charOffset, this.fileUri); get target => null; bool get hasProblem => true; Message get message; @override String get fullNameForErrors => name; } /// Represents a [builder] that's being accessed incorrectly. For example, an /// attempt to write to a final field, or to read from a setter. class AccessErrorBuilder extends ProblemBuilder { AccessErrorBuilder(String name, Builder builder, int charOffset, Uri fileUri) : super(name, builder, charOffset, fileUri); @override Builder get parent => builder; @override bool get isFinal => builder.isFinal; @override bool get isField => builder.isField; @override bool get isRegularMethod => builder.isRegularMethod; @override bool get isGetter => !builder.isGetter; @override bool get isSetter => !builder.isSetter; @override bool get isDeclarationInstanceMember => builder.isDeclarationInstanceMember; @override bool get isClassInstanceMember => builder.isClassInstanceMember; @override bool get isExtensionInstanceMember => builder.isExtensionInstanceMember; @override bool get isStatic => builder.isStatic; @override bool get isTopLevel => builder.isTopLevel; @override bool get isTypeDeclaration => builder.isTypeDeclaration; @override bool get isLocal => builder.isLocal; @override Message get message => templateAccessError.withArguments(name); } class AmbiguousBuilder extends ProblemBuilder { AmbiguousBuilder(String name, Builder builder, int charOffset, Uri fileUri) : super(name, builder, charOffset, fileUri); @override Builder get parent => null; @override Message get message => templateDuplicatedDeclarationUse.withArguments(name); // TODO(ahe): Also provide context. Builder getFirstDeclaration() { Builder declaration = builder; while (declaration.next != null) { declaration = declaration.next; } return declaration; } } class ScopeLocalDeclarationIterator implements Iterator<Builder> { Iterator<Builder> local; final Iterator<Builder> setters; @override Builder current; ScopeLocalDeclarationIterator(Scope scope) : local = scope.local.values.iterator, setters = scope.setters.values.iterator; @override bool moveNext() { Builder next = current?.next; if (next != null) { current = next; return true; } if (local != null) { if (local.moveNext()) { current = local.current; return true; } local = null; } if (setters.moveNext()) { current = setters.current; return true; } else { current = null; return false; } } } class ScopeLocalDeclarationNameIterator extends ScopeLocalDeclarationIterator implements NameIterator { Iterator<String> localNames; final Iterator<String> setterNames; @override String name; ScopeLocalDeclarationNameIterator(Scope scope) : localNames = scope.local.keys.iterator, setterNames = scope.setters.keys.iterator, super(scope); @override bool moveNext() { Builder next = current?.next; if (next != null) { current = next; return true; } if (local != null) { if (local.moveNext()) { localNames.moveNext(); current = local.current; name = localNames.current; return true; } localNames = null; } if (setters.moveNext()) { setterNames.moveNext(); current = setters.current; name = setterNames.current; return true; } else { current = null; 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/fasta/quote.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.quote; import 'problems.dart' show unhandled; import 'fasta_codes.dart' as fasta; import 'scanner/characters.dart' show $BACKSLASH, $BS, $CLOSE_CURLY_BRACKET, $CR, $FF, $LF, $OPEN_CURLY_BRACKET, $SPACE, $TAB, $VTAB, $b, $f, $n, $r, $t, $u, $v, $x, hexDigitValue, isHexDigit; enum Quote { Single, Double, MultiLineSingle, MultiLineDouble, RawSingle, RawDouble, RawMultiLineSingle, RawMultiLineDouble, } Quote analyzeQuote(String first) { if (first.startsWith('"""')) return Quote.MultiLineDouble; if (first.startsWith('r"""')) return Quote.RawMultiLineDouble; if (first.startsWith("'''")) return Quote.MultiLineSingle; if (first.startsWith("r'''")) return Quote.RawMultiLineSingle; if (first.startsWith('"')) return Quote.Double; if (first.startsWith('r"')) return Quote.RawDouble; if (first.startsWith("'")) return Quote.Single; if (first.startsWith("r'")) return Quote.RawSingle; return unhandled(first, "analyzeQuote", -1, null); } // Note: based on [StringValidator.quotingFromString] // (pkg/compiler/lib/src/string_validator.dart). int lengthOfOptionalWhitespacePrefix(String first, int start) { List<int> codeUnits = first.codeUnits; for (int i = start; i < codeUnits.length; i++) { int code = codeUnits[i]; if (code == $BACKSLASH) { i++; if (i < codeUnits.length) { code = codeUnits[i]; } else { break; } } if (code == $TAB || code == $SPACE) continue; if (code == $CR) { if (i + 1 < codeUnits.length && codeUnits[i + 1] == $LF) { i++; } return i + 1; } if (code == $LF) { return i + 1; } break; // Not a white-space character. } return start; } int firstQuoteLength(String first, Quote quote) { switch (quote) { case Quote.Single: case Quote.Double: return 1; case Quote.MultiLineSingle: case Quote.MultiLineDouble: return lengthOfOptionalWhitespacePrefix(first, 3); case Quote.RawSingle: case Quote.RawDouble: return 2; case Quote.RawMultiLineSingle: case Quote.RawMultiLineDouble: return lengthOfOptionalWhitespacePrefix(first, 4); } return unhandled("$quote", "firstQuoteLength", -1, null); } int lastQuoteLength(Quote quote) { switch (quote) { case Quote.Single: case Quote.Double: case Quote.RawSingle: case Quote.RawDouble: return 1; case Quote.MultiLineSingle: case Quote.MultiLineDouble: case Quote.RawMultiLineSingle: case Quote.RawMultiLineDouble: return 3; } return unhandled("$quote", "lastQuoteLength", -1, null); } String unescapeFirstStringPart(String first, Quote quote, Object location, UnescapeErrorListener listener) { return unescape(first.substring(firstQuoteLength(first, quote)), quote, location, listener); } String unescapeLastStringPart(String last, Quote quote, Object location, bool isLastQuoteSynthetic, UnescapeErrorListener listener) { int end = last.length - (isLastQuoteSynthetic ? 0 : lastQuoteLength(quote)); return unescape(last.substring(0, end), quote, location, listener); } String unescapeString( String string, Object location, UnescapeErrorListener listener) { Quote quote = analyzeQuote(string); return unescape( string.substring(firstQuoteLength(string, quote), string.length - lastQuoteLength(quote)), quote, location, listener); } String unescape(String string, Quote quote, Object location, UnescapeErrorListener listener) { switch (quote) { case Quote.Single: case Quote.Double: return !string.contains("\\") ? string : unescapeCodeUnits(string.codeUnits, false, location, listener); case Quote.MultiLineSingle: case Quote.MultiLineDouble: return !string.contains("\\") && !string.contains("\r") ? string : unescapeCodeUnits(string.codeUnits, false, location, listener); case Quote.RawSingle: case Quote.RawDouble: return string; case Quote.RawMultiLineSingle: case Quote.RawMultiLineDouble: return !string.contains("\r") ? string : unescapeCodeUnits(string.codeUnits, true, location, listener); } return unhandled("$quote", "unescape", -1, null); } // Note: based on // [StringValidator.validateString](pkg/compiler/lib/src/string_validator.dart). String unescapeCodeUnits(List<int> codeUnits, bool isRaw, Object location, UnescapeErrorListener listener) { // Can't use Uint8List or Uint16List here, the code units may be larger. List<int> result = new List<int>(codeUnits.length); int resultOffset = 0; for (int i = 0; i < codeUnits.length; i++) { int code = codeUnits[i]; if (code == $CR) { if (i + 1 < codeUnits.length && codeUnits[i + 1] == $LF) { i++; } code = $LF; } else if (!isRaw && code == $BACKSLASH) { if (codeUnits.length == ++i) { listener.handleUnescapeError( fasta.messageInvalidUnicodeEscape, location, i, 1); return new String.fromCharCodes(codeUnits); } code = codeUnits[i]; /// `\n` for newline, equivalent to `\x0A`. /// `\r` for carriage return, equivalent to `\x0D`. /// `\f` for form feed, equivalent to `\x0C`. /// `\b` for backspace, equivalent to `\x08`. /// `\t` for tab, equivalent to `\x09`. /// `\v` for vertical tab, equivalent to `\x0B`. /// `\xXX` for hex escape. /// `\uXXXX` or `\u{XX?X?X?X?X?}` for Unicode hex escape. if (code == $n) { code = $LF; } else if (code == $r) { code = $CR; } else if (code == $f) { code = $FF; } else if (code == $b) { code = $BS; } else if (code == $t) { code = $TAB; } else if (code == $v) { code = $VTAB; } else if (code == $x) { // Expect exactly 2 hex digits. int begin = i; if (codeUnits.length <= i + 2) { listener.handleUnescapeError(fasta.messageInvalidHexEscape, location, begin, codeUnits.length + 1 - begin); return new String.fromCharCodes(codeUnits); } code = 0; for (int j = 0; j < 2; j++) { int digit = codeUnits[++i]; if (!isHexDigit(digit)) { listener.handleUnescapeError( fasta.messageInvalidHexEscape, location, begin, i + 1 - begin); return new String.fromCharCodes(codeUnits); } code = (code << 4) + hexDigitValue(digit); } } else if (code == $u) { int begin = i; if (codeUnits.length == i + 1) { listener.handleUnescapeError(fasta.messageInvalidUnicodeEscape, location, begin, codeUnits.length + 1 - begin); return new String.fromCharCodes(codeUnits); } code = codeUnits[i + 1]; if (code == $OPEN_CURLY_BRACKET) { // Expect 1-6 hex digits followed by '}'. if (codeUnits.length == ++i) { listener.handleUnescapeError(fasta.messageInvalidUnicodeEscape, location, begin, i + 1 - begin); return new String.fromCharCodes(codeUnits); } code = 0; for (int j = 0; j < 7; j++) { if (codeUnits.length == ++i) { listener.handleUnescapeError(fasta.messageInvalidUnicodeEscape, location, begin, i + 1 - begin); return new String.fromCharCodes(codeUnits); } int digit = codeUnits[i]; if (j != 0 && digit == $CLOSE_CURLY_BRACKET) break; if (!isHexDigit(digit)) { listener.handleUnescapeError(fasta.messageInvalidUnicodeEscape, location, begin, i + 2 - begin); return new String.fromCharCodes(codeUnits); } code = (code << 4) + hexDigitValue(digit); } } else { // Expect exactly 4 hex digits. if (codeUnits.length <= i + 4) { listener.handleUnescapeError(fasta.messageInvalidUnicodeEscape, location, begin, codeUnits.length + 1 - begin); return new String.fromCharCodes(codeUnits); } code = 0; for (int j = 0; j < 4; j++) { int digit = codeUnits[++i]; if (!isHexDigit(digit)) { listener.handleUnescapeError(fasta.messageInvalidUnicodeEscape, location, begin, i + 1 - begin); return new String.fromCharCodes(codeUnits); } code = (code << 4) + hexDigitValue(digit); } } if (code > 0x10FFFF) { listener.handleUnescapeError( fasta.messageInvalidCodePoint, location, begin, i + 1 - begin); return new String.fromCharCodes(codeUnits); } } else { // Nothing, escaped character is passed through; } } result[resultOffset++] = code; } return new String.fromCharCodes(result, 0, resultOffset); } abstract class UnescapeErrorListener { void handleUnescapeError( fasta.Message message, covariant location, int offset, int length); }
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/fasta/problems.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.problems; import 'package:kernel/ast.dart' show FileUriNode, TreeNode; import 'compiler_context.dart' show CompilerContext; import 'messages.dart' show LocatedMessage, Message, noLength, templateInternalProblemDebugAbort, templateInternalProblemUnexpected, templateInternalProblemUnhandled, templateInternalProblemUnimplemented, templateInternalProblemUnsupported; import 'severity.dart' show Severity, severityTexts; class DebugAbort { final LocatedMessage message; DebugAbort(Uri uri, int charOffset, Severity severity, StackTrace trace) : message = templateInternalProblemDebugAbort .withArguments(severityTexts[severity], "$trace") .withLocation(uri, charOffset, noLength); toString() => "DebugAbort: ${message.message}"; } /// Used to report an internal error. /// /// Internal errors should be avoided as best as possible, but are preferred /// over assertion failures. The message should start with an upper-case letter /// and contain a short description that may help a developer debug the issue. /// This method should be called instead of using `throw`, as this allows us to /// ensure that there are no throws anywhere else in the codebase. /// /// Before printing the message, the string `"Internal error: "` is prepended. dynamic internalProblem(Message message, int charOffset, Uri uri) { throw CompilerContext.current.format( message.withLocation(uri, charOffset, noLength), Severity.internalProblem); } dynamic unimplemented(String what, int charOffset, Uri uri) { return internalProblem( templateInternalProblemUnimplemented.withArguments(what), charOffset, uri); } dynamic unhandled(String what, String where, int charOffset, Uri uri) { return internalProblem( templateInternalProblemUnhandled.withArguments(what, where), charOffset, uri); } dynamic unexpected(String expected, String actual, int charOffset, Uri uri) { return internalProblem( templateInternalProblemUnexpected.withArguments(expected, actual), charOffset, uri); } dynamic unsupported(String operation, int charOffset, Uri uri) { return internalProblem( templateInternalProblemUnsupported.withArguments(operation), charOffset, uri); } Uri getFileUri(TreeNode node) { do { if (node is FileUriNode) return node.fileUri; node = node.parent; } while (node is TreeNode); return 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/fasta/target_implementation.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.target_implementation; import 'package:kernel/ast.dart' show Source; import 'package:kernel/target/targets.dart' as backend show Target; import '../base/processed_options.dart' show ProcessedOptions; import 'builder/builder.dart' show Builder, ClassBuilder, LibraryBuilder; import 'compiler_context.dart' show CompilerContext; import 'loader.dart' show Loader; import 'messages.dart' show FormattedMessage, LocatedMessage, Message; import 'rewrite_severity.dart' show rewriteSeverity; import 'severity.dart' show Severity; import 'target.dart' show Target; import 'ticker.dart' show Ticker; import 'uri_translator.dart' show UriTranslator; import '../api_prototype/experimental_flags.dart' show ExperimentalFlag; /// Provides the implementation details used by a loader for a target. abstract class TargetImplementation extends Target { final UriTranslator uriTranslator; final backend.Target backendTarget; final CompilerContext context = CompilerContext.current; /// Shared with [CompilerContext]. final Map<Uri, Source> uriToSource = CompilerContext.current.uriToSource; Builder cachedAbstractClassInstantiationError; Builder cachedCompileTimeError; Builder cachedDuplicatedFieldInitializerError; Builder cachedFallThroughError; Builder cachedNativeAnnotation; Builder cachedNativeExtensionAnnotation; bool enableExtensionMethods; bool enableNonNullable; bool enableTripleShift; bool enableVariance; TargetImplementation(Ticker ticker, this.uriTranslator, this.backendTarget) : enableExtensionMethods = CompilerContext.current.options .isExperimentEnabled(ExperimentalFlag.extensionMethods), enableNonNullable = CompilerContext.current.options .isExperimentEnabled(ExperimentalFlag.nonNullable), enableTripleShift = CompilerContext.current.options .isExperimentEnabled(ExperimentalFlag.tripleShift), enableVariance = CompilerContext.current.options .isExperimentEnabled(ExperimentalFlag.variance), super(ticker); /// Creates a [LibraryBuilder] corresponding to [uri], if one doesn't exist /// already. /// /// [fileUri] must not be null and is a URI that can be passed to FileSystem /// to locate the corresponding file. /// /// [origin] is non-null if the created library is a patch to [origin]. LibraryBuilder createLibraryBuilder( Uri uri, Uri fileUri, covariant LibraryBuilder origin); /// The class [cls] is involved in a cyclic definition. This method should /// ensure that the cycle is broken, for example, by removing superclass and /// implemented interfaces. void breakCycle(ClassBuilder cls); Uri translateUri(Uri uri) => uriTranslator.translate(uri); /// Returns a reference to the constructor of /// [AbstractClassInstantiationError] error. The constructor is expected to /// accept a single argument of type String, which is the name of the /// abstract class. Builder getAbstractClassInstantiationError(Loader loader) { if (cachedAbstractClassInstantiationError != null) { return cachedAbstractClassInstantiationError; } return cachedAbstractClassInstantiationError = loader.coreLibrary.getConstructor("AbstractClassInstantiationError"); } /// Returns a reference to the constructor used for creating a compile-time /// error. The constructor is expected to accept a single argument of type /// String, which is the compile-time error message. Builder getCompileTimeError(Loader loader) { if (cachedCompileTimeError != null) return cachedCompileTimeError; return cachedCompileTimeError = loader.coreLibrary .getConstructor("_CompileTimeError", bypassLibraryPrivacy: true); } /// Returns a reference to the constructor used for creating a runtime error /// when a final field is initialized twice. The constructor is expected to /// accept a single argument which is the name of the field. Builder getDuplicatedFieldInitializerError(Loader loader) { if (cachedDuplicatedFieldInitializerError != null) { return cachedDuplicatedFieldInitializerError; } return cachedDuplicatedFieldInitializerError = loader.coreLibrary .getConstructor("_DuplicatedFieldInitializerError", bypassLibraryPrivacy: true); } /// Returns a reference to the constructor used for creating `native` /// annotations. The constructor is expected to accept a single argument of /// type String, which is the name of the native method. Builder getNativeAnnotation(Loader loader) { if (cachedNativeAnnotation != null) return cachedNativeAnnotation; LibraryBuilder internal = loader.read(Uri.parse("dart:_internal"), -1, accessor: loader.coreLibrary); return cachedNativeAnnotation = internal.getConstructor("ExternalName"); } void loadExtraRequiredLibraries(Loader loader) { for (String uri in backendTarget.extraRequiredLibraries) { loader.read(Uri.parse(uri), 0, accessor: loader.coreLibrary); } if (context.compilingPlatform) { for (String uri in backendTarget.extraRequiredLibrariesPlatform) { loader.read(Uri.parse(uri), 0, accessor: loader.coreLibrary); } } } void addSourceInformation( Uri importUri, Uri fileUri, List<int> lineStarts, List<int> sourceCode); void readPatchFiles(covariant LibraryBuilder library) {} FormattedMessage createFormattedMessage( Message message, int charOffset, int length, Uri fileUri, List<LocatedMessage> messageContext, Severity severity) { ProcessedOptions processedOptions = context.options; return processedOptions.format( message.withLocation(fileUri, charOffset, length), severity, messageContext); } Severity fixSeverity(Severity severity, Message message, Uri fileUri) { severity ??= message.code.severity; if (severity == Severity.errorLegacyWarning) { severity = Severity.error; } return rewriteSeverity(severity, message.code, fileUri); } String get currentSdkVersion { return CompilerContext.current.options.currentSdkVersion; } int _currentSdkVersionMajor; int _currentSdkVersionMinor; int get currentSdkVersionMajor { if (_currentSdkVersionMajor != null) return _currentSdkVersionMajor; _parseCurrentSdkVersion(); return _currentSdkVersionMajor; } int get currentSdkVersionMinor { if (_currentSdkVersionMinor != null) return _currentSdkVersionMinor; _parseCurrentSdkVersion(); return _currentSdkVersionMinor; } void _parseCurrentSdkVersion() { bool good = false; if (currentSdkVersion != null) { List<String> dotSeparatedParts = currentSdkVersion.split("."); if (dotSeparatedParts.length >= 2) { _currentSdkVersionMajor = int.tryParse(dotSeparatedParts[0]); _currentSdkVersionMinor = int.tryParse(dotSeparatedParts[1]); good = true; } } if (!good) { throw new StateError("Unparsable sdk version given: $currentSdkVersion"); } } }
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/fasta/export.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.export; import 'builder/builder.dart' show Builder, LibraryBuilder; import 'combinator.dart' show Combinator; class Export { /// The library that is exporting [exported]; final LibraryBuilder exporter; /// The library being exported. final LibraryBuilder exported; final List<Combinator> combinators; final int charOffset; Export(this.exporter, this.exported, this.combinators, this.charOffset); Uri get fileUri => exporter.fileUri; bool addToExportScope(String name, Builder member) { if (combinators != null) { for (Combinator combinator in combinators) { if (combinator.isShow && !combinator.names.contains(name)) return false; if (combinator.isHide && combinator.names.contains(name)) return false; } } return exporter.addToExportScope(name, member, charOffset); } }
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/flow_analysis/flow_analysis.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 'package:meta/meta.dart'; /// [AssignedVariables] is a helper class capable of computing the set of /// variables that are potentially written to, and potentially captured by /// closures, at various locations inside the code being analyzed. This class /// should be used prior to running flow analysis, to compute the sets of /// variables to pass in to flow analysis. /// /// This class is intended to be used in two phases. In the first phase, the /// client should traverse the source code recursively, making calls to /// [beginNode] and [endNode] to indicate the constructs in which writes should /// be tracked, and calls to [write] to indicate when a write is encountered. /// The order of visiting is not important provided that nesting is respected. /// This phase is called the "pre-traversal" because it should happen prior to /// flow analysis. /// /// Then, in the second phase, the client may make queries using /// [capturedAnywhere], [writtenInNode], and [capturedInNode]. /// /// We use the term "node" to refer generally to a loop statement, switch /// statement, try statement, loop collection element, local function, or /// closure. class AssignedVariables<Node, Variable> { /// Mapping from a node to the set of local variables that are potentially /// written to within that node. final Map<Node, Set<Variable>> _writtenInNode = {}; /// Mapping from a node to the set of local variables for which a potential /// write is captured by a local function or closure inside that node. final Map<Node, Set<Variable>> _capturedInNode = {}; /// Stack of sets accumulating variables that are potentially written to. /// /// A set is pushed onto the stack when a node is entered, and popped when /// a node is left. final List<Set<Variable>> _writtenStack = []; /// Stack of sets accumulating variables for which a potential write is /// captured by a local function or closure. /// /// A set is pushed onto the stack when a node is entered, and popped when /// a node is left. final List<Set<Variable>> _capturedStack = []; /// Stack of integers counting the number of entries in [_capturedStack] that /// should be updated when a variable write is seen. /// /// When a closure is entered, the length of [_capturedStack] is pushed onto /// this stack; when a node is left, it is popped. /// /// Each time a write occurs, we consult the top of this stack to determine /// how many elements of [capturedStack] should be updated. final List<int> _closureIndexStack = []; AssignedVariables(); /// This method should be called during pre-traversal, to mark the start of a /// loop statement, switch statement, try statement, loop collection element, /// local function, or closure which might need to be queried later. /// /// [isClosure] should be true if the node is a local function or closure. /// /// The span between the call to [beginNode] and [endNode] should cover any /// statements and expressions that might be crossed by a backwards jump. So /// for instance, in a "for" loop, the condition, updaters, and body should be /// covered, but the initializers should not. Similarly, in a switch /// statement, the body of the switch statement should be covered, but the /// switch expression should not. void beginNode({bool isClosure: false}) { _writtenStack.add(new Set<Variable>.identity()); if (isClosure) { _closureIndexStack.add(_capturedStack.length); } _capturedStack.add(new Set<Variable>.identity()); } /// Queries the set of variables for which a potential write is captured by a /// local function or closure inside the [node]. Set<Variable> capturedInNode(Node node) { return _capturedInNode[node] ?? const {}; } /// This method should be called during pre-traversal, to mark the end of a /// loop statement, switch statement, try statement, loop collection element, /// local function, or closure which might need to be queried later. /// /// [isClosure] should be true if the node is a local function or closure. /// /// See [beginNode] for more details. void endNode(Node node, {bool isClosure: false}) { _writtenInNode[node] = _writtenStack.removeLast(); _capturedInNode[node] = _capturedStack.removeLast(); if (isClosure) { _closureIndexStack.removeLast(); } } /// This method should be called during pre-traversal, to mark a write to a /// variable. void write(Variable variable) { for (int i = 0; i < _writtenStack.length; ++i) { _writtenStack[i].add(variable); } if (_closureIndexStack.isNotEmpty) { int closureIndex = _closureIndexStack.last; for (int i = 0; i < closureIndex; ++i) { _capturedStack[i].add(variable); } } } /// Queries the set of variables that are potentially written to inside the /// [node]. Set<Variable> writtenInNode(Node node) { return _writtenInNode[node] ?? const {}; } } class FlowAnalysis<Statement, Expression, Variable, Type> { /// The [NodeOperations], used to manipulate expressions. final NodeOperations<Expression> nodeOperations; /// The [TypeOperations], used to access types, and check subtyping. final TypeOperations<Variable, Type> typeOperations; /// The enclosing function body, used to check for potential mutations. final FunctionBodyAccess<Variable> functionBody; /// The stack of states of variables that are not definitely assigned. final List<FlowModel<Variable, Type>> _stack = []; /// The mapping from labeled [Statement]s to the index in the [_stack] /// where the first related element is located. The number of elements /// is statement specific. Loops have two elements: `break` and `continue` /// states. final Map<Statement, int> _statementToStackIndex = {}; FlowModel<Variable, Type> _current; /// The last boolean condition, for [_conditionTrue] and [_conditionFalse]. Expression _condition; /// The state when [_condition] evaluates to `true`. FlowModel<Variable, Type> _conditionTrue; /// The state when [_condition] evaluates to `false`. FlowModel<Variable, Type> _conditionFalse; factory FlowAnalysis( NodeOperations<Expression> nodeOperations, TypeOperations<Variable, Type> typeOperations, FunctionBodyAccess<Variable> functionBody, ) { return new FlowAnalysis._(nodeOperations, typeOperations, functionBody); } FlowAnalysis._(this.nodeOperations, this.typeOperations, this.functionBody) { _current = new FlowModel<Variable, Type>(true); } /// Return `true` if the current state is reachable. bool get isReachable => _current.reachable; void booleanLiteral(Expression expression, bool value) { _condition = expression; if (value) { _conditionTrue = _current; _conditionFalse = _current.setReachable(false); } else { _conditionTrue = _current.setReachable(false); _conditionFalse = _current; } } void conditional_elseBegin(Expression thenExpression) { FlowModel<Variable, Type> afterThen = _current; FlowModel<Variable, Type> falseCondition = _stack.removeLast(); _conditionalEnd(thenExpression); // Tail of the stack: falseThen, trueThen _stack.add(afterThen); _current = falseCondition; } void conditional_end( Expression conditionalExpression, Expression elseExpression) { FlowModel<Variable, Type> afterThen = _stack.removeLast(); FlowModel<Variable, Type> afterElse = _current; _conditionalEnd(elseExpression); // Tail of the stack: falseThen, trueThen, falseElse, trueElse FlowModel<Variable, Type> trueElse = _stack.removeLast(); FlowModel<Variable, Type> falseElse = _stack.removeLast(); FlowModel<Variable, Type> trueThen = _stack.removeLast(); FlowModel<Variable, Type> falseThen = _stack.removeLast(); FlowModel<Variable, Type> trueResult = _join(trueThen, trueElse); FlowModel<Variable, Type> falseResult = _join(falseThen, falseElse); _condition = conditionalExpression; _conditionTrue = trueResult; _conditionFalse = falseResult; _current = _join(afterThen, afterElse); } void conditional_thenBegin(Expression condition) { _conditionalEnd(condition); // Tail of the stack: falseCondition, trueCondition FlowModel<Variable, Type> trueCondition = _stack.removeLast(); _current = trueCondition; } /// The [binaryExpression] checks that the [variable] is, or is not, equal to /// `null`. void conditionEqNull(Expression binaryExpression, Variable variable, {bool notEqual: false}) { if (functionBody.isPotentiallyMutatedInClosure(variable)) { return; } _condition = binaryExpression; FlowModel<Variable, Type> currentModel = _current.markNonNullable(typeOperations, variable); if (notEqual) { _conditionTrue = currentModel; _conditionFalse = _current; } else { _conditionTrue = _current; _conditionFalse = currentModel; } } void doStatement_bodyBegin( Statement doStatement, Iterable<Variable> loopAssigned) { _current = _current.removePromotedAll(loopAssigned); _statementToStackIndex[doStatement] = _stack.length; _stack.add(null); // break _stack.add(null); // continue } void doStatement_conditionBegin() { // Tail of the stack: break, continue FlowModel<Variable, Type> continueState = _stack.removeLast(); _current = _join(_current, continueState); } void doStatement_end(Expression condition) { _conditionalEnd(condition); // Tail of the stack: break, falseCondition, trueCondition _stack.removeLast(); // trueCondition FlowModel<Variable, Type> falseCondition = _stack.removeLast(); FlowModel<Variable, Type> breakState = _stack.removeLast(); _current = _join(falseCondition, breakState); } /// This method should be called at the conclusion of flow analysis for a top /// level function or method. Performs assertion checks. void finish() { assert(_stack.isEmpty); } /// Call this method just before visiting the body of a conventional "for" /// statement or collection element. See [for_conditionBegin] for details. /// /// If a "for" statement is being entered, [node] is an opaque representation /// of the loop, for use as the target of future calls to [handleBreak] or /// [handleContinue]. If a "for" collection element is being entered, [node] /// should be `null`. /// /// [condition] is an opaque representation of the loop condition; it is /// matched against expressions passed to previous calls to determine whether /// the loop condition should cause any promotions to occur. If [condition] /// is null, the condition is understood to be empty (equivalent to a /// condition of `true`). void for_bodyBegin(Statement node, Expression condition) { FlowModel<Variable, Type> trueCondition; if (condition == null) { trueCondition = _current; _stack.add(_current.setReachable(false)); } else { _conditionalEnd(condition); // Tail of the stack: falseCondition, trueCondition trueCondition = _stack.removeLast(); } // Tail of the stack: falseCondition if (node != null) { _statementToStackIndex[node] = _stack.length; } _stack.add(null); // break _stack.add(null); // continue _current = trueCondition; } /// Call this method just before visiting the condition of a conventional /// "for" statement or collection element. /// /// Note that a conventional "for" statement is a statement of the form /// `for (initializers; condition; updaters) body`. Statements of the form /// `for (variable in iterable) body` should use [forEach_bodyBegin]. Similar /// for "for" collection elements. /// /// The order of visiting a "for" statement or collection element should be: /// - Visit the initializers. /// - Call [for_conditionBegin]. /// - Visit the condition. /// - Call [for_bodyBegin]. /// - Visit the body. /// - Call [for_updaterBegin]. /// - Visit the updaters. /// - Call [for_end]. /// /// [loopAssigned] should be the set of variables that are assigned anywhere /// in the loop's condition, updaters, or body. void for_conditionBegin(Set<Variable> loopAssigned) { _current = _current.removePromotedAll(loopAssigned); } /// Call this method just after visiting the updaters of a conventional "for" /// statement or collection element. See [for_conditionBegin] for details. void for_end() { // Tail of the stack: falseCondition, break FlowModel<Variable, Type> breakState = _stack.removeLast(); FlowModel<Variable, Type> falseCondition = _stack.removeLast(); _current = _join(falseCondition, breakState); } /// Call this method just before visiting the updaters of a conventional "for" /// statement or collection element. See [for_conditionBegin] for details. void for_updaterBegin() { // Tail of the stack: falseCondition, break, continue FlowModel<Variable, Type> afterBody = _current; FlowModel<Variable, Type> continueState = _stack.removeLast(); _current = _join(afterBody, continueState); } /// Call this method just before visiting the body of a "for-in" statement or /// collection element. /// /// The order of visiting a "for-in" statement or collection element should /// be: /// - Visit the iterable expression. /// - Call [forEach_bodyBegin]. /// - Visit the body. /// - Call [forEach_end]. /// /// [loopAssigned] should be the set of variables that are assigned anywhere /// in the loop's body. [loopVariable] should be the loop variable, if it's a /// local variable, or `null` otherwise. void forEach_bodyBegin(Set<Variable> loopAssigned, Variable loopVariable) { _stack.add(_current); _current = _current.removePromotedAll(loopAssigned); if (loopVariable != null) { assert(loopAssigned.contains(loopVariable)); _current = _current.write(loopVariable); } } /// Call this method just before visiting the body of a "for-in" statement or /// collection element. See [forEach_bodyBegin] for details. void forEach_end() { FlowModel<Variable, Type> afterIterable = _stack.removeLast(); _current = _join(_current, afterIterable); } void functionExpression_begin() { _stack.add(_current); List<Variable> notPromoted = []; for (MapEntry<Variable, VariableModel<Type>> entry in _current.variableInfo.entries) { Variable variable = entry.key; Type promotedType = entry.value.promotedType; if (promotedType != null && functionBody.isPotentiallyMutatedInScope(variable)) { notPromoted.add(variable); } } if (notPromoted.isNotEmpty) { _current = _current.removePromotedAll(notPromoted); } } void functionExpression_end() { _current = _stack.removeLast(); } void handleBreak(Statement target) { int breakIndex = _statementToStackIndex[target]; if (breakIndex != null) { _stack[breakIndex] = _join(_stack[breakIndex], _current); } _current = _current.setReachable(false); } void handleContinue(Statement target) { int breakIndex = _statementToStackIndex[target]; if (breakIndex != null) { int continueIndex = breakIndex + 1; _stack[continueIndex] = _join(_stack[continueIndex], _current); } _current = _current.setReachable(false); } /// Register the fact that the current state definitely exists, e.g. returns /// from the body, throws an exception, etc. void handleExit() { _current = _current.setReachable(false); } void ifNullExpression_end() { FlowModel<Variable, Type> afterLeft = _stack.removeLast(); _current = _join(_current, afterLeft); } void ifNullExpression_rightBegin() { _stack.add(_current); // afterLeft } void ifStatement_elseBegin() { FlowModel<Variable, Type> afterThen = _current; FlowModel<Variable, Type> falseCondition = _stack.removeLast(); _stack.add(afterThen); _current = falseCondition; } void ifStatement_end(bool hasElse) { FlowModel<Variable, Type> afterThen; FlowModel<Variable, Type> afterElse; if (hasElse) { afterThen = _stack.removeLast(); afterElse = _current; } else { afterThen = _current; // no `else`, so `then` is still current afterElse = _stack.removeLast(); // `falseCond` is still on the stack } _current = _join(afterThen, afterElse); } void ifStatement_thenBegin(Expression condition) { _conditionalEnd(condition); // Tail of the stack: falseCondition, trueCondition FlowModel<Variable, Type> trueCondition = _stack.removeLast(); _current = trueCondition; } /// Return whether the [variable] is definitely assigned in the current state. bool isAssigned(Variable variable) { return _current.infoFor(variable).assigned; } void isExpression_end( Expression isExpression, Variable variable, bool isNot, Type type) { if (functionBody.isPotentiallyMutatedInClosure(variable)) { return; } _condition = isExpression; if (isNot) { _conditionTrue = _current; _conditionFalse = _current.promote(typeOperations, variable, type); } else { _conditionTrue = _current.promote(typeOperations, variable, type); _conditionFalse = _current; } } void logicalBinaryOp_end(Expression wholeExpression, Expression rightOperand, {@required bool isAnd}) { _conditionalEnd(rightOperand); // Tail of the stack: falseLeft, trueLeft, falseRight, trueRight FlowModel<Variable, Type> trueRight = _stack.removeLast(); FlowModel<Variable, Type> falseRight = _stack.removeLast(); FlowModel<Variable, Type> trueLeft = _stack.removeLast(); FlowModel<Variable, Type> falseLeft = _stack.removeLast(); FlowModel<Variable, Type> trueResult; FlowModel<Variable, Type> falseResult; if (isAnd) { trueResult = trueRight; falseResult = _join(falseLeft, falseRight); } else { trueResult = _join(trueLeft, trueRight); falseResult = falseRight; } FlowModel<Variable, Type> afterResult = _join(trueResult, falseResult); _condition = wholeExpression; _conditionTrue = trueResult; _conditionFalse = falseResult; _current = afterResult; } void logicalBinaryOp_rightBegin(Expression leftOperand, {@required bool isAnd}) { _conditionalEnd(leftOperand); // Tail of the stack: falseLeft, trueLeft if (isAnd) { FlowModel<Variable, Type> trueLeft = _stack.last; _current = trueLeft; } else { FlowModel<Variable, Type> falseLeft = _stack[_stack.length - 2]; _current = falseLeft; } } void logicalNot_end(Expression notExpression, Expression operand) { _conditionalEnd(operand); FlowModel<Variable, Type> trueExpr = _stack.removeLast(); FlowModel<Variable, Type> falseExpr = _stack.removeLast(); _condition = notExpression; _conditionTrue = falseExpr; _conditionFalse = trueExpr; } /// Retrieves the type that the [variable] is promoted to, if the [variable] /// is currently promoted. Otherwise returns `null`. Type promotedType(Variable variable) { return _current.infoFor(variable).promotedType; } /// Call this method just before visiting one of the cases in the body of a /// switch statement. See [switchStatement_expressionEnd] for details. /// /// [hasLabel] indicates whether the case has any labels. /// /// The [notPromoted] set contains all variables that are potentially assigned /// within the body of the switch statement. void switchStatement_beginCase( bool hasLabel, Iterable<Variable> notPromoted) { if (hasLabel) { _current = _stack.last.removePromotedAll(notPromoted); } else { _current = _stack.last; } } /// Call this method just after visiting the body of a switch statement. See /// [switchStatement_expressionEnd] for details. /// /// [hasDefault] indicates whether the switch statement had a "default" case. void switchStatement_end(bool hasDefault) { // Tail of the stack: break, continue, afterExpression FlowModel<Variable, Type> afterExpression = _stack.removeLast(); _stack.removeLast(); // continue FlowModel<Variable, Type> breakState = _stack.removeLast(); // It is allowed to "fall off" the end of a switch statement, so join the // current state to any breaks that were found previously. breakState = _join(breakState, _current); // And, if there is an implicit fall-through default, join it to any breaks. if (!hasDefault) breakState = _join(breakState, afterExpression); _current = breakState; } /// Call this method just after visiting the expression part of a switch /// statement. /// /// The order of visiting a switch statement should be: /// - Visit the switch expression. /// - Call [switchStatement_expressionEnd]. /// - For each switch case (including the default case, if any): /// - Call [switchStatement_beginCase]. /// - Visit the case. /// - Call [switchStatement_end]. void switchStatement_expressionEnd(Statement switchStatement) { _statementToStackIndex[switchStatement] = _stack.length; _stack.add(null); // break _stack.add(null); // continue _stack.add(_current); // afterExpression } void tryCatchStatement_bodyBegin() { _stack.add(_current); // Tail of the stack: beforeBody } void tryCatchStatement_bodyEnd(Iterable<Variable> assignedInBody) { FlowModel<Variable, Type> beforeBody = _stack.removeLast(); FlowModel<Variable, Type> beforeCatch = beforeBody.removePromotedAll(assignedInBody); _stack.add(beforeCatch); _stack.add(_current); // afterBodyAndCatches // Tail of the stack: beforeCatch, afterBodyAndCatches } void tryCatchStatement_catchBegin() { FlowModel<Variable, Type> beforeCatch = _stack[_stack.length - 2]; _current = beforeCatch; } void tryCatchStatement_catchEnd() { FlowModel<Variable, Type> afterBodyAndCatches = _stack.last; _stack.last = _join(afterBodyAndCatches, _current); } void tryCatchStatement_end() { FlowModel<Variable, Type> afterBodyAndCatches = _stack.removeLast(); _stack.removeLast(); // beforeCatch _current = afterBodyAndCatches; } void tryFinallyStatement_bodyBegin() { _stack.add(_current); // beforeTry } void tryFinallyStatement_end(Set<Variable> assignedInFinally) { FlowModel<Variable, Type> afterBody = _stack.removeLast(); _current = _current.restrict(typeOperations, afterBody, assignedInFinally); } void tryFinallyStatement_finallyBegin(Iterable<Variable> assignedInBody) { FlowModel<Variable, Type> beforeTry = _stack.removeLast(); FlowModel<Variable, Type> afterBody = _current; _stack.add(afterBody); _current = _join(afterBody, beforeTry.removePromotedAll(assignedInBody)); } void whileStatement_bodyBegin( Statement whileStatement, Expression condition) { _conditionalEnd(condition); // Tail of the stack: falseCondition, trueCondition FlowModel<Variable, Type> trueCondition = _stack.removeLast(); _statementToStackIndex[whileStatement] = _stack.length; _stack.add(null); // break _stack.add(null); // continue _current = trueCondition; } void whileStatement_conditionBegin(Iterable<Variable> loopAssigned) { _current = _current.removePromotedAll(loopAssigned); } void whileStatement_end() { _stack.removeLast(); // continue FlowModel<Variable, Type> breakState = _stack.removeLast(); FlowModel<Variable, Type> falseCondition = _stack.removeLast(); _current = _join(falseCondition, breakState); } /// Register write of the given [variable] in the current state. void write(Variable variable) { _current = _current.write(variable); } void _conditionalEnd(Expression condition) { condition = nodeOperations.unwrapParenthesized(condition); if (identical(condition, _condition)) { _stack.add(_conditionFalse); _stack.add(_conditionTrue); } else { _stack.add(_current); _stack.add(_current); } } FlowModel<Variable, Type> _join( FlowModel<Variable, Type> first, FlowModel<Variable, Type> second) => FlowModel.join(typeOperations, first, second); } /// An instance of the [FlowModel] class represents the information gathered by /// flow analysis at a single point in the control flow of the function or /// method being analyzed. /// /// Instances of this class are immutable, so the methods below that "update" /// the state actually leave `this` unchanged and return a new state object. @visibleForTesting class FlowModel<Variable, Type> { /// Indicates whether this point in the control flow is reachable. final bool reachable; /// For each variable being tracked by flow analysis, the variable's model. /// /// Flow analysis has no awareness of scope, so variables that are out of /// scope are retained in the map until such time as their declaration no /// longer dominates the control flow. So, for example, if a variable is /// declared inside the `then` branch of an `if` statement, and the `else` /// branch of the `if` statement ends in a `return` statement, then the /// variable remains in the map after the `if` statement ends, even though the /// variable is not in scope anymore. This should not have any effect on /// analysis results for error-free code, because it is an error to refer to a /// variable that is no longer in scope. final Map<Variable, VariableModel<Type> /*!*/ > variableInfo; /// Variable model for variables that have never been seen before. final VariableModel<Type> _freshVariableInfo; /// Creates a state object with the given [reachable] status. All variables /// are assumed to be unpromoted and already assigned, so joining another /// state with this one will have no effect on it. FlowModel(bool reachable) : this._( reachable, const {}, ); FlowModel._(this.reachable, this.variableInfo) : _freshVariableInfo = new VariableModel.fresh() { assert(() { for (VariableModel<Type> value in variableInfo.values) { assert(value != null); } return true; }()); } /// Gets the info for the given [variable], creating it if it doesn't exist. VariableModel<Type> infoFor(Variable variable) => variableInfo[variable] ?? _freshVariableInfo; /// Updates the state to indicate that the given [variable] has been /// determined to contain a non-null value. /// /// TODO(paulberry): should this method mark the variable as definitely /// assigned? Does it matter? FlowModel<Variable, Type> markNonNullable( TypeOperations<Variable, Type> typeOperations, Variable variable) { VariableModel<Type> info = infoFor(variable); Type previousType = info.promotedType; previousType ??= typeOperations.variableType(variable); Type type = typeOperations.promoteToNonNull(previousType); if (typeOperations.isSameType(type, previousType)) return this; return _updateVariableInfo(variable, info.withPromotedType(type)); } /// Updates the state to indicate that the given [variable] has been /// determined to satisfy the given [type], e.g. as a consequence of an `is` /// expression as the condition of an `if` statement. /// /// Note that the state is only changed if [type] is a subtype of the /// variable's previous (possibly promoted) type. /// /// TODO(paulberry): if the type is non-nullable, should this method mark the /// variable as definitely assigned? Does it matter? FlowModel<Variable, Type> promote( TypeOperations<Variable, Type> typeOperations, Variable variable, Type type, ) { VariableModel<Type> info = infoFor(variable); Type previousType = info.promotedType; previousType ??= typeOperations.variableType(variable); if (!typeOperations.isSubtypeOf(type, previousType) || typeOperations.isSameType(type, previousType)) { return this; } return _updateVariableInfo(variable, info.withPromotedType(type)); } /// Updates the state to indicate that the given [variables] are no longer /// promoted; they are presumed to have their declared types. /// /// This is used at the top of loops to conservatively cancel the promotion of /// variables that are modified within the loop, so that we correctly analyze /// code like the following: /// /// if (x is int) { /// x.isEven; // OK, promoted to int /// while (true) { /// x.isEven; // ERROR: promotion lost /// x = 'foo'; /// } /// } /// /// Note that a more accurate analysis would be to iterate to a fixed point, /// and only remove promotions if it can be shown that they aren't restored /// later in the loop body. If we switch to a fixed point analysis, we should /// be able to remove this method. FlowModel<Variable, Type> removePromotedAll(Iterable<Variable> variables) { Map<Variable, VariableModel<Type>> newVariableInfo; for (Variable variable in variables) { VariableModel<Type> info = infoFor(variable); if (info.promotedType != null) { (newVariableInfo ??= new Map<Variable, VariableModel<Type>>.from( variableInfo))[variable] = info.withPromotedType(null); } } if (newVariableInfo == null) return this; return new FlowModel<Variable, Type>._(reachable, newVariableInfo); } /// Updates the state to reflect a control path that is known to have /// previously passed through some [other] state. /// /// Approximately, this method forms the union of the definite assignments and /// promotions in `this` state and the [other] state. More precisely: /// /// The control flow path is considered reachable if both this state and the /// other state are reachable. Variables are considered definitely assigned /// if they were definitely assigned in either this state or the other state. /// Variable type promotions are taken from this state, unless the promotion /// in the other state is more specific, and the variable is "safe". A /// variable is considered safe if there is no chance that it was assigned /// more recently than the "other" state. /// /// This is used after a `try/finally` statement to combine the promotions and /// definite assignments that occurred in the `try` and `finally` blocks /// (where `this` is the state from the `finally` block and `other` is the /// state from the `try` block). Variables that are assigned in the `finally` /// block are considered "unsafe" because the assignment might have cancelled /// the effect of any promotion that occurred inside the `try` block. FlowModel<Variable, Type> restrict( TypeOperations<Variable, Type> typeOperations, FlowModel<Variable, Type> other, Set<Variable> unsafe) { bool newReachable = reachable && other.reachable; Map<Variable, VariableModel<Type>> newVariableInfo = <Variable, VariableModel<Type>>{}; bool variableInfoMatchesThis = true; bool variableInfoMatchesOther = true; for (MapEntry<Variable, VariableModel<Type>> entry in variableInfo.entries) { Variable variable = entry.key; VariableModel<Type> thisModel = entry.value; VariableModel<Type> otherModel = other.infoFor(variable); VariableModel<Type> restricted = thisModel.restrict( typeOperations, otherModel, unsafe.contains(variable)); if (!identical(restricted, _freshVariableInfo)) { newVariableInfo[variable] = restricted; } if (!identical(restricted, thisModel)) variableInfoMatchesThis = false; if (!identical(restricted, otherModel)) variableInfoMatchesOther = false; } for (MapEntry<Variable, VariableModel<Type>> entry in other.variableInfo.entries) { Variable variable = entry.key; if (variableInfo.containsKey(variable)) continue; VariableModel<Type> thisModel = _freshVariableInfo; VariableModel<Type> otherModel = entry.value; VariableModel<Type> restricted = thisModel.restrict( typeOperations, otherModel, unsafe.contains(variable)); if (!identical(restricted, _freshVariableInfo)) { newVariableInfo[variable] = restricted; } if (!identical(restricted, thisModel)) variableInfoMatchesThis = false; if (!identical(restricted, otherModel)) variableInfoMatchesOther = false; } assert(variableInfoMatchesThis == _variableInfosEqual(newVariableInfo, variableInfo)); assert(variableInfoMatchesOther == _variableInfosEqual(newVariableInfo, other.variableInfo)); if (variableInfoMatchesThis) { newVariableInfo = variableInfo; } else if (variableInfoMatchesOther) { newVariableInfo = other.variableInfo; } return _identicalOrNew(this, other, newReachable, newVariableInfo); } /// Updates the state to indicate whether the control flow path is /// [reachable]. FlowModel<Variable, Type> setReachable(bool reachable) { if (this.reachable == reachable) return this; return new FlowModel<Variable, Type>._(reachable, variableInfo); } @override String toString() => '($reachable, $variableInfo)'; /// Updates the state to indicate that an assignment was made to the given /// [variable]. The variable is marked as definitely assigned, and any /// previous type promotion is removed. /// /// TODO(paulberry): allow for writes that preserve type promotions. FlowModel<Variable, Type> write(Variable variable) { VariableModel<Type> infoForVar = infoFor(variable); VariableModel<Type> newInfoForVar = infoForVar.write(); if (identical(newInfoForVar, infoForVar)) return this; return _updateVariableInfo(variable, newInfoForVar); } /// Returns a new [FlowModel] where the information for [variable] is replaced /// with [model]. FlowModel<Variable, Type> _updateVariableInfo( Variable variable, VariableModel<Type> model) { Map<Variable, VariableModel<Type>> newVariableInfo = new Map<Variable, VariableModel<Type>>.from(variableInfo); newVariableInfo[variable] = model; return new FlowModel<Variable, Type>._(reachable, newVariableInfo); } /// Forms a new state to reflect a control flow path that might have come from /// either `this` or the [other] state. /// /// The control flow path is considered reachable if either of the input /// states is reachable. Variables are considered definitely assigned if they /// were definitely assigned in both of the input states. Variable promotions /// are kept only if they are common to both input states; if a variable is /// promoted to one type in one state and a subtype in the other state, the /// less specific type promotion is kept. static FlowModel<Variable, Type> join<Variable, Type>( TypeOperations<Variable, Type> typeOperations, FlowModel<Variable, Type> first, FlowModel<Variable, Type> second, ) { if (first == null) return second; if (second == null) return first; if (first.reachable && !second.reachable) return first; if (!first.reachable && second.reachable) return second; bool newReachable = first.reachable || second.reachable; Map<Variable, VariableModel<Type>> newVariableInfo = FlowModel.joinVariableInfo( typeOperations, first.variableInfo, second.variableInfo); return FlowModel._identicalOrNew( first, second, newReachable, newVariableInfo); } /// Joins two "variable info" maps. See [join] for details. @visibleForTesting static Map<Variable, VariableModel<Type>> joinVariableInfo<Variable, Type>( TypeOperations<Variable, Type> typeOperations, Map<Variable, VariableModel<Type>> first, Map<Variable, VariableModel<Type>> second, ) { if (identical(first, second)) return first; if (first.isEmpty || second.isEmpty) return const {}; Map<Variable, VariableModel<Type>> result = <Variable, VariableModel<Type>>{}; bool alwaysFirst = true; bool alwaysSecond = true; for (MapEntry<Variable, VariableModel<Type>> entry in first.entries) { Variable variable = entry.key; VariableModel<Type> secondModel = second[variable]; if (secondModel == null) { alwaysFirst = false; } else { VariableModel<Type> joined = VariableModel.join<Type>(typeOperations, entry.value, secondModel); result[variable] = joined; if (!identical(joined, entry.value)) alwaysFirst = false; if (!identical(joined, secondModel)) alwaysSecond = false; } } if (alwaysFirst) return first; if (alwaysSecond && result.length == second.length) return second; if (result.isEmpty) return const {}; return result; } /// Creates a new [FlowModel] object, unless it is equivalent to either /// [first] or [second], in which case one of those objects is re-used. static FlowModel<Variable, Type> _identicalOrNew<Variable, Type>( FlowModel<Variable, Type> first, FlowModel<Variable, Type> second, bool newReachable, Map<Variable, VariableModel<Type>> newVariableInfo) { if (first.reachable == newReachable && identical(first.variableInfo, newVariableInfo)) { return first; } if (second.reachable == newReachable && identical(second.variableInfo, newVariableInfo)) { return second; } return new FlowModel<Variable, Type>._(newReachable, newVariableInfo); } /// Determines whether the given "variableInfo" maps are equivalent. /// /// The equivalence check is shallow; if two variables' models are not /// identical, we return `false`. static bool _variableInfosEqual<Variable, Type>( Map<Variable, VariableModel<Type>> p1, Map<Variable, VariableModel<Type>> p2) { if (p1.length != p2.length) return false; if (!p1.keys.toSet().containsAll(p2.keys)) return false; for (MapEntry<Variable, VariableModel<Type>> entry in p1.entries) { VariableModel<Type> p1Value = entry.value; VariableModel<Type> p2Value = p2[entry.key]; if (!identical(p1Value, p2Value)) { return false; } } return true; } } /// Accessor for function body information. abstract class FunctionBodyAccess<Variable> { bool isPotentiallyMutatedInClosure(Variable variable); bool isPotentiallyMutatedInScope(Variable variable); } /// Operations on nodes, abstracted from concrete node interfaces. abstract class NodeOperations<Expression> { /// If the [node] is a parenthesized expression, recursively unwrap it. Expression unwrapParenthesized(Expression node); } /// Operations on types, abstracted from concrete type interfaces. abstract class TypeOperations<Variable, Type> { /// Returns `true` if [type1] and [type2] are the same type. bool isSameType(Type type1, Type type2); /// Return `true` if the [leftType] is a subtype of the [rightType]. bool isSubtypeOf(Type leftType, Type rightType); /// Returns the non-null promoted version of [type]. /// /// Note that some types don't have a non-nullable version (e.g. /// `FutureOr<int?>`), so [type] may be returned even if it is nullable. Type /*!*/ promoteToNonNull(Type type); /// Return the static type of the given [variable]. Type variableType(Variable variable); } /// An instance of the [VariableModel] class represents the information gathered /// by flow analysis for a single variable at a single point in the control flow /// of the function or method being analyzed. /// /// Instances of this class are immutable, so the methods below that "update" /// the state actually leave `this` unchanged and return a new state object. @visibleForTesting class VariableModel<Type> { /// The type that the variable has been promoted to, or `null` if the variable /// is not promoted. final Type promotedType; /// Indicates whether the variable has definitely been assigned. final bool assigned; VariableModel(this.promotedType, this.assigned); /// Creates a [VariableModel] representing a variable that's never been seen /// before. VariableModel.fresh() : promotedType = null, assigned = false; @override bool operator ==(Object other) { return other is VariableModel<Type> && this.promotedType == other.promotedType && this.assigned == other.assigned; } /// Returns an updated model reflect a control path that is known to have /// previously passed through some [other] state. See [FlowModel.restrict] /// for details. VariableModel<Type> restrict(TypeOperations<Object, Type> typeOperations, VariableModel<Type> otherModel, bool unsafe) { Type thisType = promotedType; Type otherType = otherModel?.promotedType; bool newAssigned = assigned || otherModel.assigned; if (!unsafe) { if (otherType != null && (thisType == null || typeOperations.isSubtypeOf(otherType, thisType))) { return _identicalOrNew(this, otherModel, otherType, newAssigned); } } return _identicalOrNew(this, otherModel, thisType, newAssigned); } @override String toString() => 'VariableModel($promotedType, $assigned)'; /// Returns a new [VariableModel] where the promoted type is replaced with /// [promotedType]. VariableModel<Type> withPromotedType(Type promotedType) => new VariableModel<Type>(promotedType, assigned); /// Returns a new [VariableModel] reflecting the fact that the variable was /// just written to. VariableModel<Type> write() { if (promotedType == null && assigned) return this; return new VariableModel<Type>(null, true); } /// Joins two variable models. See [FlowModel.join] for details. static VariableModel<Type> join<Type>( TypeOperations<Object, Type> typeOperations, VariableModel<Type> first, VariableModel<Type> second) { Type firstType = first.promotedType; Type secondType = second.promotedType; Type newPromotedType; if (identical(firstType, secondType)) { newPromotedType = firstType; } else if (firstType == null || secondType == null) { newPromotedType = null; } else if (typeOperations.isSubtypeOf(firstType, secondType)) { newPromotedType = secondType; } else if (typeOperations.isSubtypeOf(secondType, firstType)) { newPromotedType = firstType; } else { newPromotedType = null; } bool newAssigned = first.assigned && second.assigned; return _identicalOrNew(first, second, newPromotedType, newAssigned); } /// Creates a new [VariableModel] object, unless it is equivalent to either /// [first] or [second], in which case one of those objects is re-used. static VariableModel<Type> _identicalOrNew<Type>(VariableModel<Type> first, VariableModel<Type> second, Type newPromotedType, bool newAssigned) { if (identical(first.promotedType, newPromotedType) && first.assigned == newAssigned) { return first; } else if (identical(second.promotedType, newPromotedType) && second.assigned == newAssigned) { return second; } else { return new VariableModel<Type>(newPromotedType, newAssigned); } } }
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/source/outline_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.outline_builder; import 'package:kernel/ast.dart' show ProcedureKind, Variance; import '../builder/builder.dart'; import '../combinator.dart' show Combinator; import '../configuration.dart' show Configuration; import '../fasta_codes.dart' show Code, LocatedMessage, Message, messageConstConstructorWithBody, messageConstInstanceField, messageConstructorWithReturnType, messageConstructorWithTypeParameters, messageExpectedBlockToSkip, messageInterpolationInUri, messageOperatorWithOptionalFormals, messageTypedefNotFunction, Template, templateCycleInTypeVariables, templateDirectCycleInTypeVariables, templateDuplicatedParameterName, templateDuplicatedParameterNameCause, templateOperatorMinusParameterMismatch, templateOperatorParameterMismatch0, templateOperatorParameterMismatch1, templateOperatorParameterMismatch2; import '../ignored_parser_errors.dart' show isIgnoredParserError; // TODO(ahe): The outline isn't supposed to import kernel-specific builders. import '../kernel/kernel_builder.dart' show MetadataBuilder, MixinApplicationBuilder, NamedTypeBuilder, TypeBuilder; import '../kernel/type_algorithms.dart'; import '../modifier.dart' show Const, Covariant, External, Final, Modifier, Static, Var, abstractMask, constMask, covariantMask, externalMask, finalMask, lateMask, mixinDeclarationMask, requiredMask, staticMask; import '../operator.dart' show Operator, operatorFromString, operatorToString, operatorRequiredArgumentCount; import '../parser.dart' show Assert, DeclarationKind, FormalParameterKind, IdentifierContext, lengthOfSpan, MemberKind, offsetForToken, optional; import '../problems.dart' show unhandled; import '../quote.dart' show unescapeString; import '../scanner.dart' show Token; import 'source_library_builder.dart' show TypeParameterScopeBuilder, TypeParameterScopeKind, FieldInfo, SourceLibraryBuilder; import 'stack_listener.dart' show FixedNullableList, NullValue, ParserRecovery, StackListener; import 'value_kinds.dart'; enum MethodBody { Abstract, Regular, RedirectingFactoryBody, } class OutlineBuilder extends StackListener { final SourceLibraryBuilder library; final bool enableNative; final bool stringExpectedAfterNative; bool inConstructor = false; bool inConstructorName = false; int importIndex = 0; String nativeMethodName; /// Counter used for naming unnamed extension declarations. int unnamedExtensionCounter = 0; OutlineBuilder(SourceLibraryBuilder library) : library = library, enableNative = library.loader.target.backendTarget.enableNative(library.uri), stringExpectedAfterNative = library.loader.target.backendTarget.nativeExtensionExpectsString; @override Uri get uri => library.fileUri; int popCharOffset() => pop(); List<String> popIdentifierList(int count) { if (count == 0) return null; List<String> list = new List<String>(count); bool isParserRecovery = false; for (int i = count - 1; i >= 0; i--) { popCharOffset(); Object identifier = pop(); if (identifier is ParserRecovery) { isParserRecovery = true; } else { list[i] = identifier; } } return isParserRecovery ? null : list; } @override void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) { debugEvent("Metadata"); pop(); // arguments if (periodBeforeName != null) { pop(); // offset pop(); // constructor name } pop(); // type arguments pop(); // offset Object sentinel = pop(); // prefix or constructor push(sentinel is ParserRecovery ? sentinel : new MetadataBuilder(beginToken)); } @override void endMetadataStar(int count) { debugEvent("MetadataStar"); push(const FixedNullableList<MetadataBuilder>().pop(stack, count) ?? NullValue.Metadata); } @override void handleInvalidTopLevelDeclaration(Token endToken) { debugEvent("InvalidTopLevelDeclaration"); pop(); // metadata star } @override void endHide(Token hideKeyword) { debugEvent("Hide"); Object names = pop(); if (names is ParserRecovery) { push(names); } else { push(new Combinator.hide(names, hideKeyword.charOffset, library.fileUri)); } } @override void endShow(Token showKeyword) { debugEvent("Show"); Object names = pop(); if (names is ParserRecovery) { push(names); } else { push(new Combinator.show(names, showKeyword.charOffset, library.fileUri)); } } @override void endCombinators(int count) { debugEvent("Combinators"); push(const FixedNullableList<Combinator>().pop(stack, count) ?? NullValue.Combinators); } @override void endExport(Token exportKeyword, Token semicolon) { debugEvent("Export"); List<Combinator> combinators = pop(); List<Configuration> configurations = pop(); int uriOffset = popCharOffset(); String uri = pop(); List<MetadataBuilder> metadata = pop(); library.addExport(metadata, uri, configurations, combinators, exportKeyword.charOffset, uriOffset); checkEmpty(exportKeyword.charOffset); } @override void handleImportPrefix(Token deferredKeyword, Token asKeyword) { debugEvent("ImportPrefix"); if (asKeyword == null) { // If asKeyword is null, then no prefix has been pushed on the stack. // Push a placeholder indicating that there is no prefix. push(NullValue.Prefix); push(-1); } push(deferredKeyword != null); } @override void endImport(Token importKeyword, Token semicolon) { debugEvent("EndImport"); List<Combinator> combinators = pop(); bool isDeferred = pop(); int prefixOffset = pop(); Object prefix = pop(NullValue.Prefix); List<Configuration> configurations = pop(); int uriOffset = popCharOffset(); String uri = pop(); // For a conditional import, this is the default URI. List<MetadataBuilder> metadata = pop(); checkEmpty(importKeyword.charOffset); if (prefix is ParserRecovery) return; library.addImport( metadata, uri, configurations, prefix, combinators, isDeferred, importKeyword.charOffset, prefixOffset, uriOffset, importIndex++); } @override void endConditionalUris(int count) { debugEvent("EndConditionalUris"); push(const FixedNullableList<Configuration>().pop(stack, count) ?? NullValue.ConditionalUris); } @override void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) { debugEvent("EndConditionalUri"); int charOffset = popCharOffset(); String uri = pop(); if (equalSign != null) popCharOffset(); String condition = popIfNotNull(equalSign) ?? "true"; Object dottedName = pop(); if (dottedName is ParserRecovery) { push(dottedName); } else { push(new Configuration(charOffset, dottedName, condition, uri)); } } @override void handleDottedName(int count, Token firstIdentifier) { debugEvent("DottedName"); List<String> names = popIdentifierList(count); if (names == null) { push(new ParserRecovery(firstIdentifier.charOffset)); } else { push(names.join('.')); } } @override void handleRecoverImport(Token semicolon) { debugEvent("RecoverImport"); pop(); // combinators pop(NullValue.Deferred); // deferredKeyword pop(); // prefixOffset pop(NullValue.Prefix); // prefix pop(); // conditionalUris } @override void endPart(Token partKeyword, Token semicolon) { debugEvent("Part"); int charOffset = popCharOffset(); String uri = pop(); List<MetadataBuilder> metadata = pop(); library.addPart(metadata, uri, charOffset); checkEmpty(partKeyword.charOffset); } @override void handleOperatorName(Token operatorKeyword, Token token) { debugEvent("OperatorName"); push(operatorFromString(token.stringValue)); push(token.charOffset); } @override void handleInvalidOperatorName(Token operatorKeyword, Token token) { debugEvent("InvalidOperatorName"); push('invalid'); push(token.charOffset); } @override void handleIdentifier(Token token, IdentifierContext context) { if (context == IdentifierContext.enumValueDeclaration) { debugEvent("handleIdentifier"); List<MetadataBuilder> metadata = pop(); if (token.isSynthetic) { push(new ParserRecovery(token.charOffset)); } else { push(new EnumConstantInfo(metadata, token.lexeme, token.charOffset, getDocumentationComment(token))); } } else { super.handleIdentifier(token, context); push(token.charOffset); } if (inConstructor && context == IdentifierContext.methodDeclaration) { inConstructorName = true; } } @override void handleNoName(Token token) { super.handleNoName(token); push(token.charOffset); } @override void handleStringPart(Token token) { debugEvent("StringPart"); // Ignore string parts - report error later. } @override void endLiteralString(int interpolationCount, Token endToken) { debugEvent("endLiteralString"); if (interpolationCount == 0) { Token token = pop(); push(unescapeString(token.lexeme, token, this)); push(token.charOffset); } else { Token beginToken = pop(); int charOffset = beginToken.charOffset; push("${SourceLibraryBuilder.MALFORMED_URI_SCHEME}:bad${charOffset}"); push(charOffset); // Point to dollar sign int interpolationOffset = charOffset + beginToken.lexeme.length; addProblem(messageInterpolationInUri, interpolationOffset, 1); } } @override void handleNativeClause(Token nativeToken, bool hasName) { debugEvent("NativeClause"); if (hasName) { // Pop the native clause which in this case is a StringLiteral. pop(); // Char offset. Object name = pop(); if (name is ParserRecovery) { nativeMethodName = ''; } else { nativeMethodName = name; // String. } } else { nativeMethodName = ''; } } @override void handleStringJuxtaposition(int literalCount) { debugEvent("StringJuxtaposition"); List<String> list = new List<String>(literalCount); int charOffset = -1; for (int i = literalCount - 1; i >= 0; i--) { charOffset = pop(); list[i] = pop(); } push(list.join("")); push(charOffset); } @override void handleIdentifierList(int count) { debugEvent("endIdentifierList"); push(popIdentifierList(count) ?? (count == 0 ? NullValue.IdentifierList : new ParserRecovery(-1))); } @override void handleQualified(Token period) { assert(checkState(period, [ /*suffix offset*/ ValueKind.Integer, /*suffix*/ ValueKind.NameOrParserRecovery, /*prefix offset*/ ValueKind.Integer, /*prefix*/ unionOfKinds( [ValueKind.Name, ValueKind.ParserRecovery, ValueKind.QualifiedName]), ])); debugEvent("handleQualified"); int suffixOffset = pop(); Object suffix = pop(); int offset = pop(); Object prefix = pop(); if (prefix is ParserRecovery) { push(prefix); } else if (suffix is ParserRecovery) { push(suffix); } else { assert(identical(suffix, period.next.lexeme)); assert(suffixOffset == period.next.charOffset); push(new QualifiedName(prefix, period.next)); } push(offset); } @override void endLibraryName(Token libraryKeyword, Token semicolon) { debugEvent("endLibraryName"); popCharOffset(); String documentationComment = getDocumentationComment(libraryKeyword); Object name = pop(); List<MetadataBuilder> metadata = pop(); library.documentationComment = documentationComment; if (name is! ParserRecovery) { library.name = flattenName(name, offsetForToken(libraryKeyword), uri); } library.metadata = metadata; } @override void beginClassOrNamedMixinApplicationPrelude(Token token) { debugEvent("beginClassOrNamedMixinApplication"); library.beginNestedDeclaration( TypeParameterScopeKind.classOrNamedMixinApplication, "class or mixin application"); } @override void beginClassDeclaration(Token begin, Token abstractToken, Token name) { debugEvent("beginClassDeclaration"); List<TypeVariableBuilder> typeVariables = pop(); push(typeVariables ?? NullValue.TypeVariables); library.currentTypeParameterScopeBuilder .markAsClassDeclaration(name.lexeme, name.charOffset, typeVariables); push(abstractToken != null ? abstractMask : 0); } @override void beginMixinDeclaration(Token mixinKeyword, Token name) { debugEvent("beginMixinDeclaration"); List<TypeVariableBuilder> typeVariables = pop(); push(typeVariables ?? NullValue.TypeVariables); library.currentTypeParameterScopeBuilder .markAsMixinDeclaration(name.lexeme, name.charOffset, typeVariables); } @override void beginClassOrMixinBody(DeclarationKind kind, Token token) { if (kind == DeclarationKind.Extension) { assert(checkState(token, [ unionOfKinds([ValueKind.ParserRecovery, ValueKind.TypeBuilder]) ])); Object extensionThisType = peek(); if (extensionThisType is TypeBuilder) { library.currentTypeParameterScopeBuilder .registerExtensionThisType(extensionThisType); } else { // TODO(johnniwinther): Supply an invalid type as the extension on type. } } debugEvent("beginClassOrMixinBody"); // Resolve unresolved types from the class header (i.e., superclass, mixins, // and implemented types) before adding members from the class body which // should not shadow these unresolved types. library.currentTypeParameterScopeBuilder.resolveTypes( library.currentTypeParameterScopeBuilder.typeVariables, library); } @override void beginNamedMixinApplication( Token begin, Token abstractToken, Token name) { debugEvent("beginNamedMixinApplication"); List<TypeVariableBuilder> typeVariables = pop(); push(typeVariables ?? NullValue.TypeVariables); library.currentTypeParameterScopeBuilder.markAsNamedMixinApplication( name.lexeme, name.charOffset, typeVariables); push(abstractToken != null ? abstractMask : 0); } @override void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { debugEvent("ClassOrMixinImplements"); push(const FixedNullableList<NamedTypeBuilder>() .pop(stack, interfacesCount) ?? NullValue.TypeBuilderList); } @override void handleRecoverClassHeader() { debugEvent("handleRecoverClassHeader"); pop(NullValue.TypeBuilderList); // Interfaces. pop(); // Supertype offset. pop(); // Supertype. } @override void handleRecoverMixinHeader() { debugEvent("handleRecoverMixinHeader"); pop(NullValue.TypeBuilderList); // Interfaces. pop(NullValue.TypeBuilderList); // Supertype constraints. } @override void handleClassExtends(Token extendsKeyword) { debugEvent("handleClassExtends"); push(extendsKeyword?.charOffset ?? -1); } @override void handleMixinOn(Token onKeyword, int typeCount) { debugEvent("handleMixinOn"); push(const FixedNullableList<NamedTypeBuilder>().pop(stack, typeCount) ?? new ParserRecovery(offsetForToken(onKeyword))); } @override void endClassDeclaration(Token beginToken, Token endToken) { debugEvent("endClassDeclaration"); String documentationComment = getDocumentationComment(beginToken); List<TypeBuilder> interfaces = pop(NullValue.TypeBuilderList); int supertypeOffset = pop(); TypeBuilder supertype = nullIfParserRecovery(pop()); int modifiers = pop(); List<TypeVariableBuilder> typeVariables = pop(); int nameOffset = pop(); Object name = pop(); if (typeVariables != null && supertype is MixinApplicationBuilder) { supertype.typeVariables = typeVariables; } List<MetadataBuilder> metadata = pop(); checkEmpty(beginToken.charOffset); if (name is ParserRecovery) { library.endNestedDeclaration( TypeParameterScopeKind.classDeclaration, "<syntax-error>"); return; } final int startCharOffset = metadata == null ? beginToken.charOffset : metadata.first.charOffset; library.addClass( documentationComment, metadata, modifiers, name, typeVariables, supertype, interfaces, startCharOffset, nameOffset, endToken.charOffset, supertypeOffset); } Object nullIfParserRecovery(Object node) { return node is ParserRecovery ? null : node; } @override void endMixinDeclaration(Token mixinToken, Token endToken) { debugEvent("endMixinDeclaration"); String documentationComment = getDocumentationComment(mixinToken); List<TypeBuilder> interfaces = pop(NullValue.TypeBuilderList); List<TypeBuilder> supertypeConstraints = nullIfParserRecovery(pop()); List<TypeVariableBuilder> typeVariables = pop(NullValue.TypeVariables); int nameOffset = pop(); Object name = pop(); List<MetadataBuilder> metadata = pop(NullValue.Metadata); checkEmpty(mixinToken.charOffset); if (name is ParserRecovery) { library.endNestedDeclaration( TypeParameterScopeKind.mixinDeclaration, "<syntax-error>"); return; } int startOffset = metadata == null ? mixinToken.charOffset : metadata.first.charOffset; TypeBuilder supertype; if (supertypeConstraints != null && supertypeConstraints.isNotEmpty) { if (supertypeConstraints.length == 1) { supertype = supertypeConstraints.first; } else { supertype = new MixinApplicationBuilder( supertypeConstraints.first, supertypeConstraints.skip(1).toList()); } } library.addMixinDeclaration( documentationComment, metadata, mixinDeclarationMask, name, typeVariables, supertype, interfaces, startOffset, nameOffset, endToken.charOffset, -1); } @override void beginExtensionDeclarationPrelude(Token extensionKeyword) { assert(checkState(extensionKeyword, [ValueKind.MetadataListOrNull])); debugEvent("beginExtensionDeclaration"); library.beginNestedDeclaration( TypeParameterScopeKind.extensionDeclaration, "extension"); } @override void beginExtensionDeclaration(Token extensionKeyword, Token nameToken) { assert(checkState(extensionKeyword, [ValueKind.TypeVariableListOrNull, ValueKind.MetadataListOrNull])); debugEvent("beginExtensionDeclaration"); List<TypeVariableBuilder> typeVariables = pop(); int offset = nameToken?.charOffset ?? extensionKeyword.charOffset; String name = nameToken?.lexeme ?? // Synthesized name used internally. '_extension#${unnamedExtensionCounter++}'; push(name); push(offset); push(typeVariables ?? NullValue.TypeVariables); library.currentTypeParameterScopeBuilder .markAsExtensionDeclaration(name, offset, typeVariables); } @override void endExtensionDeclaration( Token extensionKeyword, Token onKeyword, Token endToken) { assert(checkState(extensionKeyword, [ unionOfKinds([ValueKind.ParserRecovery, ValueKind.TypeBuilder]), ValueKind.TypeVariableListOrNull, ValueKind.Integer, ValueKind.NameOrNull, ValueKind.MetadataListOrNull ])); debugEvent("endExtensionDeclaration"); String documentationComment = getDocumentationComment(extensionKeyword); TypeBuilder supertype = pop(); List<TypeVariableBuilder> typeVariables = pop(NullValue.TypeVariables); int nameOffset = pop(); String name = pop(NullValue.Name); if (name == null) { nameOffset = extensionKeyword.charOffset; name = '$nameOffset'; } List<MetadataBuilder> metadata = pop(NullValue.Metadata); checkEmpty(extensionKeyword.charOffset); int startOffset = metadata == null ? extensionKeyword.charOffset : metadata.first.charOffset; library.addExtensionDeclaration( documentationComment, metadata, // TODO(johnniwinther): Support modifiers on extensions? 0, name, typeVariables, supertype, startOffset, nameOffset, endToken.charOffset); } ProcedureKind computeProcedureKind(Token token) { if (token == null) return ProcedureKind.Method; if (optional("get", token)) return ProcedureKind.Getter; if (optional("set", token)) return ProcedureKind.Setter; return unhandled( token.lexeme, "computeProcedureKind", token.charOffset, uri); } @override void beginTopLevelMethod(Token lastConsumed, Token externalToken) { library.beginNestedDeclaration( TypeParameterScopeKind.topLevelMethod, "#method", hasMembers: false); push(externalToken != null ? externalMask : 0); } @override void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) { debugEvent("endTopLevelMethod"); MethodBody kind = pop(); List<FormalParameterBuilder> formals = pop(); int formalsOffset = pop(); List<TypeVariableBuilder> typeVariables = pop(); int charOffset = pop(); Object name = pop(); TypeBuilder returnType = pop(); bool isAbstract = kind == MethodBody.Abstract; if (getOrSet != null && optional("set", getOrSet)) { if (formals == null || formals.length != 1) { // This isn't abstract as we'll add an error-recovery node in // [BodyBuilder.finishFunction]. isAbstract = false; } } int modifiers = pop(); if (isAbstract) { modifiers |= abstractMask; } if (nativeMethodName != null) { modifiers |= externalMask; } List<MetadataBuilder> metadata = pop(); checkEmpty(beginToken.charOffset); library .endNestedDeclaration(TypeParameterScopeKind.topLevelMethod, "#method") .resolveTypes(typeVariables, library); if (name is ParserRecovery) return; final int startCharOffset = metadata == null ? beginToken.charOffset : metadata.first.charOffset; String documentationComment = getDocumentationComment(beginToken); library.addProcedure( documentationComment, metadata, modifiers, returnType, name, typeVariables, formals, computeProcedureKind(getOrSet), startCharOffset, charOffset, formalsOffset, endToken.charOffset, nativeMethodName, isTopLevel: true); nativeMethodName = null; } @override void handleNativeFunctionBody(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBody"); if (nativeMethodName != null) { push(MethodBody.Regular); } else { push(MethodBody.Abstract); } } @override void handleNativeFunctionBodyIgnored(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBodyIgnored"); } @override void handleNativeFunctionBodySkipped(Token nativeToken, Token semicolon) { if (!enableNative) { super.handleRecoverableError( messageExpectedBlockToSkip, nativeToken, nativeToken); } push(MethodBody.Regular); } @override void handleNoFunctionBody(Token token) { debugEvent("NoFunctionBody"); if (nativeMethodName != null) { push(MethodBody.Regular); } else { push(MethodBody.Abstract); } } @override void handleFunctionBodySkipped(Token token, bool isExpressionBody) { debugEvent("handleFunctionBodySkipped"); push(MethodBody.Regular); } @override void beginMethod(Token externalToken, Token staticToken, Token covariantToken, Token varFinalOrConst, Token getOrSet, Token name) { inConstructor = name?.lexeme == library.currentTypeParameterScopeBuilder.name && getOrSet == null; List<Modifier> modifiers; if (externalToken != null) { modifiers ??= <Modifier>[]; modifiers.add(External); } if (staticToken != null) { if (!inConstructor) { modifiers ??= <Modifier>[]; modifiers.add(Static); } } if (covariantToken != null) { modifiers ??= <Modifier>[]; modifiers.add(Covariant); } if (varFinalOrConst != null) { String lexeme = varFinalOrConst.lexeme; if (identical('var', lexeme)) { modifiers ??= <Modifier>[]; modifiers.add(Var); } else if (identical('final', lexeme)) { modifiers ??= <Modifier>[]; modifiers.add(Final); } else { modifiers ??= <Modifier>[]; modifiers.add(Const); } } push(varFinalOrConst?.charOffset ?? -1); push(modifiers ?? NullValue.Modifiers); library.beginNestedDeclaration( TypeParameterScopeKind.staticOrInstanceMethodOrConstructor, "#method", hasMembers: false); } @override void endClassMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { assert(checkState(beginToken, [ValueKind.MethodBody])); debugEvent("Method"); MethodBody bodyKind = pop(); if (bodyKind == MethodBody.RedirectingFactoryBody) { // This will cause an error later. pop(); } assert(checkState(beginToken, [ ValueKind.FormalsOrNull, ValueKind.Integer, // formals offset ValueKind.TypeVariableListOrNull, ValueKind.Integer, // name offset unionOfKinds([ ValueKind.Name, ValueKind.QualifiedName, ValueKind.Operator, ValueKind.ParserRecovery, ]), ValueKind.TypeBuilderOrNull, ValueKind.ModifiersOrNull, ValueKind.Integer, // var/final/const offset ValueKind.MetadataListOrNull, ])); List<FormalParameterBuilder> formals = pop(); int formalsOffset = pop(); List<TypeVariableBuilder> typeVariables = pop(); int charOffset = pop(); Object nameOrOperator = pop(); if (Operator.subtract == nameOrOperator && formals == null) { nameOrOperator = Operator.unaryMinus; } Object name; ProcedureKind kind; if (nameOrOperator is Operator) { name = operatorToString(nameOrOperator); kind = ProcedureKind.Operator; int requiredArgumentCount = operatorRequiredArgumentCount(nameOrOperator); if ((formals?.length ?? 0) != requiredArgumentCount) { Template<Message Function(String name)> template; switch (requiredArgumentCount) { case 0: template = templateOperatorParameterMismatch0; break; case 1: if (Operator.subtract == nameOrOperator) { template = templateOperatorMinusParameterMismatch; } else { template = templateOperatorParameterMismatch1; } break; case 2: template = templateOperatorParameterMismatch2; break; default: unhandled("$requiredArgumentCount", "operatorRequiredArgumentCount", charOffset, uri); } String string = name; addProblem(template.withArguments(name), charOffset, string.length); } else { if (formals != null) { for (FormalParameterBuilder formal in formals) { if (!formal.isRequired) { addProblem(messageOperatorWithOptionalFormals, formal.charOffset, formal.name.length); } } } } } else { name = nameOrOperator; kind = computeProcedureKind(getOrSet); } TypeBuilder returnType = pop(); bool isAbstract = bodyKind == MethodBody.Abstract; if (getOrSet != null && optional("set", getOrSet)) { if (formals == null || formals.length != 1) { // This isn't abstract as we'll add an error-recovery node in // [BodyBuilder.finishFunction]. isAbstract = false; } } int modifiers = Modifier.validate(pop(), isAbstract: isAbstract); if (nativeMethodName != null) { modifiers |= externalMask; } if ((modifiers & externalMask) != 0) { modifiers &= ~abstractMask; } bool isConst = (modifiers & constMask) != 0; int varFinalOrConstOffset = pop(); List<MetadataBuilder> metadata = pop(); String documentationComment = getDocumentationComment(beginToken); TypeParameterScopeBuilder declarationBuilder = library.endNestedDeclaration( TypeParameterScopeKind.staticOrInstanceMethodOrConstructor, "#method"); if (name is ParserRecovery) { nativeMethodName = null; inConstructor = false; declarationBuilder.resolveTypes(typeVariables, library); return; } String constructorName = kind == ProcedureKind.Getter || kind == ProcedureKind.Setter ? null : library.computeAndValidateConstructorName(name, charOffset); if (constructorName == null && (modifiers & staticMask) == 0 && library.currentTypeParameterScopeBuilder.kind == TypeParameterScopeKind.extensionDeclaration) { TypeParameterScopeBuilder extension = library.currentTypeParameterScopeBuilder; Map<TypeVariableBuilder, TypeBuilder> substitution; if (extension.typeVariables != null) { // We synthesize the names of the generated [TypeParameter]s, i.e. // rename 'T' to '#T'. We cannot do it on the builders because their // names are used to create the scope. List<TypeVariableBuilder> synthesizedTypeVariables = library .copyTypeVariables(extension.typeVariables, declarationBuilder, isExtensionTypeParameter: true); substitution = {}; for (int i = 0; i < synthesizedTypeVariables.length; i++) { substitution[extension.typeVariables[i]] = new NamedTypeBuilder.fromTypeDeclarationBuilder( synthesizedTypeVariables[i], const NullabilityBuilder.omitted()); } if (typeVariables != null) { typeVariables = synthesizedTypeVariables..addAll(typeVariables); } else { typeVariables = synthesizedTypeVariables; } } List<FormalParameterBuilder> synthesizedFormals = []; TypeBuilder thisType = extension.extensionThisType; if (substitution != null) { List<TypeBuilder> unboundTypes = []; List<TypeVariableBuilder> unboundTypeVariables = []; thisType = substitute(thisType, substitution, unboundTypes: unboundTypes, unboundTypeVariables: unboundTypeVariables); for (TypeBuilder unboundType in unboundTypes) { extension.addType(new UnresolvedType(unboundType, -1, null)); } library.boundlessTypeVariables.addAll(unboundTypeVariables); } synthesizedFormals.add(new FormalParameterBuilder( null, finalMask, thisType, "#this", null, charOffset, uri)); if (formals != null) { synthesizedFormals.addAll(formals); } formals = synthesizedFormals; } declarationBuilder.resolveTypes(typeVariables, library); if (constructorName != null) { if (isConst && bodyKind != MethodBody.Abstract) { addProblem(messageConstConstructorWithBody, varFinalOrConstOffset, 5); modifiers &= ~constMask; } if (returnType != null) { // TODO(danrubel): Report this error on the return type handleRecoverableError( messageConstructorWithReturnType, beginToken, beginToken); returnType = null; } final int startCharOffset = metadata == null ? beginToken.charOffset : metadata.first.charOffset; library.addConstructor( documentationComment, metadata, modifiers, returnType, name, constructorName, typeVariables, formals, startCharOffset, charOffset, formalsOffset, endToken.charOffset, nativeMethodName, beginInitializers: beginInitializers); } else { if (isConst) { // TODO(danrubel): consider removing this // because it is an error to have a const method. modifiers &= ~constMask; } final int startCharOffset = metadata == null ? beginToken.charOffset : metadata.first.charOffset; library.addProcedure( documentationComment, metadata, modifiers, returnType, name, typeVariables, formals, kind, startCharOffset, charOffset, formalsOffset, endToken.charOffset, nativeMethodName, isTopLevel: false); } nativeMethodName = null; inConstructor = false; } @override void handleNamedMixinApplicationWithClause(Token withKeyword) { debugEvent("NamedMixinApplicationWithClause"); Object mixins = pop(); Object supertype = pop(); if (mixins is ParserRecovery) { push(mixins); } else if (supertype is ParserRecovery) { push(supertype); } else { push(library.addMixinApplication( supertype, mixins, withKeyword.charOffset)); } } @override void endNamedMixinApplication(Token beginToken, Token classKeyword, Token equals, Token implementsKeyword, Token endToken) { debugEvent("endNamedMixinApplication"); String documentationComment = getDocumentationComment(beginToken); List<TypeBuilder> interfaces = popIfNotNull(implementsKeyword); Object mixinApplication = pop(); int modifiers = pop(); List<TypeVariableBuilder> typeVariables = pop(); int charOffset = pop(); Object name = pop(); List<MetadataBuilder> metadata = pop(); checkEmpty(beginToken.charOffset); if (name is ParserRecovery || mixinApplication is ParserRecovery) { library.endNestedDeclaration( TypeParameterScopeKind.namedMixinApplication, "<syntax-error>"); return; } int startCharOffset = beginToken.charOffset; int charEndOffset = endToken.charOffset; library.addNamedMixinApplication( documentationComment, metadata, name, typeVariables, modifiers, mixinApplication, interfaces, startCharOffset, charOffset, charEndOffset); } @override void endTypeArguments(int count, Token beginToken, Token endToken) { debugEvent("TypeArguments"); push(const FixedNullableList<TypeBuilder>().pop(stack, count) ?? NullValue.TypeArguments); } @override void handleInvalidTypeArguments(Token token) { debugEvent("InvalidTypeArguments"); pop(NullValue.TypeArguments); } @override void handleScript(Token token) { debugEvent("Script"); } @override void handleNonNullAssertExpression(Token bang) { if (!library.loader.target.enableNonNullable) { reportNonNullAssertExpressionNotEnabled(bang); } } @override void handleType(Token beginToken, Token questionMark) { debugEvent("Type"); if (!library.loader.target.enableNonNullable) { reportErrorIfNullableType(questionMark); } bool isMarkedAsNullable = questionMark != null; List<TypeBuilder> arguments = pop(); int charOffset = pop(); Object name = pop(); if (name is ParserRecovery) { push(name); } else { push(library.addNamedType( name, library.nullableBuilderIfTrue(isMarkedAsNullable), arguments, charOffset)); } } @override void endTypeList(int count) { debugEvent("TypeList"); push(const FixedNullableList<NamedTypeBuilder>().pop(stack, count) ?? new ParserRecovery(-1)); } @override void handleNoTypeVariables(Token token) { super.handleNoTypeVariables(token); inConstructorName = false; } @override void handleVoidKeyword(Token token) { debugEvent("VoidKeyword"); push(library.addVoidType(token.charOffset)); } @override void beginFormalParameter(Token token, MemberKind kind, Token requiredToken, Token covariantToken, Token varFinalOrConst) { // TODO(danrubel): handle required token if (!library.loader.target.enableNonNullable) { reportNonNullableModifierError(requiredToken); } push((covariantToken != null ? covariantMask : 0) | (requiredToken != null ? requiredMask : 0) | Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme)); } @override void endFormalParameter( Token thisKeyword, Token periodAfterThis, Token nameToken, Token initializerStart, Token initializerEnd, FormalParameterKind kind, MemberKind memberKind) { debugEvent("FormalParameter"); int charOffset = pop(); Object name = pop(); TypeBuilder type = nullIfParserRecovery(pop()); int modifiers = pop(); List<MetadataBuilder> metadata = pop(); if (name is ParserRecovery) { push(name); } else { push(library.addFormalParameter(metadata, modifiers, type, name, thisKeyword != null, charOffset, initializerStart)); } } @override void beginFormalParameterDefaultValueExpression() { // Ignored for now. } @override void endFormalParameterDefaultValueExpression() { debugEvent("FormalParameterDefaultValueExpression"); // Ignored for now. } @override void handleValuedFormalParameter(Token equals, Token token) { debugEvent("ValuedFormalParameter"); // Ignored for now. } @override void handleFormalParameterWithoutValue(Token token) { debugEvent("FormalParameterWithoutValue"); // Ignored for now. } @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<FormalParameterBuilder> parameters = const FixedNullableList<FormalParameterBuilder>().pop(stack, count); if (parameters == null) { push(new ParserRecovery(offsetForToken(beginToken))); } else { for (FormalParameterBuilder parameter in parameters) { parameter.kind = kind; } push(parameters); } } @override void endFormalParameters( int count, Token beginToken, Token endToken, MemberKind kind) { debugEvent("FormalParameters"); List<FormalParameterBuilder> formals; if (count == 1) { Object last = pop(); if (last is List<FormalParameterBuilder>) { formals = last; } else if (last is! ParserRecovery) { assert(last != null); formals = new List<FormalParameterBuilder>(1); formals[0] = last; } } else if (count > 1) { Object last = pop(); count--; if (last is ParserRecovery) { discard(count); } else if (last is List<FormalParameterBuilder>) { formals = const FixedNullableList<FormalParameterBuilder>() .popPadded(stack, count, last.length); if (formals != null) { formals.setRange(count, formals.length, last); } } else { formals = const FixedNullableList<FormalParameterBuilder>() .popPadded(stack, count, 1); if (formals != null) { formals[count] = last; } } } if (formals != null) { assert(formals.isNotEmpty); if (formals.length == 2) { // The name may be null for generalized function types. if (formals[0].name != null && formals[0].name == formals[1].name) { addProblem( templateDuplicatedParameterName.withArguments(formals[1].name), formals[1].charOffset, formals[1].name.length, context: [ templateDuplicatedParameterNameCause .withArguments(formals[1].name) .withLocation( uri, formals[0].charOffset, formals[0].name.length) ]); } } else if (formals.length > 2) { Map<String, FormalParameterBuilder> seenNames = <String, FormalParameterBuilder>{}; for (FormalParameterBuilder formal in formals) { if (formal.name == null) continue; if (seenNames.containsKey(formal.name)) { addProblem( templateDuplicatedParameterName.withArguments(formal.name), formal.charOffset, formal.name.length, context: [ templateDuplicatedParameterNameCause .withArguments(formal.name) .withLocation(uri, seenNames[formal.name].charOffset, seenNames[formal.name].name.length) ]); } else { seenNames[formal.name] = formal; } } } } push(beginToken.charOffset); push(formals ?? NullValue.FormalParameters); } @override void handleNoFormalParameters(Token token, MemberKind kind) { push(token.charOffset); super.handleNoFormalParameters(token, kind); } @override void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis, Token commaToken, Token semicolonToken) { debugEvent("Assert"); // Do nothing } @override void endEnum(Token enumKeyword, Token leftBrace, int count) { debugEvent("Enum"); String documentationComment = getDocumentationComment(enumKeyword); List<EnumConstantInfo> enumConstantInfos = const FixedNullableList<EnumConstantInfo>().pop(stack, count); int charOffset = pop(); // identifier char offset. int startCharOffset = enumKeyword.charOffset; Object name = pop(); List<MetadataBuilder> metadata = pop(); checkEmpty(enumKeyword.charOffset); if (name is ParserRecovery) return; library.addEnum(documentationComment, metadata, name, enumConstantInfos, startCharOffset, charOffset, leftBrace?.endGroup?.charOffset); } @override void beginFunctionTypeAlias(Token token) { library.beginNestedDeclaration(TypeParameterScopeKind.typedef, "#typedef", hasMembers: false); } @override void beginFunctionType(Token beginToken) { debugEvent("beginFunctionType"); library.beginNestedDeclaration( TypeParameterScopeKind.functionType, "#function_type", hasMembers: false); } @override void beginFunctionTypedFormalParameter(Token token) { debugEvent("beginFunctionTypedFormalParameter"); library.beginNestedDeclaration( TypeParameterScopeKind.functionType, "#function_type", hasMembers: false); } @override void endFunctionType(Token functionToken, Token questionMark) { debugEvent("FunctionType"); if (!library.loader.target.enableNonNullable) { reportErrorIfNullableType(questionMark); } List<FormalParameterBuilder> formals = pop(); pop(); // formals offset TypeBuilder returnType = pop(); List<TypeVariableBuilder> typeVariables = pop(); push(library.addFunctionType( returnType, typeVariables, formals, library.nullableBuilderIfTrue(questionMark != null), functionToken.charOffset)); } @override void endFunctionTypedFormalParameter(Token nameToken, Token question) { debugEvent("FunctionTypedFormalParameter"); List<FormalParameterBuilder> formals = pop(); int formalsOffset = pop(); TypeBuilder returnType = pop(); List<TypeVariableBuilder> typeVariables = pop(); if (!library.loader.target.enableNonNullable) { reportErrorIfNullableType(question); } push(library.addFunctionType(returnType, typeVariables, formals, library.nullableBuilderIfTrue(question != null), formalsOffset)); } @override void endFunctionTypeAlias( Token typedefKeyword, Token equals, Token endToken) { debugEvent("endFunctionTypeAlias"); String documentationComment = getDocumentationComment(typedefKeyword); List<TypeVariableBuilder> typeVariables; Object name; int charOffset; FunctionTypeBuilder functionType; if (equals == null) { List<FormalParameterBuilder> formals = pop(); pop(); // formals offset typeVariables = pop(); charOffset = pop(); name = pop(); TypeBuilder returnType = pop(); // Create a nested declaration that is ended below by // `library.addFunctionType`. if (name is ParserRecovery) { pop(); // Metadata. library.endNestedDeclaration( TypeParameterScopeKind.typedef, "<syntax-error>"); return; } library.beginNestedDeclaration( TypeParameterScopeKind.functionType, "#function_type", hasMembers: false); // TODO(dmitryas): Make sure that RHS of typedefs can't have '?'. functionType = library.addFunctionType(returnType, null, formals, const NullabilityBuilder.omitted(), charOffset); } else { Object type = pop(); typeVariables = pop(); charOffset = pop(); name = pop(); if (name is ParserRecovery) { pop(); // Metadata. library.endNestedDeclaration( TypeParameterScopeKind.functionType, "<syntax-error>"); return; } if (type is FunctionTypeBuilder) { // TODO(ahe): We need to start a nested declaration when parsing the // formals and return type so we can correctly bind // `type.typeVariables`. A typedef can have type variables, and a new // function type can also have type variables (representing the type of // a generic function). functionType = type; } else { // TODO(ahe): Improve this error message. addProblem(messageTypedefNotFunction, equals.charOffset, equals.length); } } List<MetadataBuilder> metadata = pop(); checkEmpty(typedefKeyword.charOffset); library.addFunctionTypeAlias(documentationComment, metadata, name, typeVariables, functionType, charOffset); } @override void endTopLevelFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("endTopLevelFields"); if (!library.loader.target.enableNonNullable) { reportNonNullableModifierError(lateToken); } List<FieldInfo> fieldInfos = popFieldInfos(count); TypeBuilder type = nullIfParserRecovery(pop()); int modifiers = (staticToken != null ? staticMask : 0) | (covariantToken != null ? covariantMask : 0) | (lateToken != null ? lateMask : 0) | Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme); List<MetadataBuilder> metadata = pop(); checkEmpty(beginToken.charOffset); if (fieldInfos == null) return; String documentationComment = getDocumentationComment(beginToken); library.addFields( documentationComment, metadata, modifiers, type, fieldInfos); } @override void endClassFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("Fields"); if (!library.loader.target.enableNonNullable) { reportNonNullableModifierError(lateToken); } List<FieldInfo> fieldInfos = popFieldInfos(count); TypeBuilder type = pop(); int modifiers = (staticToken != null ? staticMask : 0) | (covariantToken != null ? covariantMask : 0) | (lateToken != null ? lateMask : 0) | Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme); if (staticToken == null && modifiers & constMask != 0) { // It is a compile-time error if an instance variable is declared to be // constant. addProblem(messageConstInstanceField, varFinalOrConst.charOffset, varFinalOrConst.length); modifiers &= ~constMask; } List<MetadataBuilder> metadata = pop(); if (fieldInfos == null) return; String documentationComment = getDocumentationComment(beginToken); library.addFields( documentationComment, metadata, modifiers, type, fieldInfos); } List<FieldInfo> popFieldInfos(int count) { if (count == 0) return null; List<FieldInfo> fieldInfos = new List<FieldInfo>(count); bool isParserRecovery = false; for (int i = count - 1; i != -1; i--) { int charEndOffset = pop(); Token beforeLast = pop(); Token initializerTokenForInference = pop(); int charOffset = pop(); Object name = pop(NullValue.Identifier); if (name is ParserRecovery) { isParserRecovery = true; } else { fieldInfos[i] = new FieldInfo(name, charOffset, initializerTokenForInference, beforeLast, charEndOffset); } } return isParserRecovery ? null : fieldInfos; } @override void beginTypeVariable(Token token) { debugEvent("beginTypeVariable"); int charOffset = pop(); Object name = pop(); // TODO(paulberry): type variable metadata should not be ignored. See // dartbug.com/28981. /* List<MetadataBuilder<TypeBuilder>> metadata = */ pop(); if (name is ParserRecovery) { push(name); } else { push(library.addTypeVariable(name, null, charOffset)); } } @override void handleTypeVariablesDefined(Token token, int count) { debugEvent("TypeVariablesDefined"); assert(count > 0); push(const FixedNullableList<TypeVariableBuilder>().pop(stack, count) ?? NullValue.TypeVariables); } @override void endTypeVariable( Token token, int index, Token extendsOrSuper, Token variance) { debugEvent("endTypeVariable"); TypeBuilder bound = nullIfParserRecovery(pop()); // Peek to leave type parameters on top of stack. List<TypeVariableBuilder> typeParameters = peek(); if (typeParameters != null) { typeParameters[index].bound = bound; if (variance != null) { typeParameters[index].variance = Variance.fromString(variance.lexeme); } } } @override void endTypeVariables(Token beginToken, Token endToken) { debugEvent("endTypeVariables"); // Peek to leave type parameters on top of stack. List<TypeVariableBuilder> typeParameters = peek(); Map<String, TypeVariableBuilder> typeVariablesByName; if (typeParameters != null) { for (TypeVariableBuilder builder in typeParameters) { if (builder.bound != null) { if (typeVariablesByName == null) { typeVariablesByName = new Map<String, TypeVariableBuilder>(); for (TypeVariableBuilder builder in typeParameters) { typeVariablesByName[builder.name] = builder; } } // Find cycle: If there's no cycle we can at most step through all // `typeParameters` (at which point the last builders bound will be // null). // If there is a cycle with `builder` 'inside' the steps to get back // to it will also be bound by `typeParameters.length`. // If there is a cycle without `builder` 'inside' we will just ignore // it for now. It will be reported when processing one of the // `builder`s that is in fact `inside` the cycle. This matches the // cyclic class hierarchy error. TypeVariableBuilder bound = builder; for (int steps = 0; bound.bound != null && steps < typeParameters.length; ++steps) { bound = typeVariablesByName[bound.bound.name]; if (bound == null || bound == builder) break; } if (bound == builder && bound.bound != null) { // Write out cycle. List<String> via = new List<String>(); bound = typeVariablesByName[builder.bound.name]; while (bound != builder) { via.add(bound.name); bound = typeVariablesByName[bound.bound.name]; } Message message = via.isEmpty ? templateDirectCycleInTypeVariables.withArguments(builder.name) : templateCycleInTypeVariables.withArguments( builder.name, via.join("', '")); addProblem(message, builder.charOffset, builder.name.length); builder.bound = new NamedTypeBuilder( builder.name, const NullabilityBuilder.omitted(), null) ..bind(new InvalidTypeBuilder( builder.name, message.withLocation( uri, builder.charOffset, builder.name.length))); } } } } if (inConstructorName) { addProblem(messageConstructorWithTypeParameters, offsetForToken(beginToken), lengthOfSpan(beginToken, endToken)); inConstructorName = false; } } @override void handleVarianceModifier(Token variance) { if (!library.loader.target.enableVariance) { reportVarianceModifierNotEnabled(variance); } } @override void endPartOf( Token partKeyword, Token ofKeyword, Token semicolon, bool hasName) { debugEvent("endPartOf"); int charOffset = popCharOffset(); Object containingLibrary = pop(); List<MetadataBuilder> metadata = pop(); if (hasName) { library.addPartOf(metadata, flattenName(containingLibrary, charOffset, uri), null, charOffset); } else { library.addPartOf(metadata, null, containingLibrary, charOffset); } } @override void endConstructorReference( Token start, Token periodBeforeName, Token endToken) { debugEvent("ConstructorReference"); popIfNotNull(periodBeforeName); // charOffset. String suffix = popIfNotNull(periodBeforeName); List<TypeBuilder> typeArguments = pop(); int charOffset = pop(); Object name = pop(); if (name is ParserRecovery) { push(name); } else { push(library.addConstructorReference( name, typeArguments, suffix, charOffset)); } } @override void beginFactoryMethod( Token lastConsumed, Token externalToken, Token constToken) { inConstructor = true; library.beginNestedDeclaration( TypeParameterScopeKind.factoryMethod, "#factory_method", hasMembers: false); push((externalToken != null ? externalMask : 0) | (constToken != null ? constMask : 0)); } @override void endClassFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { debugEvent("ClassFactoryMethod"); MethodBody kind = pop(); ConstructorReferenceBuilder redirectionTarget; if (kind == MethodBody.RedirectingFactoryBody) { redirectionTarget = nullIfParserRecovery(pop()); } List<FormalParameterBuilder> formals = pop(); int formalsOffset = pop(); pop(); // type variables int charOffset = pop(); Object name = pop(); int modifiers = pop(); if (nativeMethodName != null) { modifiers |= externalMask; } List<MetadataBuilder> metadata = pop(); if (name is ParserRecovery) { library.endNestedDeclaration( TypeParameterScopeKind.factoryMethod, "<syntax-error>"); return; } String documentationComment = getDocumentationComment(beginToken); library.addFactoryMethod( documentationComment, metadata, modifiers, name, formals, redirectionTarget, beginToken.charOffset, charOffset, formalsOffset, endToken.charOffset, nativeMethodName); nativeMethodName = null; inConstructor = false; } @override void endRedirectingFactoryBody(Token beginToken, Token endToken) { debugEvent("RedirectingFactoryBody"); push(MethodBody.RedirectingFactoryBody); } @override void endFieldInitializer(Token assignmentOperator, Token token) { debugEvent("FieldInitializer"); Token beforeLast = assignmentOperator.next; Token next = beforeLast.next; while (next != token && !next.isEof) { // To avoid storing the rest of the token stream, we need to identify the // token before [token]. That token will be the last token of the // initializer expression and by setting its tail to EOF we only store // the tokens for the expression. // TODO(ahe): Might be clearer if this search was moved to // `library.addFields`. // TODO(ahe): I don't even think this is necessary. [token] points to ; // or , and we don't otherwise store tokens. beforeLast = next; next = next.next; } push(assignmentOperator.next); push(beforeLast); push(token.charOffset); } @override void handleNoFieldInitializer(Token token) { debugEvent("NoFieldInitializer"); push(NullValue.FieldInitializer); push(NullValue.FieldInitializer); push(token.charOffset); } @override void endInitializers(int count, Token beginToken, Token endToken) { debugEvent("Initializers"); // Ignored for now. } @override void handleNoInitializers() { debugEvent("NoInitializers"); // This is a constructor initializer and it's ignored for now. } @override void handleInvalidMember(Token endToken) { debugEvent("InvalidMember"); pop(); // metadata star } @override void endMember() { debugEvent("Member"); assert(nativeMethodName == null); } @override void handleClassWithClause(Token withKeyword) { debugEvent("ClassWithClause"); Object mixins = pop(); int extendsOffset = pop(); Object supertype = pop(); if (supertype is ParserRecovery || mixins is ParserRecovery) { push(new ParserRecovery(withKeyword.charOffset)); } else { push(library.addMixinApplication( supertype, mixins, withKeyword.charOffset)); } push(extendsOffset); } @override void handleClassNoWithClause() { debugEvent("ClassNoWithClause"); } @override void handleClassHeader(Token begin, Token classKeyword, Token nativeToken) { debugEvent("ClassHeader"); nativeMethodName = null; } @override void handleMixinHeader(Token mixinKeyword) { debugEvent("handleMixinHeader"); nativeMethodName = null; } @override void endClassOrMixinBody( DeclarationKind kind, int memberCount, Token beginToken, Token endToken) { debugEvent("ClassOrMixinBody"); } @override void handleAsyncModifier(Token asyncToken, Token starToken) { debugEvent("AsyncModifier"); } void addProblem(Message message, int charOffset, int length, {bool wasHandled: false, List<LocatedMessage> context}) { library.addProblem(message, charOffset, length, uri, wasHandled: wasHandled, context: context); } @override bool isIgnoredError(Code<dynamic> code, Token token) { return isIgnoredParserError(code, token) || super.isIgnoredError(code, token); } /// Return the documentation comment for the entity that starts at the /// given [token], or `null` if there is no preceding documentation comment. static String getDocumentationComment(Token token) { Token docToken = token.precedingComments; if (docToken == null) return null; bool inSlash = false; StringBuffer buffer = new StringBuffer(); while (docToken != null) { String lexeme = docToken.lexeme; if (lexeme.startsWith('/**')) { inSlash = false; buffer.clear(); buffer.write(lexeme); } else if (lexeme.startsWith('///')) { if (!inSlash) { inSlash = true; buffer.clear(); } if (buffer.isNotEmpty) { buffer.writeln(); } buffer.write(lexeme); } docToken = docToken.next; } return buffer.toString(); } @override void debugEvent(String name) { // printEvent('OutlineBuilder: $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/source/type_promotion_look_ahead_listener.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.type_promotion_look_ahead_listener; import '../builder/declaration.dart'; import '../messages.dart' show LocatedMessage, Message, MessageCode; import '../parser.dart' show Assert, DeclarationKind, FormalParameterKind, IdentifierContext, Listener, MemberKind; import '../problems.dart' as problems show unhandled; import '../scanner.dart' show Token; import '../scope.dart' show Scope; import '../severity.dart' show Severity; final NoArguments noArgumentsSentinel = new NoArguments(); abstract class TypePromotionState { final Uri uri; final List<Scope> scopes = <Scope>[new Scope.top(isModifiable: true)]; final List<Builder> stack = <Builder>[]; TypePromotionState(this.uri); Scope get currentScope => scopes.last; void enterScope(String debugName) { scopes.add(new Scope.nested(currentScope, "block")); } Scope exitScope(Token token) { return scopes.removeLast(); } void declareIdentifier(Token token) { String name = token.lexeme; LocatedMessage error = currentScope.declare( name, new UnspecifiedDeclaration(name, uri, token.charOffset), uri); if (error != null) { report(error, Severity.error); } pushNull(token.lexeme, token); } void registerWrite(UnspecifiedDeclaration declaration, Token token) {} void registerPromotionCandidate( UnspecifiedDeclaration declaration, Token token) {} void pushReference(Token token) { String name = token.lexeme; Builder declaration = currentScope.lookup(name, token.charOffset, uri); stack.add(declaration); } Builder pop() => stack.removeLast(); void push(Builder declaration) { stack.add(declaration); } Builder popPushNull(String name, Token token) { int last = stack.length - 1; Builder declaration = stack[last]; stack[last] = nullValue(name, token); return declaration; } void discard(int count) { stack.length = stack.length - count; } void pushNull(String name, Token token) { stack.add(nullValue(name, token)); } Builder nullValue(String name, Token token) => null; void report(LocatedMessage message, Severity severity, {List<LocatedMessage> context}); void trace(String message, Token token) {} void checkEmpty(Token token) {} } class UnspecifiedDeclaration extends BuilderImpl { final String name; @override final Uri fileUri; @override int charOffset; UnspecifiedDeclaration(this.name, this.fileUri, this.charOffset); @override Builder get parent => null; @override String get fullNameForErrors => name; @override String toString() => "UnspecifiedDeclaration($name)"; } class NoArguments extends BuilderImpl { NoArguments(); @override Uri get fileUri => null; @override int get charOffset => -1; @override Builder get parent => null; @override String get fullNameForErrors => "<<no arguments>>"; @override String toString() => fullNameForErrors; } class TypePromotionLookAheadListener extends Listener { final TypePromotionState state; TypePromotionLookAheadListener(this.state); Uri get uri => state.uri; void logEvent(String name) { throw new UnimplementedError(name); } void debugEvent(String name, Token token) { // state.trace(name, token); } @override void endArguments(int count, Token beginToken, Token endToken) { debugEvent("Arguments", beginToken); state.discard(count); state.pushNull("%Arguments%", endToken); } @override void handleNoArguments(Token token) { debugEvent("NoArguments", token); state.push(noArgumentsSentinel); } @override void handleAsOperator(Token operator) { debugEvent("AsOperator", operator); state.popPushNull(operator.lexeme, operator); } @override void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis, Token commaToken, Token semicolonToken) { debugEvent("Assert", assertKeyword); if (commaToken != null) { state.pop(); // Message. } state.pop(); // Condition. switch (kind) { case Assert.Expression: state.pushNull("%AssertExpression%", assertKeyword); break; case Assert.Initializer: state.pushNull("%AssertInitializer%", assertKeyword); break; case Assert.Statement: break; } } @override void handleAssignmentExpression(Token token) { debugEvent("AssignmentExpression", token); state.pop(); // Right-hand side. Builder lhs = state.popPushNull(token.lexeme, token); if (lhs is UnspecifiedDeclaration) { state.registerWrite(lhs, token); } } @override void handleAsyncModifier(Token asyncToken, Token starToken) { debugEvent("AsyncModifier", asyncToken); } @override void endAwaitExpression(Token beginToken, Token endToken) { debugEvent("AwaitExpression", beginToken); state.popPushNull(beginToken.lexeme, beginToken); // Expression. } @override void endInvalidAwaitExpression( Token beginToken, Token endToken, MessageCode errorCode) { debugEvent("InvalidAwaitExpression", beginToken); state.popPushNull(beginToken.lexeme, beginToken); // Expression. } @override void endBinaryExpression(Token token) { debugEvent("BinaryExpression", token); state.pop(); // Right-hand side. state.popPushNull(token.lexeme, token); // Left-hand side. } @override void beginBlock(Token token) { debugEvent("beginBlock", token); state.enterScope("block"); } @override void endBlock(int count, Token beginToken, Token endToken) { debugEvent("Block", beginToken); state.exitScope(endToken); } @override void beginBlockFunctionBody(Token token) { debugEvent("beginBlockFunctionBody", token); state.enterScope("block-function-body"); } @override void endBlockFunctionBody(int count, Token beginToken, Token endToken) { debugEvent("BlockFunctionBody", beginToken); state.exitScope(endToken); } @override void handleBreakStatement( bool hasTarget, Token breakKeyword, Token endToken) { debugEvent("BreakStatement", breakKeyword); if (hasTarget) { state.pop(); // Target. } } @override void endCascade() { debugEvent("Cascade", null); state.popPushNull("%Cascade%", null); } @override void endCaseExpression(Token colon) { debugEvent("CaseExpression", colon); state.pop(); // Expression. } @override void handleCaseMatch(Token caseKeyword, Token colon) { debugEvent("CaseMatch", caseKeyword); } @override void handleCatchBlock(Token onKeyword, Token catchKeyword, Token comma) { debugEvent("CatchBlock", catchKeyword); } @override void endCatchClause(Token token) { debugEvent("CatchClause", token); } @override void endClassDeclaration(Token beginToken, Token endToken) { debugEvent("ClassDeclaration", beginToken); state.checkEmpty(endToken); } @override void handleClassExtends(Token extendsKeyword) { debugEvent("ClassExtends", extendsKeyword); } @override void handleClassHeader(Token begin, Token classKeyword, Token nativeToken) { debugEvent("ClassHeader", begin); state.pop(); // Class name. state.checkEmpty(classKeyword); } @override void handleClassNoWithClause() { debugEvent("ClassNoWithClause", null); } @override void endClassOrMixinBody( DeclarationKind kind, int memberCount, Token beginToken, Token endToken) { debugEvent("ClassOrMixinBody", beginToken); state.checkEmpty(endToken); } @override void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { debugEvent("ClassOrMixinImplements", implementsKeyword); } @override void handleClassWithClause(Token withKeyword) { debugEvent("ClassWithClause", withKeyword); } @override void endCombinators(int count) { debugEvent("Combinators", null); } @override void handleCommentReference( Token newKeyword, Token prefix, Token period, Token token) { debugEvent("CommentReference", newKeyword); unhandled("CommentReference", newKeyword); } @override void handleNoCommentReference() { debugEvent("NoCommentReference", null); unhandled("NoCommentReference", null); } @override void handleCommentReferenceText(String referenceSource, int referenceOffset) { debugEvent("CommentReferenceText", null); unhandled("CommentReferenceText", null); } @override void endCompilationUnit(int count, Token token) { debugEvent("CompilationUnit", token); print(state.stack); } @override void endConditionalExpression(Token question, Token colon) { debugEvent("ConditionalExpression", question); state.pop(); // Otherwise expression. state.pop(); // Then expression. state.popPushNull(question.lexeme, question); // Condition. } @override void handleConditionalExpressionColon() { debugEvent("ConditionalExpressionColon", null); // TODO(ahe): Rename this event. This is not handling any colons as it // isn't being passed a colon. One alternative is // handleConditionalThenExpression, but check the specification for naming // conventions. Kernel uses "then" and "otherwise". } @override void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) { debugEvent("ConditionalUri", ifKeyword); unhandled("ConditionalUri", ifKeyword); } @override void endConditionalUris(int count) { debugEvent("ConditionalUris", null); } @override void endConstExpression(Token token) { debugEvent("ConstExpression", token); doConstuctorInvocation(token, true); } @override void endForControlFlow(Token token) { // TODO(danrubel) add support for for control flow collection entries // but for now this is ignored and an error reported in the body builder. } @override void endForInControlFlow(Token token) { // TODO(danrubel) add support for for control flow collection entries // but for now this is ignored and an error reported in the body builder. } @override void handleElseControlFlow(Token token) {} @override void endIfControlFlow(Token token) { state.pop(); // Element. state.pop(); // Condition. state.pushNull("%IfControlFlow%", token); } @override void endIfElseControlFlow(Token token) { state.pop(); // Else element. state.pop(); // Then element. state.pop(); // Condition. state.pushNull("%IfElseControlFlow%", token); } @override void handleSpreadExpression(Token spreadToken) { // TODO(danrubel) add support for spread collections // but for now this is ignored and an error reported in the body builder. // The top of stack is the spread collection expression. } void doConstuctorInvocation(Token token, bool isConst) { state.pop(); // Arguments. state.popPushNull(token.lexeme, token); // Constructor reference. } @override void endConstLiteral(Token token) { debugEvent("ConstLiteral", token); state.popPushNull("%ConstLiteral%", token); } @override void endConstructorReference( Token start, Token periodBeforeName, Token endToken) { debugEvent("ConstructorReference", start); if (periodBeforeName != null) { state.pop(); // Prefix. } state.popPushNull("%ConstructorReference%", start); } @override void handleNoConstructorReferenceContinuationAfterTypeArguments(Token token) { debugEvent("NoConstructorReferenceContinuationAfterTypeArguments", token); } @override void handleContinueStatement( bool hasTarget, Token continueKeyword, Token endToken) { debugEvent("ContinueStatement", continueKeyword); if (hasTarget) { state.pop(); // Target. } } @override void handleDirectivesOnly() { debugEvent("DirectivesOnly", null); unhandled("DirectivesOnly", null); } @override void endDoWhileStatement( Token doKeyword, Token whileKeyword, Token endToken) { debugEvent("DoWhileStatement", doKeyword); state.pop(); // Condition. } @override void endDoWhileStatementBody(Token token) { debugEvent("DoWhileStatementBody", token); } @override void handleDottedName(int count, Token firstIdentifier) { debugEvent("DottedName", firstIdentifier); unhandled("DottedName", firstIdentifier); } @override void endElseStatement(Token token) { debugEvent("ElseStatement", token); } @override void handleEmptyFunctionBody(Token semicolon) { debugEvent("EmptyFunctionBody", semicolon); } @override void handleEmptyStatement(Token token) { debugEvent("EmptyStatement", token); } @override void beginEnum(Token enumKeyword) { debugEvent("beginEnum", enumKeyword); state.checkEmpty(enumKeyword); } @override void endEnum(Token enumKeyword, Token leftBrace, int count) { debugEvent("endEnum", enumKeyword); state.discard(count); // Enum values. state.pop(); // Enum name. state.checkEmpty(enumKeyword); } @override void endExport(Token exportKeyword, Token semicolon) { debugEvent("Export", exportKeyword); state.pop(); // Export URI. state.checkEmpty(semicolon); } @override void handleExpressionFunctionBody(Token arrowToken, Token endToken) { debugEvent("ExpressionFunctionBody", arrowToken); state.pop(); } @override void handleExpressionStatement(Token token) { debugEvent("ExpressionStatement", token); state.pop(); } @override void handleExtraneousExpression(Token token, Message message) { debugEvent("ExtraneousExpression", token); unhandled("ExtraneousExpression", token); } @override void endClassFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { debugEvent("ClassFactoryMethod", beginToken); state.pop(); // Name. state.checkEmpty(endToken); } @override void endFieldInitializer(Token assignment, Token token) { debugEvent("FieldInitializer", assignment); state.pop(); // Initializer. } @override void handleNoFieldInitializer(Token token) { debugEvent("NoFieldInitializer", token); } @override void endClassFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("Fields", staticToken); state.discard(count); // Field names. state.checkEmpty(endToken); } @override void handleFinallyBlock(Token finallyKeyword) { debugEvent("FinallyBlock", finallyKeyword); } @override void endForIn(Token endToken) { debugEvent("ForIn", endToken); } @override void endForInBody(Token token) { debugEvent("ForInBody", token); } @override void endForInExpression(Token token) { debugEvent("ForInExpression", token); state.pop(); // Expression. } @override void handleForInitializerEmptyStatement(Token token) { debugEvent("ForInitializerEmptyStatement", token); } @override void handleForInitializerExpressionStatement(Token token) { debugEvent("ForInitializerExpressionStatement", token); state.pop(); // Expression. } @override void handleForInitializerLocalVariableDeclaration(Token token) { debugEvent("ForInitializerLocalVariableDeclaration", token); } @override void handleForLoopParts(Token forKeyword, Token leftParen, Token leftSeparator, int updateExpressionCount) { debugEvent("handleForLoopParts", forKeyword); state.discard(updateExpressionCount); } @override void endForStatement(Token endToken) { debugEvent("ForStatement", endToken); } @override void endForStatementBody(Token token) { debugEvent("ForStatementBody", token); } @override void endFormalParameter( Token thisKeyword, Token periodAfterThis, Token nameToken, Token initializerStart, Token initializerEnd, FormalParameterKind kind, MemberKind memberKind) { debugEvent("FormalParameter", thisKeyword); state.pop(); // Parameter name. } @override void endFormalParameterDefaultValueExpression() { debugEvent("FormalParameterDefaultValueExpression", null); state.pop(); } @override void handleFormalParameterWithoutValue(Token token) { debugEvent("FormalParameterWithoutValue", token); } @override void endFormalParameters( int count, Token beginToken, Token endToken, MemberKind kind) { debugEvent("FormalParameters", beginToken); } @override void handleNoFormalParameters(Token token, MemberKind kind) { debugEvent("NoFormalParameters", token); } @override void handleNoFunctionBody(Token token) { debugEvent("NoFunctionBody", token); unhandled("NoFunctionBody", token); } @override void handleFunctionBodySkipped(Token token, bool isExpressionBody) { debugEvent("FunctionBodySkipped", token); unhandled("FunctionBodySkipped", token); } @override void endFunctionExpression(Token beginToken, Token token) { debugEvent("FunctionExpression", beginToken); state.pushNull("%function%", token); } @override void endFunctionName(Token beginToken, Token token) { debugEvent("FunctionName", beginToken); } @override void endFunctionType(Token functionToken, Token questionMark) { debugEvent("FunctionType", functionToken); } @override void endFunctionTypeAlias( Token typedefKeyword, Token equals, Token endToken) { debugEvent("FunctionTypeAlias", typedefKeyword); state.pop(); // Name. state.checkEmpty(endToken); } @override void endFunctionTypedFormalParameter(Token nameToken, Token question) { debugEvent("FunctionTypedFormalParameter", nameToken); } @override void endHide(Token hideKeyword) { debugEvent("Hide", hideKeyword); } @override void handleIdentifier(Token token, IdentifierContext context) { debugEvent("Identifier ${context}", token); if (context.inSymbol) { // Do nothing. } else if (context.inDeclaration) { if (identical(IdentifierContext.localVariableDeclaration, context) || identical(IdentifierContext.formalParameterDeclaration, context)) { state.declareIdentifier(token); } else { state.pushNull(token.lexeme, token); } } else if (context.isContinuation) { state.pushNull(token.lexeme, token); } else if (context.isScopeReference) { state.pushReference(token); } else { state.pushNull(token.lexeme, token); } } @override void handleIdentifierList(int count) { debugEvent("IdentifierList", null); state.discard(count); } @override void endIfStatement(Token ifToken, Token elseToken) { debugEvent("IfStatement", ifToken); state.pop(); // Condition. } @override void endImplicitCreationExpression(Token token) { debugEvent("ImplicitCreationExpression", token); doConstuctorInvocation(token, false); } @override void endImport(Token importKeyword, Token semicolon) { debugEvent("Import", importKeyword); state.pop(); // Import URI. state.checkEmpty(semicolon); } @override void handleImportPrefix(Token deferredKeyword, Token asKeyword) { debugEvent("ImportPrefix", deferredKeyword); if (asKeyword != null) { state.pop(); // Prefix name. } } @override void handleIndexedExpression( Token openSquareBracket, Token closeSquareBracket) { debugEvent("IndexedExpression", openSquareBracket); state.pop(); // Index. state.popPushNull("%indexed%", closeSquareBracket); // Expression. } @override void endInitializedIdentifier(Token nameToken) { debugEvent("InitializedIdentifier", nameToken); } @override void endInitializer(Token token) { debugEvent("Initializer", token); state.pop(); // Initializer. } @override void endInitializers(int count, Token beginToken, Token endToken) { debugEvent("Initializers", beginToken); } @override void handleNoInitializers() { debugEvent("NoInitializers", null); } @override void handleInterpolationExpression(Token leftBracket, Token rightBracket) { debugEvent("InterpolationExpression", leftBracket); state.popPushNull(r"$", leftBracket); } @override void handleInvalidExpression(Token token) { // TODO(ahe): The parser doesn't generate this event anymore. debugEvent("InvalidExpression", token); unhandled("InvalidExpression", token); } @override void handleInvalidFunctionBody(Token token) { debugEvent("InvalidFunctionBody", token); } @override void handleInvalidMember(Token endToken) { debugEvent("InvalidMember", endToken); state.checkEmpty(endToken); } @override void handleInvalidOperatorName(Token operatorKeyword, Token token) { debugEvent("InvalidOperatorName", operatorKeyword); state.checkEmpty(operatorKeyword); } @override void handleInvalidStatement(Token token, Message message) { debugEvent("InvalidStatement", token); } @override void handleInvalidTopLevelBlock(Token token) { debugEvent("InvalidTopLevelBlock", token); state.checkEmpty(token); } @override void handleInvalidTopLevelDeclaration(Token endToken) { debugEvent("InvalidTopLevelDeclaration", endToken); state.checkEmpty(endToken); } @override void handleInvalidTypeArguments(Token token) { debugEvent("InvalidTypeArguments", token); } @override void handleInvalidTypeReference(Token token) { debugEvent("InvalidTypeReference", token); unhandled("InvalidTypeReference", token); } @override void handleIsOperator(Token isOperator, Token not) { debugEvent("IsOperator", isOperator); Builder lhs = state.popPushNull(isOperator.lexeme, isOperator); if (not == null && lhs is UnspecifiedDeclaration) { state.registerPromotionCandidate(lhs, isOperator); } } @override void handleLabel(Token token) { debugEvent("Label", token); state.pop(); // Label. } @override void endLabeledStatement(int labelCount) { debugEvent("LabeledStatement", null); } @override void endLibraryName(Token libraryKeyword, Token semicolon) { debugEvent("LibraryName", libraryKeyword); state.pop(); // Library name. state.checkEmpty(semicolon); } @override void handleLiteralBool(Token token) { debugEvent("LiteralBool", token); state.pushNull(token.lexeme, token); } @override void handleLiteralDouble(Token token) { debugEvent("LiteralDouble", token); state.pushNull(token.lexeme, token); } @override void handleLiteralInt(Token token) { debugEvent("LiteralInt", token); state.pushNull(token.lexeme, token); } @override void handleLiteralList( int count, Token leftBracket, Token constKeyword, Token rightBracket) { debugEvent("LiteralList", leftBracket); state.discard(count); state.pushNull("[]", leftBracket); } @override void handleLiteralSetOrMap( int count, Token leftBrace, Token constKeyword, Token rightBrace, // TODO(danrubel): hasSetEntry parameter exists for replicating existing // behavior and will be removed once unified collection has been enabled bool hasSetEntry, ) { debugEvent("LiteralSetOrMap", leftBrace); state.discard(count); state.pushNull("{}", leftBrace); } @override void handleLiteralMapEntry(Token colon, Token endToken) { debugEvent("LiteralMapEntry", colon); state.pop(); // Value. state.popPushNull("%LiteralMapEntry%", colon); // Key. } @override void handleLiteralNull(Token token) { debugEvent("LiteralNull", token); state.pushNull(token.lexeme, token); } @override void beginLiteralString(Token token) { debugEvent("beginLiteralString", token); state.pushNull(token.lexeme, token); } @override void endLiteralString(int interpolationCount, Token endToken) { debugEvent("LiteralString", endToken); state.discard(interpolationCount * 2); state.popPushNull("%string%", endToken); } @override void endLiteralSymbol(Token hashToken, int identifierCount) { debugEvent("LiteralSymbol", hashToken); state.pushNull(hashToken.lexeme, hashToken); } @override void endLocalFunctionDeclaration(Token endToken) { debugEvent("LocalFunctionDeclaration", endToken); state.pop(); // Function name. } @override void endMember() { debugEvent("Member", null); state.checkEmpty(null); } @override void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) { debugEvent("Metadata", beginToken); state.pop(); // Arguments. if (periodBeforeName != null) { state.pop(); // Suffix. } state.pop(); // Qualifier. } @override void endMetadataStar(int count) { debugEvent("MetadataStar", null); } @override void beginMethod(Token externalToken, Token staticToken, Token covariantToken, Token varFinalOrConst, Token getOrSet, Token name) { debugEvent("beginMethod", name); state.checkEmpty(name); } @override void endClassMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { debugEvent("endMethod", endToken); state.pop(); // Method name. state.checkEmpty(endToken); } @override void endMixinDeclaration(Token mixinKeyword, Token endToken) { debugEvent("MixinDeclaration", mixinKeyword); state.checkEmpty(endToken); } @override void handleMixinHeader(Token mixinKeyword) { debugEvent("MixinHeader", mixinKeyword); state.pop(); // Mixin name. state.checkEmpty(mixinKeyword); } @override void handleMixinOn(Token onKeyword, int typeCount) { debugEvent("MixinOn", onKeyword); } @override void handleNoName(Token token) { debugEvent("NoName", token); state.pushNull("%NoName%", token); } @override void handleNamedArgument(Token colon) { debugEvent("NamedArgument", colon); state.pop(); // Expression. state.popPushNull("%NamedArgument%", colon); // Identifier. } @override void endNamedFunctionExpression(Token endToken) { debugEvent("NamedFunctionExpression", endToken); state.popPushNull( "%named function expression%", endToken); // Function name. } @override void endNamedMixinApplication(Token begin, Token classKeyword, Token equals, Token implementsKeyword, Token endToken) { debugEvent("NamedMixinApplication", begin); state.pop(); // Mixin application name. state.checkEmpty(endToken); } @override void handleNamedMixinApplicationWithClause(Token withKeyword) { debugEvent("NamedMixinApplicationWithClause", withKeyword); } @override void handleNativeClause(Token nativeToken, bool hasName) { debugEvent("NativeClause", nativeToken); if (hasName) { state.pop(); // Name. } } @override void handleNativeFunctionBody(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBody", nativeToken); } @override void handleNativeFunctionBodyIgnored(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBodyIgnored", nativeToken); } @override void handleNativeFunctionBodySkipped(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBodySkipped", nativeToken); } @override void endNewExpression(Token token) { debugEvent("NewExpression", token); doConstuctorInvocation(token, false); } @override void handleOperator(Token token) { debugEvent("Operator", token); unhandled("Operator", token); } @override void handleOperatorName(Token operatorKeyword, Token token) { debugEvent("OperatorName", operatorKeyword); state.pushNull(token.lexeme, token); } @override void endOptionalFormalParameters( int count, Token beginToken, Token endToken) { debugEvent("OptionalFormalParameters", beginToken); } @override void handleParenthesizedCondition(Token token) { debugEvent("ParenthesizedCondition", token); } @override void handleParenthesizedExpression(Token token) { debugEvent("ParenthesizedExpression", token); state.popPushNull("%(expr)%", token); } @override void endPart(Token partKeyword, Token semicolon) { debugEvent("Part", partKeyword); state.pop(); // URI. state.checkEmpty(semicolon); } @override void endPartOf( Token partKeyword, Token ofKeyword, Token semicolon, bool hasName) { debugEvent("PartOf", partKeyword); state.pop(); // Name or URI. state.checkEmpty(semicolon); } @override void handleQualified(Token period) { debugEvent("Qualified", period); state.pop(); // Suffix. state.popPushNull("%Qualified%", period); // Qualifier. } @override void handleRecoverClassHeader() { debugEvent("RecoverClassHeader", null); state.checkEmpty(null); } @override void handleRecoverImport(Token semicolon) { debugEvent("RecoverImport", semicolon); unhandled("RecoverImport", semicolon); } @override void handleRecoverMixinHeader() { debugEvent("RecoverMixinHeader", null); state.checkEmpty(null); } @override void handleRecoverableError( Message message, Token startToken, Token endToken) { debugEvent("RecoverableError ${message.message}", startToken); } @override void endRedirectingFactoryBody(Token beginToken, Token endToken) { debugEvent("RedirectingFactoryBody", beginToken); state.pop(); // Constructor reference. } @override void endRethrowStatement(Token rethrowToken, Token endToken) { debugEvent("RethrowStatement", rethrowToken); } @override void endReturnStatement( bool hasExpression, Token beginToken, Token endToken) { debugEvent("ReturnStatement", beginToken); if (hasExpression) { state.pop(); // Expression. } } @override void handleScript(Token token) { debugEvent("Script", token); unhandled("Script", token); } @override void handleSend(Token beginToken, Token endToken) { debugEvent("Send", beginToken); Builder arguments = state.pop(); if (identical(arguments, noArgumentsSentinel)) { // Leave the receiver on the stack. } else { state.popPushNull("%send%", beginToken); } } @override void endShow(Token showKeyword) { debugEvent("Show", showKeyword); } @override void handleStringJuxtaposition(int literalCount) { debugEvent("StringJuxtaposition", null); state.discard(literalCount); state.pushNull("%StringJuxtaposition%", null); } @override void handleStringPart(Token token) { debugEvent("StringPart", token); state.pushNull(token.lexeme, token); } @override void handleSuperExpression(Token token, IdentifierContext context) { debugEvent("SuperExpression", token); state.pushNull(token.lexeme, token); } @override void endSwitchBlock(int caseCount, Token beginToken, Token endToken) { debugEvent("SwitchBlock", beginToken); state.pop(); // Expression. } @override void endSwitchCase( int labelCount, int expressionCount, Token defaultKeyword, Token colonAfterDefault, int statementCount, Token firstToken, Token endToken) { debugEvent("SwitchCase", defaultKeyword); } @override void endSwitchStatement(Token switchKeyword, Token endToken) { debugEvent("SwitchStatement", switchKeyword); } @override void handleSymbolVoid(Token token) { debugEvent("SymbolVoid", token); unhandled("SymbolVoid", token); } @override void endThenStatement(Token token) { debugEvent("ThenStatement", token); } @override void handleThisExpression(Token token, IdentifierContext context) { debugEvent("ThisExpression", token); state.pushNull(token.lexeme, token); } @override void handleThrowExpression(Token throwToken, Token endToken) { debugEvent("ThrowExpression", throwToken); state.popPushNull(throwToken.lexeme, throwToken); } @override void endTopLevelDeclaration(Token token) { debugEvent("TopLevelDeclaration", token); state.checkEmpty(token); } @override void endTopLevelFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("TopLevelFields", staticToken); state.discard(count); // Field names. state.checkEmpty(endToken); } @override void beginTopLevelMethod(Token lastConsumed, Token externalToken) { debugEvent("beginTopLevelMethod", lastConsumed.next); state.checkEmpty(lastConsumed.next); } @override void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) { debugEvent("endTopLevelMethod", beginToken); state.pop(); // Method name. state.checkEmpty(endToken); } @override void endTryStatement(int catchCount, Token tryKeyword, Token finallyKeyword) { debugEvent("TryStatement", tryKeyword); } @override void handleType(Token beginToken, Token questionMark) { debugEvent("Type", beginToken); state.pop(); } @override void handleNoType(Token lastConsumed) { debugEvent("NoType", lastConsumed); } @override void endTypeArguments(int count, Token beginToken, Token endToken) { debugEvent("TypeArguments", beginToken); } @override void handleNoTypeArguments(Token token) { debugEvent("NoTypeArguments", token); } @override void endTypeList(int count) { debugEvent("TypeList", null); } @override void endTypeVariable( Token token, int index, Token extendsOrSuper, Token variance) { debugEvent("TypeVariable", token); state.pop(); // Name. } @override void endTypeVariables(Token beginToken, Token endToken) { debugEvent("TypeVariables", beginToken); } @override void handleVarianceModifier(Token variance) { debugEvent("VarianceModifier", variance); } @override void handleNoTypeVariables(Token token) { debugEvent("NoTypeVariables", token); } @override void handleTypeVariablesDefined(Token token, int count) { debugEvent("TypeVariablesDefined", token); } @override void handleUnaryPostfixAssignmentExpression(Token token) { debugEvent("UnaryPostfixAssignmentExpression", token); Builder expr = state.popPushNull(token.lexeme, token); if (expr is UnspecifiedDeclaration) { state.registerWrite(expr, token); } } @override void handleUnaryPrefixAssignmentExpression(Token token) { debugEvent("UnaryPrefixAssignmentExpression", token); Builder expr = state.popPushNull(token.lexeme, token); if (expr is UnspecifiedDeclaration) { state.registerWrite(expr, token); } } @override void handleUnaryPrefixExpression(Token token) { debugEvent("UnaryPrefixExpression", token); state.popPushNull("%UnaryPrefixExpression%", token); } @override void handleNonNullAssertExpression(Token token) { debugEvent("NonNullAssertExpression", token); state.popPushNull("%NonNullAssertExpression%", token); } @override void handleUnescapeError( Message message, Token location, int stringOffset, int length) { debugEvent("UnescapeError", location); unhandled("UnescapeError", location); } @override void handleValuedFormalParameter(Token equals, Token token) { debugEvent("ValuedFormalParameter", equals); } @override void endVariableInitializer(Token assignmentOperator) { debugEvent("VariableInitializer", assignmentOperator); state.pop(); // Initializer. } @override void handleNoVariableInitializer(Token token) { debugEvent("NoVariableInitializer", token); } @override void endVariablesDeclaration(int count, Token endToken) { debugEvent("VariablesDeclaration", endToken); state.discard(count); // Variable names. } @override void handleVoidKeyword(Token token) { debugEvent("VoidKeyword", token); } @override void endWhileStatement(Token whileKeyword, Token endToken) { debugEvent("WhileStatement", whileKeyword); state.pop(); // Condition. } @override void endWhileStatementBody(Token token) { debugEvent("WhileStatementBody", token); } @override void endYieldStatement(Token yieldToken, Token starToken, Token endToken) { debugEvent("YieldStatement", yieldToken); state.pop(); // Expression. } void unhandled(String event, Token token) { problems.unhandled( event, "TypePromotionLookAheadListener", token?.charOffset ?? -1, uri); } }
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/source/stack_listener.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.stack_listener; import 'package:kernel/ast.dart' show AsyncMarker, Expression, FunctionNode, TreeNode; import '../fasta_codes.dart' show Code, LocatedMessage, Message, codeCatchSyntaxExtraParameters, codeNativeClauseShouldBeAnnotation, templateInternalProblemStackNotEmpty; import '../parser.dart' show Listener, MemberKind, Parser, lengthOfSpan, offsetForToken; import '../parser/identifier_context.dart' show IdentifierContext; import '../problems.dart' show internalProblem, unhandled, unimplemented, unsupported; import '../quote.dart' show unescapeString; import '../scanner.dart' show Token; import 'value_kinds.dart'; enum NullValue { Arguments, As, AwaitToken, Block, BreakTarget, CascadeReceiver, Combinators, Comments, ConditionalUris, ConditionallySelectedImport, ConstructorInitializerSeparator, ConstructorInitializers, ConstructorReferenceContinuationAfterTypeArguments, ContinueTarget, Deferred, DocumentationComment, Expression, ExtendsClause, FieldInitializer, FormalParameters, FunctionBody, FunctionBodyAsyncToken, FunctionBodyStarToken, Identifier, IdentifierList, Initializers, Labels, Metadata, Modifiers, Name, ParameterDefaultValue, Prefix, StringLiteral, SwitchScope, Token, Type, TypeArguments, TypeBuilderList, TypeList, TypeVariable, TypeVariables, VarFinalOrConstToken, WithClause, } abstract class StackListener extends Listener { final Stack stack = new Stack(); /// Checks that [value] matches the expected [kind]. /// /// Use this in assert statements like /// /// assert(checkValue(token, ValueKind.Token, value)); /// /// to document and validate the expected value kind. bool checkValue(Token token, ValueKind kind, Object value) { if (!kind.check(value)) { String message = 'Unexpected value `${value}` (${value.runtimeType}). ' 'Expected ${kind}.'; if (token != null) { // If offset is available report and internal problem to show the // parsed code in the output. throw internalProblem( new Message(null, message: message), token.charOffset, uri); } else { throw message; } } return true; } /// Checks the top of the current stack against [kinds]. If a mismatch is /// found, a top of the current stack is print along with the expected [kinds] /// marking the frames that don't match, and throws an exception. /// /// Use this in assert statements like /// /// assert(checkState(token, [ValueKind.Integer, ValueKind.StringOrNull])) /// /// to document the expected stack and get earlier errors on unexpected stack /// content. bool checkState(Token token, List<ValueKind> kinds) { bool success = true; for (int kindIndex = 0; kindIndex < kinds.length; kindIndex++) { int stackIndex = stack.arrayLength - kindIndex - 1; ValueKind kind = kinds[kindIndex]; if (stackIndex >= 0) { Object value = stack.array[stackIndex]; if (!kind.check(value)) { success = false; } } else { success = false; } } if (!success) { StringBuffer sb = new StringBuffer(); String safeToString(Object object) { try { return '$object'; } catch (e) { // Judgments fail on toString. return object.runtimeType.toString(); } } String padLeft(Object object, int length) { String text = safeToString(object); if (text.length < length) { return ' ' * (length - text.length) + text; } return text; } String padRight(Object object, int length) { String text = safeToString(object); if (text.length < length) { return text + ' ' * (length - text.length); } return text; } // Compute kind/stack frame information for all expected values plus 3 more // stack elements if available. for (int kindIndex = 0; kindIndex < kinds.length + 3; kindIndex++) { int stackIndex = stack.arrayLength - kindIndex - 1; if (stackIndex < 0 && kindIndex >= kinds.length) { // No more stack elements nor kinds to display. break; } sb.write(padLeft(kindIndex, 4)); sb.write(': '); ValueKind kind; if (kindIndex < kinds.length) { kind = kinds[kindIndex]; sb.write(padRight(kind, 60)); } else { sb.write(padRight('---', 60)); } if (stackIndex >= 0) { Object value = stack.array[stackIndex]; if (kind == null || kind.check(value)) { sb.write(' '); } else { sb.write('*'); } sb.write(safeToString(value)); sb.write(' (${value.runtimeType})'); } else { if (kind == null) { sb.write(' '); } else { sb.write('*'); } sb.write('---'); } sb.writeln(); } String message = '$runtimeType failure\n$sb'; if (token != null) { // If offset is available report and internal problem to show the // parsed code in the output. throw internalProblem( new Message(null, message: message), token.charOffset, uri); } else { throw message; } } return success; } @override Uri get uri; void discard(int n) { for (int i = 0; i < n; i++) { pop(); } } // TODO(ahe): This doesn't belong here. Only implemented by body_builder.dart // and ast_builder.dart. void finishFunction( covariant formals, AsyncMarker asyncModifier, covariant body) { return unsupported("finishFunction", -1, uri); } // TODO(ahe): This doesn't belong here. Only implemented by body_builder.dart // and ast_builder.dart. dynamic finishFields() { return unsupported("finishFields", -1, uri); } // TODO(ahe): This doesn't belong here. Only implemented by body_builder.dart // and ast_builder.dart. List<Expression> finishMetadata(TreeNode parent) { return unsupported("finishMetadata", -1, uri); } // TODO(ahe): This doesn't belong here. Only implemented by body_builder.dart // and ast_builder.dart. void exitLocalScope() => unsupported("exitLocalScope", -1, uri); // TODO(ahe): This doesn't belong here. Only implemented by body_builder.dart. dynamic parseSingleExpression( Parser parser, Token token, FunctionNode parameters) { return unsupported("finishSingleExpression", -1, uri); } void push(Object node) { if (node == null) unhandled("null", "push", -1, uri); stack.push(node); } void pushIfNull(Token tokenOrNull, NullValue nullValue) { if (tokenOrNull == null) stack.push(nullValue); } Object peek() => stack.isNotEmpty ? stack.last : null; Object pop([NullValue nullValue]) { return stack.pop(nullValue); } Object popIfNotNull(Object value) { return value == null ? null : pop(); } void debugEvent(String name) { // printEvent(name); } void printEvent(String name) { print('\n------------------'); for (Object o in stack.values) { String s = " $o"; int index = s.indexOf("\n"); if (index != -1) { s = s.substring(0, index) + "..."; } print(s); } print(" >> $name"); } @override void logEvent(String name) { printEvent(name); unhandled(name, "$runtimeType", -1, uri); } @override void handleIdentifier(Token token, IdentifierContext context) { debugEvent("handleIdentifier"); if (!token.isSynthetic) { push(token.lexeme); } else { // This comes from a synthetic token which is inserted by the parser in // an attempt to recover. This almost always means that the parser has // gotten very confused and we need to ignore the results. push(new ParserRecovery(token.charOffset)); } } @override void handleNoName(Token token) { debugEvent("NoName"); push(NullValue.Identifier); } @override void endInitializer(Token token) { debugEvent("Initializer"); } void checkEmpty(int charOffset) { if (stack.isNotEmpty) { internalProblem( templateInternalProblemStackNotEmpty.withArguments( "${runtimeType}", stack.values.join("\n ")), charOffset, uri); } } @override void endTopLevelDeclaration(Token token) { debugEvent("TopLevelDeclaration"); checkEmpty(token.charOffset); } @override void endCompilationUnit(int count, Token token) { debugEvent("CompilationUnit"); checkEmpty(token.charOffset); } @override void handleClassExtends(Token extendsKeyword) { debugEvent("ClassExtends"); } @override void handleMixinOn(Token onKeyword, int typeCount) { debugEvent("MixinOn"); } @override void handleClassHeader(Token begin, Token classKeyword, Token nativeToken) { debugEvent("ClassHeader"); } @override void handleMixinHeader(Token mixinKeyword) { debugEvent("MixinHeader"); } @override void handleRecoverClassHeader() { debugEvent("RecoverClassHeader"); } @override void handleRecoverMixinHeader() { debugEvent("RecoverMixinHeader"); } @override void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { debugEvent("ClassImplements"); } @override void handleNoTypeArguments(Token token) { debugEvent("NoTypeArguments"); push(NullValue.TypeArguments); } @override void handleNoTypeVariables(Token token) { debugEvent("NoTypeVariables"); push(NullValue.TypeVariables); } @override void handleNoConstructorReferenceContinuationAfterTypeArguments(Token token) { debugEvent("NoConstructorReferenceContinuationAfterTypeArguments"); } @override void handleNoType(Token lastConsumed) { debugEvent("NoType"); push(NullValue.Type); } @override void handleNoFormalParameters(Token token, MemberKind kind) { debugEvent("NoFormalParameters"); push(NullValue.FormalParameters); } @override void handleNoArguments(Token token) { debugEvent("NoArguments"); push(NullValue.Arguments); } @override void handleNativeFunctionBody(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBody"); push(NullValue.FunctionBody); } @override void handleNativeFunctionBodyIgnored(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBodyIgnored"); } @override void handleNativeFunctionBodySkipped(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBodySkipped"); } @override void handleNoFunctionBody(Token token) { debugEvent("NoFunctionBody"); push(NullValue.FunctionBody); } @override void handleNoInitializers() { debugEvent("NoInitializers"); push(NullValue.Initializers); } @override void handleParenthesizedCondition(Token token) { debugEvent("handleParenthesizedCondition"); } @override void handleParenthesizedExpression(Token token) { debugEvent("ParenthesizedExpression"); } @override void beginLiteralString(Token token) { debugEvent("beginLiteralString"); push(token); } @override void endLiteralString(int interpolationCount, Token endToken) { debugEvent("endLiteralString"); if (interpolationCount == 0) { Token token = pop(); push(unescapeString(token.lexeme, token, this)); } else { unimplemented("string interpolation", endToken.charOffset, uri); } } @override void handleNativeClause(Token nativeToken, bool hasName) { debugEvent("NativeClause"); if (hasName) { pop(); // Pop the native name which is a String. } } @override void handleDirectivesOnly() { pop(); // Discard the metadata. } void handleExtraneousExpression(Token token, Message message) { debugEvent("ExtraneousExpression"); pop(); // Discard the extraneous expression. } @override void endCaseExpression(Token colon) { debugEvent("CaseExpression"); } @override void endCatchClause(Token token) { debugEvent("CatchClause"); } @override void handleRecoverableError( Message message, Token startToken, Token endToken) { debugEvent("Error: ${message.message}"); if (isIgnoredError(message.code, startToken)) return; addProblem(message, offsetForToken(startToken), lengthOfSpan(startToken, endToken)); } bool isIgnoredError(Code<dynamic> code, Token token) { if (code == codeNativeClauseShouldBeAnnotation) { // TODO(danrubel): Ignore this error until we deprecate `native` // support. return true; } else if (code == codeCatchSyntaxExtraParameters) { // Ignored. This error is handled by the BodyBuilder. return true; } else { return false; } } @override void handleUnescapeError( Message message, Token token, int stringOffset, int length) { addProblem(message, token.charOffset + stringOffset, length); } void addProblem(Message message, int charOffset, int length, {bool wasHandled: false, List<LocatedMessage> context}); } class Stack { List<Object> array = new List<Object>(8); int arrayLength = 0; bool get isNotEmpty => arrayLength > 0; int get length => arrayLength; Object get last { final Object value = array[arrayLength - 1]; return value is NullValue ? null : value; } void push(Object value) { array[arrayLength++] = value; if (array.length == arrayLength) { _grow(); } } Object pop(NullValue nullValue) { assert(arrayLength > 0); final Object value = array[--arrayLength]; array[arrayLength] = null; if (value is! NullValue) { return value; } else if (nullValue == null || value == nullValue) { return null; } else { return value; } } List<Object> popList(int count, List<Object> list, NullValue nullValue) { assert(arrayLength >= count); final List<Object> array = this.array; final int length = arrayLength; final int startIndex = length - count; bool isParserRecovery = false; for (int i = 0; i < count; i++) { int arrayIndex = startIndex + i; final Object value = array[arrayIndex]; array[arrayIndex] = null; if (value is NullValue && nullValue == null || identical(value, nullValue)) { list[i] = null; } else if (value is ParserRecovery) { isParserRecovery = true; } else { if (value is NullValue) { print(value); } list[i] = value; } } arrayLength -= count; return isParserRecovery ? null : list; } List<Object> get values { final int length = arrayLength; final List<Object> list = new List<Object>(length); list.setRange(0, length, array); return list; } void _grow() { final int length = array.length; final List<Object> newArray = new List<Object>(length * 2); newArray.setRange(0, length, array, 0); array = newArray; } } /// Helper constant for popping a list of the top of a [Stack]. This helper /// returns null instead of empty lists, and the lists returned are of fixed /// length. class FixedNullableList<T> { const FixedNullableList(); List<T> pop(Stack stack, int count, [NullValue nullValue]) { if (count == 0) return null; return stack.popList(count, new List<T>(count), nullValue); } List<T> popPadded(Stack stack, int count, int padding, [NullValue nullValue]) { if (count + padding == 0) return null; return stack.popList(count, new List<T>(count + padding), nullValue); } } /// Helper constant for popping a list of the top of a [Stack]. This helper /// returns growable lists (also when empty). class GrowableList<T> { const GrowableList(); List<T> pop(Stack stack, int count, [NullValue nullValue]) { return stack.popList( count, new List<T>.filled(count, null, growable: true), nullValue); } } class ParserRecovery { final int charOffset; ParserRecovery(this.charOffset); String toString() => "ParserRecovery(@$charOffset)"; }
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/source/directive_listener.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. /// Listener used in combination with `TopLevelParser` to extract the URIs of /// import, part, and export directives. library front_end.src.fasta.source.directive_listener; import '../../scanner/token.dart' show Token; import '../fasta_codes.dart' show messageExpectedBlockToSkip; import '../parser/identifier_context.dart'; import '../parser/listener.dart'; import '../quote.dart'; /// Listener that records imports, exports, and part directives. /// /// This is normally used in combination with the `TopLevelParser`, which skips /// over the body of declarations like classes and function that are irrelevant /// for directives. Note that on correct programs directives cannot occur after /// any top-level declaration, but we recommend to continue parsing the entire /// file in order to gracefully handle input errors. class DirectiveListener extends Listener { /// Import directives with URIs and combinators. final List<NamespaceDirective> imports = <NamespaceDirective>[]; /// Export directives with URIs and combinators. final List<NamespaceDirective> exports = <NamespaceDirective>[]; /// Collects URIs that occur on any part directive. final Set<String> parts = new Set<String>(); bool _inPart = false; String _uri; List<NamespaceCombinator> _combinators; List<String> _combinatorNames; DirectiveListener(); @override beginExport(Token export) { _combinators = <NamespaceCombinator>[]; } @override void beginHide(Token hide) { _combinatorNames = <String>[]; } @override beginImport(Token import) { _combinators = <NamespaceCombinator>[]; } @override void beginLiteralString(Token token) { if (_combinators != null || _inPart) { _uri = unescapeString(token.lexeme, token, this); } } @override beginPart(Token part) { _inPart = true; } @override void beginShow(Token show) { _combinatorNames = <String>[]; } @override endExport(Token export, Token semicolon) { exports.add(new NamespaceDirective.export(_uri, _combinators)); _uri = null; _combinators = null; } @override void endHide(Token hide) { _combinators.add(new NamespaceCombinator.hide(_combinatorNames)); _combinatorNames = null; } @override endImport(Token import, Token semicolon) { imports.add(new NamespaceDirective.import(_uri, _combinators)); _uri = null; _combinators = null; } @override endPart(Token part, Token semicolon) { parts.add(_uri); _uri = null; _inPart = false; } @override void endShow(Token show) { _combinators.add(new NamespaceCombinator.show(_combinatorNames)); _combinatorNames = null; } @override void handleIdentifier(Token token, IdentifierContext context) { if (_combinatorNames != null && context == IdentifierContext.combinator) { _combinatorNames.add(token.lexeme); } } /// By default, native clauses are not handled and an error is thrown. @override void handleNativeFunctionBodySkipped(Token nativeToken, Token semicolon) { super.handleRecoverableError( messageExpectedBlockToSkip, nativeToken, nativeToken); } } class NamespaceCombinator { final bool isShow; final Set<String> names; NamespaceCombinator.hide(List<String> names) : isShow = false, names = names.toSet(); NamespaceCombinator.show(List<String> names) : isShow = true, names = names.toSet(); } class NamespaceDirective { final bool isImport; final String uri; final List<NamespaceCombinator> combinators; NamespaceDirective.export(this.uri, this.combinators) : isImport = false; NamespaceDirective.import(this.uri, this.combinators) : isImport = true; }
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/source/source_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.source_class_builder; import 'package:kernel/ast.dart' show Class, Constructor, Member, Supertype, TreeNode; import '../builder/class_builder.dart'; import '../dill/dill_member_builder.dart' show DillMemberBuilder; import '../fasta_codes.dart' show Message, noLength, templateBadTypeVariableInSupertype, templateConflictsWithConstructor, templateConflictsWithFactory, templateConflictsWithMember, templateConflictsWithMemberWarning, templateConflictsWithSetter, templateConflictsWithSetterWarning, templateSupertypeIsIllegal; import '../kernel/kernel_builder.dart' show ConstructorReferenceBuilder, Builder, FieldBuilder, FunctionBuilder, InvalidTypeBuilder, NamedTypeBuilder, LibraryBuilder, MetadataBuilder, NullabilityBuilder, Scope, TypeBuilder, TypeVariableBuilder, compareProcedures; import '../kernel/type_algorithms.dart' show Variance, computeVariance; import '../problems.dart' show unexpected, unhandled; import 'source_library_builder.dart' show SourceLibraryBuilder; Class initializeClass( Class cls, List<TypeVariableBuilder> typeVariables, String name, SourceLibraryBuilder parent, int startCharOffset, int charOffset, int charEndOffset) { cls ??= new Class( name: name, typeParameters: TypeVariableBuilder.typeParametersFromBuilders(typeVariables)); cls.fileUri ??= parent.fileUri; if (cls.startFileOffset == TreeNode.noOffset) { cls.startFileOffset = startCharOffset; } if (cls.fileOffset == TreeNode.noOffset) { cls.fileOffset = charOffset; } if (cls.fileEndOffset == TreeNode.noOffset) { cls.fileEndOffset = charEndOffset; } return cls; } class SourceClassBuilder extends ClassBuilderImpl implements Comparable<SourceClassBuilder> { @override final Class actualCls; final List<ConstructorReferenceBuilder> constructorReferences; TypeBuilder mixedInType; bool isMixinDeclaration; SourceClassBuilder( List<MetadataBuilder> metadata, int modifiers, String name, List<TypeVariableBuilder> typeVariables, TypeBuilder supertype, List<TypeBuilder> interfaces, List<TypeBuilder> onTypes, Scope scope, Scope constructors, LibraryBuilder parent, this.constructorReferences, int startCharOffset, int nameOffset, int charEndOffset, {Class cls, this.mixedInType, this.isMixinDeclaration = false}) : actualCls = initializeClass(cls, typeVariables, name, parent, startCharOffset, nameOffset, charEndOffset), super(metadata, modifiers, name, typeVariables, supertype, interfaces, onTypes, scope, constructors, parent, nameOffset); @override Class get cls => origin.actualCls; @override SourceLibraryBuilder get library => super.library; Class build(SourceLibraryBuilder library, LibraryBuilder coreLibrary) { void buildBuilders(String name, Builder declaration) { do { if (declaration.parent != this) { if (fileUri != declaration.parent.fileUri) { unexpected("$fileUri", "${declaration.parent.fileUri}", charOffset, fileUri); } else { unexpected(fullNameForErrors, declaration.parent?.fullNameForErrors, charOffset, fileUri); } } else if (declaration is FieldBuilder) { // TODO(ahe): It would be nice to have a common interface for the // build method to avoid duplicating these two cases. Member field = declaration.build(library); if (!declaration.isPatch && declaration.next == null) { cls.addMember(field); } } else if (declaration is FunctionBuilder) { Member member = declaration.build(library); member.parent = cls; if (!declaration.isPatch && declaration.next == null) { cls.addMember(member); } } else { unhandled("${declaration.runtimeType}", "buildBuilders", declaration.charOffset, declaration.fileUri); } declaration = declaration.next; } while (declaration != null); } scope.forEach(buildBuilders); constructors.forEach(buildBuilders); supertype = checkSupertype(supertype); actualCls.supertype = supertype?.buildSupertype(library, charOffset, fileUri); if (!isMixinDeclaration && actualCls.supertype != null && actualCls.superclass.isMixinDeclaration) { // Declared mixins have interfaces that can be implemented, but they // cannot be extended. However, a mixin declaration with a single // superclass constraint is encoded with the constraint as the supertype, // and that is allowed to be a mixin's interface. library.addProblem( templateSupertypeIsIllegal.withArguments(actualCls.superclass.name), charOffset, noLength, fileUri); actualCls.supertype = null; } if (actualCls.supertype == null && supertype is! NamedTypeBuilder) { supertype = null; } mixedInType = checkSupertype(mixedInType); actualCls.mixedInType = mixedInType?.buildMixedInType(library, charOffset, fileUri); if (actualCls.mixedInType == null && mixedInType is! NamedTypeBuilder) { mixedInType = null; } actualCls.isMixinDeclaration = isMixinDeclaration; // TODO(ahe): If `cls.supertype` is null, and this isn't Object, report a // compile-time error. cls.isAbstract = isAbstract; if (interfaces != null) { for (int i = 0; i < interfaces.length; ++i) { interfaces[i] = checkSupertype(interfaces[i]); Supertype supertype = interfaces[i].buildSupertype(library, charOffset, fileUri); if (supertype != null) { // TODO(ahe): Report an error if supertype is null. actualCls.implementedTypes.add(supertype); } } } constructors.forEach((String name, Builder constructor) { Builder member = scopeBuilder[name]; if (member == null) return; if (!member.isStatic) return; // TODO(ahe): Revisit these messages. It seems like the last two should // be `context` parameter to this message. addProblem(templateConflictsWithMember.withArguments(name), constructor.charOffset, noLength); if (constructor.isFactory) { addProblem( templateConflictsWithFactory.withArguments("${this.name}.${name}"), member.charOffset, noLength); } else { addProblem( templateConflictsWithConstructor .withArguments("${this.name}.${name}"), member.charOffset, noLength); } }); scope.setters.forEach((String name, Builder setter) { Builder member = scopeBuilder[name]; if (member == null || !(member.isField && !member.isFinal && !member.isConst || member.isRegularMethod && member.isStatic && setter.isStatic)) { return; } if (member.isDeclarationInstanceMember == setter.isDeclarationInstanceMember) { addProblem(templateConflictsWithMember.withArguments(name), setter.charOffset, noLength); // TODO(ahe): Context argument to previous message? addProblem(templateConflictsWithSetter.withArguments(name), member.charOffset, noLength); } else { addProblem(templateConflictsWithMemberWarning.withArguments(name), setter.charOffset, noLength); // TODO(ahe): Context argument to previous message? addProblem(templateConflictsWithSetterWarning.withArguments(name), member.charOffset, noLength); } }); scope.setters.forEach((String name, Builder setter) { Builder constructor = constructorScopeBuilder[name]; if (constructor == null || !setter.isStatic) return; addProblem(templateConflictsWithConstructor.withArguments(name), setter.charOffset, noLength); addProblem(templateConflictsWithSetter.withArguments(name), constructor.charOffset, noLength); }); cls.procedures.sort(compareProcedures); return cls; } TypeBuilder checkSupertype(TypeBuilder supertype) { if (typeVariables == null || supertype == null) return supertype; Message message; for (int i = 0; i < typeVariables.length; ++i) { int variance = computeVariance(typeVariables[i], supertype); if (variance == Variance.contravariant || variance == Variance.invariant) { message = templateBadTypeVariableInSupertype.withArguments( typeVariables[i].name, supertype.name); library.addProblem(message, charOffset, noLength, fileUri); } } if (message != null) { return new NamedTypeBuilder( supertype.name, const NullabilityBuilder.omitted(), null) ..bind(new InvalidTypeBuilder(supertype.name, message.withLocation(fileUri, charOffset, noLength))); } return supertype; } void addSyntheticConstructor(Constructor constructor) { String name = constructor.name.name; cls.constructors.add(constructor); constructor.parent = cls; DillMemberBuilder memberBuilder = new DillMemberBuilder(constructor, this); memberBuilder.next = constructorScopeBuilder[name]; constructorScopeBuilder.addMember(name, memberBuilder); } @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 cls.annotations.forEach((m) => m.fileOffset = origin.cls.fileOffset); int count = 0; scope.forEach((String name, Builder declaration) { count += declaration.finishPatch(); }); constructors.forEach((String name, Builder declaration) { count += declaration.finishPatch(); }); return count; } List<Builder> computeDirectSupertypes(ClassBuilder objectClass) { final List<Builder> result = <Builder>[]; final TypeBuilder supertype = this.supertype; if (supertype != null) { result.add(supertype.declaration); } else if (objectClass != this) { result.add(objectClass); } final List<TypeBuilder> interfaces = this.interfaces; if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { TypeBuilder interface = interfaces[i]; result.add(interface.declaration); } } final TypeBuilder mixedInType = this.mixedInType; if (mixedInType != null) { result.add(mixedInType.declaration); } return result; } @override int compareTo(SourceClassBuilder other) { int result = "$fileUri".compareTo("${other.fileUri}"); if (result != 0) return result; return charOffset.compareTo(other.charOffset); } }
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/source/diet_parser.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.diet_parser; import '../../scanner/token.dart' show Token; import '../parser.dart' show ClassMemberParser, Listener, MemberKind; // TODO(ahe): Move this to parser package. class DietParser extends ClassMemberParser { DietParser(Listener listener) : super(listener); Token parseFormalParametersRest(Token token, MemberKind kind) { return skipFormalParametersRest(token, kind); } }
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/source/source_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.source_loader; import 'dart:async' show Future; import 'dart:convert' show utf8; import 'dart:typed_data' show Uint8List; import 'package:kernel/ast.dart' show Arguments, BottomType, Class, Component, DartType, Expression, FunctionNode, InterfaceType, Library, LibraryDependency, ProcedureKind, Supertype, TreeNode; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy, HandleAmbiguousSupertypes; import 'package:kernel/core_types.dart' show CoreTypes; import '../../api_prototype/file_system.dart'; import '../../base/instrumentation.dart' show Instrumentation; import '../blacklisted_classes.dart' show blacklistedCoreClasses; import '../builder/extension_builder.dart'; import '../export.dart' show Export; import '../import.dart' show Import; import '../fasta_codes.dart' show LocatedMessage, Message, SummaryTemplate, Template, messageObjectExtends, messageObjectImplements, messageObjectMixesIn, messagePartOrphan, noLength, templateAmbiguousSupertypes, templateCantReadFile, templateCyclicClassHierarchy, templateDuplicatedLibraryExport, templateDuplicatedLibraryExportContext, templateDuplicatedLibraryImport, templateDuplicatedLibraryImportContext, templateExtendingEnum, templateExtendingRestricted, templateIllegalMixin, templateIllegalMixinDueToConstructors, templateIllegalMixinDueToConstructorsCause, templateInternalProblemUriMissingScheme, templateSourceOutlineSummary, templateUntranslatableUri; import '../kernel/kernel_shadow_ast.dart' show ShadowTypeInferenceEngine; import '../kernel/kernel_builder.dart' show ClassBuilder, ClassHierarchyBuilder, Builder, DelayedMember, DelayedOverrideCheck, EnumBuilder, FieldBuilder, ProcedureBuilder, LibraryBuilder, MemberBuilder, NamedTypeBuilder, TypeBuilder, TypeDeclarationBuilder; import '../kernel/kernel_target.dart' show KernelTarget; import '../kernel/body_builder.dart' show BodyBuilder; import '../kernel/transform_collections.dart' show CollectionTransformer; import '../kernel/transform_set_literals.dart' show SetLiteralTransformer; import '../kernel/type_builder_computer.dart' show TypeBuilderComputer; import '../loader.dart' show Loader, untranslatableUriScheme; import '../parser/class_member_parser.dart' show ClassMemberParser; import '../parser.dart' show Parser, lengthForToken, offsetForToken; import '../problems.dart' show internalProblem; import '../scanner.dart' show ErrorToken, LanguageVersionToken, ScannerConfiguration, ScannerResult, Token, scan; import '../type_inference/type_inferrer.dart'; import 'diet_listener.dart' show DietListener; import 'diet_parser.dart' show DietParser; import 'outline_builder.dart' show OutlineBuilder; import 'source_class_builder.dart' show SourceClassBuilder; import 'source_library_builder.dart' show SourceLibraryBuilder; class SourceLoader extends Loader { /// The [FileSystem] which should be used to access files. final FileSystem fileSystem; /// Whether comments should be scanned and parsed. final bool includeComments; final Map<Uri, List<int>> sourceBytes = <Uri, List<int>>{}; ClassHierarchyBuilder builderHierarchy; // Used when building directly to kernel. ClassHierarchy hierarchy; CoreTypes coreTypes; // Used when checking whether a return type of an async function is valid. DartType futureOfBottom; DartType iterableOfBottom; DartType streamOfBottom; ShadowTypeInferenceEngine typeInferenceEngine; Instrumentation instrumentation; CollectionTransformer collectionTransformer; SetLiteralTransformer setLiteralTransformer; SourceLoader(this.fileSystem, this.includeComments, KernelTarget target) : super(target); Template<SummaryTemplate> get outlineSummaryTemplate => templateSourceOutlineSummary; bool get isSourceLoader => true; Future<Token> tokenize(SourceLibraryBuilder library, {bool suppressLexicalErrors: false}) async { Uri uri = library.fileUri; // Lookup the file URI in the cache. List<int> bytes = sourceBytes[uri]; if (bytes == null) { // Error recovery. if (uri.scheme == untranslatableUriScheme) { Message message = templateUntranslatableUri.withArguments(library.uri); library.addProblemAtAccessors(message); bytes = synthesizeSourceForMissingFile(library.uri, null); } else if (!uri.hasScheme) { return internalProblem( templateInternalProblemUriMissingScheme.withArguments(uri), -1, library.uri); } else if (uri.scheme == SourceLibraryBuilder.MALFORMED_URI_SCHEME) { bytes = synthesizeSourceForMissingFile(library.uri, null); } if (bytes != null) { Uint8List zeroTerminatedBytes = new Uint8List(bytes.length + 1); zeroTerminatedBytes.setRange(0, bytes.length, bytes); bytes = zeroTerminatedBytes; sourceBytes[uri] = bytes; } } if (bytes == null) { // If it isn't found in the cache, read the file read from the file // system. List<int> rawBytes; try { rawBytes = await fileSystem.entityForUri(uri).readAsBytes(); } on FileSystemException catch (e) { Message message = templateCantReadFile.withArguments(uri, e.message); library.addProblemAtAccessors(message); rawBytes = synthesizeSourceForMissingFile(library.uri, message); } Uint8List zeroTerminatedBytes = new Uint8List(rawBytes.length + 1); zeroTerminatedBytes.setRange(0, rawBytes.length, rawBytes); bytes = zeroTerminatedBytes; sourceBytes[uri] = bytes; byteCount += rawBytes.length; } ScannerResult result = scan(bytes, includeComments: includeComments, configuration: new ScannerConfiguration( enableTripleShift: target.enableTripleShift, enableExtensionMethods: target.enableExtensionMethods, enableNonNullable: target.enableNonNullable), languageVersionChanged: (_, LanguageVersionToken version) { library.setLanguageVersion(version.major, version.minor, offset: version.offset, length: version.length, explicit: true); }); Token token = result.tokens; if (!suppressLexicalErrors) { List<int> source = getSource(bytes); Uri importUri = library.uri; if (library.isPatch) { // For patch files we create a "fake" import uri. // We cannot use the import uri from the patched library because // several different files would then have the same import uri, // and the VM does not support that. Also, what would, for instance, // setting a breakpoint on line 42 of some import uri mean, if the uri // represented several files? List<String> newPathSegments = new List<String>.from(importUri.pathSegments); newPathSegments.add(library.fileUri.pathSegments.last); newPathSegments[0] = "${newPathSegments[0]}-patch"; importUri = importUri.replace(pathSegments: newPathSegments); } target.addSourceInformation( importUri, library.fileUri, result.lineStarts, source); } library.issuePostponedProblems(); while (token is ErrorToken) { if (!suppressLexicalErrors) { ErrorToken error = token; library.addProblem(error.assertionMessage, offsetForToken(token), lengthForToken(token), uri); } token = token.next; } return token; } List<int> synthesizeSourceForMissingFile(Uri uri, Message message) { switch ("$uri") { case "dart:core": return utf8.encode(defaultDartCoreSource); case "dart:async": return utf8.encode(defaultDartAsyncSource); case "dart:collection": return utf8.encode(defaultDartCollectionSource); case "dart:_internal": return utf8.encode(defaultDartInternalSource); case "dart:typed_data": return utf8.encode(defaultDartTypedDataSource); default: return utf8.encode(message == null ? "" : "/* ${message.message} */"); } } List<int> getSource(List<int> bytes) { // bytes is 0-terminated. We don't want that included. if (bytes is Uint8List) { return new Uint8List.view( bytes.buffer, bytes.offsetInBytes, bytes.length - 1); } return bytes.sublist(0, bytes.length - 1); } Future<Null> buildOutline(SourceLibraryBuilder library) async { Token tokens = await tokenize(library); if (tokens == null) return; OutlineBuilder listener = new OutlineBuilder(library); new ClassMemberParser(listener).parseUnit(tokens); } Future<Null> buildBody(LibraryBuilder library) async { if (library is SourceLibraryBuilder) { // We tokenize source files twice to keep memory usage low. This is the // second time, and the first time was in [buildOutline] above. So this // time we suppress lexical errors. Token tokens = await tokenize(library, suppressLexicalErrors: true); if (tokens == null) return; DietListener listener = createDietListener(library); DietParser parser = new DietParser(listener); parser.parseUnit(tokens); for (SourceLibraryBuilder part in library.parts) { if (part.partOfLibrary != library) { // Part was included in multiple libraries. Skip it here. continue; } Token tokens = await tokenize(part); if (tokens != null) { listener.uri = part.fileUri; parser.parseUnit(tokens); } } } } // TODO(johnniwinther,jensj): Handle expression in extensions? Future<Expression> buildExpression( SourceLibraryBuilder library, String enclosingClass, bool isClassInstanceMember, FunctionNode parameters) async { Token token = await tokenize(library, suppressLexicalErrors: false); if (token == null) return null; DietListener dietListener = createDietListener(library); Builder parent = library; if (enclosingClass != null) { Builder cls = dietListener.memberScope.lookup(enclosingClass, -1, null); if (cls is ClassBuilder) { parent = cls; dietListener ..currentDeclaration = cls ..memberScope = cls.scope.copyWithParent( dietListener.memberScope.withTypeVariables(cls.typeVariables), "debugExpression in $enclosingClass"); } } ProcedureBuilder builder = new ProcedureBuilder(null, 0, null, "debugExpr", null, null, ProcedureKind.Method, library, 0, 0, -1, -1) ..parent = parent; BodyBuilder listener = dietListener.createListener( builder, dietListener.memberScope, isDeclarationInstanceMember: isClassInstanceMember); return listener.parseSingleExpression( new Parser(listener), token, parameters); } KernelTarget get target => super.target; DietListener createDietListener(SourceLibraryBuilder library) { return new DietListener(library, hierarchy, coreTypes, typeInferenceEngine); } void resolveParts() { List<Uri> parts = <Uri>[]; List<SourceLibraryBuilder> libraries = <SourceLibraryBuilder>[]; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { if (library.isPart) { parts.add(uri); } else { libraries.add(library); } } }); Set<Uri> usedParts = new Set<Uri>(); for (SourceLibraryBuilder library in libraries) { library.includeParts(usedParts); } for (Uri uri in parts) { if (usedParts.contains(uri)) { builders.remove(uri); } else { SourceLibraryBuilder part = builders[uri]; part.addProblem(messagePartOrphan, 0, 1, part.fileUri); part.validatePart(null, null); } } ticker.logMs("Resolved parts"); builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { library.applyPatches(); } }); ticker.logMs("Applied patches"); } void computeLibraryScopes() { Set<LibraryBuilder> exporters = new Set<LibraryBuilder>(); Set<LibraryBuilder> exportees = new Set<LibraryBuilder>(); builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { SourceLibraryBuilder sourceLibrary = library; sourceLibrary.buildInitialScopes(); } if (library.exporters.isNotEmpty) { exportees.add(library); for (Export exporter in library.exporters) { exporters.add(exporter.exporter); } } }); Set<SourceLibraryBuilder> both = new Set<SourceLibraryBuilder>(); for (LibraryBuilder exported in exportees) { if (exporters.contains(exported)) { both.add(exported); } for (Export export in exported.exporters) { exported.exportScope.forEach(export.addToExportScope); } } bool wasChanged = false; do { wasChanged = false; for (SourceLibraryBuilder exported in both) { for (Export export in exported.exporters) { exported.exportScope.forEach((String name, Builder member) { if (export.addToExportScope(name, member)) { wasChanged = true; } }); } } } while (wasChanged); builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { SourceLibraryBuilder sourceLibrary = library; sourceLibrary.addImportsToScope(); } }); for (LibraryBuilder exportee in exportees) { // TODO(ahe): Change how we track exporters. Currently, when a library // (exporter) exports another library (exportee) we add a reference to // exporter to exportee. This creates a reference in the wrong direction // and can lead to memory leaks. exportee.exporters.clear(); } ticker.logMs("Computed library scopes"); // debugPrintExports(); } void debugPrintExports() { // TODO(sigmund): should be `covariant SourceLibraryBuilder`. builders.forEach((Uri uri, dynamic l) { SourceLibraryBuilder library = l; Set<Builder> members = new Set<Builder>(); Iterator<Builder> iterator = library.iterator; while (iterator.moveNext()) { members.add(iterator.current); } List<String> exports = <String>[]; library.exportScope.forEach((String name, Builder member) { while (member != null) { if (!members.contains(member)) { exports.add(name); } member = member.next; } }); if (exports.isNotEmpty) { print("$uri exports $exports"); } }); } void resolveTypes() { int typeCount = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { SourceLibraryBuilder sourceLibrary = library; typeCount += sourceLibrary.resolveTypes(); } }); ticker.logMs("Resolved $typeCount types"); } void finishDeferredLoadTearoffs() { int count = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { count += library.finishDeferredLoadTearoffs(); } }); ticker.logMs("Finished deferred load tearoffs $count"); } void finishNoSuchMethodForwarders() { int count = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { count += library.finishForwarders(); } }); ticker.logMs("Finished forwarders for $count procedures"); } void resolveConstructors() { int count = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { count += library.resolveConstructors(null); } }); ticker.logMs("Resolved $count constructors"); } void finishTypeVariables(ClassBuilder object, TypeBuilder dynamicType) { int count = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { count += library.finishTypeVariables(object, dynamicType); } }); ticker.logMs("Resolved $count type-variable bounds"); } void computeDefaultTypes(TypeBuilder dynamicType, TypeBuilder bottomType, ClassBuilder objectClass) { int count = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { count += library.computeDefaultTypes(dynamicType, bottomType, objectClass); } }); ticker.logMs("Computed default types for $count type variables"); } void finishNativeMethods() { int count = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { count += library.finishNativeMethods(); } }); ticker.logMs("Finished $count native methods"); } void finishPatchMethods() { int count = 0; builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { count += library.finishPatchMethods(); } }); ticker.logMs("Finished $count patch methods"); } /// Check that [objectClass] has no supertypes. Recover by removing any /// found. void checkObjectClassHierarchy(ClassBuilder objectClass) { if (objectClass is SourceClassBuilder && objectClass.library.loader == this) { if (objectClass.supertype != null) { objectClass.supertype = null; objectClass.addProblem( messageObjectExtends, objectClass.charOffset, noLength); } if (objectClass.interfaces != null) { objectClass.addProblem( messageObjectImplements, objectClass.charOffset, noLength); objectClass.interfaces = null; } if (objectClass.mixedInType != null) { objectClass.addProblem( messageObjectMixesIn, objectClass.charOffset, noLength); objectClass.mixedInType = null; } } } /// Returns a list of all class builders declared in this loader. As the /// classes are sorted, any cycles in the hierarchy are reported as /// errors. Recover by breaking the cycles. This means that the rest of the /// pipeline (including backends) can assume that there are no hierarchy /// cycles. List<SourceClassBuilder> handleHierarchyCycles(ClassBuilder objectClass) { // Compute the initial work list of all classes declared in this loader. List<SourceClassBuilder> workList = <SourceClassBuilder>[]; for (LibraryBuilder library in builders.values) { if (library.loader == this) { Iterator<Builder> members = library.iterator; while (members.moveNext()) { Builder member = members.current; if (member is SourceClassBuilder) { workList.add(member); } } } } Set<ClassBuilder> blackListedClasses = new Set<ClassBuilder>(); for (int i = 0; i < blacklistedCoreClasses.length; i++) { blackListedClasses.add(coreLibrary .lookupLocalMember(blacklistedCoreClasses[i], required: true)); } // Sort the classes topologically. Set<SourceClassBuilder> topologicallySortedClasses = new Set<SourceClassBuilder>(); List<SourceClassBuilder> previousWorkList; do { previousWorkList = workList; workList = <SourceClassBuilder>[]; for (int i = 0; i < previousWorkList.length; i++) { SourceClassBuilder cls = previousWorkList[i]; List<Builder> directSupertypes = cls.computeDirectSupertypes(objectClass); bool allSupertypesProcessed = true; for (int i = 0; i < directSupertypes.length; i++) { Builder supertype = directSupertypes[i]; if (supertype is SourceClassBuilder && supertype.library.loader == this && !topologicallySortedClasses.contains(supertype)) { allSupertypesProcessed = false; break; } } if (allSupertypesProcessed && cls.isPatch) { allSupertypesProcessed = topologicallySortedClasses.contains(cls.origin); } if (allSupertypesProcessed) { topologicallySortedClasses.add(cls); checkClassSupertypes(cls, directSupertypes, blackListedClasses); } else { workList.add(cls); } } } while (previousWorkList.length != workList.length); List<SourceClassBuilder> classes = topologicallySortedClasses.toList(); List<SourceClassBuilder> classesWithCycles = previousWorkList; // Once the work list doesn't change in size, it's either empty, or // contains all classes with cycles. // Sort the classes to ensure consistent output. classesWithCycles.sort(); for (int i = 0; i < classesWithCycles.length; i++) { SourceClassBuilder cls = classesWithCycles[i]; target.breakCycle(cls); classes.add(cls); cls.addProblem( templateCyclicClassHierarchy.withArguments(cls.fullNameForErrors), cls.charOffset, noLength); } ticker.logMs("Checked class hierarchy"); return classes; } void checkClassSupertypes(SourceClassBuilder cls, List<Builder> directSupertypes, Set<ClassBuilder> blackListedClasses) { // Check that the direct supertypes aren't black-listed or enums. for (int i = 0; i < directSupertypes.length; i++) { Builder supertype = directSupertypes[i]; if (supertype is EnumBuilder) { cls.addProblem(templateExtendingEnum.withArguments(supertype.name), cls.charOffset, noLength); } else if (!cls.library.mayImplementRestrictedTypes && blackListedClasses.contains(supertype)) { cls.addProblem( templateExtendingRestricted .withArguments(supertype.fullNameForErrors), cls.charOffset, noLength); } } // Check that the mixed-in type can be used as a mixin. final TypeBuilder mixedInType = cls.mixedInType; if (mixedInType != null) { bool isClassBuilder = false; if (mixedInType is NamedTypeBuilder) { TypeDeclarationBuilder builder = mixedInType.declaration; if (builder is ClassBuilder) { isClassBuilder = true; for (Builder constructor in builder.constructors.local.values) { if (constructor.isConstructor && !constructor.isSynthetic) { cls.addProblem( templateIllegalMixinDueToConstructors .withArguments(builder.fullNameForErrors), cls.charOffset, noLength, context: [ templateIllegalMixinDueToConstructorsCause .withArguments(builder.fullNameForErrors) .withLocation(constructor.fileUri, constructor.charOffset, noLength) ]); } } } } if (!isClassBuilder) { // TODO(ahe): Either we need to check this for superclass and // interfaces, or this shouldn't be necessary (or handled elsewhere). cls.addProblem( templateIllegalMixin.withArguments(mixedInType.fullNameForErrors), cls.charOffset, noLength); } } } List<SourceClassBuilder> checkSemantics(ClassBuilder objectClass) { checkObjectClassHierarchy(objectClass); List<SourceClassBuilder> classes = handleHierarchyCycles(objectClass); // Check imports and exports for duplicate names. // This is rather silly, e.g. it makes importing 'foo' and exporting another // 'foo' ok. builders.forEach((Uri uri, LibraryBuilder library) { if (library is SourceLibraryBuilder && library.loader == this) { // Check exports. if (library.exports.isNotEmpty) { Map<String, List<Export>> nameToExports; bool errorExports = false; for (Export export in library.exports) { String name = export.exported?.name ?? ''; if (name != '') { nameToExports ??= new Map<String, List<Export>>(); List<Export> exports = nameToExports[name] ??= <Export>[]; exports.add(export); if (exports[0].exported != export.exported) errorExports = true; } } if (errorExports) { for (String name in nameToExports.keys) { List<Export> exports = nameToExports[name]; if (exports.length < 2) continue; List<LocatedMessage> context = <LocatedMessage>[]; for (Export export in exports.skip(1)) { context.add(templateDuplicatedLibraryExportContext .withArguments(name) .withLocation(uri, export.charOffset, noLength)); } library.addProblem( templateDuplicatedLibraryExport.withArguments(name), exports[0].charOffset, noLength, uri, context: context); } } } // Check imports. if (library.imports.isNotEmpty) { Map<String, List<Import>> nameToImports; bool errorImports; for (Import import in library.imports) { String name = import.imported?.name ?? ''; if (name != '') { nameToImports ??= new Map<String, List<Import>>(); List<Import> imports = nameToImports[name] ??= <Import>[]; imports.add(import); if (imports[0].imported != import.imported) errorImports = true; } } if (errorImports != null) { for (String name in nameToImports.keys) { List<Import> imports = nameToImports[name]; if (imports.length < 2) continue; List<LocatedMessage> context = <LocatedMessage>[]; for (Import import in imports.skip(1)) { context.add(templateDuplicatedLibraryImportContext .withArguments(name) .withLocation(uri, import.charOffset, noLength)); } library.addProblem( templateDuplicatedLibraryImport.withArguments(name), imports[0].charOffset, noLength, uri, context: context); } } } } }); ticker.logMs("Checked imports and exports for duplicate names"); return classes; } void buildComponent() { builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { SourceLibraryBuilder sourceLibrary = library; Library target = sourceLibrary.build(coreLibrary); if (!library.isPatch) { libraries.add(target); } } }); ticker.logMs("Built component"); } Component computeFullComponent() { Set<Library> libraries = new Set<Library>(); List<Library> workList = <Library>[]; builders.forEach((Uri uri, LibraryBuilder libraryBuilder) { if (!libraryBuilder.isPatch && (libraryBuilder.loader == this || libraryBuilder.uri.scheme == "dart" || libraryBuilder == this.first)) { if (libraries.add(libraryBuilder.library)) { workList.add(libraryBuilder.library); } } }); while (workList.isNotEmpty) { Library library = workList.removeLast(); for (LibraryDependency dependency in library.dependencies) { if (libraries.add(dependency.targetLibrary)) { workList.add(dependency.targetLibrary); } } } return new Component()..libraries.addAll(libraries); } void computeHierarchy() { List<AmbiguousTypesRecord> ambiguousTypesRecords = []; HandleAmbiguousSupertypes onAmbiguousSupertypes = (Class cls, Supertype a, Supertype b) { if (ambiguousTypesRecords != null) { ambiguousTypesRecords.add(new AmbiguousTypesRecord(cls, a, b)); } }; if (hierarchy == null) { hierarchy = new ClassHierarchy(computeFullComponent(), onAmbiguousSupertypes: onAmbiguousSupertypes); } else { hierarchy.onAmbiguousSupertypes = onAmbiguousSupertypes; Component component = computeFullComponent(); hierarchy.applyTreeChanges(const [], component.libraries, reissueAmbiguousSupertypesFor: component); } for (AmbiguousTypesRecord record in ambiguousTypesRecords) { handleAmbiguousSupertypes(record.cls, record.a, record.b); } ambiguousTypesRecords = null; ticker.logMs("Computed class hierarchy"); } void handleAmbiguousSupertypes(Class cls, Supertype a, Supertype b) { addProblem( templateAmbiguousSupertypes.withArguments( cls.name, a.asInterfaceType, b.asInterfaceType), cls.fileOffset, noLength, cls.fileUri); } void ignoreAmbiguousSupertypes(Class cls, Supertype a, Supertype b) {} void computeCoreTypes(Component component) { coreTypes = new CoreTypes(component); futureOfBottom = new InterfaceType( coreTypes.futureClass, <DartType>[const BottomType()]); iterableOfBottom = new InterfaceType( coreTypes.iterableClass, <DartType>[const BottomType()]); streamOfBottom = new InterfaceType( coreTypes.streamClass, <DartType>[const BottomType()]); ticker.logMs("Computed core types"); } void checkSupertypes(List<SourceClassBuilder> sourceClasses) { for (SourceClassBuilder builder in sourceClasses) { if (builder.library.loader == this && !builder.isPatch) { builder.checkSupertypes(coreTypes); } } ticker.logMs("Checked supertypes"); } void checkBounds() { builders.forEach((Uri uri, LibraryBuilder library) { if (library is SourceLibraryBuilder) { if (library.loader == this) { library .checkBoundsInOutline(typeInferenceEngine.typeSchemaEnvironment); } } }); ticker.logMs("Checked type arguments of supers against the bounds"); } void checkOverrides(List<SourceClassBuilder> sourceClasses) { List<DelayedOverrideCheck> overrideChecks = builderHierarchy.overrideChecks.toList(); builderHierarchy.overrideChecks.clear(); for (int i = 0; i < overrideChecks.length; i++) { overrideChecks[i].check(builderHierarchy); } ticker.logMs("Checked ${overrideChecks.length} overrides"); typeInferenceEngine?.finishTopLevelInitializingFormals(); ticker.logMs("Finished initializing formals"); } void checkAbstractMembers(List<SourceClassBuilder> sourceClasses) { List<DelayedMember> delayedMemberChecks = builderHierarchy.delayedMemberChecks.toList(); builderHierarchy.delayedMemberChecks.clear(); Set<Class> changedClasses = new Set<Class>(); for (int i = 0; i < delayedMemberChecks.length; i++) { delayedMemberChecks[i].check(builderHierarchy); changedClasses.add(delayedMemberChecks[i].classBuilder.cls); } ticker.logMs( "Computed ${delayedMemberChecks.length} combined member signatures"); hierarchy.applyMemberChanges(changedClasses, findDescendants: false); ticker .logMs("Updated ${changedClasses.length} classes in kernel hierarchy"); } void checkRedirectingFactories(List<SourceClassBuilder> sourceClasses) { // TODO(ahe): Move this to [ClassHierarchyBuilder]. for (SourceClassBuilder builder in sourceClasses) { if (builder.library.loader == this && !builder.isPatch) { builder.checkRedirectingFactories( typeInferenceEngine.typeSchemaEnvironment); } } ticker.logMs("Checked redirecting factories"); } void addNoSuchMethodForwarders(List<SourceClassBuilder> sourceClasses) { // TODO(ahe): Move this to [ClassHierarchyBuilder]. if (!target.backendTarget.enableNoSuchMethodForwarders) return; List<Class> changedClasses = new List<Class>(); for (SourceClassBuilder builder in sourceClasses) { if (builder.library.loader == this && !builder.isPatch) { if (builder.addNoSuchMethodForwarders(target, hierarchy)) { changedClasses.add(builder.cls); } } } hierarchy.applyMemberChanges(changedClasses, findDescendants: true); ticker.logMs("Added noSuchMethod forwarders"); } void checkMixins(List<SourceClassBuilder> sourceClasses) { for (SourceClassBuilder builder in sourceClasses) { if (builder.library.loader == this && !builder.isPatch) { Class mixedInClass = builder.cls.mixedInClass; if (mixedInClass != null && mixedInClass.isMixinDeclaration) { builder.checkMixinApplication(hierarchy); } } } ticker.logMs("Checked mixin declaration applications"); } void buildOutlineExpressions() { builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == this) { library.buildOutlineExpressions(); Iterator<Builder> iterator = library.iterator; while (iterator.moveNext()) { Builder declaration = iterator.current; if (declaration is ClassBuilder) { declaration.buildOutlineExpressions(library); } else if (declaration is ExtensionBuilder) { declaration.buildOutlineExpressions(library); } else if (declaration is MemberBuilder) { declaration.buildOutlineExpressions(library); } } } }); } void buildClassHierarchy( List<SourceClassBuilder> sourceClasses, ClassBuilder objectClass) { builderHierarchy = ClassHierarchyBuilder.build( objectClass, sourceClasses, this, coreTypes); typeInferenceEngine?.hierarchyBuilder = builderHierarchy; ticker.logMs("Built class hierarchy"); } void createTypeInferenceEngine() { typeInferenceEngine = new ShadowTypeInferenceEngine(instrumentation); } void performTopLevelInference(List<SourceClassBuilder> sourceClasses) { /// The first phase of top level initializer inference, which consists of /// creating kernel objects for all fields and top level variables that /// might be subject to type inference, and records dependencies between /// them. typeInferenceEngine.prepareTopLevel(coreTypes, hierarchy); List<FieldBuilder> allImplicitlyTypedFields = <FieldBuilder>[]; for (LibraryBuilder library in builders.values) { if (library.loader == this) { List<FieldBuilder> implicitlyTypedFields = library.takeImplicitlyTypedFields(); if (implicitlyTypedFields != null) { allImplicitlyTypedFields.addAll(implicitlyTypedFields); } } } for (int i = 0; i < allImplicitlyTypedFields.length; i++) { // TODO(ahe): This can cause a crash for parts that failed to get // included, see for example, // tests/standalone_2/io/http_cookie_date_test.dart. allImplicitlyTypedFields[i].inferType(); } typeInferenceEngine.isTypeInferencePrepared = true; // Since finalization of covariance may have added forwarding stubs, we need // to recompute the class hierarchy so that method compilation will properly // target those forwarding stubs. hierarchy.onAmbiguousSupertypes = ignoreAmbiguousSupertypes; ticker.logMs("Performed top level inference"); } void transformPostInference( TreeNode node, bool transformSetLiterals, bool transformCollections) { if (transformCollections) { node.accept(collectionTransformer ??= new CollectionTransformer(this)); } if (transformSetLiterals) { node.accept(setLiteralTransformer ??= new SetLiteralTransformer(this)); } } void transformListPostInference(List<TreeNode> list, bool transformSetLiterals, bool transformCollections) { if (transformCollections) { CollectionTransformer transformer = collectionTransformer ??= new CollectionTransformer(this); for (int i = 0; i < list.length; ++i) { list[i] = list[i].accept(transformer); } } if (transformSetLiterals) { SetLiteralTransformer transformer = setLiteralTransformer ??= new SetLiteralTransformer(this); for (int i = 0; i < list.length; ++i) { list[i] = list[i].accept(transformer); } } } Expression instantiateInvocation(Expression receiver, String name, Arguments arguments, int offset, bool isSuper) { return target.backendTarget.instantiateInvocation( coreTypes, receiver, name, arguments, offset, isSuper); } Expression instantiateNoSuchMethodError( Expression receiver, String name, Arguments arguments, int offset, {bool isMethod: false, bool isGetter: false, bool isSetter: false, bool isField: false, bool isLocalVariable: false, bool isDynamic: false, bool isSuper: false, bool isStatic: false, bool isConstructor: false, bool isTopLevel: false}) { return target.backendTarget.instantiateNoSuchMethodError( coreTypes, receiver, name, arguments, offset, isMethod: isMethod, isGetter: isGetter, isSetter: isSetter, isField: isField, isLocalVariable: isLocalVariable, isDynamic: isDynamic, isSuper: isSuper, isStatic: isStatic, isConstructor: isConstructor, isTopLevel: isTopLevel); } void releaseAncillaryResources() { hierarchy = null; typeInferenceEngine = null; } @override ClassBuilder computeClassBuilderFromTargetClass(Class cls) { Library kernelLibrary = cls.enclosingLibrary; LibraryBuilder library = builders[kernelLibrary.importUri]; if (library == null) { return target.dillTarget.loader.computeClassBuilderFromTargetClass(cls); } return library.lookupLocalMember(cls.name, required: true); } @override TypeBuilder computeTypeBuilder(DartType type) { return type.accept(new TypeBuilderComputer(this)); } BodyBuilder createBodyBuilderForField( FieldBuilder field, TypeInferrer typeInferrer) { return new BodyBuilder.forField(field, typeInferrer); } } /// A minimal implementation of dart:core that is sufficient to create an /// instance of [CoreTypes] and compile a program. const String defaultDartCoreSource = """ import 'dart:_internal'; import 'dart:async'; export 'dart:async' show Future, Stream; print(object) {} class Iterator {} class Iterable {} class List extends Iterable { factory List.unmodifiable(elements) => null; } class Map extends Iterable { factory Map.unmodifiable(other) => null; } class NoSuchMethodError { NoSuchMethodError.withInvocation(receiver, invocation); } class Null {} class Object { noSuchMethod(invocation) => null; } class String {} class Symbol {} class Set {} class Type {} class _InvocationMirror { _InvocationMirror._withType(_memberName, _type, _typeArguments, _positionalArguments, _namedArguments); } class bool {} class double extends num {} class int extends num {} class num {} class _SyncIterable {} class _SyncIterator { var _current; var _yieldEachIterable; } class Function {} """; /// A minimal implementation of dart:async that is sufficient to create an /// instance of [CoreTypes] and compile program. const String defaultDartAsyncSource = """ _asyncErrorWrapperHelper(continuation) {} _asyncStackTraceHelper(async_op) {} _asyncThenWrapperHelper(continuation) {} _awaitHelper(object, thenCallback, errorCallback, awaiter) {} _completeOnAsyncReturn(completer, value) {} class _AsyncStarStreamController { add(event) {} addError(error, stackTrace) {} addStream(stream) {} close() {} get stream => null; } class Completer { factory Completer.sync() => null; get future; complete([value]); completeError(error, [stackTrace]); } class Future { factory Future.microtask(computation) => null; } class FutureOr { } class _AsyncAwaitCompleter implements Completer { get future => null; complete([value]) {} completeError(error, [stackTrace]) {} } class Stream {} class _StreamIterator { get current => null; moveNext() {} cancel() {} } """; /// A minimal implementation of dart:collection that is sufficient to create an /// instance of [CoreTypes] and compile program. const String defaultDartCollectionSource = """ class _UnmodifiableSet { final Map _map; const _UnmodifiableSet(this._map); } """; /// A minimal implementation of dart:_internal that is sufficient to create an /// instance of [CoreTypes] and compile program. const String defaultDartInternalSource = """ class Symbol { const Symbol(String name); } """; /// A minimal implementation of dart:typed_data that is sufficient to create an /// instance of [CoreTypes] and compile program. const String defaultDartTypedDataSource = """ class Endian { static const Endian little = null; static const Endian big = null; static final Endian host = null; } """; class AmbiguousTypesRecord { final Class cls; final Supertype a; final Supertype b; const AmbiguousTypesRecord(this.cls, this.a, this.b); }
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/source/source_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 '../../base/common.dart'; import '../builder/declaration.dart'; import '../builder/extension_builder.dart'; import '../builder/library_builder.dart'; import '../builder/metadata_builder.dart'; import '../builder/procedure_builder.dart'; import '../builder/type_builder.dart'; import '../builder/type_variable_builder.dart'; import '../scope.dart'; import '../kernel/kernel_builder.dart'; import '../problems.dart'; import '../fasta_codes.dart' show messagePatchDeclarationMismatch, messagePatchDeclarationOrigin, noLength, templateConflictsWithMember, templateConflictsWithMemberWarning, templateConflictsWithSetter, templateConflictsWithSetterWarning, templateExtensionMemberConflictsWithObjectMember; import 'source_library_builder.dart'; class SourceExtensionBuilder extends ExtensionBuilderImpl { final Extension _extension; SourceExtensionBuilder _origin; SourceExtensionBuilder patchForTesting; SourceExtensionBuilder( List<MetadataBuilder> metadata, int modifiers, String name, List<TypeVariableBuilder> typeParameters, TypeBuilder onType, Scope scope, LibraryBuilder parent, int startOffset, int nameOffset, int endOffset) : _extension = new Extension( name: name, fileUri: parent.fileUri, typeParameters: TypeVariableBuilder.typeParametersFromBuilders(typeParameters)) ..fileOffset = nameOffset, super(metadata, modifiers, name, parent, nameOffset, scope, typeParameters, onType); @override SourceExtensionBuilder get origin => _origin ?? this; Extension get extension => isPatch ? origin._extension : _extension; /// Builds the [Extension] for this extension build and inserts the members /// into the [Library] of [libraryBuilder]. /// /// [addMembersToLibrary] is `true` if the extension members should be added /// to the library. This is `false` if the extension is in conflict with /// another library member. In this case, the extension member should not be /// added to the library to avoid name clashes with other members in the /// library. Extension build( SourceLibraryBuilder libraryBuilder, LibraryBuilder coreLibrary, {bool addMembersToLibrary}) { ClassBuilder objectClassBuilder = coreLibrary.lookupLocalMember('Object', required: true); void buildBuilders(String name, Builder declaration) { do { Builder objectGetter = objectClassBuilder.lookupLocalMember(name); Builder objectSetter = objectClassBuilder.lookupLocalMember(name, setter: true); if (objectGetter != null || objectSetter != null) { addProblem( templateExtensionMemberConflictsWithObjectMember .withArguments(name), declaration.charOffset, name.length); } if (declaration.parent != this) { if (fileUri != declaration.parent.fileUri) { unexpected("$fileUri", "${declaration.parent.fileUri}", charOffset, fileUri); } else { unexpected(fullNameForErrors, declaration.parent?.fullNameForErrors, charOffset, fileUri); } } else if (declaration is FieldBuilder) { Field field = declaration.build(libraryBuilder); if (addMembersToLibrary && declaration.next == null) { libraryBuilder.library.addMember(field); extension.members.add(new ExtensionMemberDescriptor( name: new Name(declaration.name, libraryBuilder.library), member: field.reference, isStatic: declaration.isStatic, kind: ExtensionMemberKind.Field)); } } else if (declaration is ProcedureBuilder) { Member function = declaration.build(libraryBuilder); if (addMembersToLibrary && !declaration.isPatch && declaration.next == null) { libraryBuilder.library.addMember(function); ExtensionMemberKind kind; switch (declaration.kind) { case ProcedureKind.Method: kind = ExtensionMemberKind.Method; break; case ProcedureKind.Getter: kind = ExtensionMemberKind.Getter; break; case ProcedureKind.Setter: kind = ExtensionMemberKind.Setter; break; case ProcedureKind.Operator: kind = ExtensionMemberKind.Operator; break; case ProcedureKind.Factory: unsupported("Extension method kind: ${declaration.kind}", declaration.charOffset, declaration.fileUri); } extension.members.add(new ExtensionMemberDescriptor( name: new Name(declaration.name, libraryBuilder.library), member: function.reference, isStatic: declaration.isStatic, kind: kind)); Procedure tearOff = declaration.extensionTearOff; if (tearOff != null) { libraryBuilder.library.addMember(tearOff); _extension.members.add(new ExtensionMemberDescriptor( name: new Name(declaration.name, libraryBuilder.library), member: tearOff.reference, isStatic: false, kind: ExtensionMemberKind.TearOff)); } } } else { unhandled("${declaration.runtimeType}", "buildBuilders", declaration.charOffset, declaration.fileUri); } declaration = declaration.next; } while (declaration != null); } scope.forEach(buildBuilders); scope.setters.forEach((String name, Builder setter) { Builder member = scopeBuilder[name]; if (member == null || !(member.isField && !member.isFinal && !member.isConst || member.isRegularMethod && member.isStatic && setter.isStatic)) { return; } if (member.isDeclarationInstanceMember == setter.isDeclarationInstanceMember) { addProblem(templateConflictsWithMember.withArguments(name), setter.charOffset, noLength); // TODO(ahe): Context argument to previous message? addProblem(templateConflictsWithSetter.withArguments(name), member.charOffset, noLength); } else { addProblem(templateConflictsWithMemberWarning.withArguments(name), setter.charOffset, noLength); // TODO(ahe): Context argument to previous message? addProblem(templateConflictsWithSetterWarning.withArguments(name), member.charOffset, noLength); } }); _extension.onType = onType?.build(libraryBuilder); return _extension; } @override void applyPatch(Builder patch) { if (patch is SourceExtensionBuilder) { patch._origin = this; if (retainDataForTesting) { patchForTesting = patch; } 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); } }); // TODO(johnniwinther): Check that type parameters and on-type match // with origin declaration. } else { library.addProblem(messagePatchDeclarationMismatch, patch.charOffset, noLength, patch.fileUri, context: [ messagePatchDeclarationOrigin.withLocation( fileUri, charOffset, noLength) ]); } } @override int finishPatch() { if (!isPatch) return 0; int count = 0; scope.forEach((String name, Builder declaration) { count += declaration.finishPatch(); }); return count; } }
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/source/diet_listener.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.diet_listener; import 'package:kernel/ast.dart' show AsyncMarker, Expression, InterfaceType, Library, LibraryDependency, LibraryPart, TreeNode, TypeParameter, VariableDeclaration; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy; import 'package:kernel/core_types.dart' show CoreTypes; import '../../scanner/token.dart' show Token; import '../builder/builder.dart'; import '../builder/declaration_builder.dart'; import '../constant_context.dart' show ConstantContext; import '../crash.dart' show Crash; import '../fasta_codes.dart' show Code, LocatedMessage, Message, messageExpectedBlockToSkip, templateInternalProblemNotFound; import '../ignored_parser_errors.dart' show isIgnoredParserError; import '../kernel/body_builder.dart' show BodyBuilder; import '../kernel/kernel_builder.dart' show FormalParameterBuilder, TypeAliasBuilder, TypeBuilder; import '../parser.dart' show Assert, DeclarationKind, MemberKind, Parser, optional; import '../problems.dart' show DebugAbort, internalProblem, unexpected, unhandled; import '../type_inference/type_inference_engine.dart' show TypeInferenceEngine; import '../type_inference/type_inferrer.dart' show TypeInferrer; import 'source_library_builder.dart' show SourceLibraryBuilder; import 'stack_listener.dart' show FixedNullableList, NullValue, ParserRecovery, StackListener; import '../source/value_kinds.dart'; import '../quote.dart' show unescapeString; class DietListener extends StackListener { final SourceLibraryBuilder libraryBuilder; final ClassHierarchy hierarchy; final CoreTypes coreTypes; final bool enableNative; final bool stringExpectedAfterNative; final TypeInferenceEngine typeInferenceEngine; int importExportDirectiveIndex = 0; int partDirectiveIndex = 0; DeclarationBuilder _currentDeclaration; ClassBuilder _currentClass; bool currentClassIsParserRecovery = false; /// Counter used for naming unnamed extension declarations. int unnamedExtensionCounter = 0; /// For top-level declarations, this is the library scope. For class members, /// this is the instance scope of [currentDeclaration]. Scope memberScope; @override Uri uri; DietListener(SourceLibraryBuilder library, this.hierarchy, this.coreTypes, this.typeInferenceEngine) : libraryBuilder = library, uri = library.fileUri, memberScope = library.scope, enableNative = library.loader.target.backendTarget.enableNative(library.uri), stringExpectedAfterNative = library.loader.target.backendTarget.nativeExtensionExpectsString; DeclarationBuilder get currentDeclaration => _currentDeclaration; void set currentDeclaration(DeclarationBuilder builder) { if (builder == null) { _currentClass = _currentDeclaration = null; } else { _currentDeclaration = builder; _currentClass = builder is ClassBuilder ? builder : null; } } ClassBuilder get currentClass => _currentClass; @override void endMetadataStar(int count) { assert(checkState(null, repeatedKinds(ValueKind.Token, count))); debugEvent("MetadataStar"); if (count > 0) { discard(count - 1); push(pop(NullValue.Token) ?? NullValue.Token); } else { push(NullValue.Token); } } @override void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) { debugEvent("Metadata"); discard(periodBeforeName == null ? 1 : 2); push(beginToken); } @override void endPartOf( Token partKeyword, Token ofKeyword, Token semicolon, bool hasName) { debugEvent("PartOf"); if (hasName) discard(1); discard(1); // Metadata. } @override void handleInvalidTopLevelDeclaration(Token beginToken) { debugEvent("InvalidTopLevelDeclaration"); pop(); // metadata star } @override void handleNoArguments(Token token) { debugEvent("NoArguments"); } @override void handleNoTypeArguments(Token token) { debugEvent("NoTypeArguments"); } @override void handleNoConstructorReferenceContinuationAfterTypeArguments(Token token) { debugEvent("NoConstructorReferenceContinuationAfterTypeArguments"); } @override void handleNoType(Token lastConsumed) { debugEvent("NoType"); } @override void handleType(Token beginToken, Token questionMark) { debugEvent("Type"); discard(1); } @override void endTypeList(int count) { debugEvent("TypeList"); } @override void handleNamedMixinApplicationWithClause(Token withKeyword) { debugEvent("NamedMixinApplicationWithClause"); } @override void handleClassWithClause(Token withKeyword) { debugEvent("ClassWithClause"); } @override void handleClassNoWithClause() { debugEvent("ClassNoWithClause"); } @override void endTypeArguments(int count, Token beginToken, Token endToken) { debugEvent("TypeArguments"); } @override void handleInvalidTypeArguments(Token token) { debugEvent("InvalidTypeArguments"); } @override void endFieldInitializer(Token assignmentOperator, Token token) { debugEvent("FieldInitializer"); } @override void handleNoFieldInitializer(Token token) { debugEvent("NoFieldInitializer"); } @override void handleNoTypeVariables(Token token) { debugEvent("NoTypeVariables"); } @override void endFormalParameters( int count, Token beginToken, Token endToken, MemberKind kind) { debugEvent("FormalParameters"); assert(count == 0); // Count is always 0 as the diet parser skips formals. if (kind != MemberKind.GeneralizedFunctionType && identical(peek(), "-") && identical(beginToken.next, endToken)) { pop(); push("unary-"); } push(beginToken); } @override void handleNoFormalParameters(Token token, MemberKind kind) { debugEvent("NoFormalParameters"); if (identical(peek(), "-")) { pop(); push("unary-"); } push(token); } @override void endFunctionType(Token functionToken, Token questionMark) { debugEvent("FunctionType"); discard(1); } @override void endFunctionTypeAlias( Token typedefKeyword, Token equals, Token endToken) { debugEvent("FunctionTypeAlias"); if (equals == null) pop(); // endToken Object name = pop(); Token metadata = pop(); checkEmpty(typedefKeyword.charOffset); if (name is ParserRecovery) return; TypeAliasBuilder typedefBuilder = lookupBuilder(typedefKeyword, null, name); parseMetadata(typedefBuilder, metadata, typedefBuilder.typedef); if (typedefBuilder is TypeAliasBuilder) { TypeBuilder type = typedefBuilder.type; if (type is FunctionTypeBuilder) { List<FormalParameterBuilder> formals = type.formals; if (formals != null) { for (int i = 0; i < formals.length; ++i) { FormalParameterBuilder formal = formals[i]; List<MetadataBuilder> metadata = formal.metadata; if (metadata != null && metadata.length > 0) { // [parseMetadata] is using [Parser.parseMetadataStar] under the // hood, so we only need the offset of the first annotation. Token metadataToken = tokenForOffset( typedefKeyword, endToken, metadata[0].charOffset); List<Expression> annotations = parseMetadata(typedefBuilder, metadataToken, null); if (formal.isPositional) { VariableDeclaration parameter = typedefBuilder.typedef.positionalParameters[i]; for (Expression annotation in annotations) { parameter.addAnnotation(annotation); } } else { for (VariableDeclaration named in typedefBuilder.typedef.namedParameters) { if (named.name == formal.name) { for (Expression annotation in annotations) { named.addAnnotation(annotation); } } } } } } } } } else if (typedefBuilder != null) { unhandled("${typedefBuilder.fullNameForErrors}", "endFunctionTypeAlias", typedefKeyword.charOffset, uri); } checkEmpty(typedefKeyword.charOffset); } @override void endClassFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("Fields"); buildFields(count, beginToken, false); } @override void handleAsyncModifier(Token asyncToken, Token startToken) { debugEvent("AsyncModifier"); } @override void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) { debugEvent("TopLevelMethod"); Token bodyToken = pop(); Object name = pop(); Token metadata = pop(); checkEmpty(beginToken.charOffset); if (name is ParserRecovery) return; final StackListener listener = createFunctionListener(lookupBuilder(beginToken, getOrSet, name)); buildFunctionBody(listener, bodyToken, metadata, MemberKind.TopLevelMethod); } @override void handleNoFunctionBody(Token token) { debugEvent("NoFunctionBody"); } @override void endTopLevelFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("TopLevelFields"); buildFields(count, beginToken, true); } @override void handleVoidKeyword(Token token) { debugEvent("VoidKeyword"); } @override void handleNoInitializers() { debugEvent("NoInitializers"); } @override void endInitializers(int count, Token beginToken, Token endToken) { debugEvent("Initializers"); } @override void handleQualified(Token period) { assert(checkState(period, [ /*suffix*/ ValueKind.NameOrParserRecovery, /*prefix*/ unionOfKinds([ ValueKind.Name, ValueKind.Generator, ValueKind.ParserRecovery, ValueKind.QualifiedName, ]), ])); debugEvent("handleQualified"); Object suffix = pop(); Object prefix = pop(); if (prefix is ParserRecovery) { push(prefix); } else if (suffix is ParserRecovery) { push(suffix); } else { assert(identical(suffix, period.next.lexeme)); push(new QualifiedName(prefix, period.next)); } } @override void endLibraryName(Token libraryKeyword, Token semicolon) { debugEvent("endLibraryName"); pop(); // Name. pop(); // Annotations. } @override void beginLiteralString(Token token) { debugEvent("beginLiteralString"); } @override void handleStringPart(Token token) { debugEvent("StringPart"); } @override void endLiteralString(int interpolationCount, Token endToken) { debugEvent("endLiteralString"); } @override void handleNativeClause(Token nativeToken, bool hasName) { debugEvent("NativeClause"); } @override void handleScript(Token token) { debugEvent("Script"); } @override void handleStringJuxtaposition(int literalCount) { debugEvent("StringJuxtaposition"); } @override void handleDottedName(int count, Token firstIdentifier) { debugEvent("DottedName"); discard(count); } @override void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) { debugEvent("ConditionalUri"); } @override void endConditionalUris(int count) { debugEvent("ConditionalUris"); } @override void handleOperatorName(Token operatorKeyword, Token token) { debugEvent("OperatorName"); push(token.stringValue); } @override void handleInvalidOperatorName(Token operatorKeyword, Token token) { debugEvent("InvalidOperatorName"); push('invalid'); } @override void handleIdentifierList(int count) { debugEvent("IdentifierList"); discard(count); } @override void endShow(Token showKeyword) { debugEvent("Show"); } @override void endHide(Token hideKeyword) { debugEvent("Hide"); } @override void endCombinators(int count) { debugEvent("Combinators"); } @override void handleImportPrefix(Token deferredKeyword, Token asKeyword) { debugEvent("ImportPrefix"); pushIfNull(asKeyword, NullValue.Prefix); } @override void endImport(Token importKeyword, Token semicolon) { debugEvent("Import"); Object name = pop(NullValue.Prefix); Token metadata = pop(); checkEmpty(importKeyword.charOffset); if (name is ParserRecovery) return; // Native imports must be skipped because they aren't assigned corresponding // LibraryDependency nodes. Token importUriToken = importKeyword.next; String importUri = unescapeString(importUriToken.lexeme, importUriToken, this); if (importUri.startsWith("dart-ext:")) return; Library libraryNode = libraryBuilder.library; LibraryDependency dependency = libraryNode.dependencies[importExportDirectiveIndex++]; parseMetadata(libraryBuilder, metadata, dependency); } @override void handleRecoverImport(Token semicolon) { pop(NullValue.Prefix); } @override void endExport(Token exportKeyword, Token semicolon) { debugEvent("Export"); Token metadata = pop(); Library libraryNode = libraryBuilder.library; LibraryDependency dependency = libraryNode.dependencies[importExportDirectiveIndex++]; parseMetadata(libraryBuilder, metadata, dependency); } @override void endPart(Token partKeyword, Token semicolon) { debugEvent("Part"); Token metadata = pop(); Library libraryNode = libraryBuilder.library; if (libraryNode.parts.length > partDirectiveIndex) { // If partDirectiveIndex >= libraryNode.parts.length we are in a case of // on part having other parts. An error has already been issued. // Don't try to parse metadata into other parts that have nothing to do // with the one this keyword is talking about. LibraryPart part = libraryNode.parts[partDirectiveIndex++]; parseMetadata(libraryBuilder, metadata, part); } } @override void beginTypeVariable(Token token) { debugEvent("beginTypeVariable"); discard(2); // Name and metadata. } @override void endTypeVariable( Token token, int index, Token extendsOrSuper, Token variance) { debugEvent("endTypeVariable"); } @override void endTypeVariables(Token beginToken, Token endToken) { debugEvent("TypeVariables"); } @override void handleVarianceModifier(Token variance) { debugEvent("VarianceModifier"); } @override void endConstructorReference( Token start, Token periodBeforeName, Token endToken) { debugEvent("ConstructorReference"); popIfNotNull(periodBeforeName); } @override void endClassFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { debugEvent("ClassFactoryMethod"); Token bodyToken = pop(); Object name = pop(); Token metadata = pop(); checkEmpty(beginToken.charOffset); if (name is ParserRecovery || currentClassIsParserRecovery) return; FunctionBuilder builder = lookupConstructor(beginToken, name); if (bodyToken == null || optional("=", bodyToken.endGroup.next)) { buildRedirectingFactoryMethod( bodyToken, builder, MemberKind.Factory, metadata); } else { buildFunctionBody(createFunctionListener(builder), bodyToken, metadata, MemberKind.Factory); } } @override void endExtensionFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { debugEvent("ExtensionFactoryMethod"); pop(); // bodyToken pop(); // name pop(); // metadata checkEmpty(beginToken.charOffset); // Skip the declaration. An error as already been produced by the parser. } @override void endExtensionConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { debugEvent("ExtensionConstructor"); pop(); // bodyToken pop(); // name pop(); // metadata checkEmpty(beginToken.charOffset); // Skip the declaration. An error as already been produced by the parser. } @override void endRedirectingFactoryBody(Token beginToken, Token endToken) { debugEvent("RedirectingFactoryBody"); discard(1); // ConstructorReference. } @override void handleNativeFunctionBody(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBody"); } @override void handleNativeFunctionBodyIgnored(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBodyIgnored"); } @override void handleNativeFunctionBodySkipped(Token nativeToken, Token semicolon) { debugEvent("NativeFunctionBodySkipped"); if (!enableNative) { super.handleRecoverableError( messageExpectedBlockToSkip, nativeToken, nativeToken); } } @override void endClassMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { debugEvent("Method"); // TODO(danrubel): Consider removing the beginParam parameter // and using bodyToken, but pushing a NullValue on the stack // in handleNoFormalParameters rather than the supplied token. pop(); // bodyToken Object name = pop(); Token metadata = pop(); checkEmpty(beginToken.charOffset); if (name is ParserRecovery || currentClassIsParserRecovery) return; FunctionBuilder builder; if (name is QualifiedName || (getOrSet == null && name == currentClass?.name)) { builder = lookupConstructor(beginToken, name); } else { builder = lookupBuilder(beginToken, getOrSet, name); } buildFunctionBody( createFunctionListener(builder), beginParam, metadata, builder.isStatic ? MemberKind.StaticMethod : MemberKind.NonStaticMethod); } StackListener createListener(ModifierBuilder builder, Scope memberScope, {bool isDeclarationInstanceMember, VariableDeclaration extensionThis, List<TypeParameter> extensionTypeParameters, Scope formalParameterScope}) { // Note: we set thisType regardless of whether we are building a static // member, since that provides better error recovery. // TODO(johnniwinther): Provide a dummy this on static extension methods // for better error recovery? InterfaceType thisType = extensionThis == null ? currentDeclaration?.thisType : null; TypeInferrer typeInferrer = typeInferenceEngine?.createLocalTypeInferrer( uri, thisType, libraryBuilder); ConstantContext constantContext = builder.isConstructor && builder.isConst ? ConstantContext.inferred : ConstantContext.none; return createListenerInternal( builder, memberScope, formalParameterScope, isDeclarationInstanceMember, extensionThis, extensionTypeParameters, typeInferrer, constantContext); } StackListener createListenerInternal( ModifierBuilder builder, Scope memberScope, Scope formalParameterScope, bool isDeclarationInstanceMember, VariableDeclaration extensionThis, List<TypeParameter> extensionTypeParameters, TypeInferrer typeInferrer, ConstantContext constantContext) { return new BodyBuilder( libraryBuilder: libraryBuilder, member: builder, enclosingScope: memberScope, formalParameterScope: formalParameterScope, hierarchy: hierarchy, coreTypes: coreTypes, declarationBuilder: currentDeclaration, isDeclarationInstanceMember: isDeclarationInstanceMember, extensionThis: extensionThis, extensionTypeParameters: extensionTypeParameters, uri: uri, typeInferrer: typeInferrer) ..constantContext = constantContext; } StackListener createFunctionListener(FunctionBuilder builder) { final Scope typeParameterScope = builder.computeTypeParameterScope(memberScope); final Scope formalParameterScope = builder.computeFormalParameterScope(typeParameterScope); assert(typeParameterScope != null); assert(formalParameterScope != null); return createListener(builder, typeParameterScope, isDeclarationInstanceMember: builder.isDeclarationInstanceMember, extensionThis: builder.extensionThis, extensionTypeParameters: builder.extensionTypeParameters, formalParameterScope: formalParameterScope); } void buildRedirectingFactoryMethod( Token token, FunctionBuilder builder, MemberKind kind, Token metadata) { final StackListener listener = createFunctionListener(builder); try { Parser parser = new Parser(listener); if (metadata != null) { parser.parseMetadataStar(parser.syntheticPreviousToken(metadata)); listener.pop(); // Pops metadata constants. } token = parser.parseFormalParametersOpt( parser.syntheticPreviousToken(token), MemberKind.Factory); listener.pop(); // Pops formal parameters. listener.checkEmpty(token.next.charOffset); } on DebugAbort { rethrow; } catch (e, s) { throw new Crash(uri, token.charOffset, e, s); } } void buildFields(int count, Token token, bool isTopLevel) { List<String> names = const FixedNullableList<String>().pop(stack, count); Token metadata = pop(); checkEmpty(token.charOffset); if (names == null || currentClassIsParserRecovery) return; Builder declaration = lookupBuilder(token, null, names.first); // TODO(paulberry): don't re-parse the field if we've already parsed it // for type inference. parseFields( createListener(declaration, memberScope, isDeclarationInstanceMember: declaration.isDeclarationInstanceMember), token, metadata, isTopLevel); checkEmpty(token.charOffset); } @override void handleInvalidMember(Token endToken) { debugEvent("InvalidMember"); pop(); // metadata star } @override void endMember() { debugEvent("Member"); checkEmpty(-1); } @override void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis, Token commaToken, Token semicolonToken) { debugEvent("Assert"); // Do nothing } @override void beginClassOrMixinBody(DeclarationKind kind, Token token) { assert(checkState(token, [ ValueKind.Token, ValueKind.NameOrParserRecovery, ValueKind.TokenOrNull ])); debugEvent("beginClassOrMixinBody"); Token beginToken = pop(); Object name = pop(); pop(); // Annotation begin token. assert(currentDeclaration == null); assert(memberScope == libraryBuilder.scope); if (name is ParserRecovery) { currentClassIsParserRecovery = true; return; } currentDeclaration = lookupBuilder(beginToken, null, name); memberScope = currentDeclaration.scope; } @override void endClassOrMixinBody( DeclarationKind kind, int memberCount, Token beginToken, Token endToken) { debugEvent("ClassOrMixinBody"); currentDeclaration = null; currentClassIsParserRecovery = false; memberScope = libraryBuilder.scope; } @override void beginClassDeclaration(Token begin, Token abstractToken, Token name) { debugEvent("beginClassDeclaration"); push(begin); } @override void endClassDeclaration(Token beginToken, Token endToken) { debugEvent("endClassDeclaration"); checkEmpty(beginToken.charOffset); } @override void beginMixinDeclaration(Token mixinKeyword, Token name) { debugEvent("beginMixinDeclaration"); push(mixinKeyword); } @override void endMixinDeclaration(Token mixinKeyword, Token endToken) { debugEvent("endMixinDeclaration"); checkEmpty(mixinKeyword.charOffset); } @override void beginExtensionDeclaration(Token extensionKeyword, Token nameToken) { debugEvent("beginExtensionDeclaration"); String name = nameToken?.lexeme ?? // Synthesized name used internally. '_extension#${unnamedExtensionCounter++}'; push(name); push(extensionKeyword); } @override void endExtensionDeclaration( Token extensionKeyword, Token onKeyword, Token endToken) { debugEvent("endExtensionDeclaration"); checkEmpty(extensionKeyword.charOffset); } @override void endEnum(Token enumKeyword, Token leftBrace, int count) { debugEvent("Enum"); const FixedNullableList<Object>().pop(stack, count * 2); pop(); // Name. pop(); // Annotations begin token. checkEmpty(enumKeyword.charOffset); } @override void endNamedMixinApplication(Token beginToken, Token classKeyword, Token equals, Token implementsKeyword, Token endToken) { debugEvent("NamedMixinApplication"); pop(); // Name. pop(); // Annotations begin token. checkEmpty(beginToken.charOffset); } AsyncMarker getAsyncMarker(StackListener listener) => listener.pop(); /// Invokes the listener's [finishFunction] method. /// /// This is a separate method so that it may be overridden by a derived class /// if more computation must be done before finishing the function. void listenerFinishFunction( StackListener listener, Token token, MemberKind kind, dynamic formals, AsyncMarker asyncModifier, dynamic body) { listener.finishFunction(formals, asyncModifier, body); } /// Invokes the listener's [finishFields] method. /// /// This is a separate method so that it may be overridden by a derived class /// if more computation must be done before finishing the function. void listenerFinishFields(StackListener listener, Token startToken, Token metadata, bool isTopLevel) { listener.finishFields(); } void buildFunctionBody(StackListener listener, Token startToken, Token metadata, MemberKind kind) { Token token = startToken; try { Parser parser = new Parser(listener); if (metadata != null) { parser.parseMetadataStar(parser.syntheticPreviousToken(metadata)); listener.pop(); // Annotations. } token = parser.parseFormalParametersOpt( parser.syntheticPreviousToken(token), kind); Object formals = listener.pop(); listener.checkEmpty(token.next.charOffset); token = parser.parseInitializersOpt(token); token = parser.parseAsyncModifierOpt(token); AsyncMarker asyncModifier = getAsyncMarker(listener) ?? AsyncMarker.Sync; bool isExpression = false; bool allowAbstract = asyncModifier == AsyncMarker.Sync; parser.parseFunctionBody(token, isExpression, allowAbstract); Object body = listener.pop(); listener.checkEmpty(token.charOffset); listenerFinishFunction( listener, startToken, kind, formals, asyncModifier, body); } on DebugAbort { rethrow; } catch (e, s) { throw new Crash(uri, token.charOffset, e, s); } } void parseFields(StackListener listener, Token startToken, Token metadata, bool isTopLevel) { Token token = startToken; Parser parser = new Parser(listener); if (isTopLevel) { token = parser.parseTopLevelMember(metadata ?? token); } else { // TODO(danrubel): disambiguate between class/mixin/extension members token = parser.parseClassMember(metadata ?? token, null).next; } listenerFinishFields(listener, startToken, metadata, isTopLevel); listener.checkEmpty(token.charOffset); } Builder lookupBuilder(Token token, Token getOrSet, String name) { // TODO(ahe): Can I move this to Scope or ScopeBuilder? Builder declaration; if (currentDeclaration != null) { if (uri != currentDeclaration.fileUri) { unexpected("$uri", "${currentDeclaration.fileUri}", currentDeclaration.charOffset, currentDeclaration.fileUri); } if (getOrSet != null && optional("set", getOrSet)) { declaration = currentDeclaration.scope.setters[name]; } else { declaration = currentDeclaration.scope.local[name]; } } else if (getOrSet != null && optional("set", getOrSet)) { declaration = libraryBuilder.scope.setters[name]; } else { declaration = libraryBuilder.scopeBuilder[name]; } declaration = handleDuplicatedName(declaration, token); checkBuilder(token, declaration, name); return declaration; } Builder lookupConstructor(Token token, Object nameOrQualified) { assert(currentClass != null); Builder declaration; String suffix; if (nameOrQualified is QualifiedName) { suffix = nameOrQualified.name; } else { suffix = nameOrQualified == currentClass.name ? "" : nameOrQualified; } declaration = currentClass.constructors.local[suffix]; declaration = handleDuplicatedName(declaration, token); checkBuilder(token, declaration, nameOrQualified); return declaration; } Builder handleDuplicatedName(Builder declaration, Token token) { int offset = token.charOffset; if (declaration?.next == null) { return declaration; } else { Builder nearestDeclaration; int minDistance = -1; do { // Only look at declarations from this file (part). if (uri == declaration.fileUri) { // [distance] will always be non-negative as we ensure [token] is // always at the beginning of the declaration. The minimum distance // will often be larger than 0, for example, in a class declaration // where [token] will point to `abstract` or `class`, but the // declaration's offset points to the name of the class. int distance = declaration.charOffset - offset; if (distance >= 0) { if (minDistance == -1 || distance < minDistance) { minDistance = distance; nearestDeclaration = declaration; } } } declaration = declaration.next; } while (declaration != null); return nearestDeclaration; } } void checkBuilder(Token token, Builder declaration, Object name) { if (declaration == null) { internalProblem(templateInternalProblemNotFound.withArguments("$name"), token.charOffset, uri); } if (uri != declaration.fileUri) { unexpected("$uri", "${declaration.fileUri}", declaration.charOffset, declaration.fileUri); } } @override void addProblem(Message message, int charOffset, int length, {bool wasHandled: false, List<LocatedMessage> context}) { libraryBuilder.addProblem(message, charOffset, length, uri, wasHandled: wasHandled, context: context); } @override void debugEvent(String name) { // printEvent('DietListener: $name'); } /// If the [metadata] is not `null`, return the parsed metadata [Expression]s. /// Otherwise, return `null`. List<Expression> parseMetadata( ModifierBuilder builder, Token metadata, TreeNode parent) { if (metadata != null) { StackListener listener = createListener(builder, memberScope, isDeclarationInstanceMember: false); Parser parser = new Parser(listener); parser.parseMetadataStar(parser.syntheticPreviousToken(metadata)); return listener.finishMetadata(parent); } return null; } /// Returns [Token] found between [start] (inclusive) and [end] /// (non-inclusive) that has its [Token.charOffset] equal to [offset]. If /// there is no such token, null is returned. Token tokenForOffset(Token start, Token end, int offset) { if (offset < start.charOffset || offset >= end.charOffset) { return null; } while (start != end) { if (offset == start.charOffset) { return start; } start = start.next; } return null; } /// Returns list of [Token]s found between [start] (inclusive) and [end] /// (non-inclusive) that correspond to [offsets]. If there's no token between /// [start] and [end] for the given offset, the corresponding item in the /// resulting list is set to null. [offsets] are assumed to be in ascending /// order. List<Token> tokensForOffsets(Token start, Token end, List<int> offsets) { List<Token> result = new List<Token>.filled(offsets.length, null, growable: false); for (int i = 0; start != end && i < offsets.length;) { int offset = offsets[i]; if (offset < start.charOffset) { ++i; } else if (offset == start.charOffset) { result[i] = start; start = start.next; } else { start = start.next; } } return result; } @override bool isIgnoredError(Code<dynamic> code, Token token) { return isIgnoredParserError(code, token) || super.isIgnoredError(code, token); } }
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/source/scope_listener.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.scope_listener; import '../../scanner/token.dart' show Token; import '../scope.dart' show Scope; import 'stack_listener.dart' show NullValue, StackListener; export 'stack_listener.dart' show FixedNullableList, GrowableList, NullValue, ParserRecovery; enum JumpTargetKind { Break, Continue, Goto, // Continue label in switch. } abstract class ScopeListener<J> extends StackListener { Scope scope; J breakTarget; J continueTarget; ScopeListener(Scope scope) : scope = scope ?? new Scope.immutable(); J createJumpTarget(JumpTargetKind kind, int charOffset); J createBreakTarget(int charOffset) { return createJumpTarget(JumpTargetKind.Break, charOffset); } J createContinueTarget(int charOffset) { return createJumpTarget(JumpTargetKind.Continue, charOffset); } J createGotoTarget(int charOffset) { return createJumpTarget(JumpTargetKind.Goto, charOffset); } void enterLocalScope(String debugName, [Scope newScope]) { push(scope); scope = newScope ?? scope.createNestedScope(debugName); } @override void exitLocalScope() { scope = pop(); assert(scope != null); } void enterBreakTarget(int charOffset, [J target]) { push(breakTarget ?? NullValue.BreakTarget); breakTarget = target ?? createBreakTarget(charOffset); } void enterContinueTarget(int charOffset, [J target]) { push(continueTarget ?? NullValue.ContinueTarget); continueTarget = target ?? createContinueTarget(charOffset); } J exitBreakTarget() { J current = breakTarget; breakTarget = pop(); return current; } J exitContinueTarget() { J current = continueTarget; continueTarget = pop(); return current; } void enterLoop(int charOffset) { enterBreakTarget(charOffset); enterContinueTarget(charOffset); } @override void beginBlockFunctionBody(Token begin) { debugEvent("beginBlockFunctionBody"); enterLocalScope("block function body"); } @override void beginForStatement(Token token) { debugEvent("beginForStatement"); enterLoop(token.charOffset); enterLocalScope("for statement"); } @override void beginForControlFlow(Token awaitToken, Token forToken) { debugEvent("beginForControlFlow"); enterLocalScope("for in a collection"); } @override void beginBlock(Token token) { debugEvent("beginBlock"); enterLocalScope("block"); } @override void beginSwitchBlock(Token token) { debugEvent("beginSwitchBlock"); enterLocalScope("switch block"); enterBreakTarget(token.charOffset); } @override void beginDoWhileStatement(Token token) { debugEvent("beginDoWhileStatement"); enterLoop(token.charOffset); } @override void beginWhileStatement(Token token) { debugEvent("beginWhileStatement"); enterLoop(token.charOffset); } @override void beginDoWhileStatementBody(Token token) { debugEvent("beginDoWhileStatementBody"); enterLocalScope("do-while statement body"); } @override void endDoWhileStatementBody(Token token) { debugEvent("endDoWhileStatementBody"); Object body = pop(); exitLocalScope(); push(body); } @override void beginWhileStatementBody(Token token) { debugEvent("beginWhileStatementBody"); enterLocalScope("while statement body"); } @override void endWhileStatementBody(Token token) { debugEvent("endWhileStatementBody"); Object body = pop(); exitLocalScope(); push(body); } @override void beginForStatementBody(Token token) { debugEvent("beginForStatementBody"); enterLocalScope("for statement body"); } @override void endForStatementBody(Token token) { debugEvent("endForStatementBody"); Object body = pop(); exitLocalScope(); push(body); } @override void beginForInBody(Token token) { debugEvent("beginForInBody"); enterLocalScope("for-in body"); } @override void endForInBody(Token token) { debugEvent("endForInBody"); Object body = pop(); exitLocalScope(); push(body); } @override void beginThenStatement(Token token) { debugEvent("beginThenStatement"); enterLocalScope("then"); } @override void endThenStatement(Token token) { debugEvent("endThenStatement"); Object body = pop(); exitLocalScope(); push(body); } @override void beginElseStatement(Token token) { debugEvent("beginElseStatement"); enterLocalScope("else"); } @override void endElseStatement(Token token) { debugEvent("endElseStatement"); Object body = pop(); exitLocalScope(); push(body); } }
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/source/source_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.source_library_builder; import 'dart:convert' show jsonEncode; import 'package:kernel/ast.dart' show Arguments, Class, Constructor, ConstructorInvocation, DartType, DynamicType, Expression, Extension, Field, FunctionNode, FunctionType, InterfaceType, Library, LibraryDependency, LibraryPart, ListLiteral, MapLiteral, Member, Name, Procedure, ProcedureKind, SetLiteral, StaticInvocation, StringLiteral, Supertype, Typedef, TypeParameter, TypeParameterType, VariableDeclaration, VoidType; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy; import 'package:kernel/clone.dart' show CloneVisitor; import 'package:kernel/src/bounds_checks.dart' show TypeArgumentIssue, findTypeArgumentIssues, findTypeArgumentIssuesForInvocation, getGenericTypeName; import 'package:kernel/type_algebra.dart' show substitute; import 'package:kernel/type_environment.dart' show TypeEnvironment; import '../../base/resolve_relative_uri.dart' show resolveRelativeUri; import '../../scanner/token.dart' show Token; import '../builder/builder.dart' show Builder, ClassBuilder, ConstructorReferenceBuilder, EnumConstantInfo, FormalParameterBuilder, FunctionTypeBuilder, MemberBuilder, MetadataBuilder, NameIterator, PrefixBuilder, FunctionBuilder, NullabilityBuilder, QualifiedName, Scope, TypeBuilder, TypeDeclarationBuilder, TypeVariableBuilder, UnresolvedType, flattenName; import '../builder/extension_builder.dart'; import '../builder/library_builder.dart'; import '../combinator.dart' show Combinator; import '../configuration.dart' show Configuration; import '../export.dart' show Export; import '../fasta_codes.dart' show FormattedMessage, LocatedMessage, Message, messageConflictsWithTypeVariableCause, messageConstructorWithWrongName, messageExpectedUri, messageMemberWithSameNameAsClass, messageGenericFunctionTypeInBound, messageGenericFunctionTypeUsedAsActualTypeArgument, messageIncorrectTypeArgumentVariable, messageLanguageVersionInvalidInDotPackages, messageLanguageVersionMismatchInPart, messagePartExport, messagePartExportContext, messagePartInPart, messagePartInPartLibraryContext, messagePartOfSelf, messagePartOfTwoLibraries, messagePartOfTwoLibrariesContext, messageTypeVariableDuplicatedName, messageTypeVariableSameNameAsEnclosing, noLength, Template, templateConflictsWithMember, templateConflictsWithSetter, templateConflictsWithTypeVariable, templateConstructorWithWrongNameContext, templateCouldNotParseUri, templateDeferredPrefixDuplicated, templateDeferredPrefixDuplicatedCause, templateDuplicatedDeclaration, templateDuplicatedDeclarationCause, templateDuplicatedExport, templateDuplicatedExportInType, templateDuplicatedImport, templateDuplicatedImportInType, templateExportHidesExport, templateGenericFunctionTypeInferredAsActualTypeArgument, templateImportHidesImport, templateIncorrectTypeArgument, templateIncorrectTypeArgumentInReturnType, templateIncorrectTypeArgumentInferred, templateIncorrectTypeArgumentQualified, templateIncorrectTypeArgumentQualifiedInferred, templateIntersectionTypeAsTypeArgument, templateLanguageVersionTooHigh, templateLoadLibraryHidesMember, templateLocalDefinitionHidesExport, templateLocalDefinitionHidesImport, templateMissingPartOf, templateNotAPrefixInTypeAnnotation, templatePartOfInLibrary, templatePartOfLibraryNameMismatch, templatePartOfUriMismatch, templatePartOfUseUri, templatePartTwice, templatePatchInjectionFailed, templateTypeVariableDuplicatedNameCause; import '../import.dart' show Import; import '../kernel/kernel_builder.dart' show AccessErrorBuilder, BuiltinTypeBuilder, ClassBuilder, ConstructorReferenceBuilder, Builder, DynamicTypeBuilder, EnumConstantInfo, FormalParameterBuilder, FunctionTypeBuilder, ImplicitFieldType, InvalidTypeBuilder, ConstructorBuilder, EnumBuilder, FunctionBuilder, TypeAliasBuilder, FieldBuilder, MixinApplicationBuilder, NamedTypeBuilder, ProcedureBuilder, RedirectingFactoryBuilder, LibraryBuilder, LoadLibraryBuilder, MemberBuilder, MetadataBuilder, NameIterator, PrefixBuilder, QualifiedName, Scope, TypeBuilder, TypeDeclarationBuilder, TypeVariableBuilder, UnresolvedType, VoidTypeBuilder, compareProcedures, toKernelCombinators; import '../kernel/metadata_collector.dart'; import '../kernel/type_algorithms.dart' show calculateBounds, computeVariance, findGenericFunctionTypes, getNonSimplicityIssuesForDeclaration, getNonSimplicityIssuesForTypeVariables; import '../loader.dart' show Loader; import '../modifier.dart' show abstractMask, constMask, finalMask, hasConstConstructorMask, hasInitializerMask, initializingFormalMask, mixinDeclarationMask, namedMixinApplicationMask, staticMask; import '../names.dart' show indexSetName; import '../problems.dart' show unexpected, unhandled; import '../severity.dart' show Severity; import '../type_inference/type_inferrer.dart' show TypeInferrerImpl; import 'source_class_builder.dart' show SourceClassBuilder; import 'source_extension_builder.dart' show SourceExtensionBuilder; import 'source_loader.dart' show SourceLoader; class SourceLibraryBuilder extends LibraryBuilderImpl { static const String MALFORMED_URI_SCHEME = "org-dartlang-malformed-uri"; final SourceLoader loader; final TypeParameterScopeBuilder libraryDeclaration; final List<ConstructorReferenceBuilder> constructorReferences = <ConstructorReferenceBuilder>[]; final List<SourceLibraryBuilder> parts = <SourceLibraryBuilder>[]; // Can I use library.parts instead? See SourceLibraryBuilder.addPart. final List<int> partOffsets = <int>[]; final List<Import> imports = <Import>[]; final List<Export> exports = <Export>[]; final Scope importScope; final Uri fileUri; final List<ImplementationInfo> implementationBuilders = <ImplementationInfo>[]; final List<Object> accessors = <Object>[]; String documentationComment; String name; String partOfName; Uri partOfUri; List<MetadataBuilder> metadata; /// The current declaration that is being built. When we start parsing a /// declaration (class, method, and so on), we don't have enough information /// to create a builder and this object records its members and types until, /// for example, [addClass] is called. TypeParameterScopeBuilder currentTypeParameterScopeBuilder; bool canAddImplementationBuilders = false; /// Non-null if this library causes an error upon access, that is, there was /// an error reading its source. Message accessProblem; @override final Library library; final SourceLibraryBuilder actualOrigin; final List<FunctionBuilder> nativeMethods = <FunctionBuilder>[]; final List<TypeVariableBuilder> boundlessTypeVariables = <TypeVariableBuilder>[]; // A list of alternating forwarders and the procedures they were generated // for. Note that it may not include a forwarder-origin pair in cases when // the former does not need to be updated after the body of the latter was // built. final List<Procedure> forwardersOrigins = <Procedure>[]; // List of types inferred in the outline. Errors in these should be reported // differently than for specified types. // TODO(dmitryas): Find a way to mark inferred types. final Set<DartType> inferredTypes = new Set<DartType>.identity(); // While the bounds of type parameters aren't compiled yet, we can't tell the // default nullability of the corresponding type-parameter types. This list // is used to collect such type-parameter types in order to set the // nullability after the bounds are built. final List<TypeParameterType> pendingNullabilities = new List<TypeParameterType>(); // A library to use for Names generated when compiling code in this library. // This allows code generated in one library to use the private namespace of // another, for example during expression compilation (debugging). Library get nameOrigin => _nameOrigin ?? library; final Library _nameOrigin; /// Exports that can't be serialized. /// /// The key is the name of the exported member. /// /// If the name is `dynamic` or `void`, this library reexports the /// corresponding type from `dart:core`, and the value is null. /// /// Otherwise, this represents an error (an ambiguous export). In this case, /// the error message is the corresponding value in the map. Map<String, String> unserializableExports; List<FieldBuilder> implicitlyTypedFields; bool languageVersionExplicitlySet = false; bool postponedProblemsIssued = false; List<PostponedProblem> postponedProblems; SourceLibraryBuilder.internal(SourceLoader loader, Uri fileUri, Scope scope, SourceLibraryBuilder actualOrigin, Library library, Library nameOrigin) : this.fromScopes( loader, fileUri, new TypeParameterScopeBuilder.library(), scope ?? new Scope.top(), actualOrigin, library, nameOrigin); SourceLibraryBuilder.fromScopes( this.loader, this.fileUri, this.libraryDeclaration, this.importScope, this.actualOrigin, this.library, this._nameOrigin) : currentTypeParameterScopeBuilder = libraryDeclaration, super( fileUri, libraryDeclaration.toScope(importScope), new Scope.top()); SourceLibraryBuilder( Uri uri, Uri fileUri, Loader loader, SourceLibraryBuilder actualOrigin, {Scope scope, Library target, Library nameOrigin}) : this.internal( loader, fileUri, scope, actualOrigin, target ?? (actualOrigin?.library ?? new Library(uri, fileUri: fileUri) ..setLanguageVersion(loader.target.currentSdkVersionMajor, loader.target.currentSdkVersionMinor)), nameOrigin); @override bool get isPart => partOfName != null || partOfUri != null; List<UnresolvedType> get types => libraryDeclaration.types; @override bool get isSynthetic => accessProblem != null; TypeBuilder addType(TypeBuilder type, int charOffset) { currentTypeParameterScopeBuilder .addType(new UnresolvedType(type, charOffset, fileUri)); return type; } @override void setLanguageVersion(int major, int minor, {int offset: 0, int length: noLength, bool explicit: false}) { if (languageVersionExplicitlySet) return; if (explicit) languageVersionExplicitlySet = true; if (major == null || minor == null) { addPostponedProblem( messageLanguageVersionInvalidInDotPackages, offset, length, fileUri); return; } // If trying to set a langauge version that is higher than the current sdk // version it's an error. if (major > loader.target.currentSdkVersionMajor || (major == loader.target.currentSdkVersionMajor && minor > loader.target.currentSdkVersionMinor)) { addPostponedProblem( templateLanguageVersionTooHigh.withArguments( loader.target.currentSdkVersionMajor, loader.target.currentSdkVersionMinor), offset, length, fileUri); return; } library.setLanguageVersion(major, minor); } ConstructorReferenceBuilder addConstructorReference(Object name, List<TypeBuilder> typeArguments, String suffix, int charOffset) { ConstructorReferenceBuilder ref = new ConstructorReferenceBuilder( name, typeArguments, suffix, this, charOffset); constructorReferences.add(ref); return ref; } void beginNestedDeclaration(TypeParameterScopeKind kind, String name, {bool hasMembers: true}) { currentTypeParameterScopeBuilder = currentTypeParameterScopeBuilder.createNested(kind, name, hasMembers); } TypeParameterScopeBuilder endNestedDeclaration( TypeParameterScopeKind kind, String name) { assert( currentTypeParameterScopeBuilder.kind == kind, "Unexpected declaration. " "Trying to end a ${currentTypeParameterScopeBuilder.kind} as a $kind."); assert( (name?.startsWith(currentTypeParameterScopeBuilder.name) ?? (name == currentTypeParameterScopeBuilder.name)) || currentTypeParameterScopeBuilder.name == "operator" || identical(name, "<syntax-error>"), "${name} != ${currentTypeParameterScopeBuilder.name}"); TypeParameterScopeBuilder previous = currentTypeParameterScopeBuilder; currentTypeParameterScopeBuilder = currentTypeParameterScopeBuilder.parent; return previous; } bool uriIsValid(Uri uri) => uri.scheme != MALFORMED_URI_SCHEME; Uri resolve(Uri baseUri, String uri, int uriOffset, {isPart: false}) { if (uri == null) { addProblem(messageExpectedUri, uriOffset, noLength, this.uri); return new Uri(scheme: MALFORMED_URI_SCHEME); } Uri parsedUri; try { parsedUri = Uri.parse(uri); } on FormatException catch (e) { // Point to position in string indicated by the exception, // or to the initial quote if no position is given. // (Assumes the directive is using a single-line string.) addProblem(templateCouldNotParseUri.withArguments(uri, e.message), uriOffset + 1 + (e.offset ?? -1), 1, this.uri); return new Uri( scheme: MALFORMED_URI_SCHEME, query: Uri.encodeQueryComponent(uri)); } if (isPart && baseUri.scheme == "dart") { // Resolve using special rules for dart: URIs return resolveRelativeUri(baseUri, parsedUri); } else { return baseUri.resolveUri(parsedUri); } } String computeAndValidateConstructorName(Object name, int charOffset, {isFactory: false}) { String className = currentTypeParameterScopeBuilder.name; String prefix; String suffix; if (name is QualifiedName) { prefix = name.qualifier; suffix = name.name; } else { prefix = name; suffix = null; } if (prefix == className) { return suffix ?? ""; } if (suffix == null && !isFactory) { // A legal name for a regular method, but not for a constructor. return null; } addProblem( messageConstructorWithWrongName, charOffset, prefix.length, fileUri, context: [ templateConstructorWithWrongNameContext .withArguments(currentTypeParameterScopeBuilder.name) .withLocation(uri, currentTypeParameterScopeBuilder.charOffset, currentTypeParameterScopeBuilder.name.length) ]); return suffix; } void addExport( List<MetadataBuilder> metadata, String uri, List<Configuration> configurations, List<Combinator> combinators, int charOffset, int uriOffset) { if (configurations != null) { for (Configuration config in configurations) { if (lookupImportCondition(config.dottedName) == config.condition) { uri = config.importUri; break; } } } LibraryBuilder exportedLibrary = loader .read(resolve(this.uri, uri, uriOffset), charOffset, accessor: this); exportedLibrary.addExporter(this, combinators, charOffset); exports.add(new Export(this, exportedLibrary, combinators, charOffset)); } String lookupImportCondition(String dottedName) { const String prefix = "dart.library."; if (!dottedName.startsWith(prefix)) return ""; dottedName = dottedName.substring(prefix.length); if (!loader.target.uriTranslator.isLibrarySupported(dottedName)) return ""; LibraryBuilder imported = loader.builders[new Uri(scheme: "dart", path: dottedName)]; if (imported == null) { LibraryBuilder coreLibrary = loader.read( resolve( this.uri, new Uri(scheme: "dart", path: "core").toString(), -1), -1); imported = coreLibrary .loader.builders[new Uri(scheme: 'dart', path: dottedName)]; } return imported != null ? "true" : ""; } void addImport( List<MetadataBuilder> metadata, String uri, List<Configuration> configurations, String prefix, List<Combinator> combinators, bool deferred, int charOffset, int prefixCharOffset, int uriOffset, int importIndex) { if (configurations != null) { for (Configuration config in configurations) { if (lookupImportCondition(config.dottedName) == config.condition) { uri = config.importUri; break; } } } LibraryBuilder builder = null; Uri resolvedUri; String nativePath; const String nativeExtensionScheme = "dart-ext:"; if (uri.startsWith(nativeExtensionScheme)) { String strippedUri = uri.substring(nativeExtensionScheme.length); if (strippedUri.startsWith("package")) { resolvedUri = resolve( this.uri, strippedUri, uriOffset + nativeExtensionScheme.length); resolvedUri = loader.target.translateUri(resolvedUri); nativePath = resolvedUri.toString(); } else { resolvedUri = new Uri(scheme: "dart-ext", pathSegments: [uri]); nativePath = uri; } } else { resolvedUri = resolve(this.uri, uri, uriOffset); builder = loader.read(resolvedUri, uriOffset, accessor: this); } imports.add(new Import(this, builder, deferred, prefix, combinators, configurations, charOffset, prefixCharOffset, importIndex, nativeImportPath: nativePath)); } void addPart(List<MetadataBuilder> metadata, String uri, int charOffset) { Uri resolvedUri; Uri newFileUri; resolvedUri = resolve(this.uri, uri, charOffset, isPart: true); newFileUri = resolve(fileUri, uri, charOffset); parts.add(loader.read(resolvedUri, charOffset, fileUri: newFileUri, accessor: this)); partOffsets.add(charOffset); // TODO(ahe): [metadata] should be stored, evaluated, and added to [part]. LibraryPart part = new LibraryPart(<Expression>[], uri) ..fileOffset = charOffset; library.addPart(part); } void addPartOf( List<MetadataBuilder> metadata, String name, String uri, int uriOffset) { partOfName = name; if (uri != null) { partOfUri = resolve(this.uri, uri, uriOffset); Uri newFileUri = resolve(fileUri, uri, uriOffset); LibraryBuilder library = loader.read(partOfUri, uriOffset, fileUri: newFileUri, accessor: this); if (loader.first == this) { // This is a part, and it was the first input. Let the loader know // about that. loader.first = library; } } } void addFields(String documentationComment, List<MetadataBuilder> metadata, int modifiers, TypeBuilder type, List<FieldInfo> fieldInfos) { for (FieldInfo info in fieldInfos) { bool isConst = modifiers & constMask != 0; bool isFinal = modifiers & finalMask != 0; bool potentiallyNeedInitializerInOutline = isConst || isFinal; Token startToken; if (potentiallyNeedInitializerInOutline || type == null) { startToken = info.initializerToken; } if (startToken != null) { // Extract only the tokens for the initializer expression from the // token stream. Token endToken = info.beforeLast; endToken.setNext(new Token.eof(endToken.next.offset)); new Token.eof(startToken.previous.offset).setNext(startToken); } bool hasInitializer = info.initializerToken != null; addField(documentationComment, metadata, modifiers, type, info.name, info.charOffset, info.charEndOffset, startToken, hasInitializer, constInitializerToken: potentiallyNeedInitializerInOutline ? startToken : null); } } Builder addBuilder(String name, Builder declaration, int charOffset) { // TODO(ahe): Set the parent correctly here. Could then change the // implementation of MemberBuilder.isTopLevel to test explicitly for a // LibraryBuilder. if (name == null) { unhandled("null", "name", charOffset, fileUri); } if (currentTypeParameterScopeBuilder == libraryDeclaration) { if (declaration is MemberBuilder) { declaration.parent = this; } else if (declaration is TypeDeclarationBuilder) { declaration.parent = this; } else if (declaration is PrefixBuilder) { assert(declaration.parent == this); } else { return unhandled( "${declaration.runtimeType}", "addBuilder", charOffset, fileUri); } } else { assert(currentTypeParameterScopeBuilder.parent == libraryDeclaration); } bool isConstructor = declaration is FunctionBuilder && (declaration.isConstructor || declaration.isFactory); if (!isConstructor && name == currentTypeParameterScopeBuilder.name) { addProblem( messageMemberWithSameNameAsClass, charOffset, noLength, fileUri); } Map<String, Builder> members = isConstructor ? currentTypeParameterScopeBuilder.constructors : (declaration.isSetter ? currentTypeParameterScopeBuilder.setters : currentTypeParameterScopeBuilder.members); Builder existing = members[name]; if (declaration.next != null && declaration.next != existing) { unexpected( "${declaration.next.fileUri}@${declaration.next.charOffset}", "${existing?.fileUri}@${existing?.charOffset}", declaration.charOffset, declaration.fileUri); } declaration.next = existing; if (declaration is PrefixBuilder && existing is PrefixBuilder) { assert(existing.next is! PrefixBuilder); Builder deferred; Builder other; if (declaration.deferred) { deferred = declaration; other = existing; } else if (existing.deferred) { deferred = existing; other = declaration; } if (deferred != null) { addProblem(templateDeferredPrefixDuplicated.withArguments(name), deferred.charOffset, noLength, fileUri, context: [ templateDeferredPrefixDuplicatedCause .withArguments(name) .withLocation(fileUri, other.charOffset, noLength) ]); } return existing ..exportScope.merge(declaration.exportScope, (String name, Builder existing, Builder member) { return computeAmbiguousDeclaration( name, existing, member, charOffset); }); } else if (isDuplicatedDeclaration(existing, declaration)) { String fullName = name; if (isConstructor) { if (name.isEmpty) { fullName = currentTypeParameterScopeBuilder.name; } else { fullName = "${currentTypeParameterScopeBuilder.name}.$name"; } } addProblem(templateDuplicatedDeclaration.withArguments(fullName), charOffset, fullName.length, declaration.fileUri, context: <LocatedMessage>[ templateDuplicatedDeclarationCause .withArguments(fullName) .withLocation( existing.fileUri, existing.charOffset, fullName.length) ]); } else if (declaration.isExtension) { // We add the extension declaration to the extension scope only if its // name is unique. Only the first of duplicate extensions is accessible // by name or by resolution and the remaining are dropped for the output. currentTypeParameterScopeBuilder.extensions.add(declaration); } return members[name] = declaration; } bool isDuplicatedDeclaration(Builder existing, Builder other) { if (existing == null) return false; Builder next = existing.next; if (next == null) { if (existing.isGetter && other.isSetter) return false; if (existing.isSetter && other.isGetter) return false; } else { if (next is ClassBuilder && !next.isMixinApplication) return true; } if (existing is ClassBuilder && other is ClassBuilder) { // We allow multiple mixin applications with the same name. An // alternative is to share these mixin applications. This situation can // happen if you have `class A extends Object with Mixin {}` and `class B // extends Object with Mixin {}` in the same library. return !existing.isMixinApplication || !other.isMixinApplication; } return true; } Library build(LibraryBuilder coreLibrary, {bool modifyTarget}) { assert(implementationBuilders.isEmpty); canAddImplementationBuilders = true; Iterator<Builder> iterator = this.iterator; while (iterator.moveNext()) { buildBuilder(iterator.current, coreLibrary); } for (ImplementationInfo info in implementationBuilders) { String name = info.name; Builder declaration = info.declaration; int charOffset = info.charOffset; addBuilder(name, declaration, charOffset); buildBuilder(declaration, coreLibrary); } canAddImplementationBuilders = false; scope.setters.forEach((String name, Builder setter) { Builder member = scopeBuilder[name]; if (member == null || !member.isField || member.isFinal || member.isConst) { return; } addProblem(templateConflictsWithMember.withArguments(name), setter.charOffset, noLength, fileUri); // TODO(ahe): Context to previous message? addProblem(templateConflictsWithSetter.withArguments(name), member.charOffset, noLength, fileUri); }); if (modifyTarget == false) return library; library.isSynthetic = isSynthetic; addDependencies(library, new Set<SourceLibraryBuilder>()); loader.target.metadataCollector ?.setDocumentationComment(library, documentationComment); library.name = name; library.procedures.sort(compareProcedures); if (unserializableExports != null) { library.addMember(new Field(new Name("_exports#", library), initializer: new StringLiteral(jsonEncode(unserializableExports)), isStatic: true, isConst: true)); } return library; } /// Used to add implementation builder during the call to [build] above. /// Currently, only anonymous mixins are using implementation builders (see /// [MixinApplicationBuilder] /// (../kernel/kernel_mixin_application_builder.dart)). void addImplementationBuilder( String name, Builder declaration, int charOffset) { assert(canAddImplementationBuilders, "$uri"); implementationBuilders .add(new ImplementationInfo(name, declaration, charOffset)); } void validatePart(SourceLibraryBuilder library, Set<Uri> usedParts) { if (library != null && parts.isNotEmpty) { // If [library] is null, we have already reported a problem that this // part is orphaned. List<LocatedMessage> context = <LocatedMessage>[ messagePartInPartLibraryContext.withLocation(library.fileUri, -1, 1), ]; for (int offset in partOffsets) { addProblem(messagePartInPart, offset, noLength, fileUri, context: context); } for (SourceLibraryBuilder part in parts) { // Mark this part as used so we don't report it as orphaned. usedParts.add(part.uri); } } parts.clear(); if (exporters.isNotEmpty) { List<LocatedMessage> context = <LocatedMessage>[ messagePartExportContext.withLocation(fileUri, -1, 1), ]; for (Export export in exporters) { export.exporter.addProblem( messagePartExport, export.charOffset, "export".length, null, context: context); } } } void includeParts(Set<Uri> usedParts) { Set<Uri> seenParts = new Set<Uri>(); for (int i = 0; i < parts.length; i++) { SourceLibraryBuilder part = parts[i]; int partOffset = partOffsets[i]; if (part == this) { addProblem(messagePartOfSelf, -1, noLength, fileUri); } else if (seenParts.add(part.fileUri)) { if (part.partOfLibrary != null) { addProblem(messagePartOfTwoLibraries, -1, noLength, part.fileUri, context: [ messagePartOfTwoLibrariesContext.withLocation( part.partOfLibrary.fileUri, -1, noLength), messagePartOfTwoLibrariesContext.withLocation( this.fileUri, -1, noLength) ]); } else { if (isPatch) { usedParts.add(part.fileUri); } else { usedParts.add(part.uri); } includePart(part, usedParts, partOffset); } } else { addProblem(templatePartTwice.withArguments(part.fileUri), -1, noLength, fileUri); } } } bool includePart( SourceLibraryBuilder part, Set<Uri> usedParts, int partOffset) { if (part.partOfUri != null) { if (uriIsValid(part.partOfUri) && part.partOfUri != uri) { // This is an error, but the part is not removed from the list of parts, // so that metadata annotations can be associated with it. addProblem( templatePartOfUriMismatch.withArguments( part.fileUri, uri, part.partOfUri), partOffset, noLength, fileUri); return false; } } else if (part.partOfName != null) { if (name != null) { if (part.partOfName != name) { // This is an error, but the part is not removed from the list of // parts, so that metadata annotations can be associated with it. addProblem( templatePartOfLibraryNameMismatch.withArguments( part.fileUri, name, part.partOfName), partOffset, noLength, fileUri); return false; } } else { // This is an error, but the part is not removed from the list of parts, // so that metadata annotations can be associated with it. addProblem( templatePartOfUseUri.withArguments( part.fileUri, fileUri, part.partOfName), partOffset, noLength, fileUri); return false; } } else { // This is an error, but the part is not removed from the list of parts, // so that metadata annotations can be associated with it. assert(!part.isPart); if (uriIsValid(part.fileUri)) { addProblem(templateMissingPartOf.withArguments(part.fileUri), partOffset, noLength, fileUri); } return false; } // Language versions have to match. if ((this.languageVersionExplicitlySet != part.languageVersionExplicitlySet) || (this.library.languageVersionMajor != part.library.languageVersionMajor || this.library.languageVersionMinor != part.library.languageVersionMinor)) { // This is an error, but the part is not removed from the list of // parts, so that metadata annotations can be associated with it. addProblem( messageLanguageVersionMismatchInPart, partOffset, noLength, fileUri); return false; } part.validatePart(this, usedParts); NameIterator partDeclarations = part.nameIterator; while (partDeclarations.moveNext()) { String name = partDeclarations.name; Builder declaration = partDeclarations.current; if (declaration.next != null) { List<Builder> duplicated = <Builder>[]; while (declaration.next != null) { duplicated.add(declaration); partDeclarations.moveNext(); declaration = partDeclarations.current; } duplicated.add(declaration); // Handle duplicated declarations in the part. // // Duplicated declarations are handled by creating a linked list using // the `next` field. This is preferred over making all scope entries be // a `List<Declaration>`. // // We maintain the linked list so that the last entry is easy to // recognize (it's `next` field is null). This means that it is // reversed with respect to source code order. Since kernel doesn't // allow duplicated declarations, we ensure that we only add the first // declaration to the kernel tree. // // Since the duplicated declarations are stored in reverse order, we // iterate over them in reverse order as this is simpler and normally // not a problem. However, in this case we need to call [addBuilder] in // source order as it would otherwise create cycles. // // We also need to be careful preserving the order of the links. The // part library still keeps these declarations in its scope so that // DietListener can find them. for (int i = duplicated.length; i > 0; i--) { Builder declaration = duplicated[i - 1]; addBuilder(name, declaration, declaration.charOffset); } } else { addBuilder(name, declaration, declaration.charOffset); } } types.addAll(part.types); constructorReferences.addAll(part.constructorReferences); part.partOfLibrary = this; part.scope.becomePartOf(scope); // TODO(ahe): Include metadata from part? nativeMethods.addAll(part.nativeMethods); boundlessTypeVariables.addAll(part.boundlessTypeVariables); // Check that the targets are different. This is not normally a problem // but is for patch files. if (library != part.library && part.library.problemsAsJson != null) { library.problemsAsJson ??= <String>[]; library.problemsAsJson.addAll(part.library.problemsAsJson); } List<FieldBuilder> partImplicitlyTypedFields = part.takeImplicitlyTypedFields(); if (partImplicitlyTypedFields != null) { if (implicitlyTypedFields == null) { implicitlyTypedFields = partImplicitlyTypedFields; } else { implicitlyTypedFields.addAll(partImplicitlyTypedFields); } } return true; } void buildInitialScopes() { NameIterator iterator = nameIterator; while (iterator.moveNext()) { addToExportScope(iterator.name, iterator.current); } } void addImportsToScope() { bool explicitCoreImport = this == loader.coreLibrary; for (Import import in imports) { if (import.imported == loader.coreLibrary) { explicitCoreImport = true; } if (import.imported?.isPart ?? false) { addProblem( templatePartOfInLibrary.withArguments(import.imported.fileUri), import.charOffset, noLength, fileUri); } import.finalizeImports(this); } if (!explicitCoreImport) { loader.coreLibrary.exportScope.forEach((String name, Builder member) { addToScope(name, member, -1, true); }); } exportScope.forEach((String name, Builder member) { if (member.parent != this) { switch (name) { case "dynamic": case "void": unserializableExports ??= <String, String>{}; unserializableExports[name] = null; break; default: if (member is InvalidTypeBuilder) { unserializableExports ??= <String, String>{}; unserializableExports[name] = member.message.message; } else { // Eventually (in #buildBuilder) members aren't added to the // library if the have 'next' pointers, so don't add them as // additionalExports either. Add the last one only (the one that // will eventually be added to the library). Builder memberLast = member; while (memberLast.next != null) { memberLast = memberLast.next; } if (memberLast is ClassBuilder) { library.additionalExports.add(memberLast.cls.reference); } else if (memberLast is TypeAliasBuilder) { library.additionalExports.add(memberLast.typedef.reference); } else if (memberLast is ExtensionBuilder) { library.additionalExports.add(memberLast.extension.reference); } else { library.additionalExports.add(memberLast.target.reference); } } } } }); } @override void addToScope(String name, Builder member, int charOffset, bool isImport) { Map<String, Builder> map = member.isSetter ? importScope.setters : importScope.local; Builder existing = map[name]; if (existing != null) { if (existing != member) { map[name] = computeAmbiguousDeclaration( name, existing, member, charOffset, isImport: isImport); } } else { map[name] = member; } if (member.isExtension) { importScope.addExtension(member); } } /// Resolves all unresolved types in [types]. The list of types is cleared /// when done. int resolveTypes() { int typeCount = types.length; for (UnresolvedType t in types) { t.resolveIn(scope, this); t.checkType(this); } types.clear(); return typeCount; } @override int resolveConstructors(_) { int count = 0; Iterator<Builder> iterator = this.iterator; while (iterator.moveNext()) { count += iterator.current.resolveConstructors(this); } return count; } @override String get fullNameForErrors { // TODO(ahe): Consider if we should use relativizeUri here. The downside to // doing that is that this URI may be used in an error message. Ideally, we // should create a class that represents qualified names that we can // relativize when printing a message, but still store the full URI in // .dill files. return name ?? "<library '$fileUri'>"; } @override void recordAccess(int charOffset, int length, Uri fileUri) { accessors.add(fileUri); accessors.add(charOffset); accessors.add(length); if (accessProblem != null) { addProblem(accessProblem, charOffset, length, fileUri); } } void addProblemAtAccessors(Message message) { if (accessProblem == null) { if (accessors.isEmpty && this == loader.first) { // This is the entry point library, and nobody access it directly. So // we need to report a problem. loader.addProblem(message, -1, 1, null); } for (int i = 0; i < accessors.length; i += 3) { Uri accessor = accessors[i]; int charOffset = accessors[i + 1]; int length = accessors[i + 2]; addProblem(message, charOffset, length, accessor); } accessProblem = message; } } @override SourceLibraryBuilder get origin => actualOrigin ?? this; Uri get uri => library.importUri; void addSyntheticDeclarationOfDynamic() { addBuilder( "dynamic", new DynamicTypeBuilder(const DynamicType(), this, -1), -1); } TypeBuilder addNamedType(Object name, NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments, int charOffset) { return addType( new NamedTypeBuilder(name, nullabilityBuilder, arguments), charOffset); } TypeBuilder addMixinApplication( TypeBuilder supertype, List<TypeBuilder> mixins, int charOffset) { return addType(new MixinApplicationBuilder(supertype, mixins), charOffset); } TypeBuilder addVoidType(int charOffset) { // 'void' is always nullable. return addNamedType( "void", const NullabilityBuilder.nullable(), null, charOffset) ..bind(new VoidTypeBuilder(const VoidType(), this, charOffset)); } /// Add a problem that might not be reported immediately. /// /// Problems will be issued after source information has been added. /// Once the problems has been issued, adding a new "postponed" problem will /// be issued immediately. void addPostponedProblem( Message message, int charOffset, int length, Uri fileUri) { if (postponedProblemsIssued) { addProblem(message, charOffset, length, fileUri); } else { postponedProblems ??= <PostponedProblem>[]; postponedProblems .add(new PostponedProblem(message, charOffset, length, fileUri)); } } void issuePostponedProblems() { postponedProblemsIssued = true; if (postponedProblems == null) return; for (int i = 0; i < postponedProblems.length; ++i) { PostponedProblem postponedProblem = postponedProblems[i]; addProblem(postponedProblem.message, postponedProblem.charOffset, postponedProblem.length, postponedProblem.fileUri); } postponedProblems = null; } @override FormattedMessage addProblem( Message message, int charOffset, int length, Uri fileUri, {bool wasHandled: false, List<LocatedMessage> context, Severity severity, bool problemOnLibrary: false}) { FormattedMessage formattedMessage = super.addProblem( message, charOffset, length, fileUri, wasHandled: wasHandled, context: context, severity: severity, problemOnLibrary: true); if (formattedMessage != null) { library.problemsAsJson ??= <String>[]; library.problemsAsJson.add(formattedMessage.toJsonString()); } return formattedMessage; } void addClass( String documentationComment, List<MetadataBuilder> metadata, int modifiers, String className, List<TypeVariableBuilder> typeVariables, TypeBuilder supertype, List<TypeBuilder> interfaces, int startOffset, int nameOffset, int endOffset, int supertypeOffset) { _addClass( TypeParameterScopeKind.classDeclaration, documentationComment, metadata, modifiers, className, typeVariables, supertype, interfaces, startOffset, nameOffset, endOffset, supertypeOffset); } void addMixinDeclaration( String documentationComment, List<MetadataBuilder> metadata, int modifiers, String className, List<TypeVariableBuilder> typeVariables, TypeBuilder supertype, List<TypeBuilder> interfaces, int startOffset, int nameOffset, int endOffset, int supertypeOffset) { _addClass( TypeParameterScopeKind.mixinDeclaration, documentationComment, metadata, modifiers, className, typeVariables, supertype, interfaces, startOffset, nameOffset, endOffset, supertypeOffset); } void _addClass( TypeParameterScopeKind kind, String documentationComment, List<MetadataBuilder> metadata, int modifiers, String className, List<TypeVariableBuilder> typeVariables, TypeBuilder supertype, List<TypeBuilder> interfaces, int startOffset, int nameOffset, int endOffset, int supertypeOffset) { // Nested declaration began in `OutlineBuilder.beginClassDeclaration`. TypeParameterScopeBuilder declaration = endNestedDeclaration(kind, className) ..resolveTypes(typeVariables, this); assert(declaration.parent == libraryDeclaration); Map<String, MemberBuilder> members = declaration.members; Map<String, MemberBuilder> constructors = declaration.constructors; Map<String, MemberBuilder> setters = declaration.setters; Scope classScope = new Scope( local: members, setters: setters, parent: scope.withTypeVariables(typeVariables), debugName: "class $className", isModifiable: false); // When looking up a constructor, we don't consider type variables or the // library scope. Scope constructorScope = new Scope( local: constructors, debugName: className, isModifiable: false); bool isMixinDeclaration = false; if (modifiers & mixinDeclarationMask != 0) { isMixinDeclaration = true; modifiers = (modifiers & ~mixinDeclarationMask) | abstractMask; } if (declaration.hasConstConstructor) { modifiers |= hasConstConstructorMask; } ClassBuilder classBuilder = new SourceClassBuilder( metadata, modifiers, className, typeVariables, applyMixins(supertype, startOffset, nameOffset, endOffset, className, isMixinDeclaration, typeVariables: typeVariables), interfaces, // TODO(johnniwinther): Add the `on` clause types of a mixin declaration // here. null, classScope, constructorScope, this, new List<ConstructorReferenceBuilder>.from(constructorReferences), startOffset, nameOffset, endOffset, isMixinDeclaration: isMixinDeclaration); loader.target.metadataCollector ?.setDocumentationComment(classBuilder.cls, documentationComment); constructorReferences.clear(); Map<String, TypeVariableBuilder> typeVariablesByName = checkTypeVariables(typeVariables, classBuilder); void setParent(String name, MemberBuilder member) { while (member != null) { member.parent = classBuilder; member = member.next; } } void setParentAndCheckConflicts(String name, MemberBuilder member) { if (typeVariablesByName != null) { TypeVariableBuilder tv = typeVariablesByName[name]; if (tv != null) { classBuilder.addProblem( templateConflictsWithTypeVariable.withArguments(name), member.charOffset, name.length, context: [ messageConflictsWithTypeVariableCause.withLocation( tv.fileUri, tv.charOffset, name.length) ]); } } setParent(name, member); } members.forEach(setParentAndCheckConflicts); constructors.forEach(setParentAndCheckConflicts); setters.forEach(setParentAndCheckConflicts); addBuilder(className, classBuilder, nameOffset); } Map<String, TypeVariableBuilder> checkTypeVariables( List<TypeVariableBuilder> typeVariables, Builder owner) { if (typeVariables?.isEmpty ?? true) return null; Map<String, TypeVariableBuilder> typeVariablesByName = <String, TypeVariableBuilder>{}; for (TypeVariableBuilder tv in typeVariables) { TypeVariableBuilder existing = typeVariablesByName[tv.name]; if (existing != null) { if (existing.isExtensionTypeParameter) { // The type parameter from the extension is shadowed by the type // parameter from the member. Rename the shadowed type parameter. existing.parameter.name = '#${existing.name}'; typeVariablesByName[tv.name] = tv; } else { addProblem(messageTypeVariableDuplicatedName, tv.charOffset, tv.name.length, fileUri, context: [ templateTypeVariableDuplicatedNameCause .withArguments(tv.name) .withLocation( fileUri, existing.charOffset, existing.name.length) ]); } } else { typeVariablesByName[tv.name] = tv; if (owner is ClassBuilder) { // Only classes and type variables can't have the same name. See // [#29555](https://github.com/dart-lang/sdk/issues/29555). if (tv.name == owner.name) { addProblem(messageTypeVariableSameNameAsEnclosing, tv.charOffset, tv.name.length, fileUri); } } } } return typeVariablesByName; } void addExtensionDeclaration( String documentationComment, List<MetadataBuilder> metadata, int modifiers, String extensionName, List<TypeVariableBuilder> typeVariables, TypeBuilder type, int startOffset, int nameOffset, int endOffset) { // Nested declaration began in `OutlineBuilder.beginExtensionDeclaration`. TypeParameterScopeBuilder declaration = endNestedDeclaration( TypeParameterScopeKind.extensionDeclaration, extensionName) ..resolveTypes(typeVariables, this); assert(declaration.parent == libraryDeclaration); Map<String, MemberBuilder> members = declaration.members; Map<String, MemberBuilder> constructors = declaration.constructors; Map<String, MemberBuilder> setters = declaration.setters; Scope classScope = new Scope( local: members, setters: setters, parent: scope.withTypeVariables(typeVariables), debugName: "extension $extensionName", isModifiable: false); ExtensionBuilder extensionBuilder = new SourceExtensionBuilder( metadata, modifiers, extensionName, typeVariables, type, classScope, this, startOffset, nameOffset, endOffset); loader.target.metadataCollector?.setDocumentationComment( extensionBuilder.extension, documentationComment); constructorReferences.clear(); Map<String, TypeVariableBuilder> typeVariablesByName = checkTypeVariables(typeVariables, extensionBuilder); void setParent(String name, MemberBuilder member) { while (member != null) { member.parent = extensionBuilder; member = member.next; } } void setParentAndCheckConflicts(String name, MemberBuilder member) { if (typeVariablesByName != null) { TypeVariableBuilder tv = typeVariablesByName[name]; if (tv != null) { extensionBuilder.addProblem( templateConflictsWithTypeVariable.withArguments(name), member.charOffset, name.length, context: [ messageConflictsWithTypeVariableCause.withLocation( tv.fileUri, tv.charOffset, name.length) ]); } } setParent(name, member); } members.forEach(setParentAndCheckConflicts); constructors.forEach(setParentAndCheckConflicts); setters.forEach(setParentAndCheckConflicts); addBuilder(extensionName, extensionBuilder, nameOffset); } TypeBuilder applyMixins(TypeBuilder type, int startCharOffset, int charOffset, int charEndOffset, String subclassName, bool isMixinDeclaration, {String documentationComment, List<MetadataBuilder> metadata, String name, List<TypeVariableBuilder> typeVariables, int modifiers, List<TypeBuilder> interfaces}) { if (name == null) { // The following parameters should only be used when building a named // mixin application. if (documentationComment != null) { unhandled("documentationComment", "unnamed mixin application", charOffset, fileUri); } else if (metadata != null) { unhandled("metadata", "unnamed mixin application", charOffset, fileUri); } else if (interfaces != null) { unhandled( "interfaces", "unnamed mixin application", charOffset, fileUri); } } if (type is MixinApplicationBuilder) { // Documentation below assumes the given mixin application is in one of // these forms: // // class C extends S with M1, M2, M3; // class Named = S with M1, M2, M3; // // When we refer to the subclass, we mean `C` or `Named`. /// The current supertype. /// /// Starts out having the value `S` and on each iteration of the loop /// below, it will take on the value corresponding to: /// /// 1. `S with M1`. /// 2. `(S with M1) with M2`. /// 3. `((S with M1) with M2) with M3`. TypeBuilder supertype = type.supertype ?? loader.target.objectType; /// The variable part of the mixin application's synthetic name. It /// starts out as the name of the superclass, but is only used after it /// has been combined with the name of the current mixin. In the examples /// from above, it will take these values: /// /// 1. `S&M1` /// 2. `S&M1&M2` /// 3. `S&M1&M2&M3`. /// /// The full name of the mixin application is obtained by prepending the /// name of the subclass (`C` or `Named` in the above examples) to the /// running name. For the example `C`, that leads to these full names: /// /// 1. `_C&S&M1` /// 2. `_C&S&M1&M2` /// 3. `_C&S&M1&M2&M3`. /// /// For a named mixin application, the last name has been given by the /// programmer, so for the example `Named` we see these full names: /// /// 1. `_Named&S&M1` /// 2. `_Named&S&M1&M2` /// 3. `Named`. String runningName = extractName(supertype.name); /// True when we're building a named mixin application. Notice that for /// the `Named` example above, this is only true on the last /// iteration because only the full mixin application is named. bool isNamedMixinApplication; /// The names of the type variables of the subclass. Set<String> typeVariableNames; if (typeVariables != null) { typeVariableNames = new Set<String>(); for (TypeVariableBuilder typeVariable in typeVariables) { typeVariableNames.add(typeVariable.name); } } /// Helper function that returns `true` if a type variable with a name /// from [typeVariableNames] is referenced in [type]. bool usesTypeVariables(TypeBuilder type) { if (type is NamedTypeBuilder) { if (type.declaration is TypeVariableBuilder) { return typeVariableNames.contains(type.declaration.name); } List<TypeBuilder> typeArguments = type.arguments; if (typeArguments != null && typeVariables != null) { for (TypeBuilder argument in typeArguments) { if (usesTypeVariables(argument)) { return true; } } } } else if (type is FunctionTypeBuilder) { if (type.formals != null) { for (FormalParameterBuilder formal in type.formals) { if (usesTypeVariables(formal.type)) { return true; } } } return usesTypeVariables(type.returnType); } return false; } /// Iterate over the mixins from left to right. At the end of each /// iteration, a new [supertype] is computed that is the mixin /// application of [supertype] with the current mixin. for (int i = 0; i < type.mixins.length; i++) { TypeBuilder mixin = type.mixins[i]; isNamedMixinApplication = name != null && mixin == type.mixins.last; bool isGeneric = false; if (!isNamedMixinApplication) { if (supertype is NamedTypeBuilder) { isGeneric = isGeneric || usesTypeVariables(supertype); } if (mixin is NamedTypeBuilder) { runningName += "&${extractName(mixin.name)}"; isGeneric = isGeneric || usesTypeVariables(mixin); } } String fullname = isNamedMixinApplication ? name : "_$subclassName&$runningName"; List<TypeVariableBuilder> applicationTypeVariables; List<TypeBuilder> applicationTypeArguments; if (isNamedMixinApplication) { // If this is a named mixin application, it must be given all the // declarated type variables. applicationTypeVariables = typeVariables; } else { // Otherwise, we pass the fresh type variables to the mixin // application in the same order as they're declared on the subclass. if (isGeneric) { this.beginNestedDeclaration( TypeParameterScopeKind.unnamedMixinApplication, "mixin application"); applicationTypeVariables = copyTypeVariables( typeVariables, currentTypeParameterScopeBuilder); List<TypeBuilder> newTypes = <TypeBuilder>[]; if (supertype is NamedTypeBuilder && supertype.arguments != null) { for (int i = 0; i < supertype.arguments.length; ++i) { supertype.arguments[i] = supertype.arguments[i].clone(newTypes); } } if (mixin is NamedTypeBuilder && mixin.arguments != null) { for (int i = 0; i < mixin.arguments.length; ++i) { mixin.arguments[i] = mixin.arguments[i].clone(newTypes); } } for (TypeBuilder newType in newTypes) { currentTypeParameterScopeBuilder .addType(new UnresolvedType(newType, -1, null)); } TypeParameterScopeBuilder mixinDeclaration = this .endNestedDeclaration( TypeParameterScopeKind.unnamedMixinApplication, "mixin application"); mixinDeclaration.resolveTypes(applicationTypeVariables, this); applicationTypeArguments = <TypeBuilder>[]; for (TypeVariableBuilder typeVariable in typeVariables) { applicationTypeArguments.add(addNamedType(typeVariable.name, const NullabilityBuilder.omitted(), null, charOffset) ..bind( // The type variable types passed as arguments to the // generic class representing the anonymous mixin // application should refer back to the type variables of // the class that extend the anonymous mixin application. typeVariable)); } } } final int computedStartCharOffset = (isNamedMixinApplication ? metadata : null) == null ? startCharOffset : metadata.first.charOffset; SourceClassBuilder application = new SourceClassBuilder( isNamedMixinApplication ? metadata : null, isNamedMixinApplication ? modifiers | namedMixinApplicationMask : abstractMask, fullname, applicationTypeVariables, isMixinDeclaration ? null : supertype, isNamedMixinApplication ? interfaces : isMixinDeclaration ? [supertype, mixin] : null, null, // No `on` clause types. new Scope( local: <String, MemberBuilder>{}, setters: <String, MemberBuilder>{}, parent: scope.withTypeVariables(typeVariables), debugName: "mixin $fullname ", isModifiable: false), new Scope( local: <String, MemberBuilder>{}, debugName: fullname, isModifiable: false), this, <ConstructorReferenceBuilder>[], computedStartCharOffset, charOffset, charEndOffset, mixedInType: isMixinDeclaration ? null : mixin); if (isNamedMixinApplication) { loader.target.metadataCollector ?.setDocumentationComment(application.cls, documentationComment); } // TODO(ahe, kmillikin): Should always be true? // pkg/analyzer/test/src/summary/resynthesize_kernel_test.dart can't // handle that :( application.cls.isAnonymousMixin = !isNamedMixinApplication; addBuilder(fullname, application, charOffset); supertype = addNamedType(fullname, const NullabilityBuilder.omitted(), applicationTypeArguments, charOffset); } return supertype; } else { return type; } } void addNamedMixinApplication( String documentationComment, List<MetadataBuilder> metadata, String name, List<TypeVariableBuilder> typeVariables, int modifiers, TypeBuilder mixinApplication, List<TypeBuilder> interfaces, int startCharOffset, int charOffset, int charEndOffset) { // Nested declaration began in `OutlineBuilder.beginNamedMixinApplication`. endNestedDeclaration(TypeParameterScopeKind.namedMixinApplication, name) .resolveTypes(typeVariables, this); NamedTypeBuilder supertype = applyMixins(mixinApplication, startCharOffset, charOffset, charEndOffset, name, false, documentationComment: documentationComment, metadata: metadata, name: name, typeVariables: typeVariables, modifiers: modifiers, interfaces: interfaces); checkTypeVariables(typeVariables, supertype.declaration); } void addField( String documentationComment, List<MetadataBuilder> metadata, int modifiers, TypeBuilder type, String name, int charOffset, int charEndOffset, Token initializerToken, bool hasInitializer, {Token constInitializerToken}) { if (hasInitializer) { modifiers |= hasInitializerMask; } FieldBuilder fieldBuilder = new FieldBuilder( metadata, type, name, modifiers, this, charOffset, charEndOffset); fieldBuilder.constInitializerToken = constInitializerToken; addBuilder(name, fieldBuilder, charOffset); if (type == null && initializerToken != null) { fieldBuilder.field.type = new ImplicitFieldType(fieldBuilder, initializerToken); (implicitlyTypedFields ??= <FieldBuilder>[]).add(fieldBuilder); } loader.target.metadataCollector ?.setDocumentationComment(fieldBuilder.field, documentationComment); } void addConstructor( String documentationComment, List<MetadataBuilder> metadata, int modifiers, TypeBuilder returnType, final Object name, String constructorName, List<TypeVariableBuilder> typeVariables, List<FormalParameterBuilder> formals, int startCharOffset, int charOffset, int charOpenParenOffset, int charEndOffset, String nativeMethodName, {Token beginInitializers}) { MetadataCollector metadataCollector = loader.target.metadataCollector; ConstructorBuilder constructorBuilder = new ConstructorBuilder( metadata, modifiers & ~abstractMask, returnType, constructorName, typeVariables, formals, this, startCharOffset, charOffset, charOpenParenOffset, charEndOffset, nativeMethodName); metadataCollector?.setDocumentationComment( constructorBuilder.constructor, documentationComment); metadataCollector?.setConstructorNameOffset( constructorBuilder.constructor, name); checkTypeVariables(typeVariables, constructorBuilder); addBuilder(constructorName, constructorBuilder, charOffset); if (nativeMethodName != null) { addNativeMethod(constructorBuilder); } if (constructorBuilder.isConst) { currentTypeParameterScopeBuilder?.hasConstConstructor = true; // const constructors will have their initializers compiled and written // into the outline. constructorBuilder.beginInitializers = beginInitializers ?? new Token.eof(-1); } } void addProcedure( String documentationComment, List<MetadataBuilder> metadata, int modifiers, TypeBuilder returnType, String name, List<TypeVariableBuilder> typeVariables, List<FormalParameterBuilder> formals, ProcedureKind kind, int startCharOffset, int charOffset, int charOpenParenOffset, int charEndOffset, String nativeMethodName, {bool isTopLevel}) { MetadataCollector metadataCollector = loader.target.metadataCollector; if (returnType == null) { if (kind == ProcedureKind.Operator && identical(name, indexSetName.name)) { returnType = addVoidType(charOffset); } else if (kind == ProcedureKind.Setter) { returnType = addVoidType(charOffset); } } ProcedureBuilder procedureBuilder = new ProcedureBuilder( metadata, modifiers, returnType, name, typeVariables, formals, kind, this, startCharOffset, charOffset, charOpenParenOffset, charEndOffset, nativeMethodName); metadataCollector?.setDocumentationComment( procedureBuilder.procedure, documentationComment); checkTypeVariables(typeVariables, procedureBuilder); addBuilder(name, procedureBuilder, charOffset); if (nativeMethodName != null) { addNativeMethod(procedureBuilder); } } void addFactoryMethod( String documentationComment, List<MetadataBuilder> metadata, int modifiers, Object name, List<FormalParameterBuilder> formals, ConstructorReferenceBuilder redirectionTarget, int startCharOffset, int charOffset, int charOpenParenOffset, int charEndOffset, String nativeMethodName) { TypeBuilder returnType = addNamedType( currentTypeParameterScopeBuilder.parent.name, const NullabilityBuilder.omitted(), <TypeBuilder>[], charOffset); // Nested declaration began in `OutlineBuilder.beginFactoryMethod`. TypeParameterScopeBuilder factoryDeclaration = endNestedDeclaration( TypeParameterScopeKind.factoryMethod, "#factory_method"); // Prepare the simple procedure name. String procedureName; String constructorName = computeAndValidateConstructorName(name, charOffset, isFactory: true); if (constructorName != null) { procedureName = constructorName; } else { procedureName = name; } ProcedureBuilder procedureBuilder; if (redirectionTarget != null) { procedureBuilder = new RedirectingFactoryBuilder( metadata, staticMask | modifiers, returnType, procedureName, copyTypeVariables( currentTypeParameterScopeBuilder.typeVariables ?? const <TypeVariableBuilder>[], factoryDeclaration), formals, this, startCharOffset, charOffset, charOpenParenOffset, charEndOffset, nativeMethodName, redirectionTarget); } else { procedureBuilder = new ProcedureBuilder( metadata, staticMask | modifiers, returnType, procedureName, copyTypeVariables( currentTypeParameterScopeBuilder.typeVariables ?? const <TypeVariableBuilder>[], factoryDeclaration), formals, ProcedureKind.Factory, this, startCharOffset, charOffset, charOpenParenOffset, charEndOffset, nativeMethodName); } MetadataCollector metadataCollector = loader.target.metadataCollector; metadataCollector?.setDocumentationComment( procedureBuilder.procedure, documentationComment); metadataCollector?.setConstructorNameOffset( procedureBuilder.procedure, name); TypeParameterScopeBuilder savedDeclaration = currentTypeParameterScopeBuilder; currentTypeParameterScopeBuilder = factoryDeclaration; for (TypeVariableBuilder tv in procedureBuilder.typeVariables) { NamedTypeBuilder t = procedureBuilder.returnType; t.arguments.add(addNamedType(tv.name, const NullabilityBuilder.omitted(), null, procedureBuilder.charOffset)); } currentTypeParameterScopeBuilder = savedDeclaration; factoryDeclaration.resolveTypes(procedureBuilder.typeVariables, this); addBuilder(procedureName, procedureBuilder, charOffset); if (nativeMethodName != null) { addNativeMethod(procedureBuilder); } } void addEnum( String documentationComment, List<MetadataBuilder> metadata, String name, List<EnumConstantInfo> enumConstantInfos, int startCharOffset, int charOffset, int charEndOffset) { MetadataCollector metadataCollector = loader.target.metadataCollector; EnumBuilder builder = new EnumBuilder(metadataCollector, metadata, name, enumConstantInfos, this, startCharOffset, charOffset, charEndOffset); addBuilder(name, builder, charOffset); metadataCollector?.setDocumentationComment( builder.cls, documentationComment); } void addFunctionTypeAlias( String documentationComment, List<MetadataBuilder> metadata, String name, List<TypeVariableBuilder> typeVariables, FunctionTypeBuilder type, int charOffset) { if (typeVariables != null) { for (int i = 0; i < typeVariables.length; ++i) { TypeVariableBuilder variable = typeVariables[i]; variable.variance = computeVariance(variable, type); } } TypeAliasBuilder typedefBuilder = new TypeAliasBuilder( metadata, name, typeVariables, type, this, charOffset); loader.target.metadataCollector ?.setDocumentationComment(typedefBuilder.typedef, documentationComment); checkTypeVariables(typeVariables, typedefBuilder); // Nested declaration began in `OutlineBuilder.beginFunctionTypeAlias`. endNestedDeclaration(TypeParameterScopeKind.typedef, "#typedef") .resolveTypes(typeVariables, this); addBuilder(name, typedefBuilder, charOffset); } FunctionTypeBuilder addFunctionType( TypeBuilder returnType, List<TypeVariableBuilder> typeVariables, List<FormalParameterBuilder> formals, NullabilityBuilder nullabilityBuilder, int charOffset) { FunctionTypeBuilder builder = new FunctionTypeBuilder( returnType, typeVariables, formals, nullabilityBuilder); checkTypeVariables(typeVariables, null); // Nested declaration began in `OutlineBuilder.beginFunctionType` or // `OutlineBuilder.beginFunctionTypedFormalParameter`. endNestedDeclaration(TypeParameterScopeKind.functionType, "#function_type") .resolveTypes(typeVariables, this); return addType(builder, charOffset); } FormalParameterBuilder addFormalParameter( List<MetadataBuilder> metadata, int modifiers, TypeBuilder type, String name, bool hasThis, int charOffset, Token initializerToken) { if (hasThis) { modifiers |= initializingFormalMask; } FormalParameterBuilder formal = new FormalParameterBuilder( metadata, modifiers, type, name, this, charOffset, uri); formal.initializerToken = initializerToken; return formal; } TypeVariableBuilder addTypeVariable( String name, TypeBuilder bound, int charOffset) { TypeVariableBuilder builder = new TypeVariableBuilder(name, this, charOffset, bound: bound); boundlessTypeVariables.add(builder); return builder; } @override void buildOutlineExpressions() { MetadataBuilder.buildAnnotations(library, metadata, this, null, null); } void buildBuilder(Builder declaration, LibraryBuilder coreLibrary) { Class cls; Extension extension; Member member; Typedef typedef; if (declaration is SourceClassBuilder) { cls = declaration.build(this, coreLibrary); } else if (declaration is SourceExtensionBuilder) { extension = declaration.build(this, coreLibrary, addMembersToLibrary: declaration.next == null); } else if (declaration is FieldBuilder) { member = declaration.build(this)..isStatic = true; } else if (declaration is ProcedureBuilder) { member = declaration.build(this)..isStatic = true; } else if (declaration is TypeAliasBuilder) { typedef = declaration.build(this); } else if (declaration is EnumBuilder) { cls = declaration.build(this, coreLibrary); } else if (declaration is PrefixBuilder) { // Ignored. Kernel doesn't represent prefixes. return; } else if (declaration is BuiltinTypeBuilder) { // Nothing needed. return; } else { unhandled("${declaration.runtimeType}", "buildBuilder", declaration.charOffset, declaration.fileUri); return; } if (declaration.isPatch) { // The kernel node of a patch is shared with the origin declaration. We // have two builders: the origin, and the patch, but only one kernel node // (which corresponds to the final output). Consequently, the node // shouldn't be added to its apparent kernel parent as this would create // a duplicate entry in the parent's list of children/members. return; } if (cls != null) { if (declaration.next != null) { int count = 0; Builder current = declaration.next; while (current != null) { count++; current = current.next; } cls.name += "#$count"; } library.addClass(cls); } else if (extension != null) { if (declaration.next == null) { library.addExtension(extension); } } else if (member != null) { if (declaration.next == null) { library.addMember(member); } } else if (typedef != null) { if (declaration.next == null) { library.addTypedef(typedef); } } } void addNativeDependency(String nativeImportPath) { Builder constructor = loader.getNativeAnnotation(); Arguments arguments = new Arguments(<Expression>[new StringLiteral(nativeImportPath)]); Expression annotation; if (constructor.isConstructor) { annotation = new ConstructorInvocation(constructor.target, arguments) ..isConst = true; } else { annotation = new StaticInvocation(constructor.target, arguments) ..isConst = true; } library.addAnnotation(annotation); } void addDependencies(Library library, Set<SourceLibraryBuilder> seen) { if (!seen.add(this)) { return; } // Merge import and export lists to have the dependencies in source order. // This is required for the DietListener to correctly match up metadata. int importIndex = 0; int exportIndex = 0; while (importIndex < imports.length || exportIndex < exports.length) { if (exportIndex >= exports.length || (importIndex < imports.length && imports[importIndex].charOffset < exports[exportIndex].charOffset)) { // Add import Import import = imports[importIndex++]; // Rather than add a LibraryDependency, we attach an annotation. if (import.nativeImportPath != null) { addNativeDependency(import.nativeImportPath); continue; } if (import.deferred && import.prefixBuilder?.dependency != null) { library.addDependency(import.prefixBuilder.dependency); } else { library.addDependency(new LibraryDependency.import( import.imported.library, name: import.prefix, combinators: toKernelCombinators(import.combinators)) ..fileOffset = import.charOffset); } } else { // Add export Export export = exports[exportIndex++]; library.addDependency(new LibraryDependency.export( export.exported.library, combinators: toKernelCombinators(export.combinators)) ..fileOffset = export.charOffset); } } for (SourceLibraryBuilder part in parts) { part.addDependencies(library, seen); } } @override Builder computeAmbiguousDeclaration( String name, Builder declaration, Builder other, int charOffset, {bool isExport: false, bool isImport: false}) { // TODO(ahe): Can I move this to Scope or Prefix? if (declaration == other) return declaration; if (declaration is InvalidTypeBuilder) return declaration; if (other is InvalidTypeBuilder) return other; if (declaration is AccessErrorBuilder) { AccessErrorBuilder error = declaration; declaration = error.builder; } if (other is AccessErrorBuilder) { AccessErrorBuilder error = other; other = error.builder; } bool isLocal = false; bool isLoadLibrary = false; Builder preferred; Uri uri; Uri otherUri; Uri preferredUri; Uri hiddenUri; if (scope.local[name] == declaration) { isLocal = true; preferred = declaration; hiddenUri = computeLibraryUri(other); } else { uri = computeLibraryUri(declaration); otherUri = computeLibraryUri(other); if (declaration is LoadLibraryBuilder) { isLoadLibrary = true; preferred = declaration; preferredUri = otherUri; } else if (other is LoadLibraryBuilder) { isLoadLibrary = true; preferred = other; preferredUri = uri; } else if (otherUri?.scheme == "dart" && uri?.scheme != "dart") { preferred = declaration; preferredUri = uri; hiddenUri = otherUri; } else if (uri?.scheme == "dart" && otherUri?.scheme != "dart") { preferred = other; preferredUri = otherUri; hiddenUri = uri; } } if (preferred != null) { if (isLocal) { Template<Message Function(String name, Uri uri)> template = isExport ? templateLocalDefinitionHidesExport : templateLocalDefinitionHidesImport; addProblem(template.withArguments(name, hiddenUri), charOffset, noLength, fileUri); } else if (isLoadLibrary) { addProblem(templateLoadLibraryHidesMember.withArguments(preferredUri), charOffset, noLength, fileUri); } else { Template<Message Function(String name, Uri uri, Uri uri2)> template = isExport ? templateExportHidesExport : templateImportHidesImport; addProblem(template.withArguments(name, preferredUri, hiddenUri), charOffset, noLength, fileUri); } return preferred; } if (declaration.next == null && other.next == null) { if (isImport && declaration is PrefixBuilder && other is PrefixBuilder) { // Handles the case where the same prefix is used for different // imports. return declaration ..exportScope.merge(other.exportScope, (String name, Builder existing, Builder member) { return computeAmbiguousDeclaration( name, existing, member, charOffset, isExport: isExport, isImport: isImport); }); } } Template<Message Function(String name, Uri uri, Uri uri2)> template = isExport ? templateDuplicatedExport : templateDuplicatedImport; Message message = template.withArguments(name, uri, otherUri); addProblem(message, charOffset, noLength, fileUri); Template<Message Function(String name, Uri uri, Uri uri2)> builderTemplate = isExport ? templateDuplicatedExportInType : templateDuplicatedImportInType; message = builderTemplate.withArguments( name, // TODO(ahe): We should probably use a context object here // instead of including URIs in this message. uri, otherUri); // We report the error lazily (setting suppressMessage to false) because the // spec 18.1 states that 'It is not an error if N is introduced by two or // more imports but never referred to.' return new InvalidTypeBuilder( name, message.withLocation(fileUri, charOffset, name.length), suppressMessage: false); } int finishDeferredLoadTearoffs() { int total = 0; for (Import import in imports) { if (import.deferred) { Procedure tearoff = import.prefixBuilder.loadLibraryBuilder.tearoff; if (tearoff != null) library.addMember(tearoff); total++; } } return total; } int finishForwarders() { int count = 0; CloneVisitor cloner = new CloneVisitor(); for (int i = 0; i < forwardersOrigins.length; i += 2) { Procedure forwarder = forwardersOrigins[i]; Procedure origin = forwardersOrigins[i + 1]; int positionalCount = origin.function.positionalParameters.length; if (forwarder.function.positionalParameters.length != positionalCount) { return unexpected( "$positionalCount", "${forwarder.function.positionalParameters.length}", origin.fileOffset, origin.fileUri); } for (int j = 0; j < positionalCount; ++j) { VariableDeclaration forwarderParameter = forwarder.function.positionalParameters[j]; VariableDeclaration originParameter = origin.function.positionalParameters[j]; if (originParameter.initializer != null) { forwarderParameter.initializer = cloner.clone(originParameter.initializer); forwarderParameter.initializer.parent = forwarderParameter; } } Map<String, VariableDeclaration> originNamedMap = <String, VariableDeclaration>{}; for (VariableDeclaration originNamed in origin.function.namedParameters) { originNamedMap[originNamed.name] = originNamed; } for (VariableDeclaration forwarderNamed in forwarder.function.namedParameters) { VariableDeclaration originNamed = originNamedMap[forwarderNamed.name]; if (originNamed == null) { return unhandled( "null", forwarder.name.name, origin.fileOffset, origin.fileUri); } if (originNamed.initializer == null) continue; forwarderNamed.initializer = cloner.clone(originNamed.initializer); forwarderNamed.initializer.parent = forwarderNamed; } ++count; } forwardersOrigins.clear(); return count; } void addNativeMethod(FunctionBuilder method) { nativeMethods.add(method); } int finishNativeMethods() { for (FunctionBuilder method in nativeMethods) { method.becomeNative(loader); } return nativeMethods.length; } /// Creates a copy of [original] into the scope of [declaration]. /// /// This is used for adding copies of class type parameters to factory /// methods and unnamed mixin applications, and for adding copies of /// extension type parameters to extension instance methods. /// /// If [synthesizeTypeParameterNames] is `true` the names of the /// [TypeParameter] are prefix with '#' to indicate that their synthesized. List<TypeVariableBuilder> copyTypeVariables( List<TypeVariableBuilder> original, TypeParameterScopeBuilder declaration, {bool isExtensionTypeParameter: false}) { List<TypeBuilder> newTypes = <TypeBuilder>[]; List<TypeVariableBuilder> copy = <TypeVariableBuilder>[]; for (TypeVariableBuilder variable in original) { TypeVariableBuilder newVariable = new TypeVariableBuilder( variable.name, this, variable.charOffset, bound: variable.bound?.clone(newTypes), isExtensionTypeParameter: isExtensionTypeParameter); copy.add(newVariable); boundlessTypeVariables.add(newVariable); } for (TypeBuilder newType in newTypes) { declaration.addType(new UnresolvedType(newType, -1, null)); } return copy; } int finishTypeVariables(ClassBuilder object, TypeBuilder dynamicType) { int count = boundlessTypeVariables.length; for (TypeVariableBuilder builder in boundlessTypeVariables) { builder.finish(this, object, dynamicType); } boundlessTypeVariables.clear(); TypeVariableBuilder.finishNullabilities(this, pendingNullabilities); pendingNullabilities.clear(); return count; } int computeDefaultTypes(TypeBuilder dynamicType, TypeBuilder bottomType, ClassBuilder objectClass) { int count = 0; int computeDefaultTypesForVariables(List<TypeVariableBuilder> variables, {bool inErrorRecovery}) { if (variables == null) return 0; bool haveErroneousBounds = false; if (!inErrorRecovery) { for (int i = 0; i < variables.length; ++i) { TypeVariableBuilder variable = variables[i]; List<TypeBuilder> genericFunctionTypes = <TypeBuilder>[]; findGenericFunctionTypes(variable.bound, result: genericFunctionTypes); if (genericFunctionTypes.length > 0) { haveErroneousBounds = true; addProblem(messageGenericFunctionTypeInBound, variable.charOffset, variable.name.length, variable.fileUri); } } if (!haveErroneousBounds) { List<TypeBuilder> calculatedBounds = calculateBounds(variables, dynamicType, bottomType, objectClass); for (int i = 0; i < variables.length; ++i) { variables[i].defaultType = calculatedBounds[i]; } } } if (inErrorRecovery || haveErroneousBounds) { // Use dynamic in case of errors. for (int i = 0; i < variables.length; ++i) { variables[i].defaultType = dynamicType; } } return variables.length; } void reportIssues(List<Object> issues) { for (int i = 0; i < issues.length; i += 3) { TypeDeclarationBuilder declaration = issues[i]; Message message = issues[i + 1]; List<LocatedMessage> context = issues[i + 2]; addProblem(message, declaration.charOffset, declaration.name.length, declaration.fileUri, context: context); } } for (Builder declaration in libraryDeclaration.members.values) { if (declaration is ClassBuilder) { { List<Object> issues = getNonSimplicityIssuesForDeclaration( declaration, performErrorRecovery: true); reportIssues(issues); count += computeDefaultTypesForVariables(declaration.typeVariables, inErrorRecovery: issues.isNotEmpty); } declaration.forEach((String name, Builder member) { if (member is ProcedureBuilder) { List<Object> issues = getNonSimplicityIssuesForTypeVariables(member.typeVariables); reportIssues(issues); count += computeDefaultTypesForVariables(member.typeVariables, inErrorRecovery: issues.isNotEmpty); } }); } else if (declaration is TypeAliasBuilder) { List<Object> issues = getNonSimplicityIssuesForDeclaration(declaration, performErrorRecovery: true); reportIssues(issues); count += computeDefaultTypesForVariables(declaration.typeVariables, inErrorRecovery: issues.isNotEmpty); } else if (declaration is FunctionBuilder) { List<Object> issues = getNonSimplicityIssuesForTypeVariables(declaration.typeVariables); reportIssues(issues); count += computeDefaultTypesForVariables(declaration.typeVariables, inErrorRecovery: issues.isNotEmpty); } } return count; } @override void applyPatches() { if (!isPatch) return; NameIterator originDeclarations = origin.nameIterator; while (originDeclarations.moveNext()) { String name = originDeclarations.name; Builder member = originDeclarations.current; bool isSetter = member.isSetter; Builder patch = isSetter ? scope.setters[name] : scope.local[name]; if (patch != null) { // [patch] has the same name as a [member] in [origin] library, so it // must be a patch to [member]. member.applyPatch(patch); // TODO(ahe): Verify that patch has the @patch annotation. } else { // No member with [name] exists in this library already. So we need to // import it into the patch library. This ensures that the origin // library is in scope of the patch library. if (isSetter) { scopeBuilder.addSetter(name, member); } else { scopeBuilder.addMember(name, member); } } } NameIterator patchDeclarations = nameIterator; while (patchDeclarations.moveNext()) { String name = patchDeclarations.name; Builder member = patchDeclarations.current; // We need to inject all non-patch members into the origin library. This // should only apply to private members. if (member.isPatch) { // Ignore patches. } else if (name.startsWith("_")) { origin.injectMemberFromPatch(name, member); } else { origin.exportMemberFromPatch(name, member); } } } int finishPatchMethods() { if (!isPatch) return 0; int count = 0; Iterator<Builder> iterator = this.iterator; while (iterator.moveNext()) { count += iterator.current.finishPatch(); } return count; } void injectMemberFromPatch(String name, Builder member) { if (member.isSetter) { assert(scope.setters[name] == null); scopeBuilder.addSetter(name, member); } else { assert(scope.local[name] == null); scopeBuilder.addMember(name, member); } } void exportMemberFromPatch(String name, Builder member) { if (uri.scheme != "dart" || !uri.path.startsWith("_")) { addProblem(templatePatchInjectionFailed.withArguments(name, uri), member.charOffset, noLength, member.fileUri); } // Platform-private libraries, such as "dart:_internal" have special // semantics: public members are injected into the origin library. // TODO(ahe): See if we can remove this special case. // If this member already exist in the origin library scope, it should // have been marked as patch. assert((member.isSetter && scope.setters[name] == null) || (!member.isSetter && scope.local[name] == null)); addToExportScope(name, member); } void reportTypeArgumentIssues( List<TypeArgumentIssue> issues, Uri fileUri, int offset, {bool inferred, DartType targetReceiver, String targetName}) { for (TypeArgumentIssue issue in issues) { DartType argument = issue.argument; TypeParameter typeParameter = issue.typeParameter; Message message; bool issueInferred = inferred ?? inferredTypes.contains(argument); if (argument is FunctionType && argument.typeParameters.length > 0) { if (issueInferred) { message = templateGenericFunctionTypeInferredAsActualTypeArgument .withArguments(argument); } else { message = messageGenericFunctionTypeUsedAsActualTypeArgument; } typeParameter = null; } else if (argument is TypeParameterType && argument.promotedBound != null) { addProblem( templateIntersectionTypeAsTypeArgument.withArguments( typeParameter.name, argument, argument.promotedBound), offset, noLength, fileUri); continue; } else { if (issue.enclosingType == null && targetReceiver != null) { if (issueInferred) { message = templateIncorrectTypeArgumentQualifiedInferred.withArguments( argument, typeParameter.bound, typeParameter.name, targetReceiver, targetName); } else { message = templateIncorrectTypeArgumentQualified.withArguments( argument, typeParameter.bound, typeParameter.name, targetReceiver, targetName); } } else { String enclosingName = issue.enclosingType == null ? targetName : getGenericTypeName(issue.enclosingType); assert(enclosingName != null); if (issueInferred) { message = templateIncorrectTypeArgumentInferred.withArguments( argument, typeParameter.bound, typeParameter.name, enclosingName); } else { message = templateIncorrectTypeArgument.withArguments(argument, typeParameter.bound, typeParameter.name, enclosingName); } } } reportTypeArgumentIssue(message, fileUri, offset, typeParameter); } } void reportTypeArgumentIssue(Message message, Uri fileUri, int fileOffset, TypeParameter typeParameter) { List<LocatedMessage> context; if (typeParameter != null && typeParameter.fileOffset != -1) { // It looks like when parameters come from patch files, they don't // have a reportable location. context = <LocatedMessage>[ messageIncorrectTypeArgumentVariable.withLocation( typeParameter.location.file, typeParameter.fileOffset, noLength) ]; } addProblem(message, fileOffset, noLength, fileUri, context: context); } void checkBoundsInField(Field field, TypeEnvironment typeEnvironment) { checkBoundsInType( field.type, typeEnvironment, field.fileUri, field.fileOffset, allowSuperBounded: true); } void checkBoundsInFunctionNodeParts( TypeEnvironment typeEnvironment, Uri fileUri, int fileOffset, {List<TypeParameter> typeParameters, List<VariableDeclaration> positionalParameters, List<VariableDeclaration> namedParameters, DartType returnType}) { if (typeParameters != null) { for (TypeParameter parameter in typeParameters) { checkBoundsInType( parameter.bound, typeEnvironment, fileUri, parameter.fileOffset, allowSuperBounded: true); } } if (positionalParameters != null) { for (VariableDeclaration formal in positionalParameters) { checkBoundsInType( formal.type, typeEnvironment, fileUri, formal.fileOffset, allowSuperBounded: true); } } if (namedParameters != null) { for (VariableDeclaration named in namedParameters) { checkBoundsInType( named.type, typeEnvironment, fileUri, named.fileOffset, allowSuperBounded: true); } } if (returnType != null) { List<TypeArgumentIssue> issues = findTypeArgumentIssues( returnType, typeEnvironment, allowSuperBounded: true); if (issues != null) { int offset = fileOffset; for (TypeArgumentIssue issue in issues) { DartType argument = issue.argument; TypeParameter typeParameter = issue.typeParameter; // We don't need to check if [argument] was inferred or specified // here, because inference in return types boils down to instantiate- // -to-bound, and it can't provide a type that violates the bound. Message message; if (argument is FunctionType && argument.typeParameters.length > 0) { message = messageGenericFunctionTypeUsedAsActualTypeArgument; typeParameter = null; } else { message = templateIncorrectTypeArgumentInReturnType.withArguments( argument, typeParameter.bound, typeParameter.name, getGenericTypeName(issue.enclosingType)); } reportTypeArgumentIssue(message, fileUri, offset, typeParameter); } } } } void checkBoundsInFunctionNode( FunctionNode function, TypeEnvironment typeEnvironment, Uri fileUri) { checkBoundsInFunctionNodeParts( typeEnvironment, fileUri, function.fileOffset, typeParameters: function.typeParameters, positionalParameters: function.positionalParameters, namedParameters: function.namedParameters, returnType: function.returnType); } void checkBoundsInListLiteral( ListLiteral node, TypeEnvironment typeEnvironment, Uri fileUri, {bool inferred = false}) { checkBoundsInType( node.typeArgument, typeEnvironment, fileUri, node.fileOffset, inferred: inferred, allowSuperBounded: true); } void checkBoundsInSetLiteral( SetLiteral node, TypeEnvironment typeEnvironment, Uri fileUri, {bool inferred = false}) { checkBoundsInType( node.typeArgument, typeEnvironment, fileUri, node.fileOffset, inferred: inferred, allowSuperBounded: true); } void checkBoundsInMapLiteral( MapLiteral node, TypeEnvironment typeEnvironment, Uri fileUri, {bool inferred = false}) { checkBoundsInType(node.keyType, typeEnvironment, fileUri, node.fileOffset, inferred: inferred, allowSuperBounded: true); checkBoundsInType(node.valueType, typeEnvironment, fileUri, node.fileOffset, inferred: inferred, allowSuperBounded: true); } void checkBoundsInType( DartType type, TypeEnvironment typeEnvironment, Uri fileUri, int offset, {bool inferred, bool allowSuperBounded = true}) { List<TypeArgumentIssue> issues = findTypeArgumentIssues( type, typeEnvironment, allowSuperBounded: allowSuperBounded); if (issues != null) { reportTypeArgumentIssues(issues, fileUri, offset, inferred: inferred); } } void checkBoundsInVariableDeclaration( VariableDeclaration node, TypeEnvironment typeEnvironment, Uri fileUri, {bool inferred = false}) { if (node.type == null) return; checkBoundsInType(node.type, typeEnvironment, fileUri, node.fileOffset, inferred: inferred, allowSuperBounded: true); } void checkBoundsInConstructorInvocation( ConstructorInvocation node, TypeEnvironment typeEnvironment, Uri fileUri, {bool inferred = false}) { if (node.arguments.types.isEmpty) return; Constructor constructor = node.target; Class klass = constructor.enclosingClass; DartType constructedType = new InterfaceType(klass, node.arguments.types); checkBoundsInType( constructedType, typeEnvironment, fileUri, node.fileOffset, inferred: inferred, allowSuperBounded: false); } void checkBoundsInFactoryInvocation( StaticInvocation node, TypeEnvironment typeEnvironment, Uri fileUri, {bool inferred = false}) { if (node.arguments.types.isEmpty) return; Procedure factory = node.target; assert(factory.isFactory); Class klass = factory.enclosingClass; DartType constructedType = new InterfaceType(klass, node.arguments.types); checkBoundsInType( constructedType, typeEnvironment, fileUri, node.fileOffset, inferred: inferred, allowSuperBounded: false); } void checkBoundsInStaticInvocation( StaticInvocation node, TypeEnvironment typeEnvironment, Uri fileUri, {bool inferred = false}) { // TODO(johnniwinther): Handle partially inferred type arguments in // extension method calls. Currently all are considered inferred in the // error messages. if (node.arguments.types.isEmpty) return; Class klass = node.target.enclosingClass; List<TypeParameter> parameters = node.target.function.typeParameters; List<DartType> arguments = node.arguments.types; // The following error is to be reported elsewhere. if (parameters.length != arguments.length) return; List<TypeArgumentIssue> issues = findTypeArgumentIssuesForInvocation( parameters, arguments, typeEnvironment); if (issues != null) { DartType targetReceiver; if (klass != null) { targetReceiver = new InterfaceType(klass); } String targetName = node.target.name.name; reportTypeArgumentIssues(issues, fileUri, node.fileOffset, inferred: inferred, targetReceiver: targetReceiver, targetName: targetName); } } void checkBoundsInMethodInvocation( DartType receiverType, TypeEnvironment typeEnvironment, ClassHierarchy hierarchy, TypeInferrerImpl typeInferrer, Name name, Member interfaceTarget, Arguments arguments, Uri fileUri, int offset, {bool inferred = false}) { if (arguments.types.isEmpty) return; Class klass; List<DartType> receiverTypeArguments; if (receiverType is InterfaceType) { klass = receiverType.classNode; receiverTypeArguments = receiverType.typeArguments; } else { return; } // TODO(dmitryas): Find a better way than relying on [interfaceTarget]. Member method = hierarchy.getDispatchTarget(klass, name) ?? interfaceTarget; if (method == null || method is! Procedure) { return; } if (klass != method.enclosingClass) { Supertype parent = hierarchy.getClassAsInstanceOf(klass, method.enclosingClass); klass = method.enclosingClass; receiverTypeArguments = parent.typeArguments; } Map<TypeParameter, DartType> substitutionMap = <TypeParameter, DartType>{}; for (int i = 0; i < receiverTypeArguments.length; ++i) { substitutionMap[klass.typeParameters[i]] = receiverTypeArguments[i]; } List<TypeParameter> methodParameters = method.function.typeParameters; // The error is to be reported elsewhere. if (methodParameters.length != arguments.types.length) return; List<TypeParameter> instantiatedMethodParameters = new List<TypeParameter>.filled(methodParameters.length, null); for (int i = 0; i < instantiatedMethodParameters.length; ++i) { instantiatedMethodParameters[i] = new TypeParameter(methodParameters[i].name); substitutionMap[methodParameters[i]] = new TypeParameterType(instantiatedMethodParameters[i]); } for (int i = 0; i < instantiatedMethodParameters.length; ++i) { instantiatedMethodParameters[i].bound = substitute(methodParameters[i].bound, substitutionMap); } List<TypeArgumentIssue> issues = findTypeArgumentIssuesForInvocation( instantiatedMethodParameters, arguments.types, typeEnvironment); if (issues != null) { reportTypeArgumentIssues(issues, fileUri, offset, inferred: inferred, targetReceiver: receiverType, targetName: name.name); } } void checkBoundsInOutline(TypeEnvironment typeEnvironment) { Iterator<Builder> iterator = this.iterator; while (iterator.moveNext()) { Builder declaration = iterator.current; if (declaration is FieldBuilder) { checkBoundsInField(declaration.field, typeEnvironment); } else if (declaration is ProcedureBuilder) { checkBoundsInFunctionNode(declaration.procedure.function, typeEnvironment, declaration.fileUri); } else if (declaration is ClassBuilder) { declaration.checkBoundsInOutline(typeEnvironment); } } inferredTypes.clear(); } @override List<FieldBuilder> takeImplicitlyTypedFields() { List<FieldBuilder> result = implicitlyTypedFields; implicitlyTypedFields = null; return result; } } // The kind of type parameter scope built by a [TypeParameterScopeBuilder] // object. enum TypeParameterScopeKind { library, classOrNamedMixinApplication, classDeclaration, mixinDeclaration, unnamedMixinApplication, namedMixinApplication, extensionDeclaration, typedef, staticOrInstanceMethodOrConstructor, topLevelMethod, factoryMethod, functionType, } /// A builder object preparing for building declarations that can introduce type /// parameter and/or members. /// /// Unlike [Scope], this scope is used during construction of builders to /// ensure types and members are added to and resolved in the correct location. class TypeParameterScopeBuilder { TypeParameterScopeKind _kind; final TypeParameterScopeBuilder parent; final Map<String, Builder> members; final Map<String, Builder> constructors; final Map<String, Builder> setters; final List<ExtensionBuilder> extensions; final List<UnresolvedType> types = <UnresolvedType>[]; // TODO(johnniwinther): Stop using [_name] for determining the declaration // kind. String _name; /// Offset of name token, updated by the outline builder along /// with the name as the current declaration changes. int _charOffset; List<TypeVariableBuilder> _typeVariables; /// The type of `this` in instance methods declared in extension declarations. /// /// Instance methods declared in extension declarations methods are extended /// with a synthesized parameter of this type. TypeBuilder _extensionThisType; bool hasConstConstructor = false; TypeParameterScopeBuilder( this._kind, this.members, this.setters, this.constructors, this.extensions, this._name, this._charOffset, this.parent) { assert(_name != null); } TypeParameterScopeBuilder.library() : this( TypeParameterScopeKind.library, <String, Builder>{}, <String, Builder>{}, null, // No support for constructors in library scopes. <ExtensionBuilder>[], "<library>", -1, null); TypeParameterScopeBuilder createNested( TypeParameterScopeKind kind, String name, bool hasMembers) { return new TypeParameterScopeBuilder( kind, hasMembers ? <String, MemberBuilder>{} : null, hasMembers ? <String, MemberBuilder>{} : null, hasMembers ? <String, MemberBuilder>{} : null, null, // No support for extensions in nested scopes. name, -1, this); } /// Registers that this builder is preparing for a class declaration with the /// given [name] and [typeVariables] located [charOffset]. void markAsClassDeclaration( String name, int charOffset, List<TypeVariableBuilder> typeVariables) { assert(_kind == TypeParameterScopeKind.classOrNamedMixinApplication, "Unexpected declaration kind: $_kind"); _kind = TypeParameterScopeKind.classDeclaration; _name = name; _charOffset = charOffset; _typeVariables = typeVariables; } /// Registers that this builder is preparing for a named mixin application /// with the given [name] and [typeVariables] located [charOffset]. void markAsNamedMixinApplication( String name, int charOffset, List<TypeVariableBuilder> typeVariables) { assert(_kind == TypeParameterScopeKind.classOrNamedMixinApplication, "Unexpected declaration kind: $_kind"); _kind = TypeParameterScopeKind.namedMixinApplication; _name = name; _charOffset = charOffset; _typeVariables = typeVariables; } /// Registers that this builder is preparing for a mixin declaration with the /// given [name] and [typeVariables] located [charOffset]. void markAsMixinDeclaration( String name, int charOffset, List<TypeVariableBuilder> typeVariables) { // TODO(johnniwinther): Avoid using 'classOrNamedMixinApplication' for mixin // declaration. These are syntactically distinct so we don't need the // transition. assert(_kind == TypeParameterScopeKind.classOrNamedMixinApplication, "Unexpected declaration kind: $_kind"); _kind = TypeParameterScopeKind.mixinDeclaration; _name = name; _charOffset = charOffset; _typeVariables = typeVariables; } /// Registers that this builder is preparing for an extension declaration with /// the given [name] and [typeVariables] located [charOffset]. void markAsExtensionDeclaration( String name, int charOffset, List<TypeVariableBuilder> typeVariables) { assert(_kind == TypeParameterScopeKind.extensionDeclaration, "Unexpected declaration kind: $_kind"); _name = name; _charOffset = charOffset; _typeVariables = typeVariables; } /// Registers the 'extension this type' of the extension declaration prepared /// for by this builder. /// /// See [extensionThisType] for terminology. void registerExtensionThisType(TypeBuilder type) { assert(_kind == TypeParameterScopeKind.extensionDeclaration, "DeclarationBuilder.registerExtensionThisType is not supported $_kind"); assert(_extensionThisType == null, "Extension this type has already been set."); _extensionThisType = type; } /// Returns what kind of declaration this [TypeParameterScopeBuilder] is /// preparing for. /// /// This information is transient for some declarations. In particular /// classes and named mixin applications are initially created with the kind /// [TypeParameterScopeKind.classOrNamedMixinApplication] before a call to /// either [markAsClassDeclaration] or [markAsNamedMixinApplication] sets the /// value to its actual kind. // TODO(johnniwinther): Avoid the transition currently used on mixin // declarations. TypeParameterScopeKind get kind => _kind; String get name => _name; int get charOffset => _charOffset; List<TypeVariableBuilder> get typeVariables => _typeVariables; /// Returns the 'extension this type' of the extension declaration prepared /// for by this builder. /// /// The 'extension this type' is the type mentioned in the on-clause of the /// extension declaration. For instance `B` in this extension declaration: /// /// extension A on B { /// B method() => this; /// } /// /// The 'extension this type' is the type if `this` expression in instance /// methods declared in extension declarations. TypeBuilder get extensionThisType { assert(kind == TypeParameterScopeKind.extensionDeclaration, "DeclarationBuilder.extensionThisType not supported on $kind."); assert(_extensionThisType != null, "DeclarationBuilder.extensionThisType has not been set on $this."); return _extensionThisType; } /// Adds the yet unresolved [type] to this scope builder. /// /// Unresolved type will be resolved through [resolveTypes] when the scope /// is fully built. This allows for resolving self-referencing types, like /// type parameter used in their own bound, for instance `<T extends A<T>>`. void addType(UnresolvedType type) { types.add(type); } /// Resolves type variables in [types] and propagate other types to [parent]. void resolveTypes( List<TypeVariableBuilder> typeVariables, SourceLibraryBuilder library) { Map<String, TypeVariableBuilder> map; if (typeVariables != null) { map = <String, TypeVariableBuilder>{}; for (TypeVariableBuilder builder in typeVariables) { map[builder.name] = builder; } } Scope scope; for (UnresolvedType type in types) { Object nameOrQualified = type.builder.name; String name = nameOrQualified is QualifiedName ? nameOrQualified.qualifier : nameOrQualified; Builder declaration; if (name != null) { if (members != null) { declaration = members[name]; } if (declaration == null && map != null) { declaration = map[name]; } } if (declaration == null) { // Since name didn't resolve in this scope, propagate it to the // parent declaration. parent.addType(type); } else if (nameOrQualified is QualifiedName) { // Attempt to use a member or type variable as a prefix. Message message = templateNotAPrefixInTypeAnnotation.withArguments( flattenName( nameOrQualified.qualifier, type.charOffset, type.fileUri), nameOrQualified.name); library.addProblem(message, type.charOffset, nameOrQualified.endCharOffset - type.charOffset, type.fileUri); type.builder.bind(type.builder.buildInvalidType(message.withLocation( type.fileUri, type.charOffset, nameOrQualified.endCharOffset - type.charOffset))); } else { scope ??= toScope(null).withTypeVariables(typeVariables); type.resolveIn(scope, library); } } types.clear(); } Scope toScope(Scope parent) { return new Scope( local: members, setters: setters, extensions: extensions, parent: parent, debugName: name, isModifiable: false); } @override String toString() => 'DeclarationBuilder(${hashCode}:kind=$kind,name=$name)'; } class FieldInfo { final String name; final int charOffset; final Token initializerToken; final Token beforeLast; final int charEndOffset; const FieldInfo(this.name, this.charOffset, this.initializerToken, this.beforeLast, this.charEndOffset); } class ImplementationInfo { final String name; final Builder declaration; final int charOffset; const ImplementationInfo(this.name, this.declaration, this.charOffset); } Uri computeLibraryUri(Builder declaration) { Builder current = declaration; do { if (current is LibraryBuilder) return current.uri; current = current.parent; } while (current != null); return unhandled("no library parent", "${declaration.runtimeType}", declaration.charOffset, declaration.fileUri); } String extractName(name) => name is QualifiedName ? name.name : name; class PostponedProblem { final Message message; final int charOffset; final int length; final Uri fileUri; PostponedProblem(this.message, this.charOffset, this.length, this.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/source/value_kinds.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 'package:kernel/ast.dart' as type; import '../builder/builder.dart' as type; import '../kernel/expression_generator.dart' as type; import '../modifier.dart' as type; import '../operator.dart' as type; import '../scanner.dart' as type show Token; import '../scope.dart' as type; import '../source/outline_builder.dart' as type; import 'stack_listener.dart' show NullValue; import 'stack_listener.dart' as type; /// [ValueKind] is used in [StackListener.checkState] to document and check the /// expected values of the stack. /// /// Add new value kinds as needed for documenting and checking the various stack /// listener implementations. abstract class ValueKind { const ValueKind(); /// Checks the [value] an returns `true` if the value is of the expected kind. bool check(Object value); static const ValueKind Arguments = const _SingleValueKind<type.Arguments>(); static const ValueKind ArgumentsOrNull = const _SingleValueKind<type.Arguments>(NullValue.Arguments); static const ValueKind Expression = const _SingleValueKind<type.Expression>(); static const ValueKind ExpressionOrNull = const _SingleValueKind<type.Expression>(NullValue.Expression); static const ValueKind Identifier = const _SingleValueKind<type.Identifier>(); static const ValueKind IdentifierOrNull = const _SingleValueKind<type.Identifier>(NullValue.Identifier); static const ValueKind Integer = const _SingleValueKind<int>(); static const ValueKind Formals = const _SingleValueKind<List<type.FormalParameterBuilder>>(); static const ValueKind FormalsOrNull = const _SingleValueKind<List<type.FormalParameterBuilder>>( NullValue.FormalParameters); static const ValueKind Generator = const _SingleValueKind<type.Generator>(); static const ValueKind Initializer = const _SingleValueKind<type.Initializer>(); static const ValueKind MethodBody = const _SingleValueKind<type.MethodBody>(); static const ValueKind Modifiers = const _SingleValueKind<List<type.Modifier>>(); static const ValueKind ModifiersOrNull = const _SingleValueKind<List<type.Modifier>>(NullValue.Modifiers); static const ValueKind Name = const _SingleValueKind<String>(); static const ValueKind NameOrNull = const _SingleValueKind<String>(NullValue.Name); static const ValueKind NameOrOperator = const _UnionValueKind([Name, Operator]); static const ValueKind NameOrQualifiedNameOrOperator = const _UnionValueKind([Name, QualifiedName, Operator]); static const ValueKind NameOrParserRecovery = const _UnionValueKind([Name, ParserRecovery]); static const ValueKind MetadataListOrNull = const _SingleValueKind<List<type.MetadataBuilder>>(NullValue.Metadata); static const ValueKind ObjectList = const _SingleValueKind<List<Object>>(); static const ValueKind Operator = const _SingleValueKind<type.Operator>(); static const ValueKind ParserRecovery = const _SingleValueKind<type.ParserRecovery>(); static const ValueKind ProblemBuilder = const _SingleValueKind<type.ProblemBuilder>(); static const ValueKind QualifiedName = const _SingleValueKind<type.QualifiedName>(); static const ValueKind Statement = const _SingleValueKind<type.Statement>(); static const ValueKind Token = const _SingleValueKind<type.Token>(); static const ValueKind TokenOrNull = const _SingleValueKind<type.Token>(NullValue.Token); static const ValueKind TypeArgumentsOrNull = const _SingleValueKind<List<type.UnresolvedType>>( NullValue.TypeArguments); static const ValueKind TypeBuilder = const _SingleValueKind<type.TypeBuilder>(); static const ValueKind TypeBuilderOrNull = const _SingleValueKind<type.TypeBuilder>(NullValue.Type); static const ValueKind TypeVariableListOrNull = const _SingleValueKind<List<type.TypeVariableBuilder>>( NullValue.TypeVariables); } /// A [ValueKind] for a particular type [T], optionally with a recognized /// [NullValue]. class _SingleValueKind<T> implements ValueKind { final NullValue nullValue; const _SingleValueKind([this.nullValue]); @override bool check(Object value) { if (nullValue != null && value == nullValue) { return true; } return value is T; } String toString() { if (nullValue != null) { return '$T or $nullValue'; } return '$T'; } } /// A [ValueKind] for the union of a list of [ValueKind]s. class _UnionValueKind implements ValueKind { final List<ValueKind> kinds; const _UnionValueKind(this.kinds); @override bool check(Object value) { for (ValueKind kind in kinds) { if (kind.check(value)) { return true; } } return false; } String toString() { StringBuffer sb = new StringBuffer(); String or = ''; for (ValueKind kind in kinds) { sb.write(or); sb.write(kind); or = ' or '; } return sb.toString(); } } /// Helper method for creating a list of [ValueKind]s of the given length /// [count]. List<ValueKind> repeatedKinds(ValueKind kind, int count) { return new List.generate(count, (_) => kind); } /// Helper method for creating a union of a list of [ValueKind]s. ValueKind unionOfKinds(List<ValueKind> kinds) { return new _UnionValueKind(kinds); }
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/kernel/constant_int_folder.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 'package:kernel/target/targets.dart'; import 'constant_evaluator.dart'; import '../fasta_codes.dart' show templateConstEvalNegativeShift, templateConstEvalZeroDivisor; abstract class ConstantIntFolder { final ConstantEvaluator evaluator; ConstantIntFolder(this.evaluator); factory ConstantIntFolder.forSemantics( ConstantEvaluator evaluator, NumberSemantics semantics) { if (semantics == NumberSemantics.js) { return new JsConstantIntFolder(evaluator); } else { return new VmConstantIntFolder(evaluator); } } bool isInt(Constant constant); Constant makeIntConstant(int value, {bool unsigned: false}); Constant foldUnaryOperator( MethodInvocation node, String op, covariant Constant operand); Constant foldBinaryOperator(MethodInvocation node, String op, covariant Constant left, covariant Constant right); Constant truncatingDivide(num left, num right); void _checkOperands(MethodInvocation node, String op, num left, num right) { if ((op == '<<' || op == '>>' || op == '>>>') && right < 0) { evaluator.report(node, templateConstEvalNegativeShift.withArguments(op, '$left', '$right')); } if ((op == '%' || op == '~/') && right == 0) { evaluator.report( node, templateConstEvalZeroDivisor.withArguments(op, '$left')); } } } class VmConstantIntFolder extends ConstantIntFolder { VmConstantIntFolder(ConstantEvaluator evaluator) : super(evaluator); @override bool isInt(Constant constant) => constant is IntConstant; @override IntConstant makeIntConstant(int value, {bool unsigned: false}) { return new IntConstant(value); } @override Constant foldUnaryOperator( MethodInvocation node, String op, IntConstant operand) { switch (op) { case 'unary-': return new IntConstant(-operand.value); case '~': return new IntConstant(~operand.value); default: return evaluator.reportInvalid(node, "Invalid unary operator $op"); } } @override Constant foldBinaryOperator( MethodInvocation node, String op, IntConstant left, IntConstant right) { int a = left.value; int b = right.value; _checkOperands(node, op, a, b); switch (op) { case '+': return new IntConstant(a + b); case '-': return new IntConstant(a - b); case '*': return new IntConstant(a * b); case '/': return new DoubleConstant(a / b); case '~/': return new IntConstant(a ~/ b); case '%': return new IntConstant(a % b); case '|': return new IntConstant(a | b); case '&': return new IntConstant(a & b); case '^': return new IntConstant(a ^ b); case '<<': return new IntConstant(a << b); case '>>': return new IntConstant(a >> b); case '>>>': int result = b >= 64 ? 0 : (a >> b) & ((1 << (64 - b)) - 1); return new IntConstant(result); case '<': return evaluator.makeBoolConstant(a < b); case '<=': return evaluator.makeBoolConstant(a <= b); case '>=': return evaluator.makeBoolConstant(a >= b); case '>': return evaluator.makeBoolConstant(a > b); default: return evaluator.reportInvalid(node, "Invalid binary operator $op"); } } @override Constant truncatingDivide(num left, num right) { return new IntConstant(left ~/ right); } } class JsConstantIntFolder extends ConstantIntFolder { JsConstantIntFolder(ConstantEvaluator evaluator) : super(evaluator); static bool _valueIsInteger(double value) { return value.isFinite && value.truncateToDouble() == value; } static int _truncate32(int value) => value & 0xFFFFFFFF; static int _toUint32(double value) { return new BigInt.from(value).toUnsigned(32).toInt(); } @override bool isInt(Constant constant) { return constant is DoubleConstant && _valueIsInteger(constant.value); } @override DoubleConstant makeIntConstant(int value, {bool unsigned: false}) { double doubleValue = value.toDouble(); assert(doubleValue.toInt() == value); if (unsigned) { const double twoTo64 = 18446744073709551616.0; if (value < 0) doubleValue += twoTo64; } return new DoubleConstant(doubleValue); } @override Constant foldUnaryOperator( MethodInvocation node, String op, DoubleConstant operand) { switch (op) { case 'unary-': return new DoubleConstant(-operand.value); case '~': int intValue = _toUint32(operand.value); return new DoubleConstant(_truncate32(~intValue).toDouble()); default: return evaluator.reportInvalid(node, "Invalid unary operator $op"); } } @override Constant foldBinaryOperator(MethodInvocation node, String op, DoubleConstant left, DoubleConstant right) { double a = left.value; double b = right.value; _checkOperands(node, op, a, b); switch (op) { case '+': return new DoubleConstant(a + b); case '-': return new DoubleConstant(a - b); case '*': return new DoubleConstant(a * b); case '/': return new DoubleConstant(a / b); case '~/': return truncatingDivide(a, b); case '%': return new DoubleConstant(a % b); case '|': return new DoubleConstant((_toUint32(a) | _toUint32(b)).toDouble()); case '&': return new DoubleConstant((_toUint32(a) & _toUint32(b)).toDouble()); case '^': return new DoubleConstant((_toUint32(a) ^ _toUint32(b)).toDouble()); case '<<': int ai = _toUint32(a); return new DoubleConstant(_truncate32(ai << b.toInt()).toDouble()); case '>>': int ai = _toUint32(a); if (a < 0) { const int signBit = 0x80000000; ai -= (ai & signBit) << 1; } return new DoubleConstant(_truncate32(ai >> b.toInt()).toDouble()); case '>>>': int ai = _toUint32(a); return new DoubleConstant(_truncate32(ai >> b.toInt()).toDouble()); case '<': return evaluator.makeBoolConstant(a < b); case '<=': return evaluator.makeBoolConstant(a <= b); case '>=': return evaluator.makeBoolConstant(a >= b); case '>': return evaluator.makeBoolConstant(a > b); default: return evaluator.reportInvalid(node, "Invalid binary operator $op"); } } @override Constant truncatingDivide(num left, num right) { double result = (left / right).truncateToDouble(); return new DoubleConstant(result == 0.0 ? 0.0 : 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/kernel/kernel_ast_api.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. /// This library exports all API from Kernel's ast.dart that can be used /// throughout fasta. library fasta.kernel_ast_api; export 'package:kernel/ast.dart' show Arguments, AsExpression, AssertStatement, AsyncMarker, Block, BottomType, BreakStatement, Catch, CheckLibraryIsLoaded, Class, Component, Constructor, ConstructorInvocation, ContinueSwitchStatement, DartType, DynamicType, EmptyStatement, Expression, ExpressionStatement, Field, ForInStatement, FunctionDeclaration, FunctionExpression, FunctionNode, FunctionType, Initializer, InterfaceType, InvalidExpression, InvalidType, IsExpression, LabeledStatement, Let, Library, LibraryDependency, LibraryPart, ListLiteral, LocalInitializer, Location, MapEntry, MapLiteral, Member, MethodInvocation, Name, NamedExpression, NamedType, Node, NullLiteral, Procedure, ProcedureKind, PropertyGet, PropertySet, Rethrow, ReturnStatement, Statement, StaticGet, StaticInvocation, StaticSet, StringConcatenation, SuperInitializer, SuperMethodInvocation, SuperPropertySet, SwitchCase, ThisExpression, TreeNode, TypeParameter, TypeParameterType, Typedef, TypedefType, VariableDeclaration, VariableGet, VariableSet, VoidType, setParents; export 'kernel_shadow_ast.dart' show ArgumentsImpl, Cascade, DeferredCheck, FactoryConstructorInvocationJudgment, FunctionDeclarationImpl, InvalidSuperInitializerJudgment, LoadLibraryTearOff, MethodInvocationImpl, NamedFunctionExpressionJudgment, NullAwareMethodInvocation, NullAwarePropertyGet, ReturnStatementImpl, ShadowInvalidFieldInitializer, ShadowInvalidInitializer, ShadowLargeIntLiteral, VariableDeclarationImpl, VariableGetImpl;
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/kernel/implicit_type_argument.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.md file. library fasta.implicit_type_argument; import 'package:kernel/ast.dart' show DartType, DartTypeVisitor, DartTypeVisitor1, Nullability, Visitor; import '../problems.dart' show unhandled, unsupported; /// Marker type used as type argument on list, set and map literals whenever /// type arguments are omitted in the source. /// /// All of these types are replaced by the type inference. It is an internal /// error if one survives to the final output. class ImplicitTypeArgument extends DartType { const ImplicitTypeArgument(); @override Nullability get nullability => unsupported("nullability", -1, null); @override R accept<R>(DartTypeVisitor<R> v) { throw unhandled("$runtimeType", "${v.runtimeType}", -1, null); } @override R accept1<R, A>(DartTypeVisitor1<R, A> v, A arg) { throw unhandled("$runtimeType", "${v.runtimeType}", -1, null); } @override visitChildren(Visitor<Object> v) { unhandled("$runtimeType", "${v.runtimeType}", -1, null); } @override ImplicitTypeArgument withNullability(Nullability nullability) { return unsupported("withNullability", -1, 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/kernel/transform_collections.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 fasta.transform_collections; import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart' show Arguments, AsExpression, Block, BlockExpression, Class, ConditionalExpression, DartType, DynamicType, Expression, ExpressionStatement, Field, ForInStatement, ForStatement, IfStatement, InterfaceType, Let, ListConcatenation, ListLiteral, MapConcatenation, MapEntry, MapLiteral, MethodInvocation, Name, Not, NullLiteral, Procedure, PropertyGet, SetConcatenation, SetLiteral, Statement, StaticInvocation, transformList, TreeNode, VariableDeclaration, VariableGet; import 'package:kernel/core_types.dart' show CoreTypes; import 'package:kernel/type_environment.dart' show SubtypeCheckMode, TypeEnvironment; import 'package:kernel/visitor.dart' show Transformer; import 'collections.dart' show ControlFlowElement, ControlFlowMapEntry, ForElement, ForInElement, ForInMapEntry, ForMapEntry, IfElement, IfMapEntry, SpreadElement, SpreadMapEntry; import '../problems.dart' show getFileUri, unhandled; import '../source/source_loader.dart' show SourceLoader; import 'redirecting_factory_body.dart' show RedirectingFactoryBody; class CollectionTransformer extends Transformer { final CoreTypes coreTypes; final TypeEnvironment typeEnvironment; final Procedure listAdd; final Procedure setFactory; final Procedure setAdd; final Procedure objectEquals; final Procedure mapEntries; final Procedure mapPut; final Class mapEntryClass; final Field mapEntryKey; final Field mapEntryValue; static Procedure _findSetFactory(CoreTypes coreTypes) { Procedure factory = coreTypes.index.getMember('dart:core', 'Set', ''); RedirectingFactoryBody body = factory?.function?.body; return body?.target; } CollectionTransformer(SourceLoader loader) : coreTypes = loader.coreTypes, typeEnvironment = loader.typeInferenceEngine.typeSchemaEnvironment, listAdd = loader.coreTypes.index.getMember('dart:core', 'List', 'add'), setFactory = _findSetFactory(loader.coreTypes), setAdd = loader.coreTypes.index.getMember('dart:core', 'Set', 'add'), objectEquals = loader.coreTypes.index.getMember('dart:core', 'Object', '=='), mapEntries = loader.coreTypes.index.getMember('dart:core', 'Map', 'get:entries'), mapPut = loader.coreTypes.index.getMember('dart:core', 'Map', '[]='), mapEntryClass = loader.coreTypes.index.getClass('dart:core', 'MapEntry'), mapEntryKey = loader.coreTypes.index.getMember('dart:core', 'MapEntry', 'key'), mapEntryValue = loader.coreTypes.index.getMember('dart:core', 'MapEntry', 'value'); TreeNode _translateListOrSet( Expression node, DartType elementType, List<Expression> elements, {bool isSet: false}) { // Translate elements in place up to the first non-expression, if any. int i = 0; for (; i < elements.length; ++i) { if (elements[i] is ControlFlowElement) break; elements[i] = elements[i].accept<TreeNode>(this)..parent = node; } // If there were only expressions, we are done. if (i == elements.length) return node; // Build a block expression and create an empty list or set. VariableDeclaration result; if (isSet) { // TODO(kmillikin): When all the back ends handle set literals we can use // one here. result = new VariableDeclaration.forValue( new StaticInvocation( setFactory, new Arguments([], types: [elementType])), type: new InterfaceType(coreTypes.setClass, [elementType]), isFinal: true); } else { result = new VariableDeclaration.forValue( new ListLiteral([], typeArgument: elementType), type: new InterfaceType(coreTypes.listClass, [elementType]), isFinal: true); } List<Statement> body = [result]; // Add the elements up to the first non-expression. for (int j = 0; j < i; ++j) { _addExpressionElement(elements[j], isSet, result, body); } // Translate the elements starting with the first non-expression. for (; i < elements.length; ++i) { _translateElement(elements[i], elementType, isSet, result, body); } return new BlockExpression(new Block(body), new VariableGet(result)); } void _translateElement(Expression element, DartType elementType, bool isSet, VariableDeclaration result, List<Statement> body) { if (element is SpreadElement) { _translateSpreadElement(element, elementType, isSet, result, body); } else if (element is IfElement) { _translateIfElement(element, elementType, isSet, result, body); } else if (element is ForElement) { _translateForElement(element, elementType, isSet, result, body); } else if (element is ForInElement) { _translateForInElement(element, elementType, isSet, result, body); } else { _addExpressionElement( element.accept<TreeNode>(this), isSet, result, body); } } void _addExpressionElement(Expression element, bool isSet, VariableDeclaration result, List<Statement> body) { body.add(new ExpressionStatement(new MethodInvocation( new VariableGet(result), new Name('add'), new Arguments([element]), isSet ? setAdd : listAdd))); } void _translateIfElement(IfElement element, DartType elementType, bool isSet, VariableDeclaration result, List<Statement> body) { List<Statement> thenStatements = []; _translateElement(element.then, elementType, isSet, result, thenStatements); List<Statement> elseStatements; if (element.otherwise != null) { _translateElement(element.otherwise, elementType, isSet, result, elseStatements = <Statement>[]); } Statement thenBody = thenStatements.length == 1 ? thenStatements.first : new Block(thenStatements); Statement elseBody; if (elseStatements != null && elseStatements.isNotEmpty) { elseBody = elseStatements.length == 1 ? elseStatements.first : new Block(elseStatements); } body.add(new IfStatement( element.condition.accept<TreeNode>(this), thenBody, elseBody) ..fileOffset = element.fileOffset); } void _translateForElement(ForElement element, DartType elementType, bool isSet, VariableDeclaration result, List<Statement> body) { List<Statement> statements = <Statement>[]; _translateElement(element.body, elementType, isSet, result, statements); Statement loopBody = statements.length == 1 ? statements.first : new Block(statements); ForStatement loop = new ForStatement(element.variables, element.condition?.accept<TreeNode>(this), element.updates, loopBody) ..fileOffset = element.fileOffset; transformList(loop.variables, this, loop); transformList(loop.updates, this, loop); body.add(loop); } void _translateForInElement(ForInElement element, DartType elementType, bool isSet, VariableDeclaration result, List<Statement> body) { List<Statement> statements; Statement prologue = element.prologue; if (prologue == null) { statements = <Statement>[]; } else { prologue = prologue.accept<TreeNode>(this); statements = prologue is Block ? prologue.statements : <Statement>[prologue]; } _translateElement(element.body, elementType, isSet, result, statements); Statement loopBody = statements.length == 1 ? statements.first : new Block(statements); if (element.problem != null) { body.add(new ExpressionStatement(element.problem.accept<TreeNode>(this))); } body.add(new ForInStatement( element.variable, element.iterable.accept<TreeNode>(this), loopBody, isAsync: element.isAsync) ..fileOffset = element.fileOffset); } void _translateSpreadElement(SpreadElement element, DartType elementType, bool isSet, VariableDeclaration result, List<Statement> body) { Expression value = element.expression.accept<TreeNode>(this); // Null-aware spreads require testing the subexpression's value. VariableDeclaration temp; if (element.isNullAware) { temp = new VariableDeclaration.forValue(value, type: const DynamicType(), isFinal: true); body.add(temp); value = new VariableGet(temp); } VariableDeclaration elt; Statement loopBody; if (element.elementType == null || !typeEnvironment.isSubtypeOf(element.elementType, elementType, SubtypeCheckMode.ignoringNullabilities)) { elt = new VariableDeclaration(null, type: const DynamicType(), isFinal: true); VariableDeclaration castedVar = new VariableDeclaration.forValue( new AsExpression(new VariableGet(elt), elementType) ..isTypeError = true ..fileOffset = element.expression.fileOffset, type: elementType); loopBody = new Block(<Statement>[ castedVar, new ExpressionStatement(new MethodInvocation( new VariableGet(result), new Name('add'), new Arguments([new VariableGet(castedVar)]), isSet ? setAdd : listAdd)) ]); } else { elt = new VariableDeclaration(null, type: elementType, isFinal: true); loopBody = new ExpressionStatement(new MethodInvocation( new VariableGet(result), new Name('add'), new Arguments([new VariableGet(elt)]), isSet ? setAdd : listAdd)); } Statement statement = new ForInStatement(elt, value, loopBody); if (element.isNullAware) { statement = new IfStatement( new Not(new MethodInvocation(new VariableGet(temp), new Name('=='), new Arguments([new NullLiteral()]), objectEquals)), statement, null); } body.add(statement); } @override TreeNode visitListLiteral(ListLiteral node) { if (node.isConst) { return _translateConstListOrSet(node, node.typeArgument, node.expressions, isSet: false); } return _translateListOrSet(node, node.typeArgument, node.expressions, isSet: false); } @override TreeNode visitSetLiteral(SetLiteral node) { if (node.isConst) { return _translateConstListOrSet(node, node.typeArgument, node.expressions, isSet: true); } return _translateListOrSet(node, node.typeArgument, node.expressions, isSet: true); } @override TreeNode visitMapLiteral(MapLiteral node) { if (node.isConst) { return _translateConstMap(node); } // Translate entries in place up to the first control-flow entry, if any. int i = 0; for (; i < node.entries.length; ++i) { if (node.entries[i] is ControlFlowMapEntry) break; node.entries[i] = node.entries[i].accept<TreeNode>(this)..parent = node; } // If there were no control-flow entries we are done. if (i == node.entries.length) return node; // Build a block expression and create an empty map. VariableDeclaration result = new VariableDeclaration.forValue( new MapLiteral([], keyType: node.keyType, valueType: node.valueType), type: new InterfaceType( coreTypes.mapClass, [node.keyType, node.valueType]), isFinal: true); List<Statement> body = [result]; // Add all the entries up to the first control-flow entry. for (int j = 0; j < i; ++j) { _addNormalEntry(node.entries[j], result, body); } for (; i < node.entries.length; ++i) { _translateEntry( node.entries[i], node.keyType, node.valueType, result, body); } return new BlockExpression(new Block(body), new VariableGet(result)); } void _translateEntry(MapEntry entry, DartType keyType, DartType valueType, VariableDeclaration result, List<Statement> body) { if (entry is SpreadMapEntry) { _translateSpreadEntry(entry, keyType, valueType, result, body); } else if (entry is IfMapEntry) { _translateIfEntry(entry, keyType, valueType, result, body); } else if (entry is ForMapEntry) { _translateForEntry(entry, keyType, valueType, result, body); } else if (entry is ForInMapEntry) { _translateForInEntry(entry, keyType, valueType, result, body); } else { _addNormalEntry(entry.accept<TreeNode>(this), result, body); } } void _addNormalEntry( MapEntry entry, VariableDeclaration result, List<Statement> body) { body.add(new ExpressionStatement(new MethodInvocation( new VariableGet(result), new Name('[]='), new Arguments([entry.key, entry.value]), mapPut))); } void _translateIfEntry(IfMapEntry entry, DartType keyType, DartType valueType, VariableDeclaration result, List<Statement> body) { List<Statement> thenBody = []; _translateEntry(entry.then, keyType, valueType, result, thenBody); List<Statement> elseBody; if (entry.otherwise != null) { _translateEntry(entry.otherwise, keyType, valueType, result, elseBody = <Statement>[]); } Statement thenStatement = thenBody.length == 1 ? thenBody.first : new Block(thenBody); Statement elseStatement; if (elseBody != null && elseBody.isNotEmpty) { elseStatement = elseBody.length == 1 ? elseBody.first : new Block(elseBody); } body.add(new IfStatement( entry.condition.accept<TreeNode>(this), thenStatement, elseStatement)); } void _translateForEntry(ForMapEntry entry, DartType keyType, DartType valueType, VariableDeclaration result, List<Statement> body) { List<Statement> statements = <Statement>[]; _translateEntry(entry.body, keyType, valueType, result, statements); Statement loopBody = statements.length == 1 ? statements.first : new Block(statements); ForStatement loop = new ForStatement(entry.variables, entry.condition?.accept<TreeNode>(this), entry.updates, loopBody) ..fileOffset = entry.fileOffset; transformList(loop.variables, this, loop); transformList(loop.updates, this, loop); body.add(loop); } void _translateForInEntry(ForInMapEntry entry, DartType keyType, DartType valueType, VariableDeclaration result, List<Statement> body) { List<Statement> statements; Statement prologue = entry.prologue; if (prologue == null) { statements = <Statement>[]; } else { prologue = prologue.accept<TreeNode>(this); statements = prologue is Block ? prologue.statements : <Statement>[prologue]; } _translateEntry(entry.body, keyType, valueType, result, statements); Statement loopBody = statements.length == 1 ? statements.first : new Block(statements); if (entry.problem != null) { body.add(new ExpressionStatement(entry.problem.accept<TreeNode>(this))); } body.add(new ForInStatement( entry.variable, entry.iterable.accept<TreeNode>(this), loopBody, isAsync: entry.isAsync) ..fileOffset = entry.fileOffset); } void _translateSpreadEntry(SpreadMapEntry entry, DartType keyType, DartType valueType, VariableDeclaration result, List<Statement> body) { Expression value = entry.expression.accept<TreeNode>(this); // Null-aware spreads require testing the subexpression's value. VariableDeclaration temp; if (entry.isNullAware) { temp = new VariableDeclaration.forValue(value, type: coreTypes.mapLegacyRawType); body.add(temp); value = new VariableGet(temp); } DartType entryType = new InterfaceType(mapEntryClass, <DartType>[keyType, valueType]); VariableDeclaration elt; Statement loopBody; if (entry.entryType == null || !typeEnvironment.isSubtypeOf(entry.entryType, entryType, SubtypeCheckMode.ignoringNullabilities)) { elt = new VariableDeclaration(null, type: new InterfaceType(mapEntryClass, <DartType>[const DynamicType(), const DynamicType()]), isFinal: true); VariableDeclaration keyVar = new VariableDeclaration.forValue( new AsExpression( new PropertyGet( new VariableGet(elt), new Name('key'), mapEntryKey), keyType) ..isTypeError = true ..fileOffset = entry.expression.fileOffset, type: keyType); VariableDeclaration valueVar = new VariableDeclaration.forValue( new AsExpression( new PropertyGet( new VariableGet(elt), new Name('value'), mapEntryValue), valueType) ..isTypeError = true ..fileOffset = entry.expression.fileOffset, type: valueType); loopBody = new Block(<Statement>[ keyVar, valueVar, new ExpressionStatement(new MethodInvocation( new VariableGet(result), new Name('[]='), new Arguments([new VariableGet(keyVar), new VariableGet(valueVar)]), mapPut)) ]); } else { elt = new VariableDeclaration(null, type: entryType, isFinal: true); loopBody = new ExpressionStatement(new MethodInvocation( new VariableGet(result), new Name('[]='), new Arguments([ new PropertyGet(new VariableGet(elt), new Name('key'), mapEntryKey), new PropertyGet( new VariableGet(elt), new Name('value'), mapEntryValue) ]), mapPut)); } Statement statement = new ForInStatement( elt, new PropertyGet(value, new Name('entries'), mapEntries), loopBody); if (entry.isNullAware) { statement = new IfStatement( new Not(new MethodInvocation(new VariableGet(temp), new Name('=='), new Arguments([new NullLiteral()]), objectEquals)), statement, null); } body.add(statement); } TreeNode _translateConstListOrSet( Expression node, DartType elementType, List<Expression> elements, {bool isSet: false}) { // Translate elements in place up to the first non-expression, if any. int i = 0; for (; i < elements.length; ++i) { if (elements[i] is ControlFlowElement) break; elements[i] = elements[i].accept<TreeNode>(this)..parent = node; } // If there were only expressions, we are done. if (i == elements.length) return node; Expression makeLiteral(List<Expression> expressions) { return isSet ? new SetLiteral(expressions, typeArgument: elementType, isConst: true) : new ListLiteral(expressions, typeArgument: elementType, isConst: true); } // Build a concatenation node. List<Expression> parts = []; List<Expression> currentPart = i > 0 ? elements.sublist(0, i) : null; for (; i < elements.length; ++i) { Expression element = elements[i]; if (element is SpreadElement) { if (currentPart != null) { parts.add(makeLiteral(currentPart)); currentPart = null; } Expression spreadExpression = element.expression.accept<TreeNode>(this); if (element.isNullAware) { VariableDeclaration temp = new VariableDeclaration(null, initializer: spreadExpression); parts.add(new Let( temp, new ConditionalExpression( new MethodInvocation(new VariableGet(temp), new Name('=='), new Arguments([new NullLiteral()])), makeLiteral([]), new VariableGet(temp), const DynamicType()))); } else { parts.add(spreadExpression); } } else if (element is IfElement) { if (currentPart != null) { parts.add(makeLiteral(currentPart)); currentPart = null; } Expression condition = element.condition.accept<TreeNode>(this); Expression then = makeLiteral([element.then]).accept<TreeNode>(this); Expression otherwise = element.otherwise != null ? makeLiteral([element.otherwise]).accept<TreeNode>(this) : makeLiteral([]); parts.add(new ConditionalExpression( condition, then, otherwise, const DynamicType())); } else if (element is ForElement || element is ForInElement) { // Rejected earlier. unhandled("${element.runtimeType}", "_translateConstListOrSet", element.fileOffset, getFileUri(element)); } else { currentPart ??= <Expression>[]; currentPart.add(element.accept<TreeNode>(this)); } } if (currentPart != null) { parts.add(makeLiteral(currentPart)); } return isSet ? new SetConcatenation(parts, typeArgument: elementType) : new ListConcatenation(parts, typeArgument: elementType); } TreeNode _translateConstMap(MapLiteral node) { // Translate entries in place up to the first control-flow entry, if any. int i = 0; for (; i < node.entries.length; ++i) { if (node.entries[i] is ControlFlowMapEntry) break; node.entries[i] = node.entries[i].accept<TreeNode>(this)..parent = node; } // If there were no control-flow entries we are done. if (i == node.entries.length) return node; MapLiteral makeLiteral(List<MapEntry> entries) { return new MapLiteral(entries, keyType: node.keyType, valueType: node.valueType, isConst: true); } // Build a concatenation node. List<Expression> parts = []; List<MapEntry> currentPart = i > 0 ? node.entries.sublist(0, i) : null; for (; i < node.entries.length; ++i) { MapEntry entry = node.entries[i]; if (entry is SpreadMapEntry) { if (currentPart != null) { parts.add(makeLiteral(currentPart)); currentPart = null; } Expression spreadExpression = entry.expression.accept<TreeNode>(this); if (entry.isNullAware) { VariableDeclaration temp = new VariableDeclaration(null, initializer: spreadExpression); parts.add(new Let( temp, new ConditionalExpression( new MethodInvocation(new VariableGet(temp), new Name('=='), new Arguments([new NullLiteral()])), makeLiteral([]), new VariableGet(temp), const DynamicType()))); } else { parts.add(spreadExpression); } } else if (entry is IfMapEntry) { if (currentPart != null) { parts.add(makeLiteral(currentPart)); currentPart = null; } Expression condition = entry.condition.accept<TreeNode>(this); Expression then = makeLiteral([entry.then]).accept<TreeNode>(this); Expression otherwise = entry.otherwise != null ? makeLiteral([entry.otherwise]).accept<TreeNode>(this) : makeLiteral([]); parts.add(new ConditionalExpression( condition, then, otherwise, const DynamicType())); } else if (entry is ForMapEntry || entry is ForInMapEntry) { // Rejected earlier. unhandled("${entry.runtimeType}", "_translateConstMap", entry.fileOffset, getFileUri(entry)); } else { currentPart ??= <MapEntry>[]; currentPart.add(entry.accept<TreeNode>(this)); } } if (currentPart != null) { parts.add(makeLiteral(currentPart)); } return new MapConcatenation(parts, keyType: node.keyType, valueType: node.valueType); } }
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/kernel/kernel_shadow_ast.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. /// This file declares a "shadow hierarchy" of concrete classes which extend /// the kernel class hierarchy, adding methods and fields needed by the /// BodyBuilder. /// /// Instances of these classes may be created using the factory methods in /// `ast_factory.dart`. /// /// Note that these classes represent the Dart language prior to desugaring. /// When a single Dart construct desugars to a tree containing multiple kernel /// AST nodes, the shadow class extends the kernel object at the top of the /// desugared tree. /// /// This means that in some cases multiple shadow classes may extend the same /// kernel class, because multiple constructs in Dart may desugar to a tree /// with the same kind of root node. import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart'; import 'package:kernel/type_algebra.dart' show Substitution; import 'package:kernel/type_environment.dart'; import 'package:kernel/clone.dart'; import '../../base/instrumentation.dart' show Instrumentation, InstrumentationValueForMember, InstrumentationValueForType, InstrumentationValueForTypeArgs; import '../builder/library_builder.dart' show LibraryBuilder; import '../fasta_codes.dart' show messageCantDisambiguateAmbiguousInformation, messageCantDisambiguateNotEnoughInformation, messageNonNullAwareSpreadIsNull, messageSwitchExpressionNotAssignableCause, messageVoidExpression, noLength, templateCantInferTypeDueToCircularity, templateForInLoopElementTypeNotAssignable, templateForInLoopTypeNotIterable, templateIntegerLiteralIsOutOfRange, templateSpreadElementTypeMismatch, templateSpreadMapEntryElementKeyTypeMismatch, templateSpreadMapEntryElementValueTypeMismatch, templateSpreadMapEntryTypeMismatch, templateSpreadTypeMismatch, templateSuperclassHasNoMethod, templateSwitchExpressionNotAssignable, templateUndefinedMethod, templateWebLiteralCannotBeRepresentedExactly; import '../names.dart'; import '../problems.dart' show unhandled, unsupported; import '../source/source_class_builder.dart' show SourceClassBuilder; import '../source/source_library_builder.dart' show SourceLibraryBuilder; import '../type_inference/inference_helper.dart' show InferenceHelper; import '../type_inference/type_inference_engine.dart' show IncludesTypeParametersNonCovariantly, TypeInferenceEngine; import '../type_inference/type_inferrer.dart'; import '../type_inference/type_promotion.dart' show TypePromoter, TypePromoterImpl, TypePromotionFact, TypePromotionScope; import '../type_inference/type_schema.dart' show UnknownType; import '../type_inference/type_schema_elimination.dart' show greatestClosure; import '../type_inference/type_schema_environment.dart' show TypeSchemaEnvironment; import 'body_builder.dart' show combineStatements; import 'collections.dart' show ControlFlowMapEntry, ForElement, ForInElement, ForInMapEntry, ForMapEntry, IfElement, IfMapEntry, SpreadElement, SpreadMapEntry, convertToElement; import 'expression_generator.dart' show makeLet; import 'implicit_type_argument.dart' show ImplicitTypeArgument; part "inference_visitor.dart"; /// Computes the return type of a (possibly factory) constructor. InterfaceType computeConstructorReturnType(Member constructor) { if (constructor is Constructor) { return constructor.enclosingClass.thisType; } else { return constructor.function.returnType; } } int getExtensionTypeParameterCount(Arguments arguments) { if (arguments is ArgumentsImpl) { return arguments._extensionTypeParameterCount; } else { // TODO(johnniwinther): Remove this path or assert why it is accepted. return 0; } } int getExtensionTypeArgumentCount(Arguments arguments) { if (arguments is ArgumentsImpl) { return arguments._extensionTypeArgumentCount; } else { // TODO(johnniwinther): Remove this path or assert why it is accepted. return 0; } } List<DartType> getExplicitExtensionTypeArguments(Arguments arguments) { if (arguments is ArgumentsImpl) { if (arguments._extensionTypeArgumentCount == 0) { return null; } else { return arguments.types .take(arguments._extensionTypeArgumentCount) .toList(); } } else { // TODO(johnniwinther): Remove this path or assert why it is accepted. return null; } } List<DartType> getExplicitTypeArguments(Arguments arguments) { if (arguments is ArgumentsImpl) { if (arguments._explicitTypeArgumentCount == 0) { return null; } else if (arguments._extensionTypeParameterCount == 0) { return arguments.types; } else { return arguments.types .skip(arguments._extensionTypeParameterCount) .toList(); } } else { // This code path should only be taken in situations where there are no // type arguments at all, e.g. calling a user-definable operator. assert(arguments.types.isEmpty); return null; } } /// Information associated with a class during type inference. class ClassInferenceInfo { /// The builder associated with this class. final SourceClassBuilder builder; /// The visitor for determining if a given type makes covariant use of one of /// the class's generic parameters, and therefore requires covariant checks. IncludesTypeParametersNonCovariantly needsCheckVisitor; /// Getters and methods in the class's API. May include forwarding nodes. final gettersAndMethods = <Member>[]; /// Setters in the class's API. May include forwarding nodes. final setters = <Member>[]; ClassInferenceInfo(this.builder); } enum InternalExpressionKind { Cascade, CompoundExtensionIndexSet, CompoundIndexSet, CompoundPropertySet, CompoundSuperIndexSet, DeferredCheck, ExtensionIndexSet, ExtensionTearOff, ExtensionSet, IfNull, IfNullExtensionIndexSet, IfNullIndexSet, IfNullPropertySet, IfNullSet, IfNullSuperIndexSet, IndexSet, LoadLibraryTearOff, LocalPostIncDec, NullAwareCompoundSet, NullAwareExtension, NullAwareIfNullSet, NullAwareMethodInvocation, NullAwarePropertyGet, NullAwarePropertySet, PropertyPostIncDec, StaticPostIncDec, SuperIndexSet, SuperPostIncDec, } /// Common base class for internal expressions. abstract class InternalExpression extends Expression { InternalExpressionKind get kind; /// Replaces this [InternalExpression] with a semantically equivalent /// [Expression] and returns the replacing [Expression]. /// /// This method most be called after inference has been performed to ensure /// that [InternalExpression] nodes do not leak. Expression replace() { throw new UnsupportedError('$runtimeType.replace()'); } @override R accept<R>(ExpressionVisitor<R> visitor) => visitor.defaultExpression(this); @override R accept1<R, A>(ExpressionVisitor1<R, A> visitor, A arg) => visitor.defaultExpression(this, arg); @override DartType getStaticType(types) => unsupported("${runtimeType}.getStaticType", -1, null); } /// Front end specific implementation of [Argument]. class ArgumentsImpl extends Arguments { // TODO(johnniwinther): Move this to the static invocation instead. final int _extensionTypeParameterCount; final int _extensionTypeArgumentCount; int _explicitTypeArgumentCount; ArgumentsImpl(List<Expression> positional, {List<DartType> types, List<NamedExpression> named}) : _explicitTypeArgumentCount = types?.length ?? 0, _extensionTypeParameterCount = 0, _extensionTypeArgumentCount = 0, super(positional, types: types, named: named); ArgumentsImpl.forExtensionMethod(int extensionTypeParameterCount, int typeParameterCount, Expression receiver, {List<DartType> extensionTypeArguments = const <DartType>[], List<DartType> typeArguments = const <DartType>[], List<Expression> positionalArguments = const <Expression>[], List<NamedExpression> namedArguments = const <NamedExpression>[]}) : _extensionTypeParameterCount = extensionTypeParameterCount, _extensionTypeArgumentCount = extensionTypeArguments.length, _explicitTypeArgumentCount = typeArguments.length, assert( extensionTypeArguments.isEmpty || extensionTypeArguments.length == extensionTypeParameterCount, "Extension type arguments must be empty or complete."), super(<Expression>[receiver]..addAll(positionalArguments), named: namedArguments, types: <DartType>[] ..addAll(_normalizeTypeArguments( extensionTypeParameterCount, extensionTypeArguments)) ..addAll( _normalizeTypeArguments(typeParameterCount, typeArguments))); static List<DartType> _normalizeTypeArguments( int length, List<DartType> arguments) { if (arguments.isEmpty && length > 0) { return new List<DartType>.filled(length, const UnknownType()); } return arguments; } static void setNonInferrableArgumentTypes( ArgumentsImpl arguments, List<DartType> types) { arguments.types.clear(); arguments.types.addAll(types); arguments._explicitTypeArgumentCount = types.length; } static void removeNonInferrableArgumentTypes(ArgumentsImpl arguments) { arguments.types.clear(); arguments._explicitTypeArgumentCount = 0; } } /// Internal expression representing a cascade expression. /// /// A cascade expression of the form `a..b()..c()` is represented as the kernel /// expression: /// /// let v = a in /// let _ = v.b() in /// let _ = v.c() in /// v /// /// In the documentation that follows, `v` is referred to as the "cascade /// variable"--this is the variable that remembers the value of the expression /// preceding the first `..` while the cascades are being evaluated. /// /// After constructing a [Cascade], the caller should /// call [finalize] with an expression representing the expression after the /// `..`. If a further `..` follows that expression, the caller should call /// [extend] followed by [finalize] for each subsequent cascade. // TODO(johnniwinther): Change the representation to be direct and perform // the [Let] encoding in [replace]. class Cascade extends InternalExpression { VariableDeclaration variable; /// Pointer to the first "let" expression in the cascade, i.e. `e1` in /// `e..e1..e2..e3`; Let _firstCascade; /// Pointer to the last "let" expression in the cascade, i.e. `e3` in // /// `e..e1..e2..e3`; Let _lastCascade; /// Creates a [Cascade] using [variable] as the cascade /// variable. Caller is responsible for ensuring that [variable]'s /// initializer is the expression preceding the first `..` of the cascade /// expression. Cascade(this.variable) { _lastCascade = _firstCascade = makeLet( new VariableDeclaration.forValue(new _UnfinishedCascade()), new VariableGet(variable)); variable?.parent = this; _firstCascade.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.Cascade; /// The initial expression of the cascade, i.e. `e` in `e..e1..e2..e3`. Expression get expression => variable.initializer; /// Returns the cascade expressions of the cascade, i.e. `e1`, `e2`, and `e3` /// in `e..e1..e2..e3`. Iterable<Expression> get cascades sync* { Let section = _firstCascade; while (true) { yield section.variable.initializer; if (section.body is! Let) break; section = section.body; } } /// Adds a new unfinalized section to the end of the cascade. Should be /// called after the previous cascade section has been finalized. void extend() { assert(_lastCascade.variable.initializer is! _UnfinishedCascade); Let newCascade = makeLet( new VariableDeclaration.forValue(new _UnfinishedCascade()), _lastCascade.body); _lastCascade.body = newCascade; newCascade.parent = _lastCascade; _lastCascade = newCascade; } /// Finalizes the last cascade section with the given [expression]. void finalize(Expression expression) { assert(_lastCascade.variable.initializer is _UnfinishedCascade); _lastCascade.variable.initializer = expression; expression.parent = _lastCascade.variable; } @override Expression replace() { Expression replacement; parent.replaceChild( this, replacement = new Let(variable, _firstCascade) ..fileOffset = fileOffset); return replacement; } @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); _firstCascade?.accept(v); } @override void transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (_firstCascade != null) { _firstCascade = _firstCascade.accept<TreeNode>(v); _firstCascade?.parent = this; } } } /// Internal expression representing a deferred check. // TODO(johnniwinther): Change the representation to be direct and perform // the [Let] encoding in [replace]. class DeferredCheck extends InternalExpression { VariableDeclaration _variable; Expression expression; DeferredCheck(this._variable, this.expression) { _variable?.parent = this; expression?.parent = this; } InternalExpressionKind get kind => InternalExpressionKind.DeferredCheck; @override Expression replace() { Expression replacement; parent.replaceChild(this, replacement = new Let(_variable, expression)..fileOffset = fileOffset); return replacement; } @override void visitChildren(Visitor<dynamic> v) { _variable?.accept(v); expression?.accept(v); } @override void transformChildren(Transformer v) { if (_variable != null) { _variable = _variable.accept<TreeNode>(v); _variable?.parent = this; } if (expression != null) { expression = expression.accept<TreeNode>(v); expression?.parent = this; } } } /// Common base class for shadow objects representing expressions in kernel /// form. abstract class ExpressionJudgment extends Expression { /// Calls back to [inferrer] to perform type inference for whatever concrete /// type of [Expression] this is. ExpressionInferenceResult acceptInference( InferenceVisitor visitor, DartType typeContext); } /// Shadow object for [StaticInvocation] when the procedure being invoked is a /// factory constructor. class FactoryConstructorInvocationJudgment extends StaticInvocation implements ExpressionJudgment { bool hasBeenInferred = false; FactoryConstructorInvocationJudgment( Procedure target, ArgumentsImpl arguments, {bool isConst: false}) : super(target, arguments, isConst: isConst); @override ExpressionInferenceResult acceptInference( InferenceVisitor visitor, DartType typeContext) { return visitor.visitFactoryConstructorInvocationJudgment(this, typeContext); } } /// Front end specific implementation of [FunctionDeclaration]. class FunctionDeclarationImpl extends FunctionDeclaration { bool _hasImplicitReturnType = false; FunctionDeclarationImpl( VariableDeclarationImpl variable, FunctionNode function) : super(variable, function); static void setHasImplicitReturnType( FunctionDeclarationImpl declaration, bool hasImplicitReturnType) { declaration._hasImplicitReturnType = hasImplicitReturnType; } } /// Concrete shadow object representing a super initializer in kernel form. class InvalidSuperInitializerJudgment extends LocalInitializer implements InitializerJudgment { final Constructor target; final ArgumentsImpl argumentsJudgment; InvalidSuperInitializerJudgment( this.target, this.argumentsJudgment, VariableDeclaration variable) : super(variable); @override void acceptInference(InferenceVisitor visitor) { return visitor.visitInvalidSuperInitializerJudgment(this); } } /// Internal expression representing an if-null expression. /// /// An if-null expression of the form `a ?? b` is encoded as: /// /// let v = a in v == null ? b : v /// class IfNullExpression extends InternalExpression { Expression left; Expression right; IfNullExpression(this.left, this.right) { left?.parent = this; right?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.IfNull; @override void visitChildren(Visitor<dynamic> v) { left?.accept(v); right?.accept(v); } @override void transformChildren(Transformer v) { if (left != null) { left = left.accept<TreeNode>(v); left?.parent = this; } if (right != null) { right = right.accept<TreeNode>(v); right?.parent = this; } } } /// Common base class for shadow objects representing initializers in kernel /// form. abstract class InitializerJudgment implements Initializer { /// Performs type inference for whatever concrete type of /// [InitializerJudgment] this is. void acceptInference(InferenceVisitor visitor); } Expression checkWebIntLiteralsErrorIfUnexact( ShadowTypeInferrer inferrer, int value, String literal, int charOffset) { if (value >= 0 && value <= (1 << 53)) return null; if (inferrer.isTopLevel) return null; if (!inferrer.library.loader.target.backendTarget .errorOnUnexactWebIntLiterals) return null; BigInt asInt = new BigInt.from(value).toUnsigned(64); BigInt asDouble = new BigInt.from(asInt.toDouble()); if (asInt == asDouble) return null; String text = literal ?? value.toString(); String nearest = text.startsWith('0x') || text.startsWith('0X') ? '0x${asDouble.toRadixString(16)}' : asDouble.toString(); int length = literal?.length ?? noLength; return inferrer.helper.buildProblem( templateWebLiteralCannotBeRepresentedExactly.withArguments(text, nearest), charOffset, length); } /// Concrete shadow object representing an integer literal in kernel form. class IntJudgment extends IntLiteral implements ExpressionJudgment { final String literal; IntJudgment(int value, this.literal) : super(value); double asDouble({bool negated: false}) { if (value == 0 && negated) return -0.0; BigInt intValue = new BigInt.from(negated ? -value : value); double doubleValue = intValue.toDouble(); return intValue == new BigInt.from(doubleValue) ? doubleValue : null; } @override ExpressionInferenceResult acceptInference( InferenceVisitor visitor, DartType typeContext) { return visitor.visitIntJudgment(this, typeContext); } } class ShadowLargeIntLiteral extends IntLiteral implements ExpressionJudgment { final String literal; final int fileOffset; bool isParenthesized = false; ShadowLargeIntLiteral(this.literal, this.fileOffset) : super(0); double asDouble({bool negated: false}) { BigInt intValue = BigInt.tryParse(negated ? '-${literal}' : literal); if (intValue == null) return null; double doubleValue = intValue.toDouble(); return !doubleValue.isNaN && !doubleValue.isInfinite && intValue == new BigInt.from(doubleValue) ? doubleValue : null; } int asInt64({bool negated: false}) { return int.tryParse(negated ? '-${literal}' : literal); } @override ExpressionInferenceResult acceptInference( InferenceVisitor visitor, DartType typeContext) { return visitor.visitShadowLargeIntLiteral(this, typeContext); } } /// Concrete shadow object representing an invalid initializer in kernel form. class ShadowInvalidInitializer extends LocalInitializer implements InitializerJudgment { ShadowInvalidInitializer(VariableDeclaration variable) : super(variable); @override void acceptInference(InferenceVisitor visitor) { return visitor.visitShadowInvalidInitializer(this); } } /// Concrete shadow object representing an invalid initializer in kernel form. class ShadowInvalidFieldInitializer extends LocalInitializer implements InitializerJudgment { final Field field; final Expression value; ShadowInvalidFieldInitializer( this.field, this.value, VariableDeclaration variable) : super(variable) { value?.parent = this; } @override void acceptInference(InferenceVisitor visitor) { return visitor.visitShadowInvalidFieldInitializer(this); } } /// Front end specific implementation of [MethodInvocation]. class MethodInvocationImpl extends MethodInvocation { /// Indicates whether this method invocation is a call to a `call` method /// resulting from the invocation of a function expression. final bool isImplicitCall; MethodInvocationImpl(Expression receiver, Name name, ArgumentsImpl arguments, {this.isImplicitCall: false, Member interfaceTarget}) : super(receiver, name, arguments, interfaceTarget); } /// Concrete shadow object representing a named function expression. /// /// Named function expressions are not legal in Dart, but they are accepted by /// the parser and BodyBuilder for error recovery purposes. /// /// A named function expression of the form `f() { ... }` is represented as the /// kernel expression: /// /// let f = () { ... } in f class NamedFunctionExpressionJudgment extends Let implements ExpressionJudgment { NamedFunctionExpressionJudgment(VariableDeclarationImpl variable) : super(variable, new VariableGet(variable)); @override ExpressionInferenceResult acceptInference( InferenceVisitor visitor, DartType typeContext) { return visitor.visitNamedFunctionExpressionJudgment(this, typeContext); } } /// Internal expression representing a null-aware method invocation. /// /// A null-aware method invocation of the form `a?.b(...)` is encoded as: /// /// let v = a in v == null ? null : v.b(...) /// class NullAwareMethodInvocation extends InternalExpression { /// The synthetic variable whose initializer hold the receiver. VariableDeclaration variable; /// The expression that invokes the method on [variable]. Expression invocation; NullAwareMethodInvocation(this.variable, this.invocation) { variable?.parent = this; invocation?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.NullAwareMethodInvocation; @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); invocation?.accept(v); } @override transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (invocation != null) { invocation = invocation.accept<TreeNode>(v); invocation?.parent = this; } } } /// Internal expression representing a null-aware read from a property. /// /// A null-aware property get of the form `a?.b` is encoded as: /// /// let v = a in v == null ? null : v.b /// class NullAwarePropertyGet extends InternalExpression { /// The synthetic variable whose initializer hold the receiver. VariableDeclaration variable; /// The expression that reads the property from [variable]. Expression read; NullAwarePropertyGet(this.variable, this.read) { variable?.parent = this; read?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.NullAwarePropertyGet; @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); read?.accept(v); } @override transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (read != null) { read = read.accept<TreeNode>(v); read?.parent = this; } } } /// Internal expression representing a null-aware read from a property. /// /// A null-aware property get of the form `a?.b = c` is encoded as: /// /// let v = a in v == null ? null : v.b = c /// class NullAwarePropertySet extends InternalExpression { /// The synthetic variable whose initializer hold the receiver. VariableDeclaration variable; /// The expression that writes the value to the property in [variable]. Expression write; NullAwarePropertySet(this.variable, this.write) { variable?.parent = this; write?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.NullAwarePropertySet; @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); write?.accept(v); } @override transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Front end specific implementation of [ReturnStatement]. class ReturnStatementImpl extends ReturnStatement { final bool isArrow; ReturnStatementImpl(this.isArrow, [Expression expression]) : super(expression); } /// Concrete implementation of [TypeInferenceEngine] specialized to work with /// kernel objects. class ShadowTypeInferenceEngine extends TypeInferenceEngine { ShadowTypeInferenceEngine(Instrumentation instrumentation) : super(instrumentation); @override ShadowTypeInferrer createLocalTypeInferrer( Uri uri, InterfaceType thisType, SourceLibraryBuilder library) { return new TypeInferrer(this, uri, false, thisType, library); } @override ShadowTypeInferrer createTopLevelTypeInferrer( Uri uri, InterfaceType thisType, SourceLibraryBuilder library) { return new TypeInferrer(this, uri, true, thisType, library); } } /// Concrete implementation of [TypeInferrer] specialized to work with kernel /// objects. class ShadowTypeInferrer extends TypeInferrerImpl { @override final TypePromoter typePromoter; ShadowTypeInferrer.private(ShadowTypeInferenceEngine engine, Uri uri, bool topLevel, InterfaceType thisType, SourceLibraryBuilder library) : typePromoter = new TypePromoter(engine.typeSchemaEnvironment), super.private(engine, uri, topLevel, thisType, library); @override Expression getFieldInitializer(Field field) { return field.initializer; } @override ExpressionInferenceResult inferExpression( Expression expression, DartType typeContext, bool typeNeeded, {bool isVoidAllowed: false}) { // `null` should never be used as the type context. An instance of // `UnknownType` should be used instead. assert(typeContext != null); // It isn't safe to do type inference on an expression without a parent, // because type inference might cause us to have to replace one expression // with another, and we can only replace a node if it has a parent pointer. assert(expression.parent != null); // For full (non-top level) inference, we need access to the // ExpressionGeneratorHelper so that we can perform error recovery. assert(isTopLevel || helper != null); // When doing top level inference, we skip subexpressions whose type isn't // needed so that we don't induce bogus dependencies on fields mentioned in // those subexpressions. if (!typeNeeded) return const ExpressionInferenceResult(null); InferenceVisitor visitor = new InferenceVisitor(this); ExpressionInferenceResult result; if (expression is ExpressionJudgment) { result = expression.acceptInference(visitor, typeContext); } else { result = expression.accept1(visitor, typeContext); } DartType inferredType = result.inferredType; assert(inferredType != null, "No type inferred for $expression."); if (inferredType is VoidType && !isVoidAllowed) { if (expression.parent is! ArgumentsImpl) { helper?.addProblem( messageVoidExpression, expression.fileOffset, noLength); } } return result; } @override void inferInitializer(InferenceHelper helper, Initializer initializer) { this.helper = helper; // Use polymorphic dispatch on [KernelInitializer] to perform whatever // kind of type inference is correct for this kind of initializer. // TODO(paulberry): experiment to see if dynamic dispatch would be better, // so that the type hierarchy will be simpler (which may speed up "is" // checks). if (initializer is InitializerJudgment) { initializer.acceptInference(new InferenceVisitor(this)); } else { initializer.accept(new InferenceVisitor(this)); } this.helper = null; } @override void inferStatement(Statement statement) { // For full (non-top level) inference, we need access to the // ExpressionGeneratorHelper so that we can perform error recovery. if (!isTopLevel) assert(helper != null); if (statement != null) { statement.accept(new InferenceVisitor(this)); } } } /// Concrete implementation of [TypePromoter] specialized to work with kernel /// objects. class ShadowTypePromoter extends TypePromoterImpl { ShadowTypePromoter.private(TypeSchemaEnvironment typeSchemaEnvironment) : super.private(typeSchemaEnvironment); @override int getVariableFunctionNestingLevel(VariableDeclaration variable) { if (variable is VariableDeclarationImpl) { return variable._functionNestingLevel; } else { // Hack to deal with the fact that BodyBuilder still creates raw // VariableDeclaration objects sometimes. // TODO(paulberry): get rid of this once the type parameter is // KernelVariableDeclaration. return 0; } } @override bool isPromotionCandidate(VariableDeclaration variable) { assert(variable is VariableDeclarationImpl); VariableDeclarationImpl kernelVariableDeclaration = variable; return !kernelVariableDeclaration._isLocalFunction; } @override bool sameExpressions(Expression a, Expression b) { return identical(a, b); } @override void setVariableMutatedAnywhere(VariableDeclaration variable) { if (variable is VariableDeclarationImpl) { variable._mutatedAnywhere = true; } else { // Hack to deal with the fact that BodyBuilder still creates raw // VariableDeclaration objects sometimes. // TODO(paulberry): get rid of this once the type parameter is // KernelVariableDeclaration. } } @override void setVariableMutatedInClosure(VariableDeclaration variable) { if (variable is VariableDeclarationImpl) { variable._mutatedInClosure = true; } else { // Hack to deal with the fact that BodyBuilder still creates raw // VariableDeclaration objects sometimes. // TODO(paulberry): get rid of this once the type parameter is // KernelVariableDeclaration. } } @override bool wasVariableMutatedAnywhere(VariableDeclaration variable) { if (variable is VariableDeclarationImpl) { return variable._mutatedAnywhere; } else { // Hack to deal with the fact that BodyBuilder still creates raw // VariableDeclaration objects sometimes. // TODO(paulberry): get rid of this once the type parameter is // KernelVariableDeclaration. return true; } } } /// Front end specific implementation of [VariableDeclaration]. class VariableDeclarationImpl extends VariableDeclaration { final bool forSyntheticToken; final bool _implicitlyTyped; // TODO(ahe): Remove this field. We can get rid of it by recording closure // mutation in [BodyBuilder]. final int _functionNestingLevel; // TODO(ahe): Remove this field. It's only used locally when compiling a // method, and this can thus be tracked in a [Set] (actually, tracking this // information in a [List] is probably even faster as the average size will // be close to zero). bool _mutatedInClosure = false; // TODO(ahe): Investigate if this can be removed. bool _mutatedAnywhere = false; // TODO(ahe): Investigate if this can be removed. final bool _isLocalFunction; VariableDeclarationImpl(String name, this._functionNestingLevel, {this.forSyntheticToken: false, Expression initializer, DartType type, bool isFinal: false, bool isConst: false, bool isFieldFormal: false, bool isCovariant: false, bool isLocalFunction: false, bool isLate: false, bool isRequired: false}) : _implicitlyTyped = type == null, _isLocalFunction = isLocalFunction, super(name, initializer: initializer, type: type ?? const DynamicType(), isFinal: isFinal, isConst: isConst, isFieldFormal: isFieldFormal, isCovariant: isCovariant, isLate: isLate, isRequired: isRequired); VariableDeclarationImpl.forEffect(Expression initializer) : forSyntheticToken = false, _functionNestingLevel = 0, _implicitlyTyped = false, _isLocalFunction = false, super.forValue(initializer); VariableDeclarationImpl.forValue(Expression initializer) : forSyntheticToken = false, _functionNestingLevel = 0, _implicitlyTyped = true, _isLocalFunction = false, super.forValue(initializer); /// Determine whether the given [VariableDeclarationImpl] had an implicit /// type. /// /// This is static to avoid introducing a method that would be visible to /// the kernel. static bool isImplicitlyTyped(VariableDeclarationImpl variable) => variable._implicitlyTyped; /// Determines whether the given [VariableDeclarationImpl] represents a /// local function. /// /// This is static to avoid introducing a method that would be visible to the /// kernel. static bool isLocalFunction(VariableDeclarationImpl variable) => variable._isLocalFunction; } /// Front end specific implementation of [VariableGet]. class VariableGetImpl extends VariableGet { final TypePromotionFact _fact; final TypePromotionScope _scope; VariableGetImpl(VariableDeclaration variable, this._fact, this._scope) : super(variable); } /// Front end specific implementation of [LoadLibrary]. class LoadLibraryImpl extends LoadLibrary { final Arguments arguments; LoadLibraryImpl(LibraryDependency import, this.arguments) : super(import); } /// Internal expression representing a tear-off of a `loadLibrary` function. class LoadLibraryTearOff extends InternalExpression { LibraryDependency import; Procedure target; LoadLibraryTearOff(this.import, this.target); @override InternalExpressionKind get kind => InternalExpressionKind.LoadLibraryTearOff; @override Expression replace() { Expression replacement; parent.replaceChild( this, replacement = new StaticGet(target)..fileOffset = fileOffset); return replacement; } @override void visitChildren(Visitor<dynamic> v) { import?.accept(v); target?.accept(v); } @override void transformChildren(Transformer v) { if (import != null) { import = import.accept<TreeNode>(v); } if (target != null) { target = target.accept<TreeNode>(v); } } } class _UnfinishedCascade extends Expression { R accept<R>(v) => unsupported("accept", -1, null); R accept1<R, A>(v, arg) => unsupported("accept1", -1, null); DartType getStaticType(types) => unsupported("getStaticType", -1, null); void transformChildren(v) => unsupported("transformChildren", -1, null); void visitChildren(v) => unsupported("visitChildren", -1, null); } /// Internal expression representing an if-null property set. /// /// An if-null property set of the form `o.a ??= b` is, if used for value, /// encoded as the expression: /// /// let v1 = o in let v2 = v1.a in v2 == null ? v1.a = b : v2 /// /// and, if used for effect, encoded as the expression: /// /// let v1 = o in v1.a == null ? v1.a = b : null /// class IfNullPropertySet extends InternalExpression { /// The synthetic variable whose initializer hold the receiver. VariableDeclaration variable; /// The expression that reads the property from [variable]. Expression read; /// The expression that writes the value to the property on [variable]. Expression write; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; IfNullPropertySet(this.variable, this.read, this.write, {this.forEffect}) : assert(forEffect != null) { variable?.parent = this; read?.parent = this; write?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.IfNullPropertySet; @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); read?.accept(v); write?.accept(v); } @override void transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (read != null) { read = read.accept<TreeNode>(v); read?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Internal expression representing an if-null assignment. /// /// An if-null assignment of the form `a ??= b` is, if used for value, /// encoded as the expression: /// /// let v1 = a in v1 == null ? a = b : v1 /// /// and, if used for effect, encoded as the expression: /// /// a == null ? a = b : null /// class IfNullSet extends InternalExpression { /// The expression that reads the property from [variable]. Expression read; /// The expression that writes the value to the property on [variable]. Expression write; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; IfNullSet(this.read, this.write, {this.forEffect}) : assert(forEffect != null) { read?.parent = this; write?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.IfNullSet; @override void visitChildren(Visitor<dynamic> v) { read?.accept(v); write?.accept(v); } @override void transformChildren(Transformer v) { if (read != null) { read = read.accept<TreeNode>(v); read?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Internal expression representing an compound property assignment. /// /// An compound property assignment of the form `o.a += b` is encoded as the /// expression: /// /// let v1 = o in v1.a = v1.a + b /// class CompoundPropertySet extends InternalExpression { /// The synthetic variable whose initializer hold the receiver. VariableDeclaration variable; /// The expression that writes the result of the binary operation to the /// property on [variable]. Expression write; CompoundPropertySet(this.variable, this.write) { variable?.parent = this; write?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.CompoundPropertySet; @override Expression replace() { Expression replacement; replaceWith( replacement = new Let(variable, write)..fileOffset = fileOffset); return replacement; } @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); write?.accept(v); } @override void transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Internal expression representing an compound property assignment. /// /// An compound property assignment of the form `o.a++` is encoded as the /// expression: /// /// let v1 = o in let v2 = v1.a in let v3 = v1.a = v2 + 1 in v2 /// class PropertyPostIncDec extends InternalExpression { /// The synthetic variable whose initializer hold the receiver. /// /// This is `null` if the receiver is read-only and therefore does not need to /// be stored in a temporary variable. VariableDeclaration variable; /// The expression that reads the property on [variable]. VariableDeclaration read; /// The expression that writes the result of the binary operation to the /// property on [variable]. VariableDeclaration write; PropertyPostIncDec(this.variable, this.read, this.write) { variable?.parent = this; read?.parent = this; write?.parent = this; } PropertyPostIncDec.onReadOnly( VariableDeclaration read, VariableDeclaration write) : this(null, read, write); @override InternalExpressionKind get kind => InternalExpressionKind.PropertyPostIncDec; @override Expression replace() { Expression replacement; if (variable != null) { replaceWith(replacement = new Let( variable, createLet(read, createLet(write, createVariableGet(read)))) ..fileOffset = fileOffset); } else { replaceWith( replacement = new Let(read, createLet(write, createVariableGet(read))) ..fileOffset = fileOffset); } return replacement; } @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); read?.accept(v); write?.accept(v); } @override void transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Internal expression representing an local variable post inc/dec expression. /// /// An local variable post inc/dec expression of the form `a++` is encoded as /// the expression: /// /// let v1 = a in let v2 = a = v1 + 1 in v1 /// class LocalPostIncDec extends InternalExpression { /// The expression that reads the local variable. VariableDeclaration read; /// The expression that writes the result of the binary operation to the /// local variable. VariableDeclaration write; LocalPostIncDec(this.read, this.write) { read?.parent = this; write?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.LocalPostIncDec; @override Expression replace() { Expression replacement; replaceWith( replacement = new Let(read, createLet(write, createVariableGet(read))) ..fileOffset = fileOffset); return replacement; } @override void visitChildren(Visitor<dynamic> v) { read?.accept(v); write?.accept(v); } @override void transformChildren(Transformer v) { if (read != null) { read = read.accept<TreeNode>(v); read?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Internal expression representing an static member post inc/dec expression. /// /// An local variable post inc/dec expression of the form `a++` is encoded as /// the expression: /// /// let v1 = a in let v2 = a = v1 + 1 in v1 /// class StaticPostIncDec extends InternalExpression { /// The expression that reads the static member. VariableDeclaration read; /// The expression that writes the result of the binary operation to the /// static member. VariableDeclaration write; StaticPostIncDec(this.read, this.write) { read?.parent = this; write?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.StaticPostIncDec; @override Expression replace() { Expression replacement; replaceWith( replacement = new Let(read, createLet(write, createVariableGet(read))) ..fileOffset = fileOffset); return replacement; } @override void visitChildren(Visitor<dynamic> v) { read?.accept(v); write?.accept(v); } @override void transformChildren(Transformer v) { if (read != null) { read = read.accept<TreeNode>(v); read?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Internal expression representing an static member post inc/dec expression. /// /// An local variable post inc/dec expression of the form `super.a++` is encoded /// as the expression: /// /// let v1 = super.a in let v2 = super.a = v1 + 1 in v1 /// class SuperPostIncDec extends InternalExpression { /// The expression that reads the static member. VariableDeclaration read; /// The expression that writes the result of the binary operation to the /// static member. VariableDeclaration write; SuperPostIncDec(this.read, this.write) { read?.parent = this; write?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.SuperPostIncDec; @override Expression replace() { Expression replacement; replaceWith( replacement = new Let(read, createLet(write, createVariableGet(read))) ..fileOffset = fileOffset); return replacement; } @override void visitChildren(Visitor<dynamic> v) { read?.accept(v); write?.accept(v); } @override void transformChildren(Transformer v) { if (read != null) { read = read.accept<TreeNode>(v); read?.parent = this; } if (write != null) { write = write.accept<TreeNode>(v); write?.parent = this; } } } /// Internal expression representing an index set expression. /// /// An index set expression of the form `o[a] = b` used for value is encoded as /// the expression: /// /// let v1 = o in let v2 = a in let v3 = b in let _ = o.[]=(v2, v3) in v3 /// /// An index set expression used for effect is encoded as /// /// o.[]=(a, b) /// /// using [MethodInvocationImpl]. /// class IndexSet extends InternalExpression { /// The receiver on which the index set operation is performed. Expression receiver; /// The index expression of the operation. Expression index; /// The value expression of the operation. Expression value; // TODO(johnniwinther): Add `readOnlyReceiver` capability. IndexSet(this.receiver, this.index, this.value) { receiver?.parent = this; index?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.IndexSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); index?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing a super index set expression. /// /// A super index set expression of the form `super[a] = b` used for value is /// encoded as the expression: /// /// let v1 = a in let v2 = b in let _ = super.[]=(v1, v2) in v2 /// /// An index set expression used for effect is encoded as /// /// super.[]=(a, b) /// /// using [SuperMethodInvocation]. /// class SuperIndexSet extends InternalExpression { /// The []= member. Member setter; /// The index expression of the operation. Expression index; /// The value expression of the operation. Expression value; SuperIndexSet(this.setter, this.index, this.value) { index?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.SuperIndexSet; @override void visitChildren(Visitor<dynamic> v) { index?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing an extension index set expression. /// /// An extension index set expression of the form `Extension(o)[a] = b` used /// for value is encoded as the expression: /// /// let receiverVariable = o /// let indexVariable = a in /// let valueVariable = b in ' /// let writeVariable = /// receiverVariable.[]=(indexVariable, valueVariable) in /// valueVariable /// /// An extension index set expression used for effect is encoded as /// /// o.[]=(a, b) /// /// using [StaticInvocation]. /// class ExtensionIndexSet extends InternalExpression { final Extension extension; final List<DartType> explicitTypeArguments; /// The receiver of the extension access. Expression receiver; /// The []= member. Member setter; /// The index expression of the operation. Expression index; /// The value expression of the operation. Expression value; ExtensionIndexSet(this.extension, this.explicitTypeArguments, this.receiver, this.setter, this.index, this.value) : assert(explicitTypeArguments == null || explicitTypeArguments.length == extension.typeParameters.length) { receiver?.parent = this; index?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.ExtensionIndexSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); index?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing an if-null index assignment. /// /// An if-null index assignment of the form `o[a] ??= b` is, if used for value, /// encoded as the expression: /// /// let v1 = o in /// let v2 = a in /// let v3 = v1[v2] in /// v3 == null /// ? (let v4 = b in /// let _ = v1.[]=(v2, v4) in /// v4) /// : v3 /// /// and, if used for effect, encoded as the expression: /// /// let v1 = o in /// let v2 = a in /// let v3 = v1[v2] in /// v3 == null ? v1.[]=(v2, b) : null /// /// If the [readOnlyReceiver] is true, no temporary variable is created for the /// receiver and its use is inlined. class IfNullIndexSet extends InternalExpression { /// The receiver on which the index set operation is performed. Expression receiver; /// The index expression of the operation. Expression index; /// The value expression of the operation. Expression value; /// The file offset for the [] operation. final int readOffset; /// The file offset for the == operation. final int testOffset; /// The file offset for the []= operation. final int writeOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; /// If `true`, the receiver is read-only and therefore doesn't need a /// temporary variable for its value. final bool readOnlyReceiver; IfNullIndexSet(this.receiver, this.index, this.value, {this.readOffset, this.testOffset, this.writeOffset, this.forEffect, this.readOnlyReceiver: false}) : assert(readOffset != null), assert(testOffset != null), assert(writeOffset != null), assert(forEffect != null) { receiver?.parent = this; index?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.IfNullIndexSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); index?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing an if-null super index set expression. /// /// An if-null super index set expression of the form `super[a] ??= b` is, if /// used for value, encoded as the expression: /// /// let v1 = a in /// let v2 = super.[](v1) in /// v2 == null /// ? (let v3 = b in /// let _ = super.[]=(v1, v3) in /// v3) /// : v2 /// /// and, if used for effect, encoded as the expression: /// /// let v1 = a in /// let v2 = super.[](v1) in /// v2 == null ? super.[]=(v1, b) : null /// class IfNullSuperIndexSet extends InternalExpression { /// The [] member; Member getter; /// The []= member; Member setter; /// The index expression of the operation. Expression index; /// The value expression of the operation. Expression value; /// The file offset for the [] operation. final int readOffset; /// The file offset for the == operation. final int testOffset; /// The file offset for the []= operation. final int writeOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; IfNullSuperIndexSet(this.getter, this.setter, this.index, this.value, {this.readOffset, this.testOffset, this.writeOffset, this.forEffect}) : assert(readOffset != null), assert(testOffset != null), assert(writeOffset != null), assert(forEffect != null) { index?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.IfNullSuperIndexSet; @override void visitChildren(Visitor<dynamic> v) { index?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing an if-null super index set expression. /// /// An if-null super index set expression of the form `super[a] ??= b` is, if /// used for value, encoded as the expression: /// /// let v1 = a in /// let v2 = super.[](v1) in /// v2 == null /// ? (let v3 = b in /// let _ = super.[]=(v1, v3) in /// v3) /// : v2 /// /// and, if used for effect, encoded as the expression: /// /// let v1 = a in /// let v2 = super.[](v1) in /// v2 == null ? super.[]=(v1, b) : null /// class IfNullExtensionIndexSet extends InternalExpression { final Extension extension; final List<DartType> explicitTypeArguments; /// The extension receiver; Expression receiver; /// The [] member; Member getter; /// The []= member; Member setter; /// The index expression of the operation. Expression index; /// The value expression of the operation. Expression value; /// The file offset for the [] operation. final int readOffset; /// The file offset for the == operation. final int testOffset; /// The file offset for the []= operation. final int writeOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; IfNullExtensionIndexSet(this.extension, this.explicitTypeArguments, this.receiver, this.getter, this.setter, this.index, this.value, {this.readOffset, this.testOffset, this.writeOffset, this.forEffect}) : assert(explicitTypeArguments == null || explicitTypeArguments.length == extension.typeParameters.length), assert(readOffset != null), assert(testOffset != null), assert(writeOffset != null), assert(forEffect != null) { receiver?.parent = this; index?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.IfNullExtensionIndexSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); index?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing a compound index assignment. /// /// An if-null index assignment of the form `o[a] += b` is, if used for value, /// encoded as the expression: /// /// let v1 = o in /// let v2 = a in /// let v3 = v1.[](v2) + b /// let v4 = v1.[]=(v2, c3) in v3 /// /// and, if used for effect, encoded as the expression: /// /// let v1 = o in let v2 = a in v1.[]=(v2, v1.[](v2) + b) /// class CompoundIndexSet extends InternalExpression { /// The receiver on which the index set operation is performed. Expression receiver; /// The index expression of the operation. Expression index; /// The name of the binary operation. Name binaryName; /// The right-hand side of the binary expression. Expression rhs; /// The file offset for the [] operation. final int readOffset; /// The file offset for the []= operation. final int writeOffset; /// The file offset for the binary operation. final int binaryOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; /// If `true`, the expression is a post-fix inc/dec expression. final bool forPostIncDec; /// If `true`, the receiver is read-only and therefore doesn't need a /// temporary variable for its value. final bool readOnlyReceiver; CompoundIndexSet(this.receiver, this.index, this.binaryName, this.rhs, {this.readOffset, this.binaryOffset, this.writeOffset, this.forEffect, this.forPostIncDec, this.readOnlyReceiver: false}) : assert(forEffect != null) { receiver?.parent = this; index?.parent = this; rhs?.parent = this; fileOffset = binaryOffset; } @override InternalExpressionKind get kind => InternalExpressionKind.CompoundIndexSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); index?.accept(v); rhs?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (rhs != null) { rhs = rhs.accept<TreeNode>(v); rhs?.parent = this; } } } /// Internal expression representing a null-aware compound assignment. /// /// A null-aware compound assignment of the form /// /// receiver?.property binaryName= rhs /// /// is, if used for value as a normal compound or prefix operation, encoded as /// the expression: /// /// let receiverVariable = receiver in /// receiverVariable == null ? null : /// let leftVariable = receiverVariable.propertyName in /// let valueVariable = leftVariable binaryName rhs in /// let writeVariable = /// receiverVariable.propertyName = valueVariable in /// valueVariable /// /// and, if used for value as a postfix operation, encoded as /// /// let receiverVariable = receiver in /// receiverVariable == null ? null : /// let leftVariable = receiverVariable.propertyName in /// let writeVariable = /// receiverVariable.propertyName = /// leftVariable binaryName rhs in /// leftVariable /// /// and, if used for effect, encoded as: /// /// let receiverVariable = receiver in /// receiverVariable == null ? null : /// receiverVariable.propertyName = receiverVariable.propertyName + rhs /// class NullAwareCompoundSet extends InternalExpression { /// The receiver on which the null aware operation is performed. Expression receiver; /// The name of the null-aware property. Name propertyName; /// The name of the binary operation. Name binaryName; /// The right-hand side of the binary expression. Expression rhs; /// The file offset for the read operation. final int readOffset; /// The file offset for the write operation. final int writeOffset; /// The file offset for the binary operation. final int binaryOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; /// If `true`, the expression is a postfix inc/dec expression. final bool forPostIncDec; NullAwareCompoundSet( this.receiver, this.propertyName, this.binaryName, this.rhs, {this.readOffset, this.binaryOffset, this.writeOffset, this.forEffect, this.forPostIncDec}) : assert(readOffset != null), assert(binaryOffset != null), assert(writeOffset != null), assert(forEffect != null), assert(forPostIncDec != null) { receiver?.parent = this; rhs?.parent = this; fileOffset = binaryOffset; } @override InternalExpressionKind get kind => InternalExpressionKind.NullAwareCompoundSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); rhs?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (rhs != null) { rhs = rhs.accept<TreeNode>(v); rhs?.parent = this; } } } /// Internal expression representing an null-aware if-null property set. /// /// A null-aware if-null property set of the form /// /// receiver?.name ??= value /// /// is, if used for value, encoded as the expression: /// /// let receiverVariable = receiver in /// receiverVariable == null ? null : /// (let readVariable = receiverVariable.name in /// readVariable == null ? /// receiverVariable.name = value : readVariable) /// /// and, if used for effect, encoded as the expression: /// /// let receiverVariable = receiver in /// receiverVariable == null ? null : /// (receiverVariable.name == null ? /// receiverVariable.name = value : null) /// /// class NullAwareIfNullSet extends InternalExpression { /// The synthetic variable whose initializer hold the receiver. Expression receiver; /// The expression that reads the property from [variable]. Name name; /// The expression that writes the value to the property on [variable]. Expression value; /// The file offset for the read operation. final int readOffset; /// The file offset for the write operation. final int writeOffset; /// The file offset for the == operation. final int testOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; NullAwareIfNullSet(this.receiver, this.name, this.value, {this.readOffset, this.writeOffset, this.testOffset, this.forEffect}) : assert(readOffset != null), assert(writeOffset != null), assert(testOffset != null), assert(forEffect != null) { receiver?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.NullAwareIfNullSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing a compound super index assignment. /// /// An if-null index assignment of the form `super[a] += b` is, if used for /// value, encoded as the expression: /// /// let v1 = a in /// let v2 = super.[](v1) + b /// let v3 = super.[]=(v1, v2) in v2 /// /// and, if used for effect, encoded as the expression: /// /// let v1 = a in super.[]=(v2, super.[](v2) + b) /// class CompoundSuperIndexSet extends InternalExpression { /// The [] member. Member getter; /// The []= member. Member setter; /// The index expression of the operation. Expression index; /// The name of the binary operation. Name binaryName; /// The right-hand side of the binary expression. Expression rhs; /// The file offset for the [] operation. final int readOffset; /// The file offset for the []= operation. final int writeOffset; /// The file offset for the binary operation. final int binaryOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; /// If `true`, the expression is a post-fix inc/dec expression. final bool forPostIncDec; CompoundSuperIndexSet( this.getter, this.setter, this.index, this.binaryName, this.rhs, {this.readOffset, this.binaryOffset, this.writeOffset, this.forEffect, this.forPostIncDec}) : assert(forEffect != null) { index?.parent = this; rhs?.parent = this; fileOffset = binaryOffset; } @override InternalExpressionKind get kind => InternalExpressionKind.CompoundSuperIndexSet; @override void visitChildren(Visitor<dynamic> v) { index?.accept(v); rhs?.accept(v); } @override void transformChildren(Transformer v) { if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (rhs != null) { rhs = rhs.accept<TreeNode>(v); rhs?.parent = this; } } } /// Internal expression representing a compound extension index assignment. /// /// An compound extension index assignment of the form `Extension(o)[a] += b` /// is, if used for value, encoded as the expression: /// /// let receiverVariable = o; /// let indexVariable = a in /// let valueVariable = receiverVariable.[](indexVariable) + b /// let writeVariable = /// receiverVariable.[]=(indexVariable, valueVariable) in /// valueVariable /// /// and, if used for effect, encoded as the expression: /// /// let receiverVariable = o; /// let indexVariable = a in /// receiverVariable.[]=(indexVariable, /// receiverVariable.[](indexVariable) + b) /// class CompoundExtensionIndexSet extends InternalExpression { final Extension extension; final List<DartType> explicitTypeArguments; Expression receiver; /// The [] member. Member getter; /// The []= member. Member setter; /// The index expression of the operation. Expression index; /// The name of the binary operation. Name binaryName; /// The right-hand side of the binary expression. Expression rhs; /// The file offset for the [] operation. final int readOffset; /// The file offset for the []= operation. final int writeOffset; /// The file offset for the binary operation. final int binaryOffset; /// If `true`, the expression is only need for effect and not for its value. final bool forEffect; /// If `true`, the expression is a post-fix inc/dec expression. final bool forPostIncDec; CompoundExtensionIndexSet( this.extension, this.explicitTypeArguments, this.receiver, this.getter, this.setter, this.index, this.binaryName, this.rhs, {this.readOffset, this.binaryOffset, this.writeOffset, this.forEffect, this.forPostIncDec}) : assert(explicitTypeArguments == null || explicitTypeArguments.length == extension.typeParameters.length), assert(readOffset != null), assert(binaryOffset != null), assert(writeOffset != null), assert(forEffect != null), assert(forPostIncDec != null) { receiver?.parent = this; index?.parent = this; rhs?.parent = this; fileOffset = binaryOffset; } @override InternalExpressionKind get kind => InternalExpressionKind.CompoundExtensionIndexSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); index?.accept(v); rhs?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (index != null) { index = index.accept<TreeNode>(v); index?.parent = this; } if (rhs != null) { rhs = rhs.accept<TreeNode>(v); rhs?.parent = this; } } } /// Internal expression representing an assignment to an extension setter. /// /// An extension set of the form `receiver.target = value` is, if used for /// value, encoded as the expression: /// /// let receiverVariable = receiver in /// let valueVariable = value in /// let writeVariable = target(receiverVariable, valueVariable) in /// valueVariable /// /// or if the receiver is read-only, like `this` or a final variable, /// /// let valueVariable = value in /// let writeVariable = target(receiver, valueVariable) in /// valueVariable /// /// and, if used for effect, encoded as a [StaticInvocation]: /// /// target(receiver, value) /// // TODO(johnniwinther): Rename read-only to side-effect-free. class ExtensionSet extends InternalExpression { final Extension extension; final List<DartType> explicitTypeArguments; /// The receiver for the assignment. Expression receiver; /// The extension member called for the assignment. Member target; /// The right-hand side value of the assignment. Expression value; /// If `true` the assignment is only needed for effect and not its result /// value. final bool forEffect; /// If `true` the receiver can be cloned instead of creating a temporary /// variable. final bool readOnlyReceiver; ExtensionSet(this.extension, this.explicitTypeArguments, this.receiver, this.target, this.value, {this.readOnlyReceiver, this.forEffect}) : assert(explicitTypeArguments == null || explicitTypeArguments.length == extension.typeParameters.length), assert(readOnlyReceiver != null), assert(forEffect != null) { receiver?.parent = this; value?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.ExtensionSet; @override void visitChildren(Visitor<dynamic> v) { receiver?.accept(v); value?.accept(v); } @override void transformChildren(Transformer v) { if (receiver != null) { receiver = receiver.accept<TreeNode>(v); receiver?.parent = this; } if (value != null) { value = value.accept<TreeNode>(v); value?.parent = this; } } } /// Internal expression representing an null-aware extension expression. /// /// An null-aware extension expression of the form `Extension(receiver)?.target` /// is encoded as the expression: /// /// let variable = receiver in /// variable == null ? null : expression /// /// where `expression` is an encoding of `receiverVariable.target`. class NullAwareExtension extends InternalExpression { VariableDeclaration variable; Expression expression; NullAwareExtension(this.variable, this.expression) { variable?.parent = this; expression?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.NullAwareExtension; @override void visitChildren(Visitor<dynamic> v) { variable?.accept(v); expression?.accept(v); } @override void transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (expression != null) { expression = expression.accept<TreeNode>(v); expression?.parent = this; } } } /// Front end specific implementation of [PropertySet]. class PropertySetImpl extends PropertySet { /// If `true` the assignment is need for its effect and not for its value. final bool forEffect; /// If `true` the receiver can be cloned and doesn't need a temporary variable /// for multiple reads. final bool readOnlyReceiver; PropertySetImpl(Expression receiver, Name name, Expression value, {Member interfaceTarget, this.forEffect, this.readOnlyReceiver}) : assert(forEffect != null), super(receiver, name, value, interfaceTarget); } /// Internal representation of a read of an extension instance member. /// /// A read of an extension instance member `o.foo` is encoded as the /// [StaticInvocation] /// /// extension|foo(o) /// /// where `extension|foo` is the top level method created for reading the /// `foo` member. If `foo` is an extension instance method, then `extension|foo` /// the special tear-off function created for extension instance methods. /// Otherwise `extension|foo` is the top level method corresponding to the /// extension instance getter being read. class ExtensionTearOff extends InternalExpression { /// The top-level method that is that target for the read operation. Member target; /// The arguments provided to the top-level method. Arguments arguments; ExtensionTearOff(this.target, this.arguments) { arguments?.parent = this; } @override InternalExpressionKind get kind => InternalExpressionKind.ExtensionTearOff; @override void visitChildren(Visitor<dynamic> v) { arguments?.accept(v); } @override void transformChildren(Transformer v) { if (arguments != null) { arguments = arguments.accept<TreeNode>(v); arguments?.parent = this; } } } /// Creates a [Let] of [variable] with the given [body] using /// `variable.fileOffset` as the file offset for the let. /// /// This is useful for create let expressions in replacement code. Let createLet(VariableDeclaration variable, Expression body) { return new Let(variable, body)..fileOffset = variable.fileOffset; } /// Creates a [VariableDeclaration] for [expression] with the static [type] /// using `expression.fileOffset` as the file offset for the declaration. /// /// This is useful for creating let variables for expressions in replacement /// code. VariableDeclaration createVariable(Expression expression, DartType type) { return new VariableDeclaration.forValue(expression, type: type) ..fileOffset = expression.fileOffset; } /// Creates a [VariableGet] of [variable] using `variable.fileOffset` as the /// file offset for the expression. /// /// This is useful for referencing let variables for expressions in replacement /// code. VariableGet createVariableGet(VariableDeclaration variable) { return new VariableGet(variable)..fileOffset = variable.fileOffset; } /// Creates a `e == null` test for the expression [left] using the [fileOffset] /// as file offset for the created nodes and [equalsMember] as the interface /// target of the created method invocation. MethodInvocation createEqualsNull( int fileOffset, Expression left, Member equalsMember) { return new MethodInvocation( left, equalsName, new Arguments(<Expression>[new NullLiteral()..fileOffset = fileOffset]) ..fileOffset = fileOffset) ..fileOffset = fileOffset ..interfaceTarget = equalsMember; }
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/kernel/kernel_api.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. /// This library exports all API from Kernel that can be used throughout fasta. library fasta.kernel_api; export 'package:kernel/type_algebra.dart' show Substitution, substitute; export 'package:kernel/class_hierarchy.dart' show ClassHierarchy; export 'package:kernel/clone.dart' show CloneVisitor; export 'package:kernel/core_types.dart' show CoreTypes; export 'package:kernel/transformations/flags.dart' show TransformerFlag; export 'package:kernel/text/ast_to_text.dart' show NameSystem; export 'package:kernel/type_environment.dart' show TypeEnvironment; export 'package:kernel/src/bounds_checks.dart' show instantiateToBounds; import 'package:kernel/text/ast_to_text.dart' show NameSystem, Printer; import 'package:kernel/ast.dart' show Class, Member, Node; void printNodeOn(Node node, StringSink sink, {NameSystem syntheticNames}) { if (node == null) { sink.write("null"); } else { syntheticNames ??= new NameSystem(); new Printer(sink, syntheticNames: syntheticNames).writeNode(node); } } void printQualifiedNameOn(Member member, StringSink sink, {NameSystem syntheticNames}) { if (member == null) { sink.write("null"); } else { syntheticNames ??= new NameSystem(); sink.write(member.enclosingLibrary.importUri); sink.write("::"); Class cls = member.enclosingClass; if (cls != null) { sink.write(cls.name ?? syntheticNames.nameClass(cls)); sink.write("::"); } sink.write(member.name?.name ?? syntheticNames.nameMember(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/kernel/transform_set_literals.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 fasta.transform_set_literals; import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart' show Arguments, Expression, InterfaceType, Let, MethodInvocation, Name, Procedure, SetLiteral, StaticInvocation, TreeNode, VariableDeclaration, VariableGet; import 'package:kernel/core_types.dart' show CoreTypes; import 'package:kernel/visitor.dart' show Transformer; import '../source/source_loader.dart' show SourceLoader; import 'redirecting_factory_body.dart' show RedirectingFactoryBody; // TODO(askesc): Delete this class when all backends support set literals. class SetLiteralTransformer extends Transformer { final CoreTypes coreTypes; final Procedure setFactory; final Procedure addMethod; static Procedure _findSetFactory(CoreTypes coreTypes) { Procedure factory = coreTypes.index.getMember('dart:core', 'Set', ''); RedirectingFactoryBody body = factory?.function?.body; return body?.target; } static Procedure _findAddMethod(CoreTypes coreTypes) { return coreTypes.index.getMember('dart:core', 'Set', 'add'); } SetLiteralTransformer(SourceLoader loader) : coreTypes = loader.coreTypes, setFactory = _findSetFactory(loader.coreTypes), addMethod = _findAddMethod(loader.coreTypes); TreeNode visitSetLiteral(SetLiteral node) { if (node.isConst) return node; // Outermost declaration of let chain: Set<E> setVar = new Set<E>(); VariableDeclaration setVar = new VariableDeclaration.forValue( new StaticInvocation( setFactory, new Arguments([], types: [node.typeArgument])), type: new InterfaceType(coreTypes.setClass, [node.typeArgument])); // Innermost body of let chain: setVar Expression setExp = new VariableGet(setVar); for (int i = node.expressions.length - 1; i >= 0; i--) { // let _ = setVar.add(expression) in rest Expression entry = node.expressions[i].accept<TreeNode>(this); setExp = new Let( new VariableDeclaration.forValue(new MethodInvocation( new VariableGet(setVar), new Name("add"), new Arguments([entry]), addMethod)), setExp); } return new Let(setVar, setExp); } }
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/kernel/unlinked_scope.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../builder/declaration.dart'; import 'kernel_builder.dart' show Builder, Scope; /// Scope that returns an [UnlinkedDeclaration] if a name can't be resolved. /// This is intended to be used as the `enclosingScope` in `BodyBuilder` to /// create ASTs with building outlines. class UnlinkedScope extends Scope { UnlinkedScope() : super.top(isModifiable: false); Builder lookupIn(String name, int charOffset, Uri fileUri, Map<String, Builder> map, bool isInstanceScope) { return new UnlinkedDeclaration(name, isInstanceScope, charOffset, fileUri); } } class UnlinkedDeclaration extends BuilderImpl { final String name; final bool isInstanceScope; @override final int charOffset; @override final Uri fileUri; UnlinkedDeclaration( this.name, this.isInstanceScope, this.charOffset, this.fileUri); @override Builder get parent => null; @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/kernel/forest.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.fangorn; import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart'; import '../names.dart'; import '../problems.dart' show unsupported; import 'collections.dart' show ForElement, ForInElement, ForInMapEntry, ForMapEntry, IfElement, IfMapEntry, SpreadElement; import 'kernel_shadow_ast.dart'; /// A shadow tree factory. class Forest { const Forest(); Arguments createArguments(int fileOffset, List<Expression> positional, {List<DartType> types, List<NamedExpression> named}) { return new ArgumentsImpl(positional, types: types, named: named) ..fileOffset = fileOffset ?? TreeNode.noOffset; } Arguments createArgumentsForExtensionMethod( int fileOffset, int extensionTypeParameterCount, int typeParameterCount, Expression receiver, {List<DartType> extensionTypeArguments = const <DartType>[], List<DartType> typeArguments = const <DartType>[], List<Expression> positionalArguments = const <Expression>[], List<NamedExpression> namedArguments = const <NamedExpression>[]}) { assert(fileOffset != null); return new ArgumentsImpl.forExtensionMethod( extensionTypeParameterCount, typeParameterCount, receiver, extensionTypeArguments: extensionTypeArguments, typeArguments: typeArguments, positionalArguments: positionalArguments, namedArguments: namedArguments) ..fileOffset = fileOffset ?? TreeNode.noOffset; } Arguments createArgumentsEmpty(int fileOffset) { assert(fileOffset != null); return createArguments(fileOffset, <Expression>[]); } List<NamedExpression> argumentsNamed(Arguments arguments) { return arguments.named; } List<Expression> argumentsPositional(Arguments arguments) { return arguments.positional; } List<DartType> argumentsTypeArguments(Arguments arguments) { return arguments.types; } void argumentsSetTypeArguments(Arguments arguments, List<DartType> types) { ArgumentsImpl.setNonInferrableArgumentTypes(arguments, types); } /// Return a representation of a boolean literal at the given [fileOffset]. /// The literal has the given [value]. BoolLiteral createBoolLiteral(int fileOffset, bool value) { assert(fileOffset != null); return new BoolLiteral(value)..fileOffset = fileOffset; } /// Return a representation of a double literal at the given [fileOffset]. The /// literal has the given [value]. DoubleLiteral createDoubleLiteral(int fileOffset, double value) { assert(fileOffset != null); return new DoubleLiteral(value)..fileOffset = fileOffset; } /// Return a representation of an integer literal at the given [fileOffset]. /// The literal has the given [value]. IntLiteral createIntLiteral(int fileOffset, int value, [String literal]) { assert(fileOffset != null); return new IntJudgment(value, literal)..fileOffset = fileOffset; } IntLiteral createIntLiteralLarge(int fileOffset, String literal) { assert(fileOffset != null); return new ShadowLargeIntLiteral(literal, fileOffset); } /// Return a representation of a list literal at the given [fileOffset]. The /// [isConst] is `true` if the literal is either explicitly or implicitly a /// constant. The [typeArgument] is the representation of the single valid /// type argument preceding the list literal, or `null` if there is no type /// argument, there is more than one type argument, or if the type argument /// cannot be resolved. The list of [expressions] is a list of the /// representations of the list elements. ListLiteral createListLiteral( int fileOffset, DartType typeArgument, List<Expression> expressions, {bool isConst}) { assert(fileOffset != null); assert(isConst != null); return new ListLiteral(expressions, typeArgument: typeArgument, isConst: isConst) ..fileOffset = fileOffset; } /// Return a representation of a set literal at the given [fileOffset]. The /// [isConst] is `true` if the literal is either explicitly or implicitly a /// constant. The [typeArgument] is the representation of the single valid /// type argument preceding the set literal, or `null` if there is no type /// argument, there is more than one type argument, or if the type argument /// cannot be resolved. The list of [expressions] is a list of the /// representations of the set elements. SetLiteral createSetLiteral( int fileOffset, DartType typeArgument, List<Expression> expressions, {bool isConst}) { assert(fileOffset != null); assert(isConst != null); return new SetLiteral(expressions, typeArgument: typeArgument, isConst: isConst) ..fileOffset = fileOffset; } /// Return a representation of a map literal at the given [fileOffset]. The /// [isConst] is `true` if the literal is either explicitly or implicitly a /// constant. The [keyType] is the representation of the first type argument /// preceding the map literal, or `null` if there are not exactly two type /// arguments or if the first type argument cannot be resolved. The /// [valueType] is the representation of the second type argument preceding /// the map literal, or `null` if there are not exactly two type arguments or /// if the second type argument cannot be resolved. The list of [entries] is a /// list of the representations of the map entries. MapLiteral createMapLiteral(int fileOffset, DartType keyType, DartType valueType, List<MapEntry> entries, {bool isConst}) { assert(fileOffset != null); assert(isConst != null); return new MapLiteral(entries, keyType: keyType, valueType: valueType, isConst: isConst) ..fileOffset = fileOffset; } /// Return a representation of a null literal at the given [fileOffset]. NullLiteral createNullLiteral(int fileOffset) { assert(fileOffset != null); return new NullLiteral()..fileOffset = fileOffset; } /// Return a representation of a simple string literal at the given /// [fileOffset]. The literal has the given [value]. This does not include /// either adjacent strings or interpolated strings. StringLiteral createStringLiteral(int fileOffset, String value) { assert(fileOffset != null); return new StringLiteral(value)..fileOffset = fileOffset; } /// Return a representation of a symbol literal defined by [value] at the /// given [fileOffset]. SymbolLiteral createSymbolLiteral(int fileOffset, String value) { assert(fileOffset != null); return new SymbolLiteral(value)..fileOffset = fileOffset; } TypeLiteral createTypeLiteral(int fileOffset, DartType type) { assert(fileOffset != null); return new TypeLiteral(type)..fileOffset = fileOffset; } /// Return a representation of a key/value pair in a literal map at the given /// [fileOffset]. The [key] is the representation of the expression used to /// compute the key. The [value] is the representation of the expression used /// to compute the value. MapEntry createMapEntry(int fileOffset, Expression key, Expression value) { assert(fileOffset != null); return new MapEntry(key, value)..fileOffset = fileOffset; } Expression createLoadLibrary( int fileOffset, LibraryDependency dependency, Arguments arguments) { assert(fileOffset != null); return new LoadLibraryImpl(dependency, arguments)..fileOffset = fileOffset; } Expression checkLibraryIsLoaded( int fileOffset, LibraryDependency dependency) { assert(fileOffset != null); return new CheckLibraryIsLoaded(dependency)..fileOffset = fileOffset; } Expression createAsExpression( int fileOffset, Expression expression, DartType type) { assert(fileOffset != null); return new AsExpression(expression, type)..fileOffset = fileOffset; } Expression createSpreadElement(int fileOffset, Expression expression, {bool isNullAware}) { assert(fileOffset != null); assert(isNullAware != null); return new SpreadElement(expression, isNullAware)..fileOffset = fileOffset; } Expression createIfElement( int fileOffset, Expression condition, Expression then, [Expression otherwise]) { assert(fileOffset != null); return new IfElement(condition, then, otherwise)..fileOffset = fileOffset; } MapEntry createIfMapEntry(int fileOffset, Expression condition, MapEntry then, [MapEntry otherwise]) { assert(fileOffset != null); return new IfMapEntry(condition, then, otherwise)..fileOffset = fileOffset; } Expression createForElement( int fileOffset, List<VariableDeclaration> variables, Expression condition, List<Expression> updates, Expression body) { assert(fileOffset != null); return new ForElement(variables, condition, updates, body) ..fileOffset = fileOffset; } MapEntry createForMapEntry( int fileOffset, List<VariableDeclaration> variables, Expression condition, List<Expression> updates, MapEntry body) { assert(fileOffset != null); return new ForMapEntry(variables, condition, updates, body) ..fileOffset = fileOffset; } Expression createForInElement( int fileOffset, VariableDeclaration variable, Expression iterable, Statement prologue, Expression body, Expression problem, {bool isAsync: false}) { assert(fileOffset != null); return new ForInElement(variable, iterable, prologue, body, problem, isAsync: isAsync) ..fileOffset = fileOffset; } MapEntry createForInMapEntry( int fileOffset, VariableDeclaration variable, Expression iterable, Statement prologue, MapEntry body, Expression problem, {bool isAsync: false}) { assert(fileOffset != null); return new ForInMapEntry(variable, iterable, prologue, body, problem, isAsync: isAsync) ..fileOffset = fileOffset; } /// Return a representation of an assert that appears in a constructor's /// initializer list. AssertInitializer createAssertInitializer( int fileOffset, AssertStatement assertStatement) { assert(fileOffset != null); return new AssertInitializer(assertStatement)..fileOffset = fileOffset; } /// Return a representation of an assert that appears as a statement. Statement createAssertStatement(int fileOffset, Expression condition, Expression message, int conditionStartOffset, int conditionEndOffset) { assert(fileOffset != null); return new AssertStatement(condition, conditionStartOffset: conditionStartOffset, conditionEndOffset: conditionEndOffset, message: message) ..fileOffset = fileOffset; } Expression createAwaitExpression(int fileOffset, Expression operand) { assert(fileOffset != null); return new AwaitExpression(operand)..fileOffset = fileOffset; } /// Return a representation of a block of [statements] at the given /// [fileOffset]. Statement createBlock(int fileOffset, List<Statement> statements) { assert(fileOffset != null); List<Statement> copy; for (int i = 0; i < statements.length; i++) { Statement statement = statements[i]; if (statement is _VariablesDeclaration) { copy ??= new List<Statement>.from(statements.getRange(0, i)); copy.addAll(statement.declarations); } else if (copy != null) { copy.add(statement); } } return new Block(copy ?? statements)..fileOffset = fileOffset; } /// Return a representation of a break statement. Statement createBreakStatement(int fileOffset, Object label) { assert(fileOffset != null); // TODO(johnniwinther): Use [label]? return new BreakStatement(null)..fileOffset = fileOffset; } /// Return a representation of a catch clause. Catch createCatch( int fileOffset, DartType exceptionType, VariableDeclaration exceptionParameter, VariableDeclaration stackTraceParameter, DartType stackTraceType, Statement body) { assert(fileOffset != null); return new Catch(exceptionParameter, body, guard: exceptionType, stackTrace: stackTraceParameter) ..fileOffset = fileOffset; } /// Return a representation of a conditional expression at the given /// [fileOffset]. The [condition] is the expression preceding the question /// mark. The [thenExpression] is the expression following the question mark. /// The [elseExpression] is the expression following the colon. Expression createConditionalExpression(int fileOffset, Expression condition, Expression thenExpression, Expression elseExpression) { return new ConditionalExpression( condition, thenExpression, elseExpression, null) ..fileOffset = fileOffset; } /// Return a representation of a continue statement. Statement createContinueStatement(int fileOffset, Object label) { assert(fileOffset != null); // TODO(johnniwinther): Use [label]? return new BreakStatement(null)..fileOffset = fileOffset; } /// Return a representation of a do statement. Statement createDoStatement( int fileOffset, Statement body, Expression condition) { assert(fileOffset != null); return new DoStatement(body, condition)..fileOffset = fileOffset; } /// Return a representation of an expression statement at the given /// [fileOffset] containing the [expression]. Statement createExpressionStatement(int fileOffset, Expression expression) { assert(fileOffset != null); return new ExpressionStatement(expression)..fileOffset = fileOffset; } /// Return a representation of an empty statement at the given [fileOffset]. Statement createEmptyStatement(int fileOffset) { assert(fileOffset != null); return new EmptyStatement()..fileOffset = fileOffset; } /// Return a representation of a for statement. Statement createForStatement( int fileOffset, List<VariableDeclaration> variables, Expression condition, Statement conditionStatement, List<Expression> updaters, Statement body) { assert(fileOffset != null); return new ForStatement(variables ?? [], condition, updaters, body) ..fileOffset = fileOffset; } /// Return a representation of an `if` statement. Statement createIfStatement(int fileOffset, Expression condition, Statement thenStatement, Statement elseStatement) { assert(fileOffset != null); return new IfStatement(condition, thenStatement, elseStatement) ..fileOffset = fileOffset; } /// Return a representation of an `is` expression at the given [fileOffset]. /// The [operand] is the representation of the left operand. The [type] is a /// representation of the type that is the right operand. If [notFileOffset] /// is non-null the test is negated the that file offset. Expression createIsExpression( int fileOffset, Expression operand, DartType type, {int notFileOffset}) { assert(fileOffset != null); Expression result = new IsExpression(operand, type) ..fileOffset = fileOffset; if (notFileOffset != null) { result = createNot(notFileOffset, result); } return result; } /// Return a representation of a logical expression at the given [fileOffset] /// having the [leftOperand], [rightOperand] and the [operator] /// (either `&&` or `||`). Expression createLogicalExpression(int fileOffset, Expression leftOperand, String operator, Expression rightOperand) { assert(fileOffset != null); assert(operator == '&&' || operator == '||'); return new LogicalExpression(leftOperand, operator, rightOperand) ..fileOffset = fileOffset; } Expression createNot(int fileOffset, Expression operand) { assert(fileOffset != null); return new Not(operand)..fileOffset = fileOffset; } /// Return a representation of a rethrow statement consisting of the /// rethrow at [rethrowFileOffset] and the statement at [statementFileOffset]. Statement createRethrowStatement( int rethrowFileOffset, int statementFileOffset) { assert(rethrowFileOffset != null); assert(statementFileOffset != null); return new ExpressionStatement( new Rethrow()..fileOffset = rethrowFileOffset) ..fileOffset = statementFileOffset; } /// Return a representation of a return statement. Statement createReturnStatement(int fileOffset, Expression expression, {bool isArrow: true}) { assert(fileOffset != null); return new ReturnStatementImpl(isArrow, expression) ..fileOffset = fileOffset ?? TreeNode.noOffset; } Expression createStringConcatenation( int fileOffset, List<Expression> expressions) { assert(fileOffset != null); return new StringConcatenation(expressions)..fileOffset = fileOffset; } /// The given [statement] is being used as the target of either a break or /// continue statement. Return the statement that should be used as the actual /// target. Statement createLabeledStatement(Statement statement) { return new LabeledStatement(statement)..fileOffset = statement.fileOffset; } Expression createThisExpression(int fileOffset) { assert(fileOffset != null); return new ThisExpression()..fileOffset = fileOffset; } /// Return a representation of a throw expression at the given [fileOffset]. Expression createThrow(int fileOffset, Expression expression) { assert(fileOffset != null); return new Throw(expression)..fileOffset = fileOffset; } bool isThrow(Object o) => o is Throw; /// Return a representation of a try statement at the given [fileOffset]. /// The statement is introduced by the given [body]. If catch clauses were /// included, then the [catchClauses] will represent them, otherwise it will /// be `null`. Similarly, if a finally block was included, then the /// [finallyBlock] will be non-`null`, otherwise both will be `null`. Statement createTryStatement(int fileOffset, Statement body, List<Catch> catchClauses, Statement finallyBlock) { assert(fileOffset != null); Statement result = body; if (catchClauses != null) { result = new TryCatch(result, catchClauses)..fileOffset = fileOffset; } if (finallyBlock != null) { result = new TryFinally(result, finallyBlock)..fileOffset = fileOffset; } return result; } _VariablesDeclaration variablesDeclaration( List<VariableDeclaration> declarations, Uri uri) { return new _VariablesDeclaration(declarations, uri); } List<VariableDeclaration> variablesDeclarationExtractDeclarations( _VariablesDeclaration variablesDeclaration) { return variablesDeclaration.declarations; } Statement wrapVariables(Statement statement) { if (statement is _VariablesDeclaration) { return new Block( new List<Statement>.from(statement.declarations, growable: true)) ..fileOffset = statement.fileOffset; } else if (statement is VariableDeclaration) { return new Block(<Statement>[statement]) ..fileOffset = statement.fileOffset; } else { return statement; } } /// Return a representation of a while statement at the given [fileOffset] /// consisting of the given [condition] and [body]. Statement createWhileStatement( int fileOffset, Expression condition, Statement body) { assert(fileOffset != null); return new WhileStatement(condition, body)..fileOffset = fileOffset; } /// Return a representation of a yield statement at the given [fileOffset] /// of the given [expression]. If [isYieldStar] is `true` the created /// statement is a yield* statement. Statement createYieldStatement(int fileOffset, Expression expression, {bool isYieldStar}) { assert(fileOffset != null); assert(isYieldStar != null); return new YieldStatement(expression, isYieldStar: isYieldStar) ..fileOffset = fileOffset; } bool isBlock(Object node) => node is Block; bool isErroneousNode(Object node) { if (node is ExpressionStatement) { ExpressionStatement statement = node; node = statement.expression; } if (node is VariableDeclaration) { VariableDeclaration variable = node; node = variable.initializer; } if (node is Let) { Let let = node; node = let.variable.initializer; } return node is InvalidExpression; } bool isThisExpression(Object node) => node is ThisExpression; bool isVariablesDeclaration(Object node) => node is _VariablesDeclaration; /// Creates [VariableDeclaration] for a variable named [name] at the given /// [functionNestingLevel]. VariableDeclaration createVariableDeclaration( int fileOffset, String name, int functionNestingLevel, {Expression initializer, DartType type, bool isFinal: false, bool isConst: false, bool isFieldFormal: false, bool isCovariant: false, bool isLocalFunction: false}) { assert(fileOffset != null); return new VariableDeclarationImpl(name, functionNestingLevel, type: type, initializer: initializer, isFinal: isFinal, isConst: isConst, isFieldFormal: isFieldFormal, isCovariant: isCovariant, isLocalFunction: isLocalFunction); } VariableDeclaration createVariableDeclarationForValue(Expression initializer, {DartType type = const DynamicType()}) { return new VariableDeclarationImpl.forValue(initializer) ..type = type ..fileOffset = initializer.fileOffset; } Let createLet(VariableDeclaration variable, Expression body) { return new Let(variable, body); } FunctionNode createFunctionNode(int fileOffset, Statement body, {List<TypeParameter> typeParameters, List<VariableDeclaration> positionalParameters, List<VariableDeclaration> namedParameters, int requiredParameterCount, DartType returnType: const DynamicType(), AsyncMarker asyncMarker: AsyncMarker.Sync, AsyncMarker dartAsyncMarker}) { assert(fileOffset != null); return new FunctionNode(body, typeParameters: typeParameters, positionalParameters: positionalParameters, namedParameters: namedParameters, requiredParameterCount: requiredParameterCount, returnType: returnType, asyncMarker: asyncMarker, dartAsyncMarker: dartAsyncMarker); } TypeParameter createTypeParameter(String name) { return new TypeParameter(name); } TypeParameterType createTypeParameterType(TypeParameter typeParameter) { return new TypeParameterType(typeParameter); } FunctionExpression createFunctionExpression( int fileOffset, FunctionNode function) { assert(fileOffset != null); return new FunctionExpression(function)..fileOffset = fileOffset; } MethodInvocation createFunctionInvocation( int fileOffset, Expression expression, Arguments arguments) { assert(fileOffset != null); return new MethodInvocationImpl(expression, callName, arguments) ..fileOffset = fileOffset; } MethodInvocation createMethodInvocation( int fileOffset, Expression expression, Name name, Arguments arguments, {bool isImplicitCall: false, Member interfaceTarget}) { assert(fileOffset != null); return new MethodInvocationImpl(expression, name, arguments, isImplicitCall: isImplicitCall) ..fileOffset = fileOffset ..interfaceTarget = interfaceTarget; } NamedExpression createNamedExpression( int fileOffset, String name, Expression expression) { assert(fileOffset != null); return new NamedExpression(name, expression)..fileOffset = fileOffset; } StaticInvocation createStaticInvocation( int fileOffset, Procedure procedure, Arguments arguments) { assert(fileOffset != null); return new StaticInvocation(procedure, arguments)..fileOffset = fileOffset; } SuperMethodInvocation createSuperMethodInvocation( int fileOffset, Name name, Procedure procedure, Arguments arguments) { assert(fileOffset != null); return new SuperMethodInvocation(name, arguments, procedure) ..fileOffset = fileOffset; } NullCheck createNullCheck(int fileOffset, Expression expression) { assert(fileOffset != null); return new NullCheck(expression)..fileOffset = fileOffset; } PropertySet createPropertySet( int fileOffset, Expression receiver, Name name, Expression value, {Member interfaceTarget, bool forEffect, bool readOnlyReceiver: false}) { assert(fileOffset != null); return new PropertySetImpl(receiver, name, value, interfaceTarget: interfaceTarget, forEffect: forEffect, readOnlyReceiver: readOnlyReceiver) ..fileOffset = fileOffset; } } class _VariablesDeclaration extends Statement { final List<VariableDeclaration> declarations; final Uri uri; _VariablesDeclaration(this.declarations, this.uri) { setParents(declarations, this); } R accept<R>(v) { throw unsupported("accept", fileOffset, uri); } R accept1<R, A>(v, arg) { throw unsupported("accept1", fileOffset, uri); } visitChildren(v) { throw unsupported("visitChildren", fileOffset, uri); } transformChildren(v) { throw unsupported("transformChildren", fileOffset, uri); } }
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/kernel/collections.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 fasta.collections; import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart' show DartType, Expression, MapEntry, NullLiteral, Statement, TreeNode, VariableDeclaration, setParents, transformList, visitList; import 'package:kernel/type_environment.dart' show TypeEnvironment; import 'package:kernel/visitor.dart' show ExpressionVisitor, ExpressionVisitor1, Transformer, TreeVisitor, Visitor; import '../messages.dart' show templateExpectedAfterButGot, templateExpectedButGot; import '../problems.dart' show getFileUri, unsupported; import '../type_inference/inference_helper.dart' show InferenceHelper; /// Mixin for spread and control-flow elements. /// /// Spread and control-flow elements are not truly expressions and they cannot /// appear in arbitrary expression contexts in the Kernel program. They can /// only appear as elements in list or set literals. They are translated into /// a lower-level representation and never serialized to .dill files. mixin ControlFlowElement on Expression { /// Spread and control-flow elements are not expressions and do not have a /// static type. @override DartType getStaticType(TypeEnvironment types) { return unsupported("getStaticType", fileOffset, getFileUri(this)); } @override R accept<R>(ExpressionVisitor<R> v) => v.defaultExpression(this); @override R accept1<R, A>(ExpressionVisitor1<R, A> v, A arg) => v.defaultExpression(this, arg); } /// A spread element in a list or set literal. class SpreadElement extends Expression with ControlFlowElement { Expression expression; bool isNullAware; /// The type of the elements of the collection that [expression] evaluates to. /// /// It is set during type inference and is used to add appropriate type casts /// during the desugaring. DartType elementType; SpreadElement(this.expression, this.isNullAware) { expression?.parent = this; } @override visitChildren(Visitor<Object> v) { expression?.accept(v); } @override transformChildren(Transformer v) { if (expression != null) { expression = expression.accept<TreeNode>(v); expression?.parent = this; } } } /// An 'if' element in a list or set literal. class IfElement extends Expression with ControlFlowElement { Expression condition; Expression then; Expression otherwise; IfElement(this.condition, this.then, this.otherwise) { condition?.parent = this; then?.parent = this; otherwise?.parent = this; } @override visitChildren(Visitor<Object> v) { condition?.accept(v); then?.accept(v); otherwise?.accept(v); } @override transformChildren(Transformer v) { if (condition != null) { condition = condition.accept<TreeNode>(v); condition?.parent = this; } if (then != null) { then = then.accept<TreeNode>(v); then?.parent = this; } if (otherwise != null) { otherwise = otherwise.accept<TreeNode>(v); otherwise?.parent = this; } } } /// A 'for' element in a list or set literal. class ForElement extends Expression with ControlFlowElement { final List<VariableDeclaration> variables; // May be empty, but not null. Expression condition; // May be null. final List<Expression> updates; // May be empty, but not null. Expression body; ForElement(this.variables, this.condition, this.updates, this.body) { setParents(variables, this); condition?.parent = this; setParents(updates, this); body?.parent = this; } @override visitChildren(Visitor<Object> v) { visitList(variables, v); condition?.accept(v); visitList(updates, v); body?.accept(v); } @override transformChildren(Transformer v) { transformList(variables, v, this); if (condition != null) { condition = condition.accept<TreeNode>(v); condition?.parent = this; } transformList(updates, v, this); if (body != null) { body = body.accept<TreeNode>(v); body?.parent = this; } } } /// A 'for-in' element in a list or set literal. class ForInElement extends Expression with ControlFlowElement { VariableDeclaration variable; // Has no initializer. Expression iterable; Statement prologue; // May be null. Expression body; Expression problem; // May be null. bool isAsync; // True if this is an 'await for' loop. ForInElement( this.variable, this.iterable, this.prologue, this.body, this.problem, {this.isAsync: false}) { variable?.parent = this; iterable?.parent = this; prologue?.parent = this; body?.parent = this; problem?.parent = this; } visitChildren(Visitor<Object> v) { variable?.accept(v); iterable?.accept(v); prologue?.accept(v); body?.accept(v); problem?.accept(v); } transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (iterable != null) { iterable = iterable.accept<TreeNode>(v); iterable?.parent = this; } if (prologue != null) { prologue = prologue.accept<TreeNode>(v); prologue?.parent = this; } if (body != null) { body = body.accept<TreeNode>(v); body?.parent = this; } if (problem != null) { problem = problem.accept<TreeNode>(v); problem?.parent = this; } } } mixin ControlFlowMapEntry implements MapEntry { @override Expression get key { throw new UnsupportedError('ControlFlowMapEntry.key getter'); } @override void set key(Expression expr) { throw new UnsupportedError('ControlFlowMapEntry.key setter'); } @override Expression get value { throw new UnsupportedError('ControlFlowMapEntry.value getter'); } @override void set value(Expression expr) { throw new UnsupportedError('ControlFlowMapEntry.value setter'); } @override R accept<R>(TreeVisitor<R> v) => v.defaultTreeNode(this); } /// A spread element in a map literal. class SpreadMapEntry extends TreeNode with ControlFlowMapEntry { Expression expression; bool isNullAware; /// The type of the map entries of the map that [expression] evaluates to. /// /// It is set during type inference and is used to add appropriate type casts /// during the desugaring. DartType entryType; SpreadMapEntry(this.expression, this.isNullAware) { expression?.parent = this; } @override visitChildren(Visitor<Object> v) { expression?.accept(v); } @override transformChildren(Transformer v) { if (expression != null) { expression = expression.accept<TreeNode>(v); expression?.parent = this; } } } /// An 'if' element in a map literal. class IfMapEntry extends TreeNode with ControlFlowMapEntry { Expression condition; MapEntry then; MapEntry otherwise; IfMapEntry(this.condition, this.then, this.otherwise) { condition?.parent = this; then?.parent = this; otherwise?.parent = this; } @override visitChildren(Visitor<Object> v) { condition?.accept(v); then?.accept(v); otherwise?.accept(v); } @override transformChildren(Transformer v) { if (condition != null) { condition = condition.accept<TreeNode>(v); condition?.parent = this; } if (then != null) { then = then.accept<TreeNode>(v); then?.parent = this; } if (otherwise != null) { otherwise = otherwise.accept<TreeNode>(v); otherwise?.parent = this; } } } /// A 'for' element in a map literal. class ForMapEntry extends TreeNode with ControlFlowMapEntry { final List<VariableDeclaration> variables; // May be empty, but not null. Expression condition; // May be null. final List<Expression> updates; // May be empty, but not null. MapEntry body; ForMapEntry(this.variables, this.condition, this.updates, this.body) { setParents(variables, this); condition?.parent = this; setParents(updates, this); body?.parent = this; } @override visitChildren(Visitor<Object> v) { visitList(variables, v); condition?.accept(v); visitList(updates, v); body?.accept(v); } @override transformChildren(Transformer v) { transformList(variables, v, this); if (condition != null) { condition = condition.accept<TreeNode>(v); condition?.parent = this; } transformList(updates, v, this); if (body != null) { body = body.accept<TreeNode>(v); body?.parent = this; } } } /// A 'for-in' element in a map literal. class ForInMapEntry extends TreeNode with ControlFlowMapEntry { VariableDeclaration variable; // Has no initializer. Expression iterable; Statement prologue; // May be null. MapEntry body; Expression problem; // May be null. bool isAsync; // True if this is an 'await for' loop. ForInMapEntry( this.variable, this.iterable, this.prologue, this.body, this.problem, {this.isAsync: false}) { variable?.parent = this; iterable?.parent = this; prologue?.parent = this; body?.parent = this; problem?.parent = this; } visitChildren(Visitor<Object> v) { variable?.accept(v); iterable?.accept(v); prologue?.accept(v); body?.accept(v); problem?.accept(v); } transformChildren(Transformer v) { if (variable != null) { variable = variable.accept<TreeNode>(v); variable?.parent = this; } if (iterable != null) { iterable = iterable.accept<TreeNode>(v); iterable?.parent = this; } if (prologue != null) { prologue = prologue.accept<TreeNode>(v); prologue?.parent = this; } if (body != null) { body = body.accept<TreeNode>(v); body?.parent = this; } if (problem != null) { problem = problem.accept<TreeNode>(v); problem?.parent = this; } } } Expression convertToElement(MapEntry entry, InferenceHelper helper) { if (entry is SpreadMapEntry) { return new SpreadElement(entry.expression, entry.isNullAware) ..fileOffset = entry.expression.fileOffset; } if (entry is IfMapEntry) { return new IfElement( entry.condition, convertToElement(entry.then, helper), entry.otherwise == null ? null : convertToElement(entry.otherwise, helper)) ..fileOffset = entry.fileOffset; } if (entry is ForMapEntry) { return new ForElement(entry.variables, entry.condition, entry.updates, convertToElement(entry.body, helper)) ..fileOffset = entry.fileOffset; } if (entry is ForInMapEntry) { return new ForInElement(entry.variable, entry.iterable, entry.prologue, convertToElement(entry.body, helper), entry.problem, isAsync: entry.isAsync) ..fileOffset = entry.fileOffset; } return helper.buildProblem( templateExpectedButGot.withArguments(','), entry.fileOffset, 1, ); } bool isConvertibleToMapEntry(Expression element) { if (element is SpreadElement) return true; if (element is IfElement) { return isConvertibleToMapEntry(element.then) && (element.otherwise == null || isConvertibleToMapEntry(element.otherwise)); } if (element is ForElement) { return isConvertibleToMapEntry(element.body); } if (element is ForInElement) { return isConvertibleToMapEntry(element.body); } return false; } MapEntry convertToMapEntry(Expression element, InferenceHelper helper) { if (element is SpreadElement) { return new SpreadMapEntry(element.expression, element.isNullAware) ..fileOffset = element.expression.fileOffset; } if (element is IfElement) { return new IfMapEntry( element.condition, convertToMapEntry(element.then, helper), element.otherwise == null ? null : convertToMapEntry(element.otherwise, helper)) ..fileOffset = element.fileOffset; } if (element is ForElement) { return new ForMapEntry(element.variables, element.condition, element.updates, convertToMapEntry(element.body, helper)) ..fileOffset = element.fileOffset; } if (element is ForInElement) { return new ForInMapEntry( element.variable, element.iterable, element.prologue, convertToMapEntry(element.body, helper), element.problem, isAsync: element.isAsync) ..fileOffset = element.fileOffset; } return new MapEntry( helper.buildProblem( templateExpectedAfterButGot.withArguments(':'), element.fileOffset, // TODO(danrubel): what is the length of the expression? 1, ), new NullLiteral()); }
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/kernel/kernel_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.kernel_target; import 'dart:async' show Future; import 'package:kernel/ast.dart' show Arguments, CanonicalName, Class, Component, Constructor, DartType, EmptyStatement, Expression, Field, FieldInitializer, FunctionNode, Initializer, InterfaceType, InvalidInitializer, Library, Name, NamedExpression, NullLiteral, Procedure, RedirectingInitializer, Source, SuperInitializer, TypeParameter, TypeParameterType, VariableDeclaration, VariableGet; import 'package:kernel/clone.dart' show CloneVisitor; import 'package:kernel/type_algebra.dart' show substitute; import 'package:kernel/target/targets.dart' show DiagnosticReporter; import 'package:kernel/type_environment.dart' show TypeEnvironment; import '../../api_prototype/file_system.dart' show FileSystem; import '../compiler_context.dart' show CompilerContext; import '../crash.dart' show withCrashReporting; import '../dill/dill_target.dart' show DillTarget; import '../dill/dill_member_builder.dart' show DillMemberBuilder; import '../fasta_codes.dart' show Message, LocatedMessage; import '../loader.dart' show Loader; import '../messages.dart' show FormattedMessage, messageConstConstructorNonFinalField, messageConstConstructorNonFinalFieldCause, messageConstConstructorRedirectionToNonConst, noLength, templateFinalFieldNotInitialized, templateFinalFieldNotInitializedByConstructor, templateInferredPackageUri, templateMissingImplementationCause, templateSuperclassHasNoDefaultConstructor; import '../problems.dart' show unhandled; import '../scope.dart' show AmbiguousBuilder; import '../source/source_class_builder.dart' show SourceClassBuilder; import '../source/source_library_builder.dart' show SourceLibraryBuilder; import '../source/source_loader.dart' show SourceLoader; import '../target_implementation.dart' show TargetImplementation; import '../uri_translator.dart' show UriTranslator; import 'constant_evaluator.dart' as constants show transformLibraries; import 'kernel_builder.dart' show ClassBuilder, Builder, InvalidTypeBuilder, FieldBuilder, NamedTypeBuilder, ProcedureBuilder, LibraryBuilder, NullabilityBuilder, TypeBuilder, TypeDeclarationBuilder; import 'kernel_constants.dart' show KernelConstantErrorReporter; import 'metadata_collector.dart' show MetadataCollector; import 'verifier.dart' show verifyComponent; class KernelTarget extends TargetImplementation { /// The [FileSystem] which should be used to access files. final FileSystem fileSystem; /// Whether comments should be scanned and parsed. final bool includeComments; final DillTarget dillTarget; /// The [MetadataCollector] to write metadata to. final MetadataCollector metadataCollector; SourceLoader loader; Component component; // 'dynamic' is always nullable. final TypeBuilder dynamicType = new NamedTypeBuilder( "dynamic", const NullabilityBuilder.nullable(), null); final NamedTypeBuilder objectType = new NamedTypeBuilder("Object", const NullabilityBuilder.omitted(), null); // Null is always nullable. final TypeBuilder bottomType = new NamedTypeBuilder("Null", const NullabilityBuilder.nullable(), null); final bool excludeSource = !CompilerContext.current.options.embedSourceText; final Map<String, String> environmentDefines = CompilerContext.current.options.environmentDefines; final bool errorOnUnevaluatedConstant = CompilerContext.current.options.errorOnUnevaluatedConstant; final List<Object> clonedFormals = <Object>[]; KernelTarget(this.fileSystem, this.includeComments, DillTarget dillTarget, UriTranslator uriTranslator, {MetadataCollector metadataCollector}) : dillTarget = dillTarget, metadataCollector = metadataCollector, super(dillTarget.ticker, uriTranslator, dillTarget.backendTarget) { loader = createLoader(); } SourceLoader createLoader() => new SourceLoader(fileSystem, includeComments, this); void addSourceInformation( Uri importUri, Uri fileUri, List<int> lineStarts, List<int> sourceCode) { uriToSource[fileUri] = new Source(lineStarts, sourceCode, importUri, fileUri); } /// Return list of same size as input with possibly translated uris. List<Uri> setEntryPoints(List<Uri> entryPoints) { Map<String, Uri> packagesMap; List<Uri> result = new List<Uri>(); for (Uri entryPoint in entryPoints) { String scheme = entryPoint.scheme; Uri fileUri; switch (scheme) { case "package": case "dart": case "data": break; default: // Attempt to reverse-lookup [entryPoint] in package config. String asString = "$entryPoint"; packagesMap ??= uriTranslator.packages.asMap(); for (String packageName in packagesMap.keys) { Uri packageUri = packagesMap[packageName]; if (packageUri?.hasFragment == true) { packageUri = packageUri.removeFragment(); } String prefix = "${packageUri}"; if (asString.startsWith(prefix)) { Uri reversed = Uri.parse( "package:$packageName/${asString.substring(prefix.length)}"); if (entryPoint == uriTranslator.translate(reversed)) { loader.addProblem( templateInferredPackageUri.withArguments(reversed), -1, 1, entryPoint); fileUri = entryPoint; entryPoint = reversed; break; } } } } result.add(entryPoint); loader.read(entryPoint, -1, accessor: loader.first, fileUri: fileUri); } return result; } @override LibraryBuilder createLibraryBuilder( Uri uri, Uri fileUri, SourceLibraryBuilder origin) { if (dillTarget.isLoaded) { LibraryBuilder builder = dillTarget.loader.builders[uri]; if (builder != null) { return builder; } } return new SourceLibraryBuilder(uri, fileUri, loader, origin); } /// Returns classes defined in libraries in [loader]. List<SourceClassBuilder> collectMyClasses() { List<SourceClassBuilder> result = <SourceClassBuilder>[]; loader.builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == loader) { Iterator<Builder> iterator = library.iterator; while (iterator.moveNext()) { Builder member = iterator.current; if (member is SourceClassBuilder && !member.isPatch) { result.add(member); } } } }); return result; } void breakCycle(ClassBuilder builder) { Class cls = builder.cls; cls.implementedTypes.clear(); cls.supertype = null; cls.mixedInType = null; builder.supertype = new NamedTypeBuilder("Object", const NullabilityBuilder.omitted(), null) ..bind(objectClassBuilder); builder.interfaces = null; builder.mixedInType = null; } @override Future<Component> buildOutlines({CanonicalName nameRoot}) async { if (loader.first == null) return null; return withCrashReporting<Component>(() async { loader.createTypeInferenceEngine(); await loader.buildOutlines(); loader.coreLibrary.becomeCoreLibrary(); dynamicType.bind( loader.coreLibrary.lookupLocalMember("dynamic", required: true)); loader.resolveParts(); loader.computeLibraryScopes(); objectType .bind(loader.coreLibrary.lookupLocalMember("Object", required: true)); bottomType .bind(loader.coreLibrary.lookupLocalMember("Null", required: true)); loader.resolveTypes(); loader.computeDefaultTypes(dynamicType, bottomType, objectClassBuilder); List<SourceClassBuilder> myClasses = loader.checkSemantics(objectClassBuilder); loader.finishTypeVariables(objectClassBuilder, dynamicType); loader.buildComponent(); installDefaultSupertypes(); installSyntheticConstructors(myClasses); loader.resolveConstructors(); component = link(new List<Library>.from(loader.libraries), nameRoot: nameRoot); computeCoreTypes(); loader.buildClassHierarchy(myClasses, objectClassBuilder); loader.computeHierarchy(); loader.performTopLevelInference(myClasses); loader.checkSupertypes(myClasses); loader.checkBounds(); loader.checkOverrides(myClasses); loader.checkAbstractMembers(myClasses); loader.checkRedirectingFactories(myClasses); loader.addNoSuchMethodForwarders(myClasses); loader.checkMixins(myClasses); loader.buildOutlineExpressions(); installAllComponentProblems(loader.allComponentProblems); loader.allComponentProblems.clear(); return component; }, () => loader?.currentUriForCrashReporting); } /// Build the kernel representation of the component loaded by this /// target. The component will contain full bodies for the code loaded from /// sources, and only references to the code loaded by the [DillTarget], /// which may or may not include method bodies (depending on what was loaded /// into that target, an outline or a full kernel component). /// /// If [verify], run the default kernel verification on the resulting /// component. @override Future<Component> buildComponent({bool verify: false}) async { if (loader.first == null) return null; return withCrashReporting<Component>(() async { ticker.logMs("Building component"); await loader.buildBodies(); finishClonedParameters(); loader.finishDeferredLoadTearoffs(); loader.finishNoSuchMethodForwarders(); List<SourceClassBuilder> myClasses = collectMyClasses(); loader.finishNativeMethods(); loader.finishPatchMethods(); finishAllConstructors(myClasses); runBuildTransformations(); if (verify) this.verify(); installAllComponentProblems(loader.allComponentProblems); return component; }, () => loader?.currentUriForCrashReporting); } void installAllComponentProblems( List<FormattedMessage> allComponentProblems) { if (allComponentProblems.isNotEmpty) { component.problemsAsJson ??= <String>[]; } for (int i = 0; i < allComponentProblems.length; i++) { FormattedMessage formattedMessage = allComponentProblems[i]; component.problemsAsJson.add(formattedMessage.toJsonString()); } } /// Creates a component by combining [libraries] with the libraries of /// `dillTarget.loader.component`. Component link(List<Library> libraries, {CanonicalName nameRoot}) { libraries.addAll(dillTarget.loader.libraries); Map<Uri, Source> uriToSource = new Map<Uri, Source>(); void copySource(Uri uri, Source source) { uriToSource[uri] = excludeSource ? new Source(source.lineStarts, const <int>[], source.importUri, source.fileUri) : source; } this.uriToSource.forEach(copySource); Component component = backendTarget.configureComponent(new Component( nameRoot: nameRoot, libraries: libraries, uriToSource: uriToSource)); if (loader.first != null) { // TODO(sigmund): do only for full program Builder declaration = loader.first.exportScope.lookup("main", -1, null); if (declaration is AmbiguousBuilder) { AmbiguousBuilder problem = declaration; declaration = problem.getFirstDeclaration(); } if (declaration is ProcedureBuilder) { component.mainMethod = declaration.actualProcedure; } else if (declaration is DillMemberBuilder) { if (declaration.member is Procedure) { component.mainMethod = declaration.member; } } } if (metadataCollector != null) { component.addMetadataRepository(metadataCollector.repository); } ticker.logMs("Linked component"); return component; } void installDefaultSupertypes() { Class objectClass = this.objectClass; loader.builders.forEach((Uri uri, LibraryBuilder library) { if (library.loader == loader) { Iterator<Builder> iterator = library.iterator; while (iterator.moveNext()) { Builder declaration = iterator.current; if (declaration is SourceClassBuilder) { Class cls = declaration.cls; if (cls != objectClass) { cls.supertype ??= objectClass.asRawSupertype; declaration.supertype ??= new NamedTypeBuilder( "Object", const NullabilityBuilder.omitted(), null) ..bind(objectClassBuilder); } if (declaration.isMixinApplication) { cls.mixedInType = declaration.mixedInType.buildMixedInType( library, declaration.charOffset, declaration.fileUri); } } } } }); ticker.logMs("Installed Object as implicit superclass"); } void installSyntheticConstructors(List<SourceClassBuilder> builders) { Class objectClass = this.objectClass; for (SourceClassBuilder builder in builders) { if (builder.cls != objectClass && !builder.isPatch) { if (builder.isPatch || builder.isMixinDeclaration || builder.isExtension) { continue; } if (builder.isMixinApplication) { installForwardingConstructors(builder); } else { installDefaultConstructor(builder); } } } ticker.logMs("Installed synthetic constructors"); } ClassBuilder get objectClassBuilder => objectType.declaration; Class get objectClass => objectClassBuilder.cls; /// If [builder] doesn't have a constructors, install the defaults. void installDefaultConstructor(SourceClassBuilder builder) { assert(!builder.isMixinApplication); assert(!builder.isExtension); // TODO(askesc): Make this check light-weight in the absence of patches. if (builder.cls.constructors.isNotEmpty) return; if (builder.cls.redirectingFactoryConstructors.isNotEmpty) return; for (Procedure proc in builder.cls.procedures) { if (proc.isFactory) return; } /// From [Dart Programming Language Specification, 4th Edition]( /// https://ecma-international.org/publications/files/ECMA-ST/ECMA-408.pdf): /// >Iff no constructor is specified for a class C, it implicitly has a /// >default constructor C() : super() {}, unless C is class Object. // The superinitializer is installed below in [finishConstructors]. builder.addSyntheticConstructor(makeDefaultConstructor(builder.cls)); } void installForwardingConstructors(SourceClassBuilder builder) { assert(builder.isMixinApplication); if (builder.library.loader != loader) return; if (builder.cls.constructors.isNotEmpty) { // These were installed by a subclass in the recursive call below. return; } /// From [Dart Programming Language Specification, 4th Edition]( /// https://ecma-international.org/publications/files/ECMA-ST/ECMA-408.pdf): /// >A mixin application of the form S with M; defines a class C with /// >superclass S. /// >... /// >Let LM be the library in which M is declared. For each generative /// >constructor named qi(Ti1 ai1, . . . , Tiki aiki), i in 1..n of S /// >that is accessible to LM , C has an implicitly declared constructor /// >named q'i = [C/S]qi of the form q'i(ai1,...,aiki) : /// >super(ai1,...,aiki);. TypeBuilder type = builder.supertype; TypeDeclarationBuilder supertype; if (type is NamedTypeBuilder) { supertype = type.declaration; } else { unhandled("${type.runtimeType}", "installForwardingConstructors", builder.charOffset, builder.fileUri); } if (supertype.isMixinApplication && supertype is SourceClassBuilder) { installForwardingConstructors(supertype); } if (supertype is ClassBuilder) { if (supertype.cls.constructors.isEmpty) { builder.addSyntheticConstructor(makeDefaultConstructor(builder.cls)); } else { Map<TypeParameter, DartType> substitutionMap = builder.getSubstitutionMap(supertype.cls); for (Constructor constructor in supertype.cls.constructors) { builder.addSyntheticConstructor(makeMixinApplicationConstructor( builder.cls, builder.cls.mixin, constructor, substitutionMap)); } } } else if (supertype is InvalidTypeBuilder) { builder.addSyntheticConstructor(makeDefaultConstructor(builder.cls)); } else { unhandled("${supertype.runtimeType}", "installForwardingConstructors", builder.charOffset, builder.fileUri); } } Constructor makeMixinApplicationConstructor(Class cls, Class mixin, Constructor constructor, Map<TypeParameter, DartType> substitutionMap) { VariableDeclaration copyFormal(VariableDeclaration formal) { // TODO(ahe): Handle initializers. VariableDeclaration copy = new VariableDeclaration(formal.name, isFinal: formal.isFinal, isConst: formal.isConst); if (formal.type != null) { copy.type = substitute(formal.type, substitutionMap); } return copy; } List<VariableDeclaration> positionalParameters = <VariableDeclaration>[]; List<VariableDeclaration> namedParameters = <VariableDeclaration>[]; List<Expression> positional = <Expression>[]; List<NamedExpression> named = <NamedExpression>[]; for (VariableDeclaration formal in constructor.function.positionalParameters) { positionalParameters.add(copyFormal(formal)); positional.add(new VariableGet(positionalParameters.last)); } for (VariableDeclaration formal in constructor.function.namedParameters) { VariableDeclaration clone = copyFormal(formal); clonedFormals..add(formal)..add(clone)..add(substitutionMap); namedParameters.add(clone); named.add(new NamedExpression( formal.name, new VariableGet(namedParameters.last))); } FunctionNode function = new FunctionNode(new EmptyStatement(), positionalParameters: positionalParameters, namedParameters: namedParameters, requiredParameterCount: constructor.function.requiredParameterCount, returnType: makeConstructorReturnType(cls)); SuperInitializer initializer = new SuperInitializer( constructor, new Arguments(positional, named: named)); return new Constructor(function, name: constructor.name, initializers: <Initializer>[initializer], isSynthetic: true, isConst: constructor.isConst && mixin.fields.isEmpty); } void finishClonedParameters() { for (int i = 0; i < clonedFormals.length; i += 3) { // Note that [original] may itself be clone. If so, it was added to // [clonedFormals] before [clone], so it's initializers are already in // place. VariableDeclaration original = clonedFormals[i]; VariableDeclaration clone = clonedFormals[i + 1]; if (original.initializer != null) { // TODO(ahe): It is unclear if it is legal to use type variables in // default values, but Fasta is currently allowing it, and the VM // accepts it. If it isn't legal, the we can speed this up by using a // single cloner without substitution. CloneVisitor cloner = new CloneVisitor(typeSubstitution: clonedFormals[i + 2]); clone.initializer = cloner.clone(original.initializer)..parent = clone; } } clonedFormals.clear(); ticker.logMs("Cloned default values of formals"); } Constructor makeDefaultConstructor(Class enclosingClass) { return new Constructor( new FunctionNode(new EmptyStatement(), returnType: makeConstructorReturnType(enclosingClass)), name: new Name(""), isSynthetic: true); } DartType makeConstructorReturnType(Class enclosingClass) { 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)); } return new InterfaceType(enclosingClass, typeParameterTypes); } void computeCoreTypes() { List<Library> libraries = <Library>[]; for (String platformLibrary in [ "dart:_internal", "dart:async", "dart:core", "dart:mirrors", ...backendTarget.extraIndexedLibraries ]) { Uri uri = Uri.parse(platformLibrary); LibraryBuilder libraryBuilder = loader.builders[uri]; if (libraryBuilder == null) { // TODO(ahe): This is working around a bug in kernel_driver_test or // kernel_driver. bool found = false; for (Library target in dillTarget.loader.libraries) { if (target.importUri == uri) { libraries.add(target); found = true; break; } } if (!found && uri.path != "mirrors") { // dart:mirrors is optional. throw "Can't find $uri"; } } else { libraries.add(libraryBuilder.library); } } Component platformLibraries = backendTarget.configureComponent(new Component()); // Add libraries directly to prevent that their parents are changed. platformLibraries.libraries.addAll(libraries); loader.computeCoreTypes(platformLibraries); } void finishAllConstructors(List<SourceClassBuilder> builders) { Class objectClass = this.objectClass; for (SourceClassBuilder builder in builders) { Class cls = builder.cls; if (cls != objectClass) { finishConstructors(builder); } } ticker.logMs("Finished constructors"); } /// Ensure constructors of [builder] have the correct initializers and other /// requirements. void finishConstructors(SourceClassBuilder builder) { if (builder.isPatch) return; Class cls = builder.cls; /// Quotes below are from [Dart Programming Language Specification, 4th /// Edition](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-408.pdf): List<Field> uninitializedFields = <Field>[]; List<Field> nonFinalFields = <Field>[]; for (Field field in cls.fields) { if (field.isInstanceMember && !field.isFinal) { nonFinalFields.add(field); } if (field.initializer == null) { uninitializedFields.add(field); } } Map<Constructor, Set<Field>> constructorInitializedFields = <Constructor, Set<Field>>{}; Constructor superTarget; for (Constructor constructor in cls.constructors) { bool isRedirecting = false; for (Initializer initializer in constructor.initializers) { if (initializer is RedirectingInitializer) { if (constructor.isConst && !initializer.target.isConst) { builder.addProblem(messageConstConstructorRedirectionToNonConst, initializer.fileOffset, initializer.target.name.name.length); } isRedirecting = true; break; } } if (!isRedirecting) { /// >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. if (constructor.initializers.isEmpty) { superTarget ??= defaultSuperConstructor(cls); Initializer initializer; if (superTarget == null) { int offset = constructor.fileOffset; if (offset == -1 && constructor.isSynthetic) { offset = cls.fileOffset; } builder.addProblem( templateSuperclassHasNoDefaultConstructor .withArguments(cls.superclass.name), offset, noLength); initializer = new InvalidInitializer(); } else { initializer = new SuperInitializer(superTarget, new Arguments.empty()) ..isSynthetic = true; } constructor.initializers.add(initializer); initializer.parent = 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; } Set<Field> myInitializedFields = new Set<Field>(); for (Initializer initializer in constructor.initializers) { if (initializer is FieldInitializer) { myInitializedFields.add(initializer.field); } } for (VariableDeclaration formal in constructor.function.positionalParameters) { if (formal.isFieldFormal) { Builder fieldBuilder = builder.scope.local[formal.name] ?? builder.origin.scope.local[formal.name]; if (fieldBuilder is FieldBuilder) { myInitializedFields.add(fieldBuilder.field); } } } constructorInitializedFields[constructor] = myInitializedFields; if (constructor.isConst && nonFinalFields.isNotEmpty) { builder.addProblem(messageConstConstructorNonFinalField, constructor.fileOffset, noLength, context: nonFinalFields .map((field) => messageConstConstructorNonFinalFieldCause .withLocation(field.fileUri, field.fileOffset, noLength)) .toList()); nonFinalFields.clear(); } } } Set<Field> initializedFields; constructorInitializedFields .forEach((Constructor constructor, Set<Field> fields) { if (initializedFields == null) { initializedFields = new Set<Field>.from(fields); } else { initializedFields.addAll(fields); } }); // Run through all fields that aren't initialized by any constructor, and // set their initializer to `null`. for (Field field in uninitializedFields) { if (initializedFields == null || !initializedFields.contains(field)) { field.initializer = new NullLiteral()..parent = field; if (field.isFinal && (cls.constructors.isNotEmpty || cls.isMixinDeclaration)) { String uri = '${field.enclosingLibrary.importUri}'; String file = field.fileUri.pathSegments.last; if (uri == 'dart:html' || uri == 'dart:svg' || uri == 'dart:_native_typed_data' || uri == 'dart:_interceptors' && file == 'js_string.dart') { // TODO(johnniwinther): Use external getters instead of final // fields. See https://github.com/dart-lang/sdk/issues/33762 } else { builder.library.addProblem( templateFinalFieldNotInitialized.withArguments(field.name.name), field.fileOffset, field.name.name.length, field.fileUri); } } } } // Run through all fields that are initialized by some constructor, and // make sure that all other constructors also initialize them. constructorInitializedFields .forEach((Constructor constructor, Set<Field> fields) { for (Field field in initializedFields.difference(fields)) { if (field.initializer == null) { FieldInitializer initializer = new FieldInitializer(field, new NullLiteral()) ..isSynthetic = true; initializer.parent = constructor; constructor.initializers.insert(0, initializer); if (field.isFinal) { builder.library.addProblem( templateFinalFieldNotInitializedByConstructor .withArguments(field.name.name), constructor.fileOffset, constructor.name.name.length, constructor.fileUri, context: [ templateMissingImplementationCause .withArguments(field.name.name) .withLocation(field.fileUri, field.fileOffset, field.name.name.length) ]); } } } }); } /// Run all transformations that are needed when building a bundle of /// libraries for the first time. void runBuildTransformations() { backendTarget.performPreConstantEvaluationTransformations( component, loader.coreTypes, loader.libraries, new KernelDiagnosticReporter(loader), logger: (String msg) => ticker.logMs(msg)); TypeEnvironment environment = new TypeEnvironment(loader.coreTypes, loader.hierarchy); constants.transformLibraries( loader.libraries, backendTarget.constantsBackend(loader.coreTypes), environmentDefines, environment, new KernelConstantErrorReporter(loader), desugarSets: !backendTarget.supportsSetLiterals, errorOnUnevaluatedConstant: errorOnUnevaluatedConstant); ticker.logMs("Evaluated constants"); backendTarget.performModularTransformationsOnLibraries( component, loader.coreTypes, loader.hierarchy, loader.libraries, environmentDefines, new KernelDiagnosticReporter(loader), logger: (String msg) => ticker.logMs(msg)); } void runProcedureTransformations(Procedure procedure) { backendTarget.performTransformationsOnProcedure( loader.coreTypes, loader.hierarchy, procedure, logger: (String msg) => ticker.logMs(msg)); } void verify() { // TODO(ahe): How to handle errors. verifyComponent(component); ticker.logMs("Verified component"); } /// Return `true` if the given [library] was built by this [KernelTarget] /// from sources, and not loaded from a [DillTarget]. bool isSourceLibrary(Library library) { return loader.libraries.contains(library); } @override void readPatchFiles(SourceLibraryBuilder library) { assert(library.uri.scheme == "dart"); List<Uri> patches = uriTranslator.getDartPatches(library.uri.path); if (patches != null) { SourceLibraryBuilder first; for (Uri patch in patches) { if (first == null) { first = library.loader.read(patch, -1, fileUri: patch, origin: library, accessor: library); } else { // If there's more than one patch file, it's interpreted as a part of // the patch library. SourceLibraryBuilder part = library.loader.read(patch, -1, origin: library, fileUri: patch, accessor: library); first.parts.add(part); first.partOffsets.add(-1); part.partOfUri = first.uri; } } } } } /// Looks for a constructor call that matches `super()` from a constructor in /// [cls]. Such a constructor may have optional arguments, but no required /// arguments. Constructor defaultSuperConstructor(Class cls) { Class superclass = cls.superclass; if (superclass != null) { for (Constructor constructor in superclass.constructors) { if (constructor.name.name.isEmpty) { return constructor.function.requiredParameterCount == 0 ? constructor : null; } } } return null; } class KernelDiagnosticReporter extends DiagnosticReporter<Message, LocatedMessage> { final Loader loader; KernelDiagnosticReporter(this.loader); void report(Message message, int charOffset, int length, Uri fileUri, {List<LocatedMessage> context}) { loader.addProblem(message, charOffset, noLength, fileUri, 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/kernel/type_builder_computer.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 fasta.type_builder_computer; import 'package:kernel/ast.dart' show BottomType, Class, DartType, DartTypeVisitor, DynamicType, FunctionType, InterfaceType, InvalidType, Library, NamedType, TypeParameter, TypeParameterType, TypedefType, VoidType; import '../kernel/kernel_builder.dart' show DynamicTypeBuilder, FunctionTypeBuilder, ClassBuilder, FormalParameterBuilder, NamedTypeBuilder, TypeVariableBuilder, LibraryBuilder, NullabilityBuilder, TypeBuilder, VoidTypeBuilder; import '../loader.dart' show Loader; import '../parser.dart' show FormalParameterKind; class TypeBuilderComputer implements DartTypeVisitor<TypeBuilder> { final Loader loader; const TypeBuilderComputer(this.loader); TypeBuilder defaultDartType(DartType node) { throw "Unsupported"; } TypeBuilder visitInvalidType(InvalidType node) { throw "Not implemented"; } TypeBuilder visitDynamicType(DynamicType node) { // 'dynamic' is always nullable. return new NamedTypeBuilder( "dynamic", const NullabilityBuilder.nullable(), null) ..bind( new DynamicTypeBuilder(const DynamicType(), loader.coreLibrary, -1)); } TypeBuilder visitVoidType(VoidType node) { // 'void' is always nullable. return new NamedTypeBuilder( "void", const NullabilityBuilder.nullable(), null) ..bind(new VoidTypeBuilder(const VoidType(), loader.coreLibrary, -1)); } TypeBuilder visitBottomType(BottomType node) { throw "Not implemented"; } TypeBuilder visitInterfaceType(InterfaceType node) { ClassBuilder cls = loader.computeClassBuilderFromTargetClass(node.classNode); List<TypeBuilder> arguments; List<DartType> kernelArguments = node.typeArguments; if (kernelArguments.isNotEmpty) { arguments = new List<TypeBuilder>(kernelArguments.length); for (int i = 0; i < kernelArguments.length; i++) { arguments[i] = kernelArguments[i].accept(this); } } return new NamedTypeBuilder(cls.name, new NullabilityBuilder.fromNullability(node.nullability), arguments) ..bind(cls); } @override TypeBuilder visitFunctionType(FunctionType node) { TypeBuilder returnType = node.returnType.accept(this); // We could compute the type variables here. However, the current // implementation of [visitTypeParameterType] is sufficient. List<TypeVariableBuilder> typeVariables = null; List<DartType> positionalParameters = node.positionalParameters; List<NamedType> namedParameters = node.namedParameters; List<FormalParameterBuilder> formals = new List<FormalParameterBuilder>( positionalParameters.length + namedParameters.length); for (int i = 0; i < positionalParameters.length; i++) { TypeBuilder type = positionalParameters[i].accept(this); FormalParameterKind kind = FormalParameterKind.mandatory; if (i >= node.requiredParameterCount) { kind = FormalParameterKind.optionalPositional; } formals[i] = new FormalParameterBuilder(null, 0, type, null, null, -1, null) ..kind = kind; } for (int i = 0; i < namedParameters.length; i++) { NamedType parameter = namedParameters[i]; TypeBuilder type = positionalParameters[i].accept(this); formals[i + positionalParameters.length] = new FormalParameterBuilder( null, 0, type, parameter.name, null, -1, null) ..kind = FormalParameterKind.optionalNamed; } return new FunctionTypeBuilder(returnType, typeVariables, formals, new NullabilityBuilder.fromNullability(node.nullability)); } TypeBuilder visitTypeParameterType(TypeParameterType node) { TypeParameter parameter = node.parameter; Class kernelClass = parameter.parent; Library kernelLibrary = kernelClass.enclosingLibrary; LibraryBuilder library = loader.builders[kernelLibrary.importUri]; return new NamedTypeBuilder(parameter.name, new NullabilityBuilder.fromNullability(node.nullability), null) ..bind(new TypeVariableBuilder.fromKernel(parameter, library)); } TypeBuilder visitTypedefType(TypedefType node) { throw "Not implemented"; } }
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/kernel/body_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.body_builder; import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart'; import 'package:kernel/type_environment.dart'; import '../builder/declaration.dart'; import '../builder/declaration_builder.dart'; import '../builder/extension_builder.dart'; import '../constant_context.dart' show ConstantContext; import '../dill/dill_library_builder.dart' show DillLibraryBuilder; 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, lateMask; import '../names.dart' show callName, emptyName, minusName, plusName; import '../parser.dart' show Assert, Parser, FormalParameterKind, IdentifierContext, MemberKind, lengthForToken, lengthOfSpan, offsetForToken, optional; import '../problems.dart' show internalProblem, 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, isUserDefinableOperator; import '../scope.dart' show ProblemBuilder; import '../severity.dart' show Severity; import '../source/scope_listener.dart' show FixedNullableList, GrowableList, JumpTargetKind, NullValue, ParserRecovery, ScopeListener; import '../source/source_library_builder.dart' show SourceLibraryBuilder; import '../source/value_kinds.dart'; import '../type_inference/type_inferrer.dart' show TypeInferrer; import '../type_inference/type_promotion.dart' show TypePromoter, TypePromotionFact, TypePromotionScope; import 'collections.dart' show SpreadElement, SpreadMapEntry, convertToMapEntry, isConvertibleToMapEntry; import 'constness.dart' show Constness; import 'expression_generator.dart'; import 'expression_generator_helper.dart' show ExpressionGeneratorHelper; import 'forest.dart' show Forest; import 'implicit_type_argument.dart' show ImplicitTypeArgument; import 'redirecting_factory_body.dart' show RedirectingFactoryBody, RedirectionTarget, getRedirectingFactoryBody, getRedirectionTarget, isRedirectingFactory; import 'type_algorithms.dart' show calculateBounds; import 'kernel_api.dart'; import 'kernel_ast_api.dart'; import 'kernel_shadow_ast.dart'; import 'kernel_builder.dart'; // TODO(ahe): Remove this and ensure all nodes have a location. const int noLocation = TreeNode.noOffset; // TODO(danrubel): Remove this once control flow and spread collection support // has been enabled by default. const Object invalidCollectionElement = const Object(); class BodyBuilder extends ScopeListener<JumpTarget> implements ExpressionGeneratorHelper, EnsureLoaded { final Forest forest; // TODO(ahe): Rename [library] to 'part'. @override final SourceLibraryBuilder libraryBuilder; final ModifierBuilder member; /// The class, mixin or extension declaration in which [member] is declared, /// if any. final DeclarationBuilder declarationBuilder; /// The class or mixin declaration in which [member] is declared, if any. final ClassBuilder classBuilder; final ClassHierarchy hierarchy; @override final CoreTypes coreTypes; final bool isDeclarationInstanceMember; 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; /// Set to `true` when we are parsing a field initializer either directly /// or within an initializer list. /// /// For instance in `<init>` in /// /// var foo = <init>; /// class Class { /// var bar = <init>; /// Class() : <init>; /// } /// /// This is used to determine whether instance properties are available. bool inFieldInitializer = false; bool inCatchClause = false; bool inCatchBlock = false; int functionNestingLevel = 0; // Set when a spread element is encountered in a collection so the collection // needs to be desugared after type inference. bool transformCollections = false; // Set by type inference when a set literal is encountered that needs to be // transformed because the backend target does not support set literals. bool transformSetLiterals = false; Statement problemInLoopOrSwitch; Scope switchScope; CloneVisitor cloner; ConstantContext constantContext = ConstantContext.none; UnresolvedType 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>[]; /// Variables with metadata. Their types need to be inferred late, for /// example, in [finishFunction]. List<VariableDeclaration> variablesWithMetadata; /// More than one variable declared in a single statement that has metadata. /// Their types need to be inferred late, for example, in [finishFunction]. List<List<VariableDeclaration>> multiVariablesWithMetadata; /// If the current member is an instance member in an extension declaration, /// [extensionThis] holds the synthetically add parameter holding the value /// for `this`. final VariableDeclaration extensionThis; final List<TypeParameter> extensionTypeParameters; BodyBuilder( {this.libraryBuilder, this.member, this.enclosingScope, this.formalParameterScope, this.hierarchy, this.coreTypes, this.declarationBuilder, this.isDeclarationInstanceMember, this.extensionThis, this.extensionTypeParameters, this.uri, this.typeInferrer}) : forest = const Forest(), classBuilder = declarationBuilder is ClassBuilder ? declarationBuilder : null, enableNative = libraryBuilder.loader.target.backendTarget .enableNative(libraryBuilder.uri), stringExpectedAfterNative = libraryBuilder .loader.target.backendTarget.nativeExtensionExpectsString, ignoreMainInGetMainClosure = libraryBuilder.uri.scheme == 'dart' && (libraryBuilder.uri.path == "_builtin" || libraryBuilder.uri.path == "ui"), needsImplicitSuperInitializer = declarationBuilder is ClassBuilder && coreTypes?.objectClass != declarationBuilder.cls, typePromoter = typeInferrer?.typePromoter, super(enclosingScope); BodyBuilder.withParents(FieldBuilder field, SourceLibraryBuilder part, DeclarationBuilder declarationBuilder, TypeInferrer typeInferrer) : this( libraryBuilder: part, member: field, enclosingScope: declarationBuilder?.scope ?? field.library.scope, formalParameterScope: null, hierarchy: part.loader.hierarchy, coreTypes: part.loader.coreTypes, declarationBuilder: declarationBuilder, isDeclarationInstanceMember: field.isDeclarationInstanceMember, extensionThis: null, uri: field.fileUri, typeInferrer: typeInferrer); BodyBuilder.forField(FieldBuilder field, TypeInferrer typeInferrer) : this.withParents( field, field.parent is DeclarationBuilder ? field.parent.parent : field.parent, field.parent is DeclarationBuilder ? field.parent : null, typeInferrer); BodyBuilder.forOutlineExpression( SourceLibraryBuilder library, DeclarationBuilder declarationBuilder, ModifierBuilder member, Scope scope, Uri fileUri) : this( libraryBuilder: library, member: member, enclosingScope: scope, formalParameterScope: null, hierarchy: library.loader.hierarchy, coreTypes: library.loader.coreTypes, declarationBuilder: declarationBuilder, isDeclarationInstanceMember: member?.isDeclarationInstanceMember ?? false, extensionThis: null, uri: fileUri, typeInferrer: library.loader.typeInferenceEngine ?.createLocalTypeInferrer( fileUri, declarationBuilder?.thisType, library)); bool get inConstructor { return functionNestingLevel == 0 && member is ConstructorBuilder; } bool get isDeclarationInstanceContext { return isDeclarationInstanceMember || member is ConstructorBuilder; } TypeEnvironment get typeEnvironment => typeInferrer?.typeSchemaEnvironment; DartType get implicitTypeArgument => const ImplicitTypeArgument(); @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.createBlock(offsetForToken(openBrace), const GrowableList<Statement>().pop(stack, count) ?? <Statement>[]); } 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, Builder 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; Builder 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 VariableBuilder( variable, member ?? classBuilder ?? libraryBuilder, 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); } void inferAnnotations(List<Expression> annotations) { if (annotations != null) { typeInferrer?.inferMetadata(this, annotations); libraryBuilder.loader.transformListPostInference( annotations, transformSetLiterals, transformCollections); } } @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, libraryBuilder.nameOrigin)); } if (name?.isNotEmpty ?? false) { Token period = periodBeforeName ?? beginToken.next.next; Generator generator = expression; expression = generator.buildPropertyAccess( new IncompletePropertyAccessGenerator( this, period.next, new Name(name, libraryBuilder.nameOrigin)), period.next.offset, false); } ConstantContext savedConstantContext = pop(); if (expression is! StaticAccessGenerator && expression is! VariableUseGenerator) { 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 lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("TopLevelFields"); if (!libraryBuilder.loader.target.enableNonNullable) { reportNonNullableModifierError(lateToken); } push(count); } @override void endClassFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { debugEvent("Fields"); if (!libraryBuilder.loader.target.enableNonNullable) { reportNonNullableModifierError(lateToken); } push(count); } @override void finishFields() { debugEvent("finishFields"); int count = pop(); List<FieldBuilder> fields = <FieldBuilder>[]; for (int i = 0; i < count; i++) { Expression initializer = pop(); Identifier identifier = pop(); String name = identifier.name; Builder declaration; if (declarationBuilder != null) { declaration = declarationBuilder.lookupLocalMember(name, required: true); } else { declaration = libraryBuilder.lookupLocalMember(name, required: true); } FieldBuilder fieldBuilder; if (declaration.isField && declaration.next == null) { fieldBuilder = declaration; } else { continue; } fields.add(fieldBuilder); if (initializer != null) { if (fieldBuilder.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 if (fieldBuilder.field.initializer != null) { // The initializer was already compiled (e.g., if it appear in the // outline, like constant field initializers) so we do not need to // perform type inference or transformations. } else { fieldBuilder.initializer = initializer; typeInferrer?.inferFieldInitializer( this, fieldBuilder.builtType, initializer); libraryBuilder.loader.transformPostInference( fieldBuilder.field, transformSetLiterals, transformCollections); } } } { // 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. } pop(); // Annotations. resolveRedirectingFactoryTargets(); finishVariableMetadata(); } @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() { FunctionBuilder member = this.member; scope = member.computeFormalParameterInitializerScope(scope); if (member is ConstructorBuilder) { member.prepareInitializers(); if (member.formals != null) { for (FormalParameterBuilder formal in member.formals) { if (formal.isInitializingFormal) { Initializer initializer; if (member.isExternal) { initializer = buildInvalidInitializer( buildProblem( fasta.messageExternalConstructorWithFieldInitializers, formal.charOffset, formal.name.length), formal.charOffset); } else { initializer = buildFieldInitializer( true, formal.name, formal.charOffset, formal.charOffset, new VariableGet(formal.variable), formalType: formal.variable.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 ModifierBuilder 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 ConstructorBuilder && !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 ProcedureBuilder) { return member.actualProcedure.function.returnType; } else { assert(member is ConstructorBuilder); return const DynamicType(); } } @override void finishFunction( FormalParameters formals, AsyncMarker asyncModifier, Statement body) { debugEvent("finishFunction"); typePromoter?.finished(); FunctionBuilder builder = member; if (formals?.parameters != null) { for (int i = 0; i < formals.parameters.length; i++) { FormalParameterBuilder parameter = formals.parameters[i]; Expression initializer = parameter.target.initializer; if (parameter.isOptional || initializer != null) { if (parameter.isOptional) { initializer ??= forest.createNullLiteral( // TODO(ahe): Should store: originParameter.fileOffset // https://github.com/dart-lang/sdk/issues/32289 noLocation); } VariableDeclaration originParameter = builder.getFormalParameter(i); originParameter.initializer = initializer..parent = originParameter; typeInferrer?.inferParameterInitializer( this, initializer, originParameter.type); libraryBuilder.loader.transformPostInference( originParameter, transformSetLiterals, transformCollections); VariableDeclaration extensionTearOffParameter = builder.getExtensionTearOffParameter(i); if (extensionTearOffParameter != null) { cloner ??= new CloneVisitor(); Expression tearOffInitializer = cloner.clone(initializer); extensionTearOffParameter.initializer = tearOffInitializer ..parent = extensionTearOffParameter; libraryBuilder.loader.transformPostInference( extensionTearOffParameter, transformSetLiterals, transformCollections); } } } } typeInferrer?.inferFunctionBody( this, _computeReturnTypeContext(member), asyncModifier, body); if (body != null) { libraryBuilder.loader.transformPostInference( body, transformSetLiterals, transformCollections); } if (builder.returnType != null) { checkAsyncReturnType(asyncModifier, builder.function.returnType, 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.member.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 (FormalParameterBuilder parameter in builder.formals) { statements.add(parameter.target); } statements.add(body); body = forest.createBlock(charOffset, statements); } body = forest.createBlock(charOffset, <Statement>[ forest.createExpressionStatement( noLocation, // This error is added after type inference is done, so we // don't need to wrap errors in SyntheticExpressionJudgment. buildProblem(fasta.messageSetterWithWrongNumberOfFormals, charOffset, noLength)), body, ]); } } // 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 = new Block(<Statement>[ new ExpressionStatement(buildProblem( fasta.messageExternalMethodWithBody, body.fileOffset, noLength)) ..fileOffset = body.fileOffset, body, ]) ..fileOffset = body.fileOffset; } } if (builder is ConstructorBuilder) { finishConstructor(builder, asyncModifier); } else if (builder is ProcedureBuilder) { builder.asyncModifier = asyncModifier; } else { unhandled("${builder.runtimeType}", "finishFunction", builder.charOffset, builder.fileUri); } resolveRedirectingFactoryTargets(); finishVariableMetadata(); } void checkAsyncReturnType(AsyncMarker asyncModifier, DartType returnType, int charOffset, int length) { // For async, async*, and sync* functions with declared return types, we // need to determine whether those types are valid. // 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 = libraryBuilder.loader.futureOfBottom; if (!typeEnvironment.isSubtypeOf(futureBottomType, returnType, SubtypeCheckMode.ignoringNullabilities)) { problem = fasta.messageIllegalAsyncReturnType; } break; case AsyncMarker.AsyncStar: DartType streamBottomType = libraryBuilder.loader.streamOfBottom; if (returnType is VoidType) { problem = fasta.messageIllegalAsyncGeneratorVoidReturnType; } else if (!typeEnvironment.isSubtypeOf(streamBottomType, returnType, SubtypeCheckMode.ignoringNullabilities)) { problem = fasta.messageIllegalAsyncGeneratorReturnType; } break; case AsyncMarker.SyncStar: DartType iterableBottomType = libraryBuilder.loader.iterableOfBottom; if (returnType is VoidType) { problem = fasta.messageIllegalSyncGeneratorVoidReturnType; } else if (!typeEnvironment.isSubtypeOf(iterableBottomType, returnType, SubtypeCheckMode.ignoringNullabilities)) { 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, charOffset, length); } } /// Ensure that the containing library of the [member] has been loaded. /// /// This is for instance important for lazy dill library builders where this /// method has to be called to ensure that /// a) The library has been fully loaded (and for instance any internal /// transformation needed has been performed); and /// b) The library is correctly marked as being used to allow for proper /// 'dependency pruning'. void ensureLoaded(Member member) { if (member == null) return; Library ensureLibraryLoaded = member.enclosingLibrary; LibraryBuilder builder = libraryBuilder.loader.builders[ensureLibraryLoaded.importUri] ?? libraryBuilder.loader.target.dillTarget.loader .builders[ensureLibraryLoaded.importUri]; if (builder is DillLibraryBuilder) { builder.ensureLoaded(); } } /// Check if the containing library of the [member] has been loaded. /// /// This is designed for use with asserts. /// See [ensureLoaded] for a description of what 'loaded' means and the ideas /// behind that. bool isLoaded(Member member) { if (member == null) return true; Library ensureLibraryLoaded = member.enclosingLibrary; LibraryBuilder builder = libraryBuilder.loader.builders[ensureLibraryLoaded.importUri] ?? libraryBuilder.loader.target.dillTarget.loader .builders[ensureLibraryLoaded.importUri]; if (builder is DillLibraryBuilder) { return builder.isBuiltAndMarked; } return true; } void resolveRedirectingFactoryTargets() { for (StaticInvocation invocation in redirectingFactoryInvocations) { // If the invocation was invalid, it or its parent has already been // desugared into an exception throwing expression. There is nothing to // resolve anymore. Note that in the case where the invocation's parent // was invalid, type inference won't reach the invocation node and won't // set its inferredType field. If type inference is disabled, reach to // the outermost parent to check if the node is a dead code. if (invocation.parent == null) continue; if (typeInferrer != null) { if (invocation is FactoryConstructorInvocationJudgment && !invocation.hasBeenInferred) { continue; } } else { TreeNode parent = invocation.parent; while (parent is! Component && parent != null) { parent = parent.parent; } if (parent == null) continue; } Procedure initialTarget = invocation.target; Expression replacementNode; RedirectionTarget redirectionTarget = getRedirectionTarget(initialTarget, this); 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); } else if (resolvedTarget is Constructor && resolvedTarget.enclosingClass.isAbstract) { replacementNode = evaluateArgumentsBefore( forest.createArguments(noLocation, invocation.arguments.positional, 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 = throwNoSuchMethodError( forest.createNullLiteral(invocation.fileOffset), errorName, forest.createArguments( noLocation, invocation.arguments.positional, 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.createArguments( noLocation, invocation.arguments.positional, types: invocation.arguments.types, named: invocation.arguments.named), constness: invocation.isConst ? Constness.explicitConst : Constness.explicitNew, charOffset: invocation.fileOffset); } } invocation.replaceWith(replacementNode); } redirectingFactoryInvocations.clear(); } void finishVariableMetadata() { List<VariableDeclaration> variablesWithMetadata = this.variablesWithMetadata; this.variablesWithMetadata = null; List<List<VariableDeclaration>> multiVariablesWithMetadata = this.multiVariablesWithMetadata; this.multiVariablesWithMetadata = null; if (variablesWithMetadata != null) { for (int i = 0; i < variablesWithMetadata.length; i++) { inferAnnotations(variablesWithMetadata[i].annotations); } } if (multiVariablesWithMetadata != null) { for (int i = 0; i < multiVariablesWithMetadata.length; i++) { List<VariableDeclaration> variables = multiVariablesWithMetadata[i]; List<Expression> annotations = variables.first.annotations; inferAnnotations(annotations); for (int i = 1; i < variables.length; i++) { cloner ??= new CloneVisitor(); VariableDeclaration variable = variables[i]; for (int i = 0; i < annotations.length; i++) { variable.addAnnotation(cloner.clone(annotations[i])); } } } } } @override List<Expression> finishMetadata(TreeNode parent) { List<Expression> expressions = pop(); inferAnnotations(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(); finishVariableMetadata(); return temporaryParent != null ? temporaryParent.expressions : expressions; } @override Expression parseSingleExpression( Parser parser, Token token, FunctionNode parameters) { List<TypeVariableBuilder> typeParameterBuilders; for (TypeParameter typeParameter in parameters.typeParameters) { typeParameterBuilders ??= <TypeVariableBuilder>[]; typeParameterBuilders.add( new TypeVariableBuilder.fromKernel(typeParameter, libraryBuilder)); } enterFunctionTypeScope(typeParameterBuilders); List<FormalParameterBuilder> formals = parameters.positionalParameters.length == 0 ? null : new List<FormalParameterBuilder>( parameters.positionalParameters.length); for (int i = 0; i < parameters.positionalParameters.length; i++) { VariableDeclaration formal = parameters.positionalParameters[i]; formals[i] = new FormalParameterBuilder( null, 0, null, formal.name, libraryBuilder, formal.fileOffset, uri) ..variable = 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)); } ReturnStatementImpl fakeReturn = new ReturnStatementImpl(true, expression); typeInferrer?.inferFunctionBody( this, const DynamicType(), AsyncMarker.Sync, fakeReturn); return fakeReturn.expression; } void parseInitializers(Token token) { Parser parser = new Parser(this); if (!token.isEof) { token = parser.parseInitializers(token); checkEmpty(token.charOffset); } else { handleNoInitializers(); } // We are passing [AsyncMarker.Sync] because the error will be reported // already. finishConstructor(member, AsyncMarker.Sync); } Expression parseFieldInitializer(Token token) { Parser parser = new Parser(this); token = parser.parseExpression(parser.syntheticPreviousToken(token)); Expression expression = popForValue(); checkEmpty(token.charOffset); return expression; } Expression parseAnnotation(Token token) { Parser parser = new Parser(this); token = parser.parseMetadata(parser.syntheticPreviousToken(token)); Expression annotation = pop(); checkEmpty(token.charOffset); return annotation; } void finishConstructor( ConstructorBuilder 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.actualConstructor; 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))); } 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.createArgumentsEmpty(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), builder.charOffset); } else { initializer = buildSuperInitializer( true, superTarget, arguments, builder.charOffset); } constructor.initializers.add(initializer); } setParents(constructor.initializers, constructor); libraryBuilder.loader.transformListPostInference( constructor.initializers, transformSetLiterals, transformCollections); 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 handleExpressionStatement(Token token) { debugEvent("ExpressionStatement"); push(forest.createExpressionStatement( offsetForToken(token), popForEffect())); } @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, argument.fileOffset, 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.createArguments(beginToken.offset, positional, 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.createArguments( beginToken.offset, new List<Expression>.from(arguments))); } } @override void handleParenthesizedCondition(Token token) { debugEvent("ParenthesizedCondition"); push(popForValue()); } @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) { assert(checkState(beginToken, [ ValueKind.ArgumentsOrNull, ValueKind.TypeArgumentsOrNull, unionOfKinds([ ValueKind.Expression, ValueKind.Generator, ValueKind.Identifier, ValueKind.ParserRecovery, ValueKind.ProblemBuilder ]) ])); debugEvent("Send"); Arguments arguments = pop(); List<UnresolvedType> 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, libraryBuilder.nameOrigin); if (arguments == null) { push(new IncompletePropertyAccessGenerator(this, beginToken, name)); } else { push(new SendAccessGenerator(this, beginToken, name, 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 Cascade) { push(expression); push(new VariableUseGenerator(this, token, expression.variable)); expression.extend(); } else { VariableDeclaration variable = forest.createVariableDeclarationForValue(expression); push(new Cascade(variable)..fileOffset = expression.fileOffset); push(new VariableUseGenerator(this, token, variable)); } } @override void endCascade() { debugEvent("endCascade"); Expression expression = popForEffect(); Cascade 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) || 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.createThisExpression(thisAccessorReceiver.fileOffset); } 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)) { if (isUserDefinableOperator(operator)) { return buildProblem( fasta.templateNotBinaryOperator.withArguments(token), token.charOffset, token.length); } else { return buildProblem(fasta.templateInvalidOperator.withArguments(token), token.charOffset, token.length); } } else { Expression result = buildMethodInvocation(a, new Name(operator), forest.createArguments(noLocation, <Expression>[b]), token.charOffset, // This *could* be a constant expression, we can't know without // evaluating [a] and [b]. isConstantExpression: !isSuper, isSuper: isSuper); return negate ? forest.createNot(noLocation, result) : result; } } void doLogicalExpression(Token token) { Expression argument = popForValue(); Expression receiver = pop(); Expression logicalExpression = forest.createLogicalExpression( offsetForToken(token), receiver, token.stringValue, argument); typePromoter?.exitLogicalExpression(argument, logicalExpression); push(logicalExpression); } /// Handle `a ?? b`. void doIfNull(Token token) { Expression b = popForValue(); Expression a = popForValue(); push(new IfNullExpression(a, b)..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, libraryBuilder.nameOrigin); List<LocatedMessage> context; if (candidate != null && candidate.location != null) { Uri uri = candidate.location.file; int offset = candidate.fileOffset; Message contextMessage; int length = noLength; if (candidate is Constructor && candidate.isSynthetic) { 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); } } return buildProblem( message.messageObject, message.charOffset, message.length, context: context); } @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}) { return classBuilder.lookupInstanceMember(hierarchy, name, isSetter: isSetter, isSuper: isSuper); } @override Constructor lookupConstructor(Name name, {bool isSuper}) { return classBuilder.lookupConstructor(name, isSuper: 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 : !member.isStatic && classBuilder != null && classBuilder.hasConstConstructor ? ConstantContext.required : 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)); } } /// Helper method to create a [VariableGet] of the [variable] using /// [charOffset] as the file offset. @override VariableGet createVariableGet(VariableDeclaration variable, int charOffset) { Object fact = typePromoter?.getFactForAccess(variable, functionNestingLevel); Object scope = typePromoter?.currentScope; return new VariableGetImpl(variable, fact, scope)..fileOffset = charOffset; } /// Helper method to create a [ReadOnlyAccessGenerator] on the [variable] /// using [token] and [charOffset] for offset information and [name] /// for `ExpressionGenerator._plainNameForRead`. ReadOnlyAccessGenerator _createReadOnlyVariableAccess( VariableDeclaration variable, Token token, int charOffset, String name) { return new ReadOnlyAccessGenerator( this, token, createVariableGet(variable, charOffset), name); } /// 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); } Builder 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, libraryBuilder); } if (declaration != null && declaration.isDeclarationInstanceMember && inFieldInitializer && !inInitializer) { // We cannot access a class instance member in an initializer of a // field. // // For instance // // class M { // int foo = bar; // int bar; // } // return new IncompleteErrorGenerator(this, token, fasta.templateThisAccessInFieldInitializer.withArguments(name)); } if (declaration == null || (!isDeclarationInstanceContext && declaration.isDeclarationInstanceMember)) { // We either didn't find a declaration or found an instance member from // a non-instance context. Name n = new Name(name, libraryBuilder.nameOrigin); if (!isQualified && isDeclarationInstanceContext) { assert(declaration == null); if (constantContext != ConstantContext.none || member.isField) { return new UnresolvedNameGenerator(this, token, n); } if (extensionThis != null) { // If we are in an extension instance member we interpret this as an // implicit access on the 'this' parameter. return PropertyAccessGenerator.make( this, token, createVariableGet(extensionThis, charOffset), n, null, null, false); } else { // This is an implicit access on 'this'. return new ThisPropertyAccessGenerator(this, token, n, lookupInstanceMember(n), lookupInstanceMember(n, isSetter: true)); } } else if (ignoreMainInGetMainClosure && name == "main" && member?.name == "_getMainClosure") { return forest.createNullLiteral(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) { return new IncompleteErrorGenerator( this, token, fasta.messageNotAConstantExpression); } // 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) { return _createReadOnlyVariableAccess( declaration.target, token, charOffset, name); } else { return new VariableUseGenerator(this, token, declaration.target); } } else if (declaration.isClassInstanceMember) { 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, libraryBuilder.nameOrigin); 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.isExtensionInstanceMember) { ExtensionBuilder extensionBuilder = declarationBuilder; Builder setter = _getCorrespondingSetterBuilder(scope, declaration, name, charOffset); // TODO(johnniwinther): Check for constantContext like below? return new ExtensionInstanceAccessGenerator.fromBuilder( this, extensionBuilder.extension, name, extensionThis, extensionTypeParameters, declaration, token, setter); } else if (declaration.isRegularMethod) { assert(declaration.isStatic || declaration.isTopLevel); return new StaticAccessGenerator( this, token, name, 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; } else { Builder setter = _getCorrespondingSetterBuilder(scope, declaration, name, charOffset); StaticAccessGenerator generator = new StaticAccessGenerator.fromBuilder( this, name, 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; } } /// Returns the setter builder corresponding to [declaration] using the /// [name] and [charOffset] for the lookup into [scope] if necessary. Builder _getCorrespondingSetterBuilder( Scope scope, Builder declaration, String name, int charOffset) { Builder setter; if (declaration.isSetter) { setter = declaration; } else if (declaration.isGetter) { setter = scope.lookupSetter(name, charOffset, uri); } else if (declaration.isField) { if (declaration.isFinal || declaration.isConst) { setter = scope.lookupSetter(name, charOffset, uri); } else { setter = declaration; } } return setter; } @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.createStringLiteral(offsetForToken(token), value)); } 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.createStringLiteral(offsetForToken(first), value)); } } 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.createStringLiteral(offsetForToken(part), value)); } } else { expressions.add(toValue(part)); } } // Contains more than just \' or \". if (last.lexeme.length > 1) { String value = unescapeLastStringPart( last.lexeme, quote, last, last.isSynthetic, this); if (value.isNotEmpty) { expressions .add(forest.createStringLiteral(offsetForToken(last), value)); } } push(forest.createStringConcatenation( offsetForToken(endToken), expressions)); } } @override void handleNativeClause(Token nativeToken, bool hasName) { debugEvent("NativeClause"); if (hasName) { pop() as StringLiteral; } } @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.createStringConcatenation(noLocation, expressions ?? parts)); } @override void handleLiteralInt(Token token) { debugEvent("LiteralInt"); int value = int.tryParse(token.lexeme); // 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.createIntLiteralLarge(offsetForToken(token), token.lexeme)); } else { push(forest.createIntLiteral(offsetForToken(token), value, token.lexeme)); } } @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.createReturnStatement(offsetForToken(beginToken), expression, isArrow: !identical(beginToken.lexeme, "return"))); } } @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.createIfStatement( offsetForToken(ifToken), condition, thenPart, 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; bool isLate = (currentLocalVariableModifiers & lateMask) != 0; assert(isConst == (constantContext == ConstantContext.inferred)); VariableDeclaration variable = new VariableDeclarationImpl( identifier.name, functionNestingLevel, forSyntheticToken: deprecated_extractToken(identifier).isSynthetic, initializer: initializer, type: buildDartType(currentLocalVariableType), isFinal: isFinal, isConst: isConst, isLate: isLate) ..fileOffset = identifier.charOffset ..fileEqualsOffset = offsetForToken(equalsToken); libraryBuilder.checkBoundsInVariableDeclaration( variable, typeEnvironment, uri); 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.inferred) { // Creating a null value to prevent the Dart VM from crashing. push(forest.createNullLiteral(offsetForToken(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 lateToken, Token varFinalOrConst) { debugEvent("beginVariablesDeclaration"); if (!libraryBuilder.loader.target.enableNonNullable) { reportNonNullableModifierError(lateToken); } UnresolvedType type = pop(); int modifiers = (lateToken != null ? lateMask : 0) | 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 (int i = 0; i < annotations.length; i++) { variable.addAnnotation(annotations[i]); } (variablesWithMetadata ??= <VariableDeclaration>[]).add(variable); } 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) { VariableDeclaration first = variables.first; for (int i = 0; i < annotations.length; i++) { first.addAnnotation(annotations[i]); } (multiVariablesWithMetadata ??= <List<VariableDeclaration>>[]) .add(variables); } 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> buildVariableDeclarations(variableOrExpression) { // TODO(ahe): This can be simplified now that we have the events // `handleForInitializer...` events. if (variableOrExpression is Generator) { variableOrExpression = variableOrExpression.buildForEffect(); } if (variableOrExpression is VariableDeclaration) { return <VariableDeclaration>[variableOrExpression]; } else if (variableOrExpression is Expression) { VariableDeclaration variable = new VariableDeclarationImpl.forEffect(variableOrExpression); return <VariableDeclaration>[variable]; } else if (variableOrExpression is ExpressionStatement) { VariableDeclaration variable = new VariableDeclarationImpl.forEffect( variableOrExpression.expression); return <VariableDeclaration>[variable]; } 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(buildVariableDeclarations(v)); } return variables; } else if (variableOrExpression == null) { return <VariableDeclaration>[]; } return null; } @override void handleForInitializerEmptyStatement(Token token) { debugEvent("ForInitializerEmptyStatement"); push(NullValue.Expression); } @override void handleForInitializerExpressionStatement(Token token) { debugEvent("ForInitializerExpressionStatement"); } @override void handleForInitializerLocalVariableDeclaration(Token token) { debugEvent("ForInitializerLocalVariableDeclaration"); } @override void handleForLoopParts(Token forKeyword, Token leftParen, Token leftSeparator, int updateExpressionCount) { push(forKeyword); push(leftParen); push(leftSeparator); push(updateExpressionCount); } @override void endForControlFlow(Token token) { debugEvent("ForControlFlow"); Object entry = pop(); int updateExpressionCount = pop(); pop(); // left separator pop(); // left parenthesis Token forToken = pop(); List<Expression> updates = popListForEffect(updateExpressionCount); Statement conditionStatement = popStatement(); // condition Object variableOrExpression = pop(); exitLocalScope(); if (constantContext != ConstantContext.none) { handleRecoverableError( fasta.templateCantUseControlFlowOrSpreadAsConstant .withArguments(forToken), forToken, forToken); push(invalidCollectionElement); return; } transformCollections = true; List<VariableDeclaration> variables = buildVariableDeclarations(variableOrExpression); Expression condition; if (conditionStatement is ExpressionStatement) { condition = conditionStatement.expression; } else { assert(conditionStatement is EmptyStatement); } if (entry is MapEntry) { push(forest.createForMapEntry( offsetForToken(forToken), variables, condition, updates, entry)); } else { push(forest.createForElement(offsetForToken(forToken), variables, condition, updates, toValue(entry))); } } @override void endForStatement(Token endToken) { assert(checkState(endToken, <ValueKind>[ /* body */ ValueKind.Statement, /* expression count */ ValueKind.Integer, /* left separator */ ValueKind.Token, /* left parenthesis */ ValueKind.Token, /* for keyword */ ValueKind.Token, ])); debugEvent("ForStatement"); Statement body = popStatement(); int updateExpressionCount = pop(); pop(); // Left separator. pop(); // Left parenthesis. Token forKeyword = pop(); assert(checkState(endToken, <ValueKind>[ /* expressions */ ...repeatedKinds( unionOfKinds(<ValueKind>[ValueKind.Expression, ValueKind.Generator]), updateExpressionCount), /* condition */ ValueKind.Statement, /* variable or expression */ unionOfKinds(<ValueKind>[ ValueKind.Generator, ValueKind.ExpressionOrNull, ValueKind.Statement, ValueKind.ObjectList, ValueKind.ParserRecovery, ]), ])); List<Expression> updates = popListForEffect(updateExpressionCount); Statement conditionStatement = popStatement(); Object variableOrExpression = pop(); List<VariableDeclaration> variables = buildVariableDeclarations(variableOrExpression); exitLocalScope(); JumpTarget continueTarget = exitContinueTarget(); JumpTarget breakTarget = exitBreakTarget(); if (continueTarget.hasUsers) { body = forest.createLabeledStatement(body); continueTarget.resolveContinues(forest, body); } Expression condition; if (conditionStatement is ExpressionStatement) { condition = conditionStatement.expression; } else { assert(conditionStatement is EmptyStatement); } Statement result = forest.createForStatement(offsetForToken(forKeyword), variables, condition, conditionStatement, updates, body); if (breakTarget.hasUsers) { result = forest.createLabeledStatement(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.createAwaitExpression(offsetForToken(keyword), popForValue())); } @override void endInvalidAwaitExpression( Token keyword, Token endToken, fasta.MessageCode errorCode) { debugEvent("AwaitExpression"); popForValue(); push(buildProblem(errorCode, keyword.offset, keyword.length)); } @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"); if (constantContext == ConstantContext.required && constKeyword == null) { addProblem(fasta.messageMissingExplicitConst, offsetForToken(leftBracket), noLength); } // TODO(danrubel): Replace this with popListForValue // when control flow and spread collections have been enabled by default List<Expression> expressions = new List<Expression>.filled(count, null, growable: true); for (int i = count - 1; i >= 0; i--) { Object elem = pop(); if (elem != invalidCollectionElement) { expressions[i] = toValue(elem); } else { expressions.removeAt(i); } } List<UnresolvedType> typeArguments = pop(); DartType typeArgument; if (typeArguments != null) { if (typeArguments.length > 1) { addProblem( fasta.messageListLiteralTooManyTypeArguments, offsetForToken(leftBracket), lengthOfSpan(leftBracket, leftBracket.endGroup)); typeArgument = const InvalidType(); } else { typeArgument = buildDartType(typeArguments.single); typeArgument = instantiateToBounds(typeArgument, coreTypes.objectClass); } } else { typeArgument = implicitTypeArgument; } Expression node = forest.createListLiteral( // TODO(johnniwinther): The file offset computed below will not be // correct if there are type arguments but no `const` keyword. offsetForToken(constKeyword ?? leftBracket), typeArgument, expressions, isConst: constKeyword != null || constantContext == ConstantContext.inferred); libraryBuilder.checkBoundsInListLiteral(node, typeEnvironment, uri); push(node); } void buildLiteralSet(List<UnresolvedType> typeArguments, Token constKeyword, Token leftBrace, List<dynamic> setOrMapEntries) { DartType typeArgument; if (typeArguments != null) { typeArgument = buildDartType(typeArguments.single); typeArgument = instantiateToBounds(typeArgument, coreTypes.objectClass); } else { typeArgument = implicitTypeArgument; } List<Expression> expressions = <Expression>[]; if (setOrMapEntries != null) { for (dynamic entry in setOrMapEntries) { if (entry is MapEntry) { // TODO(danrubel): report the error on the colon addProblem(fasta.templateExpectedButGot.withArguments(','), entry.fileOffset, 1); } else { // TODO(danrubel): Revise once control flow and spread // collection entries are supported. expressions.add(entry as Expression); } } } Expression node = forest.createSetLiteral( // TODO(johnniwinther): The file offset computed below will not be // correct if there are type arguments but no `const` keyword. offsetForToken(constKeyword ?? leftBrace), typeArgument, expressions, isConst: constKeyword != null || constantContext == ConstantContext.inferred); libraryBuilder.checkBoundsInSetLiteral(node, typeEnvironment, uri); push(node); } @override void handleLiteralSetOrMap( int count, Token leftBrace, Token constKeyword, Token rightBrace, // TODO(danrubel): hasSetEntry parameter exists for replicating existing // behavior and will be removed once unified collection has been enabled bool hasSetEntry, ) { debugEvent("LiteralSetOrMap"); if (constantContext == ConstantContext.required && constKeyword == null) { addProblem(fasta.messageMissingExplicitConst, offsetForToken(leftBrace), noLength); } List<dynamic> setOrMapEntries = new List<dynamic>.filled(count, null, growable: true); for (int i = count - 1; i >= 0; i--) { Object elem = pop(); // TODO(danrubel): Revise this to handle control flow and spread if (elem == invalidCollectionElement) { setOrMapEntries.removeAt(i); } else if (elem is MapEntry) { setOrMapEntries[i] = elem; } else { setOrMapEntries[i] = toValue(elem); } } List<UnresolvedType> typeArguments = pop(); // Replicate existing behavior that has been removed from the parser. // This will be removed once unified collections is implemented. // Determine if this is a set or map based on type args and content // TODO(danrubel): Since type resolution is needed to disambiguate // set or map in some situations, consider always deferring determination // until the type resolution phase. final int typeArgCount = typeArguments?.length; bool isSet = typeArgCount == 1 ? true : typeArgCount != null ? false : null; for (int i = 0; i < setOrMapEntries.length; ++i) { if (setOrMapEntries[i] is! MapEntry && !isConvertibleToMapEntry(setOrMapEntries[i])) { hasSetEntry = true; } } // TODO(danrubel): If the type arguments are not known (null) then // defer set/map determination until after type resolution as per the // unified collection spec: https://github.com/dart-lang/language/pull/200 // rather than trying to guess as done below. isSet ??= hasSetEntry; if (isSet) { buildLiteralSet(typeArguments, constKeyword, leftBrace, setOrMapEntries); } else { List<MapEntry> mapEntries = new List<MapEntry>(setOrMapEntries.length); for (int i = 0; i < setOrMapEntries.length; ++i) { if (setOrMapEntries[i] is MapEntry) { mapEntries[i] = setOrMapEntries[i]; } else { mapEntries[i] = convertToMapEntry(setOrMapEntries[i], this); } } buildLiteralMap(typeArguments, constKeyword, leftBrace, mapEntries); } } @override void handleLiteralBool(Token token) { debugEvent("LiteralBool"); bool value = optional("true", token); assert(value || optional("false", token)); push(forest.createBoolLiteral(offsetForToken(token), value)); } @override void handleLiteralDouble(Token token) { debugEvent("LiteralDouble"); push(forest.createDoubleLiteral( offsetForToken(token), double.parse(token.lexeme))); } @override void handleLiteralNull(Token token) { debugEvent("LiteralNull"); push(forest.createNullLiteral(offsetForToken(token))); } void buildLiteralMap(List<UnresolvedType> typeArguments, Token constKeyword, Token leftBrace, List<MapEntry> entries) { DartType keyType; DartType valueType; if (typeArguments != null) { if (typeArguments.length != 2) { keyType = const InvalidType(); valueType = const InvalidType(); } else { keyType = buildDartType(typeArguments[0]); valueType = buildDartType(typeArguments[1]); keyType = instantiateToBounds(keyType, coreTypes.objectClass); valueType = instantiateToBounds(valueType, coreTypes.objectClass); } } else { DartType implicitTypeArgument = this.implicitTypeArgument; keyType = implicitTypeArgument; valueType = implicitTypeArgument; } Expression node = forest.createMapLiteral( // TODO(johnniwinther): The file offset computed below will not be // correct if there are type arguments but no `const` keyword. offsetForToken(constKeyword ?? leftBrace), keyType, valueType, entries, isConst: constKeyword != null || constantContext == ConstantContext.inferred); libraryBuilder.checkBoundsInMapLiteral(node, typeEnvironment, uri); push(node); } @override void handleLiteralMapEntry(Token colon, Token endToken) { debugEvent("LiteralMapEntry"); Expression value = popForValue(); Expression key = popForValue(); push(forest.createMapEntry(offsetForToken(colon), key, 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.createSymbolLiteral( offsetForToken(hashToken), symbolPartToString(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.createSymbolLiteral(offsetForToken(hashToken), value)); } } @override void handleNonNullAssertExpression(Token bang) { assert(checkState(bang, [ unionOfKinds([ValueKind.Expression, ValueKind.Generator]) ])); if (!libraryBuilder.loader.target.enableNonNullable) { reportNonNullAssertExpressionNotEnabled(bang); } Object operand = pop(); Expression expression; if (operand is Generator) { expression = operand.buildSimpleRead(); } else { assert(operand is Expression); expression = operand; } push(forest.createNullCheck(offsetForToken(bang), expression)); } @override void handleType(Token beginToken, Token questionMark) { // TODO(ahe): The scope is wrong for return types of generic functions. debugEvent("Type"); if (!libraryBuilder.loader.target.enableNonNullable) { reportErrorIfNullableType(questionMark); } bool isMarkedAsNullable = questionMark != null; List<UnresolvedType> 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); Message message = fasta.templateNotAType.withArguments(displayName); libraryBuilder.addProblem( message, offset, lengthOfSpan(beginToken, suffix), uri); push(new UnresolvedType( new NamedTypeBuilder(name, libraryBuilder.nullableBuilderIfTrue(isMarkedAsNullable), null) ..bind(new InvalidTypeBuilder( name, message.withLocation( uri, offset, lengthOfSpan(beginToken, suffix)))), offset, uri)); return; } } TypeBuilder result; if (name is Generator) { result = name.buildTypeWithResolvedArguments( libraryBuilder.nullableBuilderIfTrue(isMarkedAsNullable), arguments); if (result == null) { unhandled("null", "result", beginToken.charOffset, uri); } } else if (name is ProblemBuilder) { // TODO(ahe): Arguments could be passed here. libraryBuilder.addProblem( name.message, name.charOffset, name.name.length, name.fileUri); result = new NamedTypeBuilder(name.name, libraryBuilder.nullableBuilderIfTrue(isMarkedAsNullable), null) ..bind(new InvalidTypeBuilder( name.name, name.message.withLocation( name.fileUri, name.charOffset, name.name.length))); } else { unhandled( "${name.runtimeType}", "handleType", beginToken.charOffset, uri); } push(new UnresolvedType(result, beginToken.charOffset, uri)); } @override void beginFunctionType(Token beginToken) { debugEvent("beginFunctionType"); } void enterFunctionTypeScope(List<TypeVariableBuilder> typeVariables) { debugEvent("enterFunctionTypeScope"); enterLocalScope(null, scope.createNestedScope("function-type scope", isModifiable: true)); if (typeVariables != null) { ScopeBuilder scopeBuilder = new ScopeBuilder(scope); for (TypeVariableBuilder builder in typeVariables) { String name = builder.name; TypeVariableBuilder existing = scopeBuilder[name]; if (existing == null) { scopeBuilder.addMember(name, builder); } else { reportDuplicatedDeclaration(existing, name, builder.charOffset); } } } } @override void endFunctionType(Token functionToken, Token questionMark) { debugEvent("FunctionType"); if (!libraryBuilder.loader.target.enableNonNullable) { reportErrorIfNullableType(questionMark); } FormalParameters formals = pop(); UnresolvedType returnType = pop(); List<TypeVariableBuilder> typeVariables = pop(); UnresolvedType type = formals.toFunctionType( returnType, libraryBuilder.nullableBuilderIfTrue(questionMark != null), typeVariables); exitLocalScope(); push(type); } @override void handleVoidKeyword(Token token) { debugEvent("VoidKeyword"); int offset = offsetForToken(token); // "void" is always nullable. push(new UnresolvedType( new NamedTypeBuilder("void", const NullabilityBuilder.nullable(), null) ..bind(new VoidTypeBuilder(const VoidType(), libraryBuilder, offset)), offset, uri)); } @override void handleAsOperator(Token operator) { debugEvent("AsOperator"); DartType type = buildDartType(pop()); libraryBuilder.checkBoundsInType( type, typeEnvironment, uri, operator.charOffset); Expression expression = popForValue(); Expression asExpression = forest.createAsExpression(offsetForToken(operator), expression, type); push(asExpression); } @override void handleIsOperator(Token isOperator, Token not) { debugEvent("IsOperator"); DartType type = buildDartType(pop()); Expression operand = popForValue(); bool isInverted = not != null; Expression isExpression = forest.createIsExpression( offsetForToken(isOperator), operand, type, notFileOffset: not != null ? offsetForToken(not) : null); libraryBuilder.checkBoundsInType( type, typeEnvironment, uri, isOperator.charOffset); if (operand is VariableGet) { typePromoter?.handleIsCheck(isExpression, isInverted, operand.variable, type, functionNestingLevel); } 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.createConditionalExpression( offsetForToken(question), condition, thenExpression, 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.createThrow(offsetForToken(throwToken), expression)); } } @override void beginFormalParameter(Token token, MemberKind kind, Token requiredToken, Token covariantToken, Token varFinalOrConst) { // TODO(danrubel): handle required token if (!libraryBuilder.loader.target.enableNonNullable) { reportNonNullableModifierError(requiredToken); } push((covariantToken != null ? covariantMask : 0) | Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme)); } @override void endFormalParameter( Token thisKeyword, Token periodAfterThis, Token nameToken, Token initializerStart, Token initializerEnd, FormalParameterKind kind, MemberKind memberKind) { debugEvent("FormalParameter"); if (thisKeyword != null) { if (!inConstructor) { handleRecoverableError(fasta.messageFieldInitializerOutsideConstructor, thisKeyword, thisKeyword); thisKeyword = null; } } Object nameNode = pop(); UnresolvedType 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; FormalParameterBuilder parameter; if (!inCatchClause && functionNestingLevel == 0 && memberKind != MemberKind.GeneralizedFunctionType) { FunctionBuilder member = this.member; parameter = member.getFormal(name.name); if (parameter == null) { push(new ParserRecovery(nameToken.charOffset)); return; } } else { parameter = new FormalParameterBuilder(null, modifiers, type?.builder, name?.name, libraryBuilder, offsetForToken(nameToken), uri); } VariableDeclaration variable = parameter.build(libraryBuilder, functionNestingLevel); Expression initializer = name?.initializer; if (initializer != null) { if (member is RedirectingFactoryBuilder) { RedirectingFactoryBuilder factory = member; addProblem( fasta.templateDefaultValueInRedirectingFactoryConstructor .withArguments(factory.redirectionTarget.fullNameForErrors), initializer.fileOffset, noLength); } else { variable.initializer = initializer..parent = variable; } } else if (kind != FormalParameterKind.mandatory) { variable.initializer ??= forest.createNullLiteral(noLocation) ..parent = variable; } if (annotations != null) { if (functionNestingLevel == 0) { inferAnnotations(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<FormalParameterBuilder> parameters = const FixedNullableList<FormalParameterBuilder>().pop(stack, count); if (parameters == null) { push(new ParserRecovery(offsetForToken(beginToken))); } else { for (FormalParameterBuilder parameter in parameters) { parameter.kind = kind; } push(parameters); } } @override void beginFunctionTypedFormalParameter(Token token) { debugEvent("beginFunctionTypedFormalParameter"); functionNestingLevel++; } @override void endFunctionTypedFormalParameter(Token nameToken, Token question) { debugEvent("FunctionTypedFormalParameter"); if (inCatchClause || functionNestingLevel != 0) { exitLocalScope(); } FormalParameters formals = pop(); UnresolvedType returnType = pop(); List<TypeVariableBuilder> typeVariables = pop(); if (!libraryBuilder.loader.target.enableNonNullable) { reportErrorIfNullableType(question); } UnresolvedType type = formals.toFunctionType(returnType, libraryBuilder.nullableBuilderIfTrue(question != null), typeVariables); exitLocalScope(); push(type); functionNestingLevel--; } @override void beginFormalParameterDefaultValueExpression() { super.push(constantContext); constantContext = ConstantContext.required; } @override void endFormalParameterDefaultValueExpression() { debugEvent("FormalParameterDefaultValueExpression"); Object defaultValueExpression = pop(); constantContext = pop(); push(defaultValueExpression); } @override void handleValuedFormalParameter(Token equals, Token token) { debugEvent("ValuedFormalParameter"); Expression initializer = popForValue(); Object name = pop(); if (name is ParserRecovery) { push(name); } else { 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<FormalParameterBuilder> optionals; int optionalsCount = 0; if (count > 0 && peek() is List<FormalParameterBuilder>) { optionals = pop(); count--; optionalsCount = optionals.length; } List<FormalParameterBuilder> parameters = const FixedNullableList<FormalParameterBuilder>() .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 ?? libraryBuilder, 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(); FormalParameterBuilder exception; FormalParameterBuilder stackTrace; List<Statement> compileTimeErrors; if (catchParameters?.parameters != null) { int parameterCount = catchParameters.parameters.length; if (parameterCount > 0) { exception = catchParameters.parameters[0]; exception.build(libraryBuilder, functionNestingLevel).type = exceptionType; if (parameterCount > 1) { stackTrace = catchParameters.parameters[1]; stackTrace.build(libraryBuilder, functionNestingLevel).type = coreTypes.stackTraceRawType(libraryBuilder.nonNullable); } } if (parameterCount > 2) { // If parameterCount is 0, the parser reported an error already. if (parameterCount != 0) { for (int i = 2; i < parameterCount; i++) { FormalParameterBuilder parameter = catchParameters.parameters[i]; compileTimeErrors ??= <Statement>[]; compileTimeErrors.add(buildProblemStatement( fasta.messageCatchSyntaxExtraParameters, parameter.charOffset, length: parameter.name.length)); } } } } push(forest.createCatch( offsetForToken(onKeyword ?? catchKeyword), exceptionType, exception?.target, stackTrace?.target, coreTypes.stackTraceRawType(libraryBuilder.nonNullable), body)); if (compileTimeErrors == null) { push(NullValue.Block); } else { push(forest.createBlock(noLocation, compileTimeErrors)); } } @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.createTryStatement( offsetForToken(tryKeyword), tryBlock, catchBlocks, finallyBlock); if (compileTimeErrors != null) { compileTimeErrors.add(tryStatement); push(forest.createBlock(noLocation, compileTimeErrors)); } else { push(tryStatement); } } @override void handleIndexedExpression( Token openSquareBracket, Token closeSquareBracket) { assert(checkState(openSquareBracket, [ unionOfKinds([ValueKind.Expression, ValueKind.Generator]), unionOfKinds( [ValueKind.Expression, ValueKind.Generator, ValueKind.Initializer]) ])); debugEvent("IndexedExpression"); Expression index = popForValue(); Object receiver = pop(); if (receiver is Generator) { push(receiver.buildIndexedAccess(index, openSquareBracket)); } else if (receiver is Expression) { push(IndexedAccessGenerator.make( this, openSquareBracket, receiver, index, null, null)); } else { assert(receiver is Initializer); 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.createNot(offsetForToken(token), toValue(receiver))); } 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.createThisExpression(receiver.fileOffset); } else { receiverValue = toValue(receiver); } push(buildMethodInvocation(receiverValue, new Name(operator), forest.createArgumentsEmpty(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, uri); } @override void handleUnaryPrefixAssignmentExpression(Token token) { debugEvent("UnaryPrefixAssignmentExpression"); Object generator = pop(); if (generator is Generator) { push(generator.buildPrefixIncrement(incrementOperator(token), offset: token.charOffset)); } else { push(wrapInProblem( toValue(generator), fasta.messageNotAnLvalue, noLength)); } } @override void handleUnaryPostfixAssignmentExpression(Token token) { debugEvent("UnaryPostfixAssignmentExpression"); Object generator = pop(); if (generator is Generator) { push(new DelayedPostfixIncrement( this, token, generator, incrementOperator(token), null)); } else { push(wrapInProblem( toValue(generator), fasta.messageNotAnLvalue, noLength)); } } @override void endConstructorReference( Token start, Token periodBeforeName, Token endToken) { debugEvent("ConstructorReference"); pushQualifiedReference(start, periodBeforeName); } /// A qualified reference is something that matches one of: /// /// identifier /// identifier typeArguments? '.' identifier /// identifier '.' identifier typeArguments? '.' identifier /// /// That is, one to three identifiers separated by periods and optionally one /// list of type arguments. /// /// A qualified reference can be used to represent both a reference to /// compile-time constant variable (metadata) or a constructor reference /// (used by metadata, new/const expression, and redirecting factories). /// /// Note that the parser will report errors if metadata includes type /// arguments, but will other preserve them for error recovery. /// /// A constructor reference can contain up to three identifiers: /// /// a) type typeArguments? /// b) type typeArguments? '.' name /// c) prefix '.' type typeArguments? /// d) prefix '.' type typeArguments? '.' name /// /// This isn't a legal constructor reference: /// /// type '.' name typeArguments? /// /// But the parser can't tell this from type c) above. /// /// This method pops 2 (or 3 if `periodBeforeName != null`) values from the /// stack and pushes 3 values: a generator (the type in a constructor /// reference, or an expression in metadata), a list of type arguments, and a /// name. void pushQualifiedReference(Token start, Token periodBeforeName) { assert(checkState(start, [ /*suffix*/ if (periodBeforeName != null) ValueKind.Identifier, /*type arguments*/ ValueKind.TypeArgumentsOrNull, /*type*/ unionOfKinds([ ValueKind.Generator, ValueKind.QualifiedName, ValueKind.ProblemBuilder, ValueKind.ParserRecovery ]) ])); Identifier suffix = popIfNotNull(periodBeforeName); Identifier identifier; List<UnresolvedType> typeArguments = pop(); Object type = pop(); if (type is QualifiedName) { identifier = type; QualifiedName qualified = type; Object qualifier = qualified.qualifier; assert(checkValue( start, unionOfKinds([ValueKind.Generator, ValueKind.ProblemBuilder]), qualifier)); if (qualifier is TypeUseGenerator) { type = qualifier; if (typeArguments != null) { // TODO(ahe): Point to the type arguments instead. addProblem(fasta.messageConstructorWithTypeArguments, identifier.charOffset, identifier.name.length); } } else if (qualifier is Generator) { type = qualifier.qualifiedLookup(deprecated_extractToken(identifier)); identifier = null; } else if (qualifier is ProblemBuilder) { type = qualifier; } else { unhandled("${qualifier.runtimeType}", "pushQualifiedReference", start.charOffset, uri); } } String name; if (identifier != null && suffix != null) { name = "${identifier.name}.${suffix.name}"; } else if (identifier != null) { name = identifier.name; } else if (suffix != null) { name = suffix.name; } else { name = ""; } push(type); push(typeArguments ?? NullValue.TypeArguments); push(name); push(suffix ?? identifier ?? NullValue.Identifier); assert(checkState(start, [ /*constructor name identifier*/ ValueKind.IdentifierOrNull, /*constructor name*/ ValueKind.Name, /*type arguments*/ ValueKind.TypeArgumentsOrNull, /*class*/ unionOfKinds([ ValueKind.Generator, ValueKind.ProblemBuilder, ValueKind.ParserRecovery ]), ])); } @override Expression buildStaticInvocation(Member target, Arguments arguments, {Constness constness: Constness.implicit, int charOffset: -1, int charLength: noLength}) { // The argument checks for the initial target of redirecting factories // invocations are skipped in Dart 1. List<TypeParameter> typeParameters = target.function.typeParameters; if (target is Constructor) { assert(!target.enclosingClass.isAbstract); typeParameters = target.enclosingClass.typeParameters; } LocatedMessage argMessage = checkArgumentsForFunction( target.function, arguments, charOffset, typeParameters); if (argMessage != null) { return throwNoSuchMethodError(forest.createNullLiteral(charOffset), target.name.name, arguments, charOffset, candidate: target, message: argMessage); } bool isConst = constness == Constness.explicitConst || constantContext != ConstantContext.none; if (target is Constructor) { if (constantContext == ConstantContext.required && constness == Constness.implicit) { addProblem(fasta.messageMissingExplicitConst, charOffset, charLength); } if (isConst && !target.isConst) { return buildProblem( fasta.messageNonConstConstructor, charOffset, charLength); } ConstructorInvocation node = new ConstructorInvocation(target, arguments, isConst: isConst) ..fileOffset = charOffset; libraryBuilder.checkBoundsInConstructorInvocation( node, typeEnvironment, uri); return node; } else { Procedure procedure = target; if (procedure.isFactory) { if (constantContext == ConstantContext.required && constness == Constness.implicit) { addProblem(fasta.messageMissingExplicitConst, charOffset, charLength); } if (isConst && !procedure.isConst) { return buildProblem( fasta.messageNonConstFactory, charOffset, charLength); } StaticInvocation node = new FactoryConstructorInvocationJudgment( target, arguments, isConst: isConst) ..fileOffset = charOffset; libraryBuilder.checkBoundsInFactoryInvocation( node, typeEnvironment, uri); return node; } else { assert(constness == Constness.implicit); StaticInvocation node = new StaticInvocation(target, arguments, isConst: false) ..fileOffset = charOffset; libraryBuilder.checkBoundsInStaticInvocation( node, typeEnvironment, uri); return node; } } } Expression buildExtensionMethodInvocation( int fileOffset, Procedure target, Arguments arguments, {bool isTearOff}) { List<TypeParameter> typeParameters = target.function.typeParameters; LocatedMessage argMessage = checkArgumentsForFunction( target.function, arguments, fileOffset, typeParameters); if (argMessage != null) { return throwNoSuchMethodError(forest.createNullLiteral(fileOffset), target.name.name, arguments, fileOffset, candidate: target, message: argMessage); } Expression node; if (isTearOff) { node = new ExtensionTearOff(target, arguments); } else { node = new StaticInvocation(target, arguments); } node.fileOffset = fileOffset; return node; } @override LocatedMessage checkArgumentsForFunction(FunctionNode function, Arguments arguments, int offset, List<TypeParameter> typeParameters) { if (forest.argumentsPositional(arguments).length < function.requiredParameterCount) { return fasta.templateTooFewArguments .withArguments(function.requiredParameterCount, forest.argumentsPositional(arguments).length) .withLocation(uri, arguments.fileOffset, noLength); } if (forest.argumentsPositional(arguments).length > function.positionalParameters.length) { return fasta.templateTooManyArguments .withArguments(function.positionalParameters.length, forest.argumentsPositional(arguments).length) .withLocation(uri, arguments.fileOffset, noLength); } List<Object> named = forest.argumentsNamed(arguments); if (named.isNotEmpty) { Set<String> names = new Set.from(function.namedParameters.map((a) => a.name)); for (NamedExpression argument in named) { if (!names.contains(argument.name)) { return fasta.templateNoSuchNamedParameter .withArguments(argument.name) .withLocation(uri, argument.fileOffset, argument.name.length); } } } List<DartType> types = forest.argumentsTypeArguments(arguments); if (typeParameters.length != types.length) { if (types.length == 0) { // Expected `typeParameters.length` type arguments, but none given, so // we use type inference. } else { // A wrong (non-zero) amount of type arguments given. That's an error. // TODO(jensj): Position should be on type arguments instead. return fasta.templateTypeArgumentMismatch .withArguments(typeParameters.length) .withLocation(uri, offset, noLength); } } return null; } @override LocatedMessage checkArgumentsForType( FunctionType function, Arguments arguments, int offset) { if (forest.argumentsPositional(arguments).length < function.requiredParameterCount) { return fasta.templateTooFewArguments .withArguments(function.requiredParameterCount, forest.argumentsPositional(arguments).length) .withLocation(uri, arguments.fileOffset, noLength); } if (forest.argumentsPositional(arguments).length > function.positionalParameters.length) { return fasta.templateTooManyArguments .withArguments(function.positionalParameters.length, forest.argumentsPositional(arguments).length) .withLocation(uri, arguments.fileOffset, noLength); } List<Object> named = forest.argumentsNamed(arguments); if (named.isNotEmpty) { Set<String> names = new Set.from(function.namedParameters.map((a) => a.name)); for (NamedExpression argument in named) { if (!names.contains(argument.name)) { return fasta.templateNoSuchNamedParameter .withArguments(argument.name) .withLocation(uri, argument.fileOffset, argument.name.length); } } } List<Object> types = forest.argumentsTypeArguments(arguments); List<TypeParameter> typeParameters = function.typeParameters; if (typeParameters.length != types.length && types.length != 0) { // A wrong (non-zero) amount of type arguments given. That's an error. // TODO(jensj): Position should be on type arguments instead. return fasta.templateTypeArgumentMismatch .withArguments(typeParameters.length) .withLocation(uri, offset, noLength); } return null; } @override void beginNewExpression(Token token) { debugEvent("beginNewExpression"); super.push(constantContext); if (constantContext != ConstantContext.none) { addProblem( fasta.templateNotConstantExpression.withArguments('New expression'), token.charOffset, token.length); } constantContext = ConstantContext.none; } @override void beginConstExpression(Token token) { debugEvent("beginConstExpression"); super.push(constantContext); constantContext = ConstantContext.inferred; } @override void beginConstLiteral(Token token) { debugEvent("beginConstLiteral"); super.push(constantContext); constantContext = ConstantContext.inferred; } @override void beginImplicitCreationExpression(Token token) { debugEvent("beginImplicitCreationExpression"); super.push(constantContext); } @override void endConstLiteral(Token token) { debugEvent("endConstLiteral"); Object literal = pop(); constantContext = pop(); push(literal); } @override void endNewExpression(Token token) { debugEvent("NewExpression"); _buildConstructorReferenceInvocation( token.next, token.offset, Constness.explicitNew); } void _buildConstructorReferenceInvocation( Token nameToken, int offset, Constness constness) { assert(checkState(nameToken, [ /*arguments*/ ValueKind.Arguments, /*constructor name identifier*/ ValueKind.IdentifierOrNull, /*constructor name*/ ValueKind.Name, /*type arguments*/ ValueKind.TypeArgumentsOrNull, /*class*/ unionOfKinds([ ValueKind.Generator, ValueKind.ProblemBuilder, ValueKind.ParserRecovery ]), ])); Arguments arguments = pop(); Identifier nameLastIdentifier = pop(NullValue.Identifier); Token nameLastToken = deprecated_extractToken(nameLastIdentifier) ?? nameToken; String name = pop(); List<UnresolvedType> typeArguments = pop(); Object type = pop(); ConstantContext savedConstantContext = pop(); if (type is Generator) { push(type.invokeConstructor( typeArguments, name, arguments, nameToken, nameLastToken, constness)); } else if (type is ParserRecovery) { push(new ParserErrorGenerator( this, nameToken, fasta.messageSyntheticToken)); } else { String typeName; if (type is ProblemBuilder) { typeName = type.fullNameForErrors; } push(throwNoSuchMethodError(forest.createNullLiteral(offset), debugName(typeName, name), arguments, nameToken.charOffset)); } constantContext = savedConstantContext; } @override void endImplicitCreationExpression(Token token) { debugEvent("ImplicitCreationExpression"); _buildConstructorReferenceInvocation( token, token.offset, Constness.implicit); } @override Expression buildConstructorInvocation( TypeDeclarationBuilder type, Token nameToken, Token nameLastToken, Arguments arguments, String name, List<UnresolvedType> typeArguments, int charOffset, Constness constness) { if (arguments == null) { return buildProblem(fasta.messageMissingArgumentList, nameToken.charOffset, nameToken.length); } if (name.isNotEmpty && arguments.types.isNotEmpty) { // TODO(ahe): Point to the type arguments instead. addProblem(fasta.messageConstructorWithTypeArguments, nameToken.charOffset, nameToken.length); } if (typeArguments != null) { assert(forest.argumentsTypeArguments(arguments).isEmpty); forest.argumentsSetTypeArguments( arguments, buildDartTypeArguments(typeArguments)); } String errorName; LocatedMessage message; if (type is ClassBuilder) { if (type is EnumBuilder) { return buildProblem(fasta.messageEnumInstantiation, nameToken.charOffset, nameToken.length); } Builder b = type.findConstructorOrFactory(name, charOffset, uri, libraryBuilder); Member target = b?.target; if (b == null) { // Not found. Reported below. } else if (b is ProblemBuilder) { message = b.message.withLocation(uri, charOffset, noLength); } else if (b.isConstructor) { if (type.isAbstract) { return evaluateArgumentsBefore( arguments, buildAbstractClassInstantiationError( fasta.templateAbstractClassInstantiation .withArguments(type.name), type.name, nameToken.charOffset)); } } if (target is Constructor || (target is Procedure && target.kind == ProcedureKind.Factory)) { Expression invocation; invocation = buildStaticInvocation(target, arguments, constness: constness, charOffset: nameToken.charOffset, charLength: nameToken.length); if (invocation is StaticInvocation && isRedirectingFactory(target, helper: this)) { redirectingFactoryInvocations.add(invocation); } return invocation; } else { errorName ??= debugName(type.name, name); } } else if (type is InvalidTypeBuilder) { LocatedMessage message = type.message; return evaluateArgumentsBefore( arguments, buildProblem(message.messageObject, nameToken.charOffset, nameToken.lexeme.length)); } else { errorName = debugName(type.fullNameForErrors, name); } errorName ??= name; return throwNoSuchMethodError(forest.createNullLiteral(charOffset), errorName, arguments, nameLastToken.charOffset, message: message); } @override void endConstExpression(Token token) { debugEvent("endConstExpression"); _buildConstructorReferenceInvocation( token.next, token.offset, Constness.explicitConst); } @override void beginIfControlFlow(Token ifToken) { // TODO(danrubel): consider removing this when control flow support is added // if the ifToken is not needed for error reporting push(ifToken); } @override void beginThenControlFlow(Token token) { Expression condition = popForValue(); enterThenForTypePromotion(condition); push(condition); super.beginThenControlFlow(token); } @override void handleElseControlFlow(Token elseToken) { typePromoter?.enterElse(); } @override void endIfControlFlow(Token token) { debugEvent("endIfControlFlow"); Object entry = pop(); Object condition = pop(); // parenthesized expression Token ifToken = pop(); typePromoter?.enterElse(); typePromoter?.exitConditional(); transformCollections = true; if (entry is MapEntry) { push(forest.createIfMapEntry( offsetForToken(ifToken), toValue(condition), entry)); } else { push(forest.createIfElement( offsetForToken(ifToken), toValue(condition), toValue(entry))); } } @override void endIfElseControlFlow(Token token) { debugEvent("endIfElseControlFlow"); Object elseEntry = pop(); // else entry Object thenEntry = pop(); // then entry Object condition = pop(); // parenthesized expression Token ifToken = pop(); typePromoter?.exitConditional(); transformCollections = true; if (thenEntry is MapEntry) { if (elseEntry is MapEntry) { push(forest.createIfMapEntry( offsetForToken(ifToken), toValue(condition), thenEntry, elseEntry)); } else if (elseEntry is SpreadElement) { push(forest.createIfMapEntry( offsetForToken(ifToken), toValue(condition), thenEntry, new SpreadMapEntry(elseEntry.expression, elseEntry.isNullAware))); } else { int offset = elseEntry is Expression ? elseEntry.fileOffset : offsetForToken(ifToken); push(new MapEntry( buildProblem(fasta.templateExpectedAfterButGot.withArguments(':'), offset, 1), new NullLiteral()) ..fileOffset = offsetForToken(ifToken)); } } else if (elseEntry is MapEntry) { if (thenEntry is SpreadElement) { push(forest.createIfMapEntry( offsetForToken(ifToken), toValue(condition), new SpreadMapEntry(thenEntry.expression, thenEntry.isNullAware), elseEntry)); } else { int offset = thenEntry is Expression ? thenEntry.fileOffset : offsetForToken(ifToken); push(new MapEntry( buildProblem(fasta.templateExpectedAfterButGot.withArguments(':'), offset, 1), new NullLiteral()) ..fileOffset = offsetForToken(ifToken)); } } else { push(forest.createIfElement(offsetForToken(ifToken), toValue(condition), toValue(thenEntry), toValue(elseEntry))); } } @override void handleSpreadExpression(Token spreadToken) { debugEvent("SpreadExpression"); Object expression = pop(); transformCollections = true; push(forest.createSpreadElement( offsetForToken(spreadToken), toValue(expression), isNullAware: spreadToken.lexeme == '...?')); } @override void endTypeArguments(int count, Token beginToken, Token endToken) { debugEvent("TypeArguments"); push(const FixedNullableList<UnresolvedType>().pop(stack, count) ?? NullValue.TypeArguments); } @override void handleInvalidTypeArguments(Token token) { debugEvent("InvalidTypeArguments"); pop(NullValue.TypeArguments); } @override void handleThisExpression(Token token, IdentifierContext context) { debugEvent("ThisExpression"); if (context.isScopeReference && isDeclarationInstanceContext) { if (extensionThis != null) { push(_createReadOnlyVariableAccess( extensionThis, token, offsetForToken(token), 'this')); } else { push(new ThisAccessGenerator( this, token, inInitializer, inFieldInitializer)); } } else { push(new IncompleteErrorGenerator( this, token, fasta.messageThisAsIdentifier)); } } @override void handleSuperExpression(Token token, IdentifierContext context) { debugEvent("SuperExpression"); if (context.isScopeReference && isDeclarationInstanceContext && extensionThis == null) { Member member = this.member.target; member.transformerFlags |= TransformerFlag.superCalls; push(new ThisAccessGenerator( this, token, inInitializer, inFieldInitializer, isSuper: true)); } else { push(new IncompleteErrorGenerator( this, token, fasta.messageSuperAsIdentifier)); } } @override void handleNamedArgument(Token colon) { debugEvent("NamedArgument"); Expression value = popForValue(); Identifier identifier = pop(); push(new NamedExpression(identifier.name, value) ..fileOffset = identifier.charOffset); } @override void endFunctionName(Token beginToken, Token token) { debugEvent("FunctionName"); Identifier name = pop(); Token nameToken = deprecated_extractToken(name); VariableDeclaration variable = new VariableDeclarationImpl( name.name, functionNestingLevel, forSyntheticToken: nameToken.isSynthetic, isFinal: true, isLocalFunction: true) ..fileOffset = name.charOffset; // TODO(ahe): Why are we looking up in local scope, but declaring in parent // scope? Builder existing = scope.local[name.name]; if (existing != null) { reportDuplicatedDeclaration(existing, name.name, name.charOffset); } push(new FunctionDeclarationImpl( variable, // The function node is created later. null) ..fileOffset = beginToken.charOffset); declareVariable(variable, scope.parent); } void enterFunction() { debugEvent("enterFunction"); functionNestingLevel++; push(switchScope ?? NullValue.SwitchScope); switchScope = null; push(inCatchBlock); inCatchBlock = false; } void exitFunction() { debugEvent("exitFunction"); functionNestingLevel--; inCatchBlock = pop(); switchScope = pop(); List<TypeVariableBuilder> typeVariables = pop(); exitLocalScope(); push(typeVariables ?? NullValue.TypeVariables); } @override void beginLocalFunctionDeclaration(Token token) { debugEvent("beginLocalFunctionDeclaration"); enterFunction(); } @override void beginNamedFunctionExpression(Token token) { debugEvent("beginNamedFunctionExpression"); List<TypeVariableBuilder> typeVariables = pop(); // Create an additional scope in which the named function expression is // declared. enterLocalScope("named function"); push(typeVariables ?? NullValue.TypeVariables); enterFunction(); } @override void beginFunctionExpression(Token token) { debugEvent("beginFunctionExpression"); enterFunction(); } void pushNamedFunction(Token token, bool isFunctionExpression) { Statement body = popStatement(); AsyncMarker asyncModifier = pop(); exitLocalScope(); FormalParameters formals = pop(); Object declaration = pop(); UnresolvedType returnType = pop(); bool hasImplicitReturnType = returnType == null; exitFunction(); List<TypeVariableBuilder> typeParameters = pop(); List<Expression> annotations; if (!isFunctionExpression) { annotations = pop(); // Metadata. } FunctionNode function = formals.buildFunctionNode(libraryBuilder, returnType, typeParameters, asyncModifier, body, token.charOffset); if (declaration is FunctionDeclaration) { VariableDeclaration variable = declaration.variable; if (annotations != null) { for (Expression annotation in annotations) { variable.addAnnotation(annotation); } } FunctionDeclarationImpl.setHasImplicitReturnType( declaration, hasImplicitReturnType); if (!hasImplicitReturnType) { checkAsyncReturnType(asyncModifier, function.returnType, variable.fileOffset, variable.name.length); } variable.type = function.functionType; if (isFunctionExpression) { Expression oldInitializer = variable.initializer; variable.initializer = new FunctionExpression(function) ..parent = variable ..fileOffset = formals.charOffset; exitLocalScope(); Expression expression = new NamedFunctionExpressionJudgment(variable); if (oldInitializer != null) { // This must have been a compile-time error. Expression error = oldInitializer; assert(isErroneousNode(error)); int offset = expression.fileOffset; push(new Let( new VariableDeclaration.forValue(error)..fileOffset = offset, expression) ..fileOffset = offset); } else { push(expression); } } else { declaration.function = function; function.parent = declaration; if (variable.initializer != null) { // This must have been a compile-time error. assert(isErroneousNode(variable.initializer)); push(forest.createBlock(declaration.fileOffset, <Statement>[ forest.createExpressionStatement( offsetForToken(token), variable.initializer), declaration ])); variable.initializer = null; } else { push(declaration); } } } else { return unhandled("${declaration.runtimeType}", "pushNamedFunction", token.charOffset, uri); } } @override void endNamedFunctionExpression(Token endToken) { debugEvent("NamedFunctionExpression"); pushNamedFunction(endToken, true); } @override void endLocalFunctionDeclaration(Token token) { debugEvent("LocalFunctionDeclaration"); pushNamedFunction(token, false); } @override void endFunctionExpression(Token beginToken, Token token) { debugEvent("FunctionExpression"); Statement body = popStatement(); AsyncMarker asyncModifier = pop(); exitLocalScope(); FormalParameters formals = pop(); exitFunction(); List<TypeVariableBuilder> typeParameters = pop(); FunctionNode function = formals.buildFunctionNode(libraryBuilder, null, typeParameters, asyncModifier, body, token.charOffset) ..fileOffset = beginToken.charOffset; if (constantContext != ConstantContext.none) { push(buildProblem(fasta.messageNotAConstantExpression, formals.charOffset, formals.length)); } else { push(new FunctionExpression(function) ..fileOffset = offsetForToken(beginToken)); } } @override void endDoWhileStatement( Token doKeyword, Token whileKeyword, Token endToken) { debugEvent("DoWhileStatement"); Expression condition = popForValue(); Statement body = popStatement(); JumpTarget continueTarget = exitContinueTarget(); JumpTarget breakTarget = exitBreakTarget(); if (continueTarget.hasUsers) { body = forest.createLabeledStatement(body); continueTarget.resolveContinues(forest, body); } Statement result = forest.createDoStatement(offsetForToken(doKeyword), body, condition); if (breakTarget.hasUsers) { result = forest.createLabeledStatement(result); breakTarget.resolveBreaks(forest, result); } exitLoopOrSwitch(result); } @override void beginForInExpression(Token token) { enterLocalScope(null, scope.parent); } @override void endForInExpression(Token token) { debugEvent("ForInExpression"); Expression expression = popForValue(); exitLocalScope(); push(expression ?? NullValue.Expression); } @override void handleForInLoopParts(Token awaitToken, Token forToken, Token leftParenthesis, Token inKeyword) { push(awaitToken ?? NullValue.AwaitToken); push(forToken); push(inKeyword); } @override void endForInControlFlow(Token token) { debugEvent("ForInControlFlow"); Object entry = pop(); Token inToken = pop(); Token forToken = pop(); Token awaitToken = pop(NullValue.AwaitToken); Expression iterable = popForValue(); Object lvalue = pop(); // lvalue exitLocalScope(); if (constantContext != ConstantContext.none) { handleRecoverableError( fasta.templateCantUseControlFlowOrSpreadAsConstant .withArguments(forToken), forToken, forToken); push(invalidCollectionElement); return; } transformCollections = true; VariableDeclaration variable = buildForInVariable(forToken, lvalue); Expression problem = checkForInVariable(lvalue, variable, forToken); Statement prologue = buildForInBody(lvalue, variable, forToken, inToken); if (entry is MapEntry) { push(forest.createForInMapEntry(offsetForToken(forToken), variable, iterable, prologue, entry, problem, isAsync: awaitToken != null)); } else { push(forest.createForInElement(offsetForToken(forToken), variable, iterable, prologue, toValue(entry), problem, isAsync: awaitToken != null)); } } VariableDeclaration buildForInVariable(Token token, Object lvalue) { if (lvalue is VariableDeclaration) return lvalue; return forest.createVariableDeclaration( offsetForToken(token), null, functionNestingLevel, isFinal: true); } Expression checkForInVariable( Object lvalue, VariableDeclaration variable, Token forToken) { if (lvalue is VariableDeclaration) { if (variable.isConst) { return buildProblem(fasta.messageForInLoopWithConstVariable, variable.fileOffset, variable.name.length); } } else if (lvalue is! Generator) { Message message = forest.isVariablesDeclaration(lvalue) ? fasta.messageForInLoopExactlyOneVariable : fasta.messageForInLoopNotAssignable; Token token = forToken.next.next; return buildProblem( message, offsetForToken(token), lengthForToken(token)); } return null; } Statement buildForInBody(Object lvalue, VariableDeclaration variable, Token forToken, Token inKeyword) { if (lvalue is VariableDeclaration) return null; if (lvalue is Generator) { /// We are in this case, where `lvalue` isn't a [VariableDeclaration]: /// /// for (lvalue in expression) body /// /// This is normalized to: /// /// for (final #t in expression) { /// lvalue = #t; /// body; /// } TypePromotionFact fact = typePromoter?.getFactForAccess(variable, functionNestingLevel); TypePromotionScope scope = typePromoter?.currentScope; Expression syntheticAssignment = lvalue.buildAssignment( new VariableGetImpl(variable, fact, scope) ..fileOffset = inKeyword.offset, voidContext: true); return forest.createExpressionStatement(noLocation, syntheticAssignment); } Message message = forest.isVariablesDeclaration(lvalue) ? fasta.messageForInLoopExactlyOneVariable : fasta.messageForInLoopNotAssignable; Token token = forToken.next.next; Statement body; if (forest.isVariablesDeclaration(lvalue)) { body = forest.createBlock( noLocation, // New list because the declarations are not a growable list. new List<Statement>.from( forest.variablesDeclarationExtractDeclarations(lvalue))); } else { body = forest.createExpressionStatement(noLocation, lvalue); } return combineStatements( forest.createExpressionStatement( noLocation, buildProblem( message, offsetForToken(token), lengthForToken(token))), body); } @override void endForIn(Token endToken) { debugEvent("ForIn"); Statement body = popStatement(); Token inKeyword = pop(); Token forToken = pop(); Token awaitToken = pop(NullValue.AwaitToken); Expression expression = popForValue(); Object lvalue = pop(); exitLocalScope(); JumpTarget continueTarget = exitContinueTarget(); JumpTarget breakTarget = exitBreakTarget(); if (continueTarget.hasUsers) { body = forest.createLabeledStatement(body); continueTarget.resolveContinues(forest, body); } VariableDeclaration variable = buildForInVariable(forToken, lvalue); Expression problem = checkForInVariable(lvalue, variable, forToken); Statement prologue = buildForInBody(lvalue, variable, forToken, inKeyword); if (prologue != null) { if (prologue is Block) { if (body is Block) { for (Statement statement in body.statements) { prologue.addStatement(statement); } } else { prologue.addStatement(body); } body = prologue; } else { body = combineStatements(prologue, body); } } Statement result = new ForInStatement(variable, expression, body, isAsync: awaitToken != null) ..fileOffset = awaitToken?.charOffset ?? forToken.charOffset ..bodyOffset = body.fileOffset; // TODO(ahe): Isn't this redundant? if (breakTarget.hasUsers) { result = forest.createLabeledStatement(result); breakTarget.resolveBreaks(forest, result); } if (problem != null) { result = combineStatements( forest.createExpressionStatement(noLocation, problem), result); } exitLoopOrSwitch(result); } @override void handleLabel(Token token) { debugEvent("Label"); Identifier identifier = pop(); push(new Label(identifier.name, identifier.charOffset)); } @override void beginLabeledStatement(Token token, int labelCount) { debugEvent("beginLabeledStatement"); List<Label> labels = const FixedNullableList<Label>().pop(stack, labelCount); enterLocalScope(null, scope.createNestedLabelScope()); LabelTarget target = new LabelTarget(member, functionNestingLevel, token.charOffset); if (labels != null) { for (Label label in labels) { scope.declareLabel(label.name, target); } } push(target); } @override void endLabeledStatement(int labelCount) { debugEvent("LabeledStatement"); Statement statement = pop(); LabelTarget target = pop(); exitLocalScope(); if (target.breakTarget.hasUsers || target.continueTarget.hasUsers) { if (forest.isVariablesDeclaration(statement)) { internalProblem( fasta.messageInternalProblemLabelUsageInVariablesDeclaration, statement.fileOffset, uri); } if (statement is! LabeledStatement) { statement = forest.createLabeledStatement(statement); } target.breakTarget.resolveBreaks(forest, statement); target.continueTarget.resolveContinues(forest, statement); } push(statement); } @override void endRethrowStatement(Token rethrowToken, Token endToken) { debugEvent("RethrowStatement"); if (inCatchBlock) { push(forest.createRethrowStatement( offsetForToken(rethrowToken), offsetForToken(endToken))); } else { push(new ExpressionStatement(buildProblem(fasta.messageRethrowNotCatch, offsetForToken(rethrowToken), lengthForToken(rethrowToken))) ..fileOffset = offsetForToken(rethrowToken)); } } @override void handleFinallyBlock(Token finallyKeyword) { debugEvent("FinallyBlock"); // Do nothing, handled by [endTryStatement]. } @override void endWhileStatement(Token whileKeyword, Token endToken) { debugEvent("WhileStatement"); Statement body = popStatement(); Expression condition = popForValue(); JumpTarget continueTarget = exitContinueTarget(); JumpTarget breakTarget = exitBreakTarget(); if (continueTarget.hasUsers) { body = forest.createLabeledStatement(body); continueTarget.resolveContinues(forest, body); } Statement result = forest.createWhileStatement( offsetForToken(whileKeyword), condition, body); if (breakTarget.hasUsers) { result = forest.createLabeledStatement(result); breakTarget.resolveBreaks(forest, result); } exitLoopOrSwitch(result); } @override void handleEmptyStatement(Token token) { debugEvent("EmptyStatement"); push(forest.createEmptyStatement(offsetForToken(token))); } @override void beginAssert(Token assertKeyword, Assert kind) { debugEvent("beginAssert"); // If in an assert initializer, make sure [inInitializer] is false so we // use the formal parameter scope. If this is any other kind of assert, // inInitializer should be false anyway. inInitializer = false; } @override void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis, Token commaToken, Token semicolonToken) { debugEvent("Assert"); Expression message = popForValueIfNotNull(commaToken); Expression condition = popForValue(); int fileOffset = offsetForToken(assertKeyword); /// Return a representation of an assert that appears as a statement. Statement createAssertStatement() { // Compute start and end offsets for the condition expression. // This code is a temporary workaround because expressions don't carry // their start and end offsets currently. // // The token that follows leftParenthesis is considered to be the // first token of the condition. // TODO(ahe): this really should be condition.fileOffset. int startOffset = leftParenthesis.next.offset; int endOffset; // Search forward from leftParenthesis to find the last token of // the condition - which is a token immediately followed by a commaToken, // right parenthesis or a trailing comma. Token conditionBoundary = commaToken ?? leftParenthesis.endGroup; Token conditionLastToken = leftParenthesis; while (!conditionLastToken.isEof) { Token nextToken = conditionLastToken.next; if (nextToken == conditionBoundary) { break; } else if (optional(',', nextToken) && nextToken.next == conditionBoundary) { // The next token is trailing comma, which means current token is // the last token of the condition. break; } conditionLastToken = nextToken; } if (conditionLastToken.isEof) { endOffset = startOffset = -1; } else { endOffset = conditionLastToken.offset + conditionLastToken.length; } return forest.createAssertStatement( fileOffset, condition, message, startOffset, endOffset); } switch (kind) { case Assert.Statement: push(createAssertStatement()); break; case Assert.Expression: // The parser has already reported an error indicating that assert // cannot be used in an expression. push(buildProblem( fasta.messageAssertAsExpression, fileOffset, assertKeyword.length)); break; case Assert.Initializer: push(forest.createAssertInitializer( fileOffset, createAssertStatement())); break; } } @override void endYieldStatement(Token yieldToken, Token starToken, Token endToken) { debugEvent("YieldStatement"); push(forest.createYieldStatement(offsetForToken(yieldToken), popForValue(), isYieldStar: starToken != null)); } @override void beginSwitchBlock(Token token) { debugEvent("beginSwitchBlock"); enterLocalScope("switch block"); enterSwitchScope(); enterBreakTarget(token.charOffset); } @override void beginSwitchCase(int labelCount, int expressionCount, Token firstToken) { debugEvent("beginSwitchCase"); int count = labelCount + expressionCount; List<Object> labelsAndExpressions = const FixedNullableList<Object>().pop(stack, count); List<Label> labels = labelCount == 0 ? null : new List<Label>(labelCount); List<Expression> expressions = new List<Expression>.filled(expressionCount, null, growable: true); int labelIndex = 0; int expressionIndex = 0; if (labelsAndExpressions != null) { for (Object labelOrExpression in labelsAndExpressions) { if (labelOrExpression is Label) { labels[labelIndex++] = labelOrExpression; } else { expressions[expressionIndex++] = labelOrExpression; } } } assert(scope == switchScope); if (labels != null) { for (Label label in labels) { String labelName = label.name; if (scope.hasLocalLabel(labelName)) { // TODO(ahe): Should validate this is a goto target. if (!scope.claimLabel(labelName)) { addProblem( fasta.templateDuplicateLabelInSwitchStatement .withArguments(labelName), label.charOffset, labelName.length); } } else { scope.declareLabel( labelName, createGotoTarget(firstToken.charOffset)); } } } push(expressions); push(labels ?? NullValue.Labels); enterLocalScope("switch case"); } @override void endSwitchCase( int labelCount, int expressionCount, Token defaultKeyword, Token colonAfterDefault, int statementCount, Token firstToken, Token endToken) { debugEvent("SwitchCase"); // We always create a block here so that we later know that there's always // one synthetic block when we finish compiling the switch statement and // check this switch case to see if it falls through to the next case. Statement block = popBlock(statementCount, firstToken, null); exitLocalScope(); List<Label> labels = pop(); List<Expression> expressions = pop(); List<int> expressionOffsets = <int>[]; for (Expression expression in expressions) { expressionOffsets.add(expression.fileOffset); } push(new SwitchCase(expressions, expressionOffsets, block, isDefault: defaultKeyword != null) ..fileOffset = firstToken.charOffset); push(labels ?? NullValue.Labels); } @override void endSwitchStatement(Token switchKeyword, Token endToken) { debugEvent("SwitchStatement"); List<SwitchCase> cases = pop(); JumpTarget target = exitBreakTarget(); exitSwitchScope(); exitLocalScope(); Expression expression = popForValue(); Statement result = new SwitchStatement(expression, cases) ..fileOffset = switchKeyword.charOffset; if (target.hasUsers) { result = forest.createLabeledStatement(result); target.resolveBreaks(forest, result); } exitLoopOrSwitch(result); } @override void endSwitchBlock(int caseCount, Token beginToken, Token endToken) { debugEvent("SwitchBlock"); List<SwitchCase> cases = new List<SwitchCase>.filled(caseCount, null, growable: true); for (int i = caseCount - 1; i >= 0; i--) { List<Label> labels = pop(); SwitchCase current = cases[i] = pop(); if (labels != null) { for (Label label in labels) { JumpTarget target = switchScope.lookupLabel(label.name); if (target != null) { target.resolveGotos(forest, current); } } } } for (int i = 0; i < caseCount - 1; i++) { SwitchCase current = cases[i]; Block block = current.body; // [block] is a synthetic block that is added to handle variable // declarations in the switch case. TreeNode lastNode = block.statements.isEmpty ? null : block.statements.last; if (forest.isBlock(lastNode)) { // This is a non-synthetic block. Block block = lastNode; lastNode = block.statements.isEmpty ? null : block.statements.last; } if (lastNode is ExpressionStatement) { ExpressionStatement statement = lastNode; lastNode = statement.expression; } if (lastNode is! BreakStatement && lastNode is! ContinueSwitchStatement && lastNode is! Rethrow && lastNode is! ReturnStatement && !forest.isThrow(lastNode)) { block.addStatement( new ExpressionStatement(buildFallThroughError(current.fileOffset))); } } push(cases); } @override void handleCaseMatch(Token caseKeyword, Token colon) { debugEvent("CaseMatch"); // Do nothing. Handled by [handleSwitchCase]. } @override void handleBreakStatement( bool hasTarget, Token breakKeyword, Token endToken) { debugEvent("BreakStatement"); JumpTarget target = breakTarget; Identifier identifier; String name; if (hasTarget) { identifier = pop(); name = identifier.name; target = scope.lookupLabel(name); } if (target == null && name == null) { push(problemInLoopOrSwitch = buildProblemStatement( fasta.messageBreakOutsideOfLoop, breakKeyword.charOffset)); } else if (target == null || target is! JumpTarget || !target.isBreakTarget) { Token labelToken = breakKeyword.next; push(problemInLoopOrSwitch = buildProblemStatement( fasta.templateInvalidBreakTarget.withArguments(name), labelToken.charOffset, length: labelToken.length)); } else if (target.functionNestingLevel != functionNestingLevel) { push(buildProblemTargetOutsideLocalFunction(name, breakKeyword)); } else { Statement statement = forest.createBreakStatement(offsetForToken(breakKeyword), identifier); target.addBreak(statement); push(statement); } } Statement buildProblemTargetOutsideLocalFunction(String name, Token keyword) { Statement problem; bool isBreak = optional("break", keyword); if (name != null) { Template<Message Function(String)> template = isBreak ? fasta.templateBreakTargetOutsideFunction : fasta.templateContinueTargetOutsideFunction; problem = buildProblemStatement( template.withArguments(name), offsetForToken(keyword), length: lengthOfSpan(keyword, keyword.next)); } else { Message message = isBreak ? fasta.messageAnonymousBreakTargetOutsideFunction : fasta.messageAnonymousContinueTargetOutsideFunction; problem = buildProblemStatement(message, offsetForToken(keyword), length: lengthForToken(keyword)); } problemInLoopOrSwitch ??= problem; return problem; } @override void handleContinueStatement( bool hasTarget, Token continueKeyword, Token endToken) { debugEvent("ContinueStatement"); JumpTarget target = continueTarget; Identifier identifier; String name; if (hasTarget) { identifier = pop(); name = identifier.name; Builder namedTarget = scope.lookupLabel(identifier.name); if (namedTarget != null && namedTarget is! JumpTarget) { Token labelToken = continueKeyword.next; push(problemInLoopOrSwitch = buildProblemStatement( fasta.messageContinueLabelNotTarget, labelToken.charOffset, length: labelToken.length)); return; } target = namedTarget; if (target == null) { if (switchScope == null) { push(buildProblemStatement( fasta.templateLabelNotFound.withArguments(name), continueKeyword.next.charOffset)); return; } switchScope.forwardDeclareLabel( identifier.name, target = createGotoTarget(identifier.charOffset)); } if (target.isGotoTarget && target.functionNestingLevel == functionNestingLevel) { ContinueSwitchStatement statement = new ContinueSwitchStatement(null) ..fileOffset = continueKeyword.charOffset; target.addGoto(statement); push(statement); return; } } if (target == null) { push(problemInLoopOrSwitch = buildProblemStatement( fasta.messageContinueWithoutLabelInCase, continueKeyword.charOffset, length: continueKeyword.length)); } else if (!target.isContinueTarget) { Token labelToken = continueKeyword.next; push(problemInLoopOrSwitch = buildProblemStatement( fasta.templateInvalidContinueTarget.withArguments(name), labelToken.charOffset, length: labelToken.length)); } else if (target.functionNestingLevel != functionNestingLevel) { push(buildProblemTargetOutsideLocalFunction(name, continueKeyword)); } else { Statement statement = forest.createContinueStatement( offsetForToken(continueKeyword), identifier); target.addContinue(statement); push(statement); } } @override void beginTypeVariable(Token token) { debugEvent("beginTypeVariable"); Identifier name = pop(); List<Expression> annotations = pop(); TypeVariableBuilder variable = new TypeVariableBuilder(name.name, libraryBuilder, name.charOffset); if (annotations != null) { inferAnnotations(annotations); for (Expression annotation in annotations) { variable.parameter.addAnnotation(annotation); } } push(variable); } @override void handleTypeVariablesDefined(Token token, int count) { debugEvent("handleTypeVariablesDefined"); assert(count > 0); List<TypeVariableBuilder> typeVariables = const FixedNullableList<TypeVariableBuilder>().pop(stack, count); enterFunctionTypeScope(typeVariables); push(typeVariables); } @override void endTypeVariable( Token token, int index, Token extendsOrSuper, Token variance) { debugEvent("TypeVariable"); UnresolvedType bound = pop(); // Peek to leave type parameters on top of stack. List<TypeVariableBuilder> typeVariables = peek(); TypeVariableBuilder variable = typeVariables[index]; variable.bound = bound?.builder; if (variance != null) { variable.variance = Variance.fromString(variance.lexeme); } } @override void endTypeVariables(Token beginToken, Token endToken) { debugEvent("TypeVariables"); // Peek to leave type parameters on top of stack. List<TypeVariableBuilder> typeVariables = peek(); List<TypeBuilder> calculatedBounds = calculateBounds( typeVariables, libraryBuilder.loader.target.dynamicType, libraryBuilder.loader.target.bottomType, libraryBuilder.loader.target.objectClassBuilder); for (int i = 0; i < typeVariables.length; ++i) { typeVariables[i].defaultType = calculatedBounds[i]; typeVariables[i].defaultType.resolveIn(scope, typeVariables[i].charOffset, typeVariables[i].fileUri, libraryBuilder); typeVariables[i].finish( libraryBuilder, libraryBuilder.loader.target.objectClassBuilder, libraryBuilder.loader.target.dynamicType); } TypeVariableBuilder.finishNullabilities( libraryBuilder, libraryBuilder.pendingNullabilities); libraryBuilder.pendingNullabilities.clear(); } @override void handleVarianceModifier(Token variance) { if (!libraryBuilder.loader.target.enableVariance) { reportVarianceModifierNotEnabled(variance); } } @override void handleNoTypeVariables(Token token) { debugEvent("NoTypeVariables"); enterFunctionTypeScope(null); push(NullValue.TypeVariables); } List<TypeParameter> typeVariableBuildersToKernel( List<TypeVariableBuilder> typeVariableBuilders) { if (typeVariableBuilders == null) return null; List<TypeParameter> typeParameters = new List<TypeParameter>.filled( typeVariableBuilders.length, null, growable: true); int i = 0; for (TypeVariableBuilder builder in typeVariableBuilders) { typeParameters[i++] = builder.parameter; } return typeParameters; } @override void handleInvalidStatement(Token token, Message message) { Statement statement = pop(); push(new ExpressionStatement( buildProblem(message, statement.fileOffset, noLength))); } @override Expression buildProblem(Message message, int charOffset, int length, {List<LocatedMessage> context, bool suppressMessage: false}) { if (!suppressMessage) { addProblem(message, charOffset, length, wasHandled: true, context: context); } String text = libraryBuilder.loader.target.context .format(message.withLocation(uri, charOffset, length), Severity.error); InvalidExpression expression = new InvalidExpression(text) ..fileOffset = charOffset; return expression; } @override Expression wrapInProblem(Expression expression, Message message, int length, {List<LocatedMessage> context}) { int charOffset = expression.fileOffset; Severity severity = message.code.severity; if (severity == Severity.error || severity == Severity.errorLegacyWarning) { return wrapInLocatedProblem( expression, message.withLocation(uri, charOffset, length), context: context); } else { addProblem(message, charOffset, length, context: context); return expression; } } @override Expression wrapInLocatedProblem(Expression expression, LocatedMessage message, {List<LocatedMessage> context}) { // TODO(askesc): Produce explicit error expression wrapping the original. // See [issue 29717](https://github.com/dart-lang/sdk/issues/29717) int offset = expression.fileOffset; if (offset == -1) { offset = message.charOffset; } return new Let( new VariableDeclaration.forValue( buildProblem( message.messageObject, message.charOffset, message.length, context: context), type: const BottomType()) ..fileOffset = offset, expression); } Expression buildFallThroughError(int charOffset) { addProblem(fasta.messageSwitchCaseFallThrough, charOffset, noLength); // TODO(ahe): The following doesn't make sense for the Analyzer. It should // be moved to [Forest] or conditional on `forest is Fangorn`. // TODO(ahe): Compute a LocatedMessage above instead? Location location = messages.getLocationFromUri(uri, charOffset); return forest.createThrow( charOffset, buildStaticInvocation( libraryBuilder .loader.coreTypes.fallThroughErrorUrlAndLineConstructor, forest.createArguments(noLocation, <Expression>[ forest.createStringLiteral( charOffset, "${location?.file ?? uri}"), forest.createIntLiteral(charOffset, location?.line ?? 0), ]), constness: Constness.explicitNew, charOffset: charOffset)); } Expression buildAbstractClassInstantiationError( Message message, String className, [int charOffset = -1]) { addProblemErrorIfConst(message, charOffset, className.length); // TODO(ahe): The following doesn't make sense to Analyzer AST. Builder constructor = libraryBuilder.loader.getAbstractClassInstantiationError(); Expression invocation = buildStaticInvocation( constructor.target, forest.createArguments(charOffset, <Expression>[forest.createStringLiteral(charOffset, className)]), constness: Constness.explicitNew, charOffset: charOffset); return forest.createThrow(charOffset, invocation); } Statement buildProblemStatement(Message message, int charOffset, {List<LocatedMessage> context, int length, bool suppressMessage: false}) { length ??= noLength; return new ExpressionStatement(buildProblem(message, charOffset, length, context: context, suppressMessage: suppressMessage)); } Statement wrapInProblemStatement(Statement statement, Message message) { // TODO(askesc): Produce explicit error statement wrapping the original. // See [issue 29717](https://github.com/dart-lang/sdk/issues/29717) return buildProblemStatement(message, statement.fileOffset); } @override Initializer buildInvalidInitializer(Expression expression, [int charOffset = -1]) { needsImplicitSuperInitializer = false; return new ShadowInvalidInitializer( new VariableDeclaration.forValue(expression)) ..fileOffset = charOffset; } Initializer buildInvalidSuperInitializer( Constructor target, ArgumentsImpl arguments, Expression expression, [int charOffset = -1]) { needsImplicitSuperInitializer = false; return new InvalidSuperInitializerJudgment( target, arguments, new VariableDeclaration.forValue(expression)) ..fileOffset = charOffset; } Initializer buildDuplicatedInitializer(Field field, Expression value, String name, int offset, int previousInitializerOffset) { return new ShadowInvalidFieldInitializer( field, value, new VariableDeclaration.forValue(buildProblem( fasta.templateFinalInstanceVariableAlreadyInitialized .withArguments(name), offset, noLength))) ..fileOffset = offset; } /// Parameter [formalType] should only be passed in the special case of /// building a field initializer as a desugaring of an initializing formal /// parameter. The spec says the following: /// /// "If an explicit type is attached to the initializing formal, that is its /// static type. Otherwise, the type of an initializing formal named _id_ is /// _Tid_, where _Tid_ is the type of the instance variable named _id_ in the /// immediately enclosing class. It is a static warning if the static type of /// _id_ is not a subtype of _Tid_." @override Initializer buildFieldInitializer(bool isSynthetic, String name, int fieldNameOffset, int assignmentOffset, Expression expression, {DartType formalType}) { Builder builder = declarationBuilder.lookupLocalMember(name); if (builder?.next != null) { // Duplicated name, already reported. return new LocalInitializer(new VariableDeclaration.forValue(buildProblem( fasta.templateDuplicatedDeclarationUse.withArguments(name), fieldNameOffset, name.length))) ..fileOffset = fieldNameOffset; } else if (builder is FieldBuilder && builder.isDeclarationInstanceMember) { initializedFields ??= <String, int>{}; if (initializedFields.containsKey(name)) { return buildDuplicatedInitializer(builder.field, expression, name, assignmentOffset, initializedFields[name]); } initializedFields[name] = assignmentOffset; if (builder.isFinal && builder.hasInitializer) { addProblem( fasta.templateFinalInstanceVariableAlreadyInitialized .withArguments(name), assignmentOffset, noLength, context: [ fasta.templateFinalInstanceVariableAlreadyInitializedCause .withArguments(name) .withLocation(uri, builder.charOffset, name.length) ]); Builder constructor = libraryBuilder.loader.getDuplicatedFieldInitializerError(); Expression invocation = buildStaticInvocation( constructor.target, forest.createArguments(assignmentOffset, <Expression>[ forest.createStringLiteral(assignmentOffset, name) ]), constness: Constness.explicitNew, charOffset: assignmentOffset); return new ShadowInvalidFieldInitializer( builder.field, expression, new VariableDeclaration.forValue( forest.createThrow(assignmentOffset, invocation))) ..fileOffset = assignmentOffset; } else { if (formalType != null && !typeEnvironment.isSubtypeOf(formalType, builder.field.type, SubtypeCheckMode.ignoringNullabilities)) { libraryBuilder.addProblem( fasta.templateInitializingFormalTypeMismatch .withArguments(name, formalType, builder.field.type), assignmentOffset, noLength, uri, context: [ fasta.messageInitializingFormalTypeMismatchField .withLocation(builder.fileUri, builder.charOffset, noLength) ]); } return new FieldInitializer(builder.field, expression) ..fileOffset = assignmentOffset ..isSynthetic = isSynthetic; } } else { return buildInvalidInitializer( buildProblem( fasta.templateInitializerForStaticField.withArguments(name), fieldNameOffset, name.length), fieldNameOffset); } } @override Initializer buildSuperInitializer( bool isSynthetic, Constructor constructor, Arguments arguments, [int charOffset = -1]) { if (member.isConst && !constructor.isConst) { return buildInvalidSuperInitializer( constructor, arguments, buildProblem(fasta.messageConstConstructorWithNonConstSuper, charOffset, constructor.name.name.length), charOffset); } needsImplicitSuperInitializer = false; return new SuperInitializer(constructor, arguments) ..fileOffset = charOffset ..isSynthetic = isSynthetic; } @override Initializer buildRedirectingInitializer( Constructor constructor, Arguments arguments, [int charOffset = -1]) { if (classBuilder.checkConstructorCyclic( member.name, constructor.name.name)) { int length = constructor.name.name.length; if (length == 0) length = "this".length; addProblem(fasta.messageConstructorCyclic, charOffset, length); // TODO(askesc): Produce invalid initializer. } needsImplicitSuperInitializer = false; return new RedirectingInitializer(constructor, arguments) ..fileOffset = charOffset; } @override void handleOperator(Token token) { debugEvent("Operator"); push(new Operator(token, token.charOffset)); } @override void handleSymbolVoid(Token token) { debugEvent("SymbolVoid"); push(new Identifier.preserveToken(token)); } @override void handleInvalidFunctionBody(Token token) { if (member.isNative) { push(NullValue.FunctionBody); } else { push(forest.createBlock(offsetForToken(token), <Statement>[ buildProblemStatement( fasta.templateExpectedFunctionBody.withArguments(token), token.charOffset, length: token.length) ])); } } @override UnresolvedType validateTypeUse( UnresolvedType unresolved, bool nonInstanceAccessIsError) { TypeBuilder builder = unresolved.builder; if (builder is NamedTypeBuilder && builder.declaration.isTypeVariable) { TypeVariableBuilder typeParameterBuilder = builder.declaration; TypeParameter typeParameter = typeParameterBuilder.parameter; LocatedMessage message; if (!isDeclarationInstanceContext && typeParameter.parent is Class) { message = fasta.messageTypeVariableInStaticContext.withLocation( unresolved.fileUri, unresolved.charOffset, typeParameter.name.length); } else if (constantContext == ConstantContext.inferred) { message = fasta.messageTypeVariableInConstantContext.withLocation( unresolved.fileUri, unresolved.charOffset, typeParameter.name.length); } else { return unresolved; } addProblem(message.messageObject, message.charOffset, message.length); return new UnresolvedType( new NamedTypeBuilder( typeParameter.name, builder.nullabilityBuilder, null) ..bind(new InvalidTypeBuilder(typeParameter.name, message)), unresolved.charOffset, unresolved.fileUri); } return unresolved; } @override Expression evaluateArgumentsBefore( Arguments arguments, Expression expression) { if (arguments == null) return expression; List<Expression> expressions = new List<Expression>.from(forest.argumentsPositional(arguments)); for (NamedExpression named in forest.argumentsNamed(arguments)) { expressions.add(named.value); } for (Expression argument in expressions.reversed) { expression = new Let( new VariableDeclaration.forValue(argument, isFinal: true, type: coreTypes.objectRawType(libraryBuilder.nullable)), expression); } return expression; } @override bool isIdentical(Member member) => member == coreTypes.identicalProcedure; @override Expression buildMethodInvocation( Expression receiver, Name name, Arguments arguments, int offset, {bool isConstantExpression: false, bool isNullAware: false, bool isImplicitCall: false, bool isSuper: false, Member interfaceTarget}) { if (constantContext != ConstantContext.none && !isConstantExpression) { return buildProblem( fasta.templateNotConstantExpression .withArguments('Method invocation'), offset, name.name.length); } if (isSuper) { // We can ignore [isNullAware] on super sends. assert(forest.isThisExpression(receiver)); Member target = lookupInstanceMember(name, isSuper: true); if (target == null || (target is Procedure && !target.isAccessor)) { if (target == null) { warnUnresolvedMethod(name, offset, isSuper: true); } else if (!areArgumentsCompatible(target.function, arguments)) { target = null; addProblemErrorIfConst( fasta.templateSuperclassMethodArgumentMismatch .withArguments(name.name), offset, name.name.length); } return new SuperMethodInvocation(name, arguments, target) ..fileOffset = offset; } receiver = new SuperPropertyGet(name, target)..fileOffset = offset; MethodInvocation node = new MethodInvocationImpl( receiver, callName, arguments, isImplicitCall: true) ..fileOffset = arguments.fileOffset; return node; } if (isNullAware) { VariableDeclaration variable = forest.createVariableDeclarationForValue(receiver); return new NullAwareMethodInvocation( variable, forest.createMethodInvocation(offset, createVariableGet(variable, receiver.fileOffset), name, arguments, isImplicitCall: isImplicitCall, interfaceTarget: interfaceTarget)) ..fileOffset = receiver.fileOffset; } else { MethodInvocation node = forest.createMethodInvocation( offset, receiver, name, arguments, isImplicitCall: isImplicitCall, interfaceTarget: interfaceTarget); return node; } } @override void addProblem(Message message, int charOffset, int length, {bool wasHandled: false, List<LocatedMessage> context, Severity severity}) { libraryBuilder.addProblem(message, charOffset, length, uri, wasHandled: wasHandled, context: context, severity: severity); } @override void addProblemErrorIfConst(Message message, int charOffset, int length, {bool wasHandled: false, List<LocatedMessage> context}) { // TODO(askesc): Instead of deciding on the severity, this method should // take two messages: one to use when a constant expression is // required and one to use otherwise. Severity severity = message.code.severity; if (constantContext != ConstantContext.none) { severity = Severity.error; } addProblem(message, charOffset, length, wasHandled: wasHandled, context: context, severity: severity); } @override Expression buildProblemErrorIfConst( Message message, int charOffset, int length, {bool wasHandled: false, List<LocatedMessage> context}) { addProblemErrorIfConst(message, charOffset, length, wasHandled: wasHandled, context: context); String text = libraryBuilder.loader.target.context .format(message.withLocation(uri, charOffset, length), Severity.error); InvalidExpression expression = new InvalidExpression(text) ..fileOffset = charOffset; return expression; } @override void reportDuplicatedDeclaration( Builder existing, String name, int charOffset) { List<LocatedMessage> context = existing.isSynthetic ? null : <LocatedMessage>[ fasta.templateDuplicatedDeclarationCause .withArguments(name) .withLocation( existing.fileUri, existing.charOffset, name.length) ]; addProblem(fasta.templateDuplicatedDeclaration.withArguments(name), charOffset, name.length, context: context); } @override void debugEvent(String name) { // printEvent('BodyBuilder: $name'); } @override StaticGet makeStaticGet(Member readTarget, Token token) { return new StaticGet(readTarget)..fileOffset = offsetForToken(token); } @override Expression wrapInDeferredCheck( Expression expression, PrefixBuilder prefix, int charOffset) { VariableDeclaration check = new VariableDeclaration.forValue( forest.checkLibraryIsLoaded(charOffset, prefix.dependency)); return new DeferredCheck(check, expression)..fileOffset = charOffset; } /// TODO(ahe): This method is temporarily implemented. Once type promotion is /// independent of shadow nodes, remove this method. void enterThenForTypePromotion(Expression condition) { typePromoter?.enterThen(condition); } bool isErroneousNode(TreeNode node) { return libraryBuilder.loader.handledErrors.isNotEmpty && forest.isErroneousNode(node); } @override DartType buildDartType(UnresolvedType unresolvedType, {bool nonInstanceAccessIsError: false}) { if (unresolvedType == null) return null; return validateTypeUse(unresolvedType, nonInstanceAccessIsError) .builder ?.build(libraryBuilder); } @override List<DartType> buildDartTypeArguments(List<UnresolvedType> unresolvedTypes) { if (unresolvedTypes == null) return <DartType>[]; List<DartType> types = new List<DartType>.filled(unresolvedTypes.length, null, growable: true); for (int i = 0; i < types.length; i++) { types[i] = buildDartType(unresolvedTypes[i]); } return types; } @override String constructorNameForDiagnostics(String name, {String className, bool isSuper: false}) { if (className == null) { Class cls = classBuilder.cls; if (isSuper) { cls = cls.superclass; while (cls.isMixinApplication) { cls = cls.superclass; } } className = cls.name; } return name.isEmpty ? className : "$className.$name"; } } abstract class EnsureLoaded { void ensureLoaded(Member member); bool isLoaded(Member member); } class Operator { final Token token; String get name => token.stringValue; final int charOffset; Operator(this.token, this.charOffset); String toString() => "operator($name)"; } class JumpTarget extends BuilderImpl { final List<Statement> users = <Statement>[]; final JumpTargetKind kind; final int functionNestingLevel; @override final MemberBuilder parent; @override final int charOffset; JumpTarget( this.kind, this.functionNestingLevel, this.parent, this.charOffset); @override Uri get fileUri => parent.fileUri; bool get isBreakTarget => kind == JumpTargetKind.Break; bool get isContinueTarget => kind == JumpTargetKind.Continue; bool get isGotoTarget => kind == JumpTargetKind.Goto; bool get hasUsers => users.isNotEmpty; void addBreak(Statement statement) { assert(isBreakTarget); users.add(statement); } void addContinue(Statement statement) { assert(isContinueTarget); users.add(statement); } void addGoto(Statement statement) { assert(isGotoTarget); users.add(statement); } void resolveBreaks(Forest forest, Statement target) { assert(isBreakTarget); for (BreakStatement user in users) { user.target = target; } users.clear(); } void resolveContinues(Forest forest, Statement target) { assert(isContinueTarget); for (BreakStatement user in users) { user.target = target; } users.clear(); } void resolveGotos(Forest forest, SwitchCase target) { assert(isGotoTarget); for (ContinueSwitchStatement user in users) { user.target = target; } users.clear(); } @override String get fullNameForErrors => "<jump-target>"; } class LabelTarget extends BuilderImpl implements JumpTarget { @override final MemberBuilder parent; final JumpTarget breakTarget; final JumpTarget continueTarget; final int functionNestingLevel; @override final int charOffset; LabelTarget(this.parent, this.functionNestingLevel, this.charOffset) : breakTarget = new JumpTarget( JumpTargetKind.Break, functionNestingLevel, parent, charOffset), continueTarget = new JumpTarget( JumpTargetKind.Continue, functionNestingLevel, parent, charOffset); @override Uri get fileUri => parent.fileUri; bool get hasUsers => breakTarget.hasUsers || continueTarget.hasUsers; List<Statement> get users => unsupported("users", charOffset, fileUri); JumpTargetKind get kind => unsupported("kind", charOffset, fileUri); bool get isBreakTarget => true; bool get isContinueTarget => true; bool get isGotoTarget => false; void addBreak(Statement statement) { breakTarget.addBreak(statement); } void addContinue(Statement statement) { continueTarget.addContinue(statement); } void addGoto(Statement statement) { unsupported("addGoto", charOffset, fileUri); } void resolveBreaks(Forest forest, Statement target) { breakTarget.resolveBreaks(forest, target); } void resolveContinues(Forest forest, Statement target) { continueTarget.resolveContinues(forest, target); } void resolveGotos(Forest forest, SwitchCase target) { unsupported("resolveGotos", charOffset, fileUri); } @override String get fullNameForErrors => "<label-target>"; } class FormalParameters { final List<FormalParameterBuilder> parameters; final int charOffset; final int length; final Uri uri; FormalParameters(this.parameters, this.charOffset, this.length, this.uri) { if (parameters?.isEmpty ?? false) { throw "Empty parameters should be null"; } } FunctionNode buildFunctionNode( SourceLibraryBuilder library, UnresolvedType returnType, List<TypeVariableBuilder> typeParameters, AsyncMarker asyncModifier, Statement body, int fileEndOffset) { FunctionType type = toFunctionType( returnType, const NullabilityBuilder.omitted(), typeParameters) .builder .build(library); List<VariableDeclaration> positionalParameters = <VariableDeclaration>[]; List<VariableDeclaration> namedParameters = <VariableDeclaration>[]; if (parameters != null) { for (FormalParameterBuilder parameter in parameters) { if (parameter.isNamed) { namedParameters.add(parameter.target); } else { positionalParameters.add(parameter.target); } } namedParameters.sort((VariableDeclaration a, VariableDeclaration b) { return a.name.compareTo(b.name); }); } return new FunctionNode(body, typeParameters: type.typeParameters, positionalParameters: positionalParameters, namedParameters: namedParameters, requiredParameterCount: type.requiredParameterCount, returnType: type.returnType, asyncMarker: asyncModifier) ..fileOffset = charOffset ..fileEndOffset = fileEndOffset; } UnresolvedType toFunctionType( UnresolvedType returnType, NullabilityBuilder nullabilityBuilder, [List<TypeVariableBuilder> typeParameters]) { return new UnresolvedType( new FunctionTypeBuilder(returnType?.builder, typeParameters, parameters, nullabilityBuilder), charOffset, uri); } Scope computeFormalParameterScope( Scope parent, Builder declaration, ExpressionGeneratorHelper helper) { if (parameters == null) return parent; assert(parameters.isNotEmpty); Map<String, Builder> local = <String, Builder>{}; for (FormalParameterBuilder parameter in parameters) { Builder existing = local[parameter.name]; if (existing != null) { helper.reportDuplicatedDeclaration( existing, parameter.name, parameter.charOffset); } else { local[parameter.name] = parameter; } } return new Scope( local: local, parent: parent, debugName: "formals", isModifiable: false); } String toString() { return "FormalParameters($parameters, $charOffset, $uri)"; } } /// Returns a block like this: /// /// { /// statement; /// body; /// } /// /// If [body] is a [Block], it's returned with [statement] prepended to it. Block combineStatements(Statement statement, Statement body) { if (body is Block) { body.statements.insert(0, statement); statement.parent = body; return body; } else { return new Block(<Statement>[statement, body]) ..fileOffset = statement.fileOffset; } } String debugName(String className, String name, [String prefix]) { String result = name.isEmpty ? className : "$className.$name"; return prefix == null ? result : "$prefix.result"; } // TODO(johnniwinther): This is a bit ad hoc. Call sites should know what kind // of objects can be anticipated and handle these directly. String getNodeName(Object node) { if (node is Identifier) { return node.name; } else if (node is Builder) { return node.fullNameForErrors; } else if (node is QualifiedName) { return flattenName(node, node.charOffset, null); } else { return unhandled("${node.runtimeType}", "getNodeName", -1, null); } } AsyncMarker asyncMarkerFromTokens(Token asyncToken, Token starToken) { if (asyncToken == null || identical(asyncToken.stringValue, "sync")) { if (starToken == null) { return AsyncMarker.Sync; } else { assert(identical(starToken.stringValue, "*")); return AsyncMarker.SyncStar; } } else if (identical(asyncToken.stringValue, "async")) { if (starToken == null) { return AsyncMarker.Async; } else { assert(identical(starToken.stringValue, "*")); return AsyncMarker.AsyncStar; } } else { return unhandled(asyncToken.lexeme, "asyncMarkerFromTokens", asyncToken.charOffset, null); } } /// A data holder used to hold the information about a label that is pushed on /// the stack. class Label { String name; int charOffset; Label(this.name, this.charOffset); String toString() => "label($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/kernel/type_algorithms.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'package:kernel/ast.dart' show BottomType, DartType, DartTypeVisitor, DynamicType, FunctionType, InterfaceType, InvalidType, NamedType, TypeParameter, TypeParameterType, TypedefType, Variance, VoidType; import 'package:kernel/type_algebra.dart' show containsTypeVariable; import 'package:kernel/util/graph.dart' show Graph, computeStrongComponents; import '../builder/builder.dart'; import 'kernel_builder.dart' show ClassBuilder, FormalParameterBuilder, FunctionTypeBuilder, NamedTypeBuilder, TypeAliasBuilder, TypeBuilder, TypeDeclarationBuilder, TypeVariableBuilder; import '../dill/dill_class_builder.dart' show DillClassBuilder; import '../dill/dill_type_alias_builder.dart' show DillTypeAliasBuilder; import '../fasta_codes.dart' show LocatedMessage, templateBoundIssueViaCycleNonSimplicity, templateBoundIssueViaLoopNonSimplicity, templateBoundIssueViaRawTypeWithNonSimpleBounds, templateNonSimpleBoundViaReference, templateNonSimpleBoundViaVariable; export 'package:kernel/ast.dart' show Variance; // Computes the variance of a variable in a type. The function can be run // before the types are resolved to compute variances of typedefs' type // variables. For that case if the type has its declaration set to null and its // name matches that of the variable, it's interpreted as an occurrence of a // type variable. int computeVariance(TypeVariableBuilder variable, TypeBuilder type) { if (type is NamedTypeBuilder) { TypeDeclarationBuilder declaration = type.declaration; if (declaration == null || declaration is TypeVariableBuilder) { if (type.name == variable.name) { return Variance.covariant; } else { return Variance.unrelated; } } else { if (declaration is ClassBuilder) { int result = Variance.unrelated; if (type.arguments != null) { for (TypeBuilder argument in type.arguments) { result = Variance.meet(result, computeVariance(variable, argument)); } } return result; } else if (declaration is TypeAliasBuilder) { int result = Variance.unrelated; if (type.arguments != null) { for (int i = 0; i < type.arguments.length; ++i) { result = Variance.meet( result, Variance.combine( computeVariance(variable, type.arguments[i]), computeVariance( declaration.typeVariables[i], declaration.type))); } } return result; } } } else if (type is FunctionTypeBuilder) { int result = Variance.unrelated; if (type.returnType != null) { result = Variance.meet(result, computeVariance(variable, type.returnType)); } if (type.typeVariables != null) { for (TypeVariableBuilder typeVariable in type.typeVariables) { // If [variable] is referenced in the bound at all, it makes the // variance of [variable] in the entire type invariant. The invocation // of [computeVariance] below is made to simply figure out if [variable] // occurs in the bound. if (typeVariable.bound != null && computeVariance(variable, typeVariable.bound) != Variance.unrelated) { result = Variance.invariant; } } } if (type.formals != null) { for (FormalParameterBuilder formal in type.formals) { result = Variance.meet( result, Variance.combine(Variance.contravariant, computeVariance(variable, formal.type))); } } return result; } return Variance.unrelated; } /// Combines syntactic nullabilities on types for performing type substitution. /// /// The syntactic substitution should preserve a `?` if it was either on the /// type parameter occurrence or on the type argument replacing it. NullabilityBuilder combineNullabilityBuildersForSubstitution( NullabilityBuilder a, NullabilityBuilder b) { assert( (identical(a, const NullabilityBuilder.nullable()) || identical(a, const NullabilityBuilder.omitted())) && (identical(b, const NullabilityBuilder.nullable()) || identical(b, const NullabilityBuilder.omitted())), "Both arguments to combineNullabilityBuildersForSubstitution " "should be identical to either 'const NullabilityBuilder.nullable()' or " "'const NullabilityBuilder.omitted()'."); if (identical(a, const NullabilityBuilder.nullable()) || identical(b, const NullabilityBuilder.nullable())) { return const NullabilityBuilder.nullable(); } return const NullabilityBuilder.omitted(); } TypeBuilder substituteRange( TypeBuilder type, Map<TypeVariableBuilder, TypeBuilder> upperSubstitution, Map<TypeVariableBuilder, TypeBuilder> lowerSubstitution, List<TypeBuilder> unboundTypes, List<TypeVariableBuilder> unboundTypeVariables, {final int variance = Variance.covariant}) { if (type is NamedTypeBuilder) { if (type.declaration is TypeVariableBuilder) { if (variance == Variance.contravariant) { TypeBuilder replacement = lowerSubstitution[type.declaration]; if (replacement != null) { return replacement.withNullabilityBuilder( combineNullabilityBuildersForSubstitution( replacement.nullabilityBuilder, type.nullabilityBuilder)); } return type; } TypeBuilder replacement = upperSubstitution[type.declaration]; if (replacement != null) { return replacement.withNullabilityBuilder( combineNullabilityBuildersForSubstitution( replacement.nullabilityBuilder, type.nullabilityBuilder)); } return type; } if (type.arguments == null || type.arguments.length == 0) { return type; } List<TypeBuilder> arguments; TypeDeclarationBuilder declaration = type.declaration; if (declaration == null) { assert(unboundTypes != null, "Can not handle unbound named type builders without `unboundTypes`."); assert( unboundTypeVariables != null, "Can not handle unbound named type builders without " "`unboundTypeVariables`."); assert( identical(upperSubstitution, lowerSubstitution), "Can only handle unbound named type builders identical " "`upperSubstitution` and `lowerSubstitution`."); for (int i = 0; i < type.arguments.length; ++i) { TypeBuilder substitutedArgument = substituteRange( type.arguments[i], upperSubstitution, lowerSubstitution, unboundTypes, unboundTypeVariables, variance: variance); if (substitutedArgument != type.arguments[i]) { arguments ??= type.arguments.toList(); arguments[i] = substitutedArgument; } } } else if (declaration is ClassBuilder) { for (int i = 0; i < type.arguments.length; ++i) { TypeBuilder substitutedArgument = substituteRange( type.arguments[i], upperSubstitution, lowerSubstitution, unboundTypes, unboundTypeVariables, variance: variance); if (substitutedArgument != type.arguments[i]) { arguments ??= type.arguments.toList(); arguments[i] = substitutedArgument; } } } else if (declaration is TypeAliasBuilder) { for (int i = 0; i < type.arguments.length; ++i) { TypeVariableBuilder variable = declaration.typeVariables[i]; TypeBuilder substitutedArgument = substituteRange( type.arguments[i], upperSubstitution, lowerSubstitution, unboundTypes, unboundTypeVariables, variance: Variance.combine(variance, variable.variance)); if (substitutedArgument != type.arguments[i]) { arguments ??= type.arguments.toList(); arguments[i] = substitutedArgument; } } } else if (declaration is InvalidTypeBuilder) { // Don't substitute. } else { assert(false, "Unexpected named type builder declaration: $declaration."); } if (arguments != null) { NamedTypeBuilder newTypeBuilder = new NamedTypeBuilder(type.name, type.nullabilityBuilder, arguments); if (declaration != null) { newTypeBuilder.bind(declaration); } else { unboundTypes.add(newTypeBuilder); } return newTypeBuilder; } return type; } else if (type is FunctionTypeBuilder) { List<TypeVariableBuilder> variables; if (type.typeVariables != null) { variables = new List<TypeVariableBuilder>(type.typeVariables.length); } List<FormalParameterBuilder> formals; if (type.formals != null) { formals = new List<FormalParameterBuilder>(type.formals.length); } TypeBuilder returnType; bool changed = false; Map<TypeVariableBuilder, TypeBuilder> functionTypeUpperSubstitution; Map<TypeVariableBuilder, TypeBuilder> functionTypeLowerSubstitution; if (type.typeVariables != null) { for (int i = 0; i < variables.length; i++) { TypeVariableBuilder variable = type.typeVariables[i]; TypeBuilder bound = substituteRange(variable.bound, upperSubstitution, lowerSubstitution, unboundTypes, unboundTypeVariables, variance: Variance.invariant); if (bound != variable.bound) { TypeVariableBuilder newTypeVariableBuilder = variables[i] = new TypeVariableBuilder( variable.name, variable.parent, variable.charOffset, bound: bound); unboundTypeVariables.add(newTypeVariableBuilder); if (functionTypeUpperSubstitution == null) { functionTypeUpperSubstitution = {}..addAll(upperSubstitution); functionTypeLowerSubstitution = {}..addAll(lowerSubstitution); } functionTypeUpperSubstitution[variable] = functionTypeLowerSubstitution[variable] = new NamedTypeBuilder.fromTypeDeclarationBuilder( newTypeVariableBuilder, const NullabilityBuilder.omitted()); changed = true; } else { variables[i] = variable; } } } if (type.formals != null) { for (int i = 0; i < formals.length; i++) { FormalParameterBuilder formal = type.formals[i]; TypeBuilder parameterType = substituteRange( formal.type, functionTypeUpperSubstitution ?? upperSubstitution, functionTypeLowerSubstitution ?? lowerSubstitution, unboundTypes, unboundTypeVariables, variance: Variance.combine(variance, Variance.contravariant)); if (parameterType != formal.type) { formals[i] = new FormalParameterBuilder( formal.metadata, formal.modifiers, parameterType, formal.name, formal.parent, formal.charOffset, formal.fileUri); changed = true; } else { formals[i] = formal; } } } returnType = substituteRange( type.returnType, functionTypeUpperSubstitution ?? upperSubstitution, functionTypeLowerSubstitution ?? lowerSubstitution, unboundTypes, unboundTypeVariables, variance: variance); changed = changed || returnType != type.returnType; if (changed) { return new FunctionTypeBuilder( returnType, variables, formals, type.nullabilityBuilder); } return type; } return type; } TypeBuilder substitute( TypeBuilder type, Map<TypeVariableBuilder, TypeBuilder> substitution, {List<TypeBuilder> unboundTypes, List<TypeVariableBuilder> unboundTypeVariables}) { return substituteRange( type, substitution, substitution, unboundTypes, unboundTypeVariables, variance: Variance.covariant); } /// Calculates bounds to be provided as type arguments in place of missing type /// arguments on raw types with the given type parameters. /// /// See the [description] /// (https://github.com/dart-lang/sdk/blob/master/docs/language/informal/instantiate-to-bound.md) /// of the algorithm for details. List<TypeBuilder> calculateBounds(List<TypeVariableBuilder> variables, TypeBuilder dynamicType, TypeBuilder bottomType, ClassBuilder objectClass) { List<TypeBuilder> bounds = new List<TypeBuilder>(variables.length); for (int i = 0; i < variables.length; i++) { bounds[i] = variables[i].bound ?? dynamicType; } TypeVariablesGraph graph = new TypeVariablesGraph(variables, bounds); List<List<int>> stronglyConnected = computeStrongComponents(graph); for (List<int> component in stronglyConnected) { Map<TypeVariableBuilder, TypeBuilder> dynamicSubstitution = <TypeVariableBuilder, TypeBuilder>{}; Map<TypeVariableBuilder, TypeBuilder> nullSubstitution = <TypeVariableBuilder, TypeBuilder>{}; for (int variableIndex in component) { dynamicSubstitution[variables[variableIndex]] = dynamicType; nullSubstitution[variables[variableIndex]] = bottomType; } for (int variableIndex in component) { TypeVariableBuilder variable = variables[variableIndex]; bounds[variableIndex] = substituteRange(bounds[variableIndex], dynamicSubstitution, nullSubstitution, null, null, variance: variable.variance); } } for (int i = 0; i < variables.length; i++) { Map<TypeVariableBuilder, TypeBuilder> substitution = <TypeVariableBuilder, TypeBuilder>{}; Map<TypeVariableBuilder, TypeBuilder> nullSubstitution = <TypeVariableBuilder, TypeBuilder>{}; substitution[variables[i]] = bounds[i]; nullSubstitution[variables[i]] = bottomType; for (int j = 0; j < variables.length; j++) { TypeVariableBuilder variable = variables[j]; bounds[j] = substituteRange( bounds[j], substitution, nullSubstitution, null, null, variance: variable.variance); } } return bounds; } /// Graph of mutual dependencies of type variables from the same declaration. /// Type variables are represented by their indices in the corresponding /// declaration. class TypeVariablesGraph implements Graph<int> { List<int> vertices; List<TypeVariableBuilder> variables; List<TypeBuilder> bounds; // `edges[i]` is the list of indices of type variables that reference the type // variable with the index `i` in their bounds. List<List<int>> edges; TypeVariablesGraph(this.variables, this.bounds) { assert(variables.length == bounds.length); vertices = new List<int>(variables.length); Map<TypeVariableBuilder, int> variableIndices = <TypeVariableBuilder, int>{}; edges = new List<List<int>>(variables.length); for (int i = 0; i < vertices.length; i++) { vertices[i] = i; variableIndices[variables[i]] = i; edges[i] = <int>[]; } void collectReferencesFrom(int index, TypeBuilder type) { if (type is NamedTypeBuilder) { if (type.declaration is TypeVariableBuilder && this.variables.contains(type.declaration)) { edges[variableIndices[type.declaration]].add(index); } if (type.arguments != null) { for (TypeBuilder argument in type.arguments) { collectReferencesFrom(index, argument); } } } else if (type is FunctionTypeBuilder) { if (type.typeVariables != null) { for (TypeVariableBuilder typeVariable in type.typeVariables) { collectReferencesFrom(index, typeVariable.bound); } } if (type.formals != null) { for (FormalParameterBuilder parameter in type.formals) { collectReferencesFrom(index, parameter.type); } } collectReferencesFrom(index, type.returnType); } } for (int i = 0; i < vertices.length; i++) { collectReferencesFrom(i, bounds[i]); } } /// Returns indices of type variables that depend on the type variable with /// [index]. Iterable<int> neighborsOf(int index) { return edges[index]; } } /// Finds all type builders for [variable] in [type]. /// /// Returns list of the found type builders. List<NamedTypeBuilder> findVariableUsesInType( TypeVariableBuilder variable, TypeBuilder type, ) { List<NamedTypeBuilder> uses = <NamedTypeBuilder>[]; if (type is NamedTypeBuilder) { if (type.declaration == variable) { uses.add(type); } else { if (type.arguments != null) { for (TypeBuilder argument in type.arguments) { uses.addAll(findVariableUsesInType(variable, argument)); } } } } else if (type is FunctionTypeBuilder) { uses.addAll(findVariableUsesInType(variable, type.returnType)); if (type.typeVariables != null) { for (TypeVariableBuilder dependentVariable in type.typeVariables) { if (dependentVariable.bound != null) { uses.addAll( findVariableUsesInType(variable, dependentVariable.bound)); } if (dependentVariable.defaultType != null) { uses.addAll( findVariableUsesInType(variable, dependentVariable.defaultType)); } } } if (type.formals != null) { for (FormalParameterBuilder formal in type.formals) { uses.addAll(findVariableUsesInType(variable, formal.type)); } } } return uses; } /// Finds those of [variables] that reference other [variables] in their bounds. /// /// Returns flattened list of pairs. The first element in the pair is the type /// variable builder from [variables] that references other [variables] in its /// bound. The second element in the pair is the list of found references /// represented as type builders. List<Object> findInboundReferences(List<TypeVariableBuilder> variables) { List<Object> variablesAndDependencies = <Object>[]; for (TypeVariableBuilder dependent in variables) { List<NamedTypeBuilder> dependencies = <NamedTypeBuilder>[]; for (TypeVariableBuilder dependence in variables) { List<NamedTypeBuilder> uses = findVariableUsesInType(dependence, dependent.bound); if (uses.length != 0) { dependencies.addAll(uses); } } if (dependencies.length != 0) { variablesAndDependencies.add(dependent); variablesAndDependencies.add(dependencies); } } return variablesAndDependencies; } /// Finds raw generic types in [type] with inbound references in type variables. /// /// Returns flattened list of pairs. The first element in the pair is the found /// raw generic type. The second element in the pair is the list of type /// variables of that type with inbound references in the format specified in /// [findInboundReferences]. List<Object> findRawTypesWithInboundReferences(TypeBuilder type) { List<Object> typesAndDependencies = <Object>[]; if (type is NamedTypeBuilder) { if (type.arguments == null) { TypeDeclarationBuilder declaration = type.declaration; if (declaration is DillClassBuilder) { bool hasInbound = false; List<TypeParameter> typeParameters = declaration.cls.typeParameters; for (int i = 0; i < typeParameters.length && !hasInbound; ++i) { if (containsTypeVariable( typeParameters[i].bound, typeParameters.toSet())) { hasInbound = true; } } if (hasInbound) { typesAndDependencies.add(type); typesAndDependencies.add(const <Object>[]); } } else if (declaration is DillTypeAliasBuilder) { bool hasInbound = false; List<TypeParameter> typeParameters = declaration.typedef.typeParameters; for (int i = 0; i < typeParameters.length && !hasInbound; ++i) { if (containsTypeVariable( typeParameters[i].bound, typeParameters.toSet())) { hasInbound = true; } } if (hasInbound) { typesAndDependencies.add(type); typesAndDependencies.add(const <Object>[]); } } else if (declaration is ClassBuilder && declaration.typeVariables != null) { List<Object> dependencies = findInboundReferences(declaration.typeVariables); if (dependencies.length != 0) { typesAndDependencies.add(type); typesAndDependencies.add(dependencies); } } else if (declaration is TypeAliasBuilder) { if (declaration.typeVariables != null) { List<Object> dependencies = findInboundReferences(declaration.typeVariables); if (dependencies.length != 0) { typesAndDependencies.add(type); typesAndDependencies.add(dependencies); } } if (declaration.type is FunctionTypeBuilder) { FunctionTypeBuilder type = declaration.type; if (type.typeVariables != null) { List<Object> dependencies = findInboundReferences(type.typeVariables); if (dependencies.length != 0) { typesAndDependencies.add(type); typesAndDependencies.add(dependencies); } } } } } else { for (TypeBuilder argument in type.arguments) { typesAndDependencies .addAll(findRawTypesWithInboundReferences(argument)); } } } else if (type is FunctionTypeBuilder) { typesAndDependencies .addAll(findRawTypesWithInboundReferences(type.returnType)); if (type.typeVariables != null) { for (TypeVariableBuilder variable in type.typeVariables) { if (variable.bound != null) { typesAndDependencies .addAll(findRawTypesWithInboundReferences(variable.bound)); } if (variable.defaultType != null) { typesAndDependencies .addAll(findRawTypesWithInboundReferences(variable.defaultType)); } } } if (type.formals != null) { for (FormalParameterBuilder formal in type.formals) { typesAndDependencies .addAll(findRawTypesWithInboundReferences(formal.type)); } } } return typesAndDependencies; } /// Finds issues by raw generic types with inbound references in type variables. /// /// Returns flattened list of triplets. The first element of the triplet is the /// [TypeDeclarationBuilder] for the type variable from [variables] that has raw /// generic types with inbound references in its bound. The second element of /// the triplet is the error message. The third element is the context. List<Object> getInboundReferenceIssues(List<TypeVariableBuilder> variables) { List<Object> issues = <Object>[]; for (TypeVariableBuilder variable in variables) { if (variable.bound != null) { List<Object> rawTypesAndMutualDependencies = findRawTypesWithInboundReferences(variable.bound); for (int i = 0; i < rawTypesAndMutualDependencies.length; i += 2) { NamedTypeBuilder type = rawTypesAndMutualDependencies[i]; List<Object> variablesAndDependencies = rawTypesAndMutualDependencies[i + 1]; for (int j = 0; j < variablesAndDependencies.length; j += 2) { TypeVariableBuilder dependent = variablesAndDependencies[j]; List<NamedTypeBuilder> dependencies = variablesAndDependencies[j + 1]; for (NamedTypeBuilder dependency in dependencies) { issues.add(variable); issues.add(templateBoundIssueViaRawTypeWithNonSimpleBounds .withArguments(type.declaration.name)); issues.add(<LocatedMessage>[ templateNonSimpleBoundViaVariable .withArguments(dependency.declaration.name) .withLocation(dependent.fileUri, dependent.charOffset, dependent.name.length) ]); } } if (variablesAndDependencies.length == 0) { // The inbound references are in a compiled declaration in a .dill. issues.add(variable); issues.add(templateBoundIssueViaRawTypeWithNonSimpleBounds .withArguments(type.declaration.name)); issues.add(const <LocatedMessage>[]); } } } } return issues; } /// Finds raw type paths starting from those in [start] and ending with [end]. /// /// Returns list of found paths. Each path is represented as a list of /// alternating builders of the raw generic types from the path and builders of /// type variables of the immediately preceding types that contain the reference /// to the next raw generic type in the path. The list ends with the type /// builder for [end]. /// /// The reason for putting the type variables into the paths as well as for /// using type for [start], and not the corresponding type declaration, /// is better error reporting. List<List<Object>> findRawTypePathsToDeclaration( TypeBuilder start, TypeDeclarationBuilder end, [Set<TypeDeclarationBuilder> visited]) { visited ??= new Set<TypeDeclarationBuilder>.identity(); List<List<Object>> paths = <List<Object>>[]; if (start is NamedTypeBuilder) { TypeDeclarationBuilder declaration = start.declaration; if (start.arguments == null) { if (start.declaration == end) { paths.add(<Object>[start]); } else if (visited.add(start.declaration)) { if (declaration is ClassBuilder && declaration.typeVariables != null) { for (TypeVariableBuilder variable in declaration.typeVariables) { if (variable.bound != null) { for (List<Object> path in findRawTypePathsToDeclaration( variable.bound, end, visited)) { paths.add(<Object>[start, variable]..addAll(path)); } } } } else if (declaration is TypeAliasBuilder) { if (declaration.typeVariables != null) { for (TypeVariableBuilder variable in declaration.typeVariables) { if (variable.bound != null) { for (List<Object> dependencyPath in findRawTypePathsToDeclaration( variable.bound, end, visited)) { paths.add(<Object>[start, variable]..addAll(dependencyPath)); } } } } if (declaration.type is FunctionTypeBuilder) { FunctionTypeBuilder type = declaration.type; if (type.typeVariables != null) { for (TypeVariableBuilder variable in type.typeVariables) { if (variable.bound != null) { for (List<Object> dependencyPath in findRawTypePathsToDeclaration( variable.bound, end, visited)) { paths .add(<Object>[start, variable]..addAll(dependencyPath)); } } } } } } visited.remove(start.declaration); } } else { for (TypeBuilder argument in start.arguments) { paths.addAll(findRawTypePathsToDeclaration(argument, end, visited)); } } } else if (start is FunctionTypeBuilder) { paths.addAll(findRawTypePathsToDeclaration(start.returnType, end, visited)); if (start.typeVariables != null) { for (TypeVariableBuilder variable in start.typeVariables) { if (variable.bound != null) { paths.addAll( findRawTypePathsToDeclaration(variable.bound, end, visited)); } if (variable.defaultType != null) { paths.addAll(findRawTypePathsToDeclaration( variable.defaultType, end, visited)); } } } if (start.formals != null) { for (FormalParameterBuilder formal in start.formals) { paths.addAll(findRawTypePathsToDeclaration(formal.type, end, visited)); } } } return paths; } /// Finds raw generic type cycles ending and starting with [declaration]. /// /// Returns list of found cycles. Each cycle is represented as a list of /// alternating raw generic types from the cycle and type variables of the /// immediately preceding type that reference the next type in the cycle. The /// cycle starts with a type variable from [declaration] and ends with a type /// that has [declaration] as its declaration. /// /// The reason for putting the type variables into the cycles is better error /// reporting. List<List<Object>> findRawTypeCycles(TypeDeclarationBuilder declaration) { List<List<Object>> cycles = <List<Object>>[]; if (declaration is ClassBuilder && declaration.typeVariables != null) { for (TypeVariableBuilder variable in declaration.typeVariables) { if (variable.bound != null) { for (List<Object> path in findRawTypePathsToDeclaration(variable.bound, declaration)) { cycles.add(<Object>[variable]..addAll(path)); } } } } else if (declaration is TypeAliasBuilder) { if (declaration.typeVariables != null) { for (TypeVariableBuilder variable in declaration.typeVariables) { if (variable.bound != null) { for (List<Object> dependencyPath in findRawTypePathsToDeclaration(variable.bound, declaration)) { cycles.add(<Object>[variable]..addAll(dependencyPath)); } } } } if (declaration.type is FunctionTypeBuilder) { FunctionTypeBuilder type = declaration.type; if (type.typeVariables != null) { for (TypeVariableBuilder variable in type.typeVariables) { if (variable.bound != null) { for (List<Object> dependencyPath in findRawTypePathsToDeclaration(variable.bound, declaration)) { cycles.add(<Object>[variable]..addAll(dependencyPath)); } } } } } } return cycles; } /// Converts raw generic type [cycles] for [declaration] into reportable issues. /// /// The [cycles] are expected to be in the format specified for the return value /// of [findRawTypeCycles]. /// /// Returns flattened list of triplets. The first element of the triplet is the /// [TypeDeclarationBuilder] for the type variable from [variables] that has raw /// generic types with inbound references in its bound. The second element of /// the triplet is the error message. The third element is the context. List<Object> convertRawTypeCyclesIntoIssues( TypeDeclarationBuilder declaration, List<List<Object>> cycles) { List<Object> issues = <Object>[]; for (List<Object> cycle in cycles) { if (cycle.length == 2) { // Loop. TypeVariableBuilder variable = cycle[0]; NamedTypeBuilder type = cycle[1]; issues.add(variable); issues.add(templateBoundIssueViaLoopNonSimplicity .withArguments(type.declaration.name)); issues.add(null); // Context. } else { List<LocatedMessage> context = <LocatedMessage>[]; for (int i = 0; i < cycle.length; i += 2) { TypeVariableBuilder variable = cycle[i]; NamedTypeBuilder type = cycle[i + 1]; context.add(templateNonSimpleBoundViaReference .withArguments(type.declaration.name) .withLocation( variable.fileUri, variable.charOffset, variable.name.length)); } NamedTypeBuilder firstEncounteredType = cycle[1]; issues.add(declaration); issues.add(templateBoundIssueViaCycleNonSimplicity.withArguments( declaration.name, firstEncounteredType.declaration.name)); issues.add(context); } } return issues; } /// Finds non-simplicity issues for the given set of [variables]. /// /// The issues are those caused by raw types with inbound references in the /// bounds of their type variables. /// /// Returns flattened list of triplets, each triplet representing an issue. The /// first element in the triplet is the type declaration that has the issue. /// The second element in the triplet is the error message. The third element /// in the triplet is the context. List<Object> getNonSimplicityIssuesForTypeVariables( List<TypeVariableBuilder> variables) { if (variables == null) return <Object>[]; return getInboundReferenceIssues(variables); } /// Finds non-simplicity issues for the given [declaration]. /// /// The issues are those caused by raw types with inbound references in the /// bounds of type variables from [declaration] and by cycles of raw types /// containing [declaration]. /// /// Returns flattened list of triplets, each triplet representing an issue. The /// first element in the triplet is the type declaration that has the issue. /// The second element in the triplet is the error message. The third element /// in the triplet is the context. List<Object> getNonSimplicityIssuesForDeclaration( TypeDeclarationBuilder declaration, {bool performErrorRecovery: true}) { List<Object> issues = <Object>[]; if (declaration is ClassBuilder && declaration.typeVariables != null) { issues.addAll(getInboundReferenceIssues(declaration.typeVariables)); } else if (declaration is TypeAliasBuilder && declaration.typeVariables != null) { issues.addAll(getInboundReferenceIssues(declaration.typeVariables)); } List<List<Object>> cyclesToReport = <List<Object>>[]; for (List<Object> cycle in findRawTypeCycles(declaration)) { // To avoid reporting the same error for each element of the cycle, we only // do so if it comes the first in the lexicographical order. Note that // one-element cycles shouldn't be checked, as they are loops. if (cycle.length == 2) { cyclesToReport.add(cycle); } else { String declarationPathAndName = "${declaration.fileUri}:${declaration.name}"; String lexMinPathAndName = null; for (int i = 1; i < cycle.length; i += 2) { NamedTypeBuilder type = cycle[i]; String pathAndName = "${type.declaration.fileUri}:${type.declaration.name}"; if (lexMinPathAndName == null || lexMinPathAndName.compareTo(pathAndName) > 0) { lexMinPathAndName = pathAndName; } } if (declarationPathAndName == lexMinPathAndName) { cyclesToReport.add(cycle); } } } List<Object> rawTypeCyclesAsIssues = convertRawTypeCyclesIntoIssues(declaration, cyclesToReport); issues.addAll(rawTypeCyclesAsIssues); if (performErrorRecovery) { breakCycles(cyclesToReport); } return issues; } /// Break raw generic type [cycles] as error recovery. /// /// The [cycles] are expected to be in the format specified for the return value /// of [findRawTypeCycles]. void breakCycles(List<List<Object>> cycles) { for (List<Object> cycle in cycles) { TypeVariableBuilder variable = cycle[0]; variable.bound = null; } } void findGenericFunctionTypes(TypeBuilder type, {List<TypeBuilder> result}) { result ??= <TypeBuilder>[]; if (type is FunctionTypeBuilder) { if (type.typeVariables != null && type.typeVariables.length > 0) { result.add(type); for (TypeVariableBuilder typeVariable in type.typeVariables) { findGenericFunctionTypes(typeVariable.bound, result: result); findGenericFunctionTypes(typeVariable.defaultType, result: result); } } findGenericFunctionTypes(type.returnType, result: result); if (type.formals != null) { for (FormalParameterBuilder formal in type.formals) { findGenericFunctionTypes(formal.type, result: result); } } } else if (type is NamedTypeBuilder && type.arguments != null) { for (TypeBuilder argument in type.arguments) { findGenericFunctionTypes(argument, result: result); } } } /// Returns true if [type] contains any type variables whatsoever. This should /// only be used for working around transitional issues. // TODO(ahe): Remove this method. bool hasAnyTypeVariables(DartType type) { return type.accept(const TypeVariableSearch()); } /// Don't use this directly, use [hasAnyTypeVariables] instead. But don't use /// that either. // TODO(ahe): Remove this class. class TypeVariableSearch implements DartTypeVisitor<bool> { const TypeVariableSearch(); bool defaultDartType(DartType node) => throw "unsupported"; bool anyTypeVariables(List<DartType> types) { for (DartType type in types) { if (type.accept(this)) return true; } return false; } bool visitInvalidType(InvalidType node) => false; bool visitDynamicType(DynamicType node) => false; bool visitVoidType(VoidType node) => false; bool visitBottomType(BottomType node) => false; bool visitInterfaceType(InterfaceType node) { return anyTypeVariables(node.typeArguments); } bool visitFunctionType(FunctionType node) { if (anyTypeVariables(node.positionalParameters)) return true; for (TypeParameter variable in node.typeParameters) { if (variable.bound.accept(this)) return true; } for (NamedType type in node.namedParameters) { if (type.type.accept(this)) return true; } return false; } bool visitTypeParameterType(TypeParameterType node) => true; bool visitTypedefType(TypedefType node) { return anyTypeVariables(node.typeArguments); } }
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/kernel/expression_generator_helper.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.expression_generator_helper; import '../../scanner/token.dart' show Token; import '../constant_context.dart' show ConstantContext; import '../fasta_codes.dart' show LocatedMessage; import '../messages.dart' show Message; import '../scope.dart' show Scope; import '../type_inference/inference_helper.dart' show InferenceHelper; import '../type_inference/type_promotion.dart' show TypePromoter; import 'constness.dart' show Constness; import 'forest.dart' show Forest; import 'kernel_builder.dart' show Builder, PrefixBuilder, UnresolvedType; import 'kernel_ast_api.dart' show Arguments, Constructor, DartType, Expression, FunctionNode, Initializer, Member, Name, Procedure, StaticGet, TypeParameter, VariableDeclaration; import 'kernel_builder.dart' show PrefixBuilder, LibraryBuilder, TypeDeclarationBuilder; abstract class ExpressionGeneratorHelper implements InferenceHelper { LibraryBuilder get libraryBuilder; TypePromoter get typePromoter; int get functionNestingLevel; ConstantContext get constantContext; Forest get forest; Constructor lookupConstructor(Name name, {bool isSuper}); Expression toValue(node); Member lookupInstanceMember(Name name, {bool isSetter, bool isSuper}); scopeLookup(Scope scope, String name, Token token, {bool isQualified: false, PrefixBuilder prefix}); finishSend(Object receiver, Arguments arguments, int offset); Initializer buildInvalidInitializer(Expression expression, [int offset]); Initializer buildFieldInitializer(bool isSynthetic, String name, int fieldNameOffset, int assignmentOffset, Expression expression, {DartType formalType}); Initializer buildSuperInitializer( bool isSynthetic, Constructor constructor, Arguments arguments, [int offset]); Initializer buildRedirectingInitializer( Constructor constructor, Arguments arguments, [int charOffset = -1]); Expression buildStaticInvocation(Procedure target, Arguments arguments, {Constness constness, int charOffset}); Expression buildExtensionMethodInvocation( int fileOffset, Procedure target, Arguments arguments, {bool isTearOff}); Expression throwNoSuchMethodError( Expression receiver, String name, Arguments arguments, int offset, {Member candidate, bool isSuper, bool isGetter, bool isSetter, bool isStatic, LocatedMessage message}); LocatedMessage checkArgumentsForFunction(FunctionNode function, Arguments arguments, int offset, List<TypeParameter> typeParameters); StaticGet makeStaticGet(Member readTarget, Token token); Expression wrapInDeferredCheck( Expression expression, PrefixBuilder prefix, int charOffset); bool isIdentical(Member member); Expression buildMethodInvocation( Expression receiver, Name name, Arguments arguments, int offset, {bool isConstantExpression, bool isNullAware, bool isImplicitCall, bool isSuper, Member interfaceTarget}); Expression buildConstructorInvocation( TypeDeclarationBuilder type, Token nameToken, Token nameLastToken, Arguments arguments, String name, List<UnresolvedType> typeArguments, int charOffset, Constness constness); UnresolvedType validateTypeUse( UnresolvedType unresolved, bool nonInstanceAccessIsError); void addProblemErrorIfConst(Message message, int charOffset, int length); Expression buildProblemErrorIfConst( Message message, int charOffset, int length); Message warnUnresolvedGet(Name name, int charOffset, {bool isSuper}); Message warnUnresolvedSet(Name name, int charOffset, {bool isSuper}); Message warnUnresolvedMethod(Name name, int charOffset, {bool isSuper}); void warnTypeArgumentsMismatch(String name, int expected, int charOffset); Expression wrapInLocatedProblem(Expression expression, LocatedMessage message, {List<LocatedMessage> context}); Expression evaluateArgumentsBefore( Arguments arguments, Expression expression); DartType buildDartType(UnresolvedType unresolvedType, {bool nonInstanceAccessIsError}); List<DartType> buildDartTypeArguments(List<UnresolvedType> unresolvedTypes); void reportDuplicatedDeclaration( Builder existing, String name, int charOffset); /// Creates a [VariableGet] of the [variable] using [charOffset] as the file /// offset of the created node. Expression createVariableGet(VariableDeclaration variable, int charOffset); }
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/kernel/metadata_collector.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:kernel/kernel.dart' show Member, MetadataRepository, NamedNode; /// The collector to add target specific metadata to. abstract class MetadataCollector { /// Metadata is remembered in this repository, so that when it is added /// to a component, metadata is serialized with the component. MetadataRepository<dynamic> get repository; void setConstructorNameOffset(Member node, Object name); void setDocumentationComment(NamedNode node, String comment); }
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/kernel/kernel_constants.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 fasta.kernel_constants; import 'package:kernel/ast.dart' show InvalidExpression; import '../fasta_codes.dart' show LocatedMessage; import '../loader.dart' show Loader; import 'constant_evaluator.dart' show ErrorReporter; class KernelConstantErrorReporter extends ErrorReporter { final Loader loader; KernelConstantErrorReporter(this.loader); @override void report(LocatedMessage message, List<LocatedMessage> context) { loader.addProblem( message.messageObject, message.charOffset, message.length, message.uri, context: context); } @override void reportInvalidExpression(InvalidExpression node) { // Assumed to be already reported. } }
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/kernel/constant_evaluator.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. /// This library implements a kernel2kernel constant evaluation transformation. /// /// Even though it is expected that the frontend does not emit kernel AST which /// contains compile-time errors, this transformation still performs some /// validation and throws a [ConstantEvaluationError] if there was a /// compile-time errors. /// /// Due to the lack information which is is only available in the front-end, /// this validation is incomplete (e.g. whether an integer literal used the /// hexadecimal syntax or not). /// /// Furthermore due to the lowering of certain constructs in the front-end /// (e.g. '??') we need to support a super-set of the normal constant expression /// language. Issue(http://dartbug.com/31799) library fasta.constant_evaluator; import 'dart:core' hide MapEntry; import 'dart:io' as io; import 'package:kernel/ast.dart'; import 'package:kernel/class_hierarchy.dart'; import 'package:kernel/clone.dart'; import 'package:kernel/core_types.dart'; import 'package:kernel/kernel.dart'; import 'package:kernel/type_algebra.dart'; import 'package:kernel/type_environment.dart'; import 'package:kernel/target/targets.dart'; import '../fasta_codes.dart' show LocatedMessage, Message, messageConstEvalCircularity, messageConstEvalContext, messageConstEvalFailedAssertion, messageConstEvalNotListOrSetInSpread, messageConstEvalNotMapInSpread, messageConstEvalNullValue, messageConstEvalStartingPoint, messageConstEvalUnevaluated, noLength, templateConstEvalDeferredLibrary, templateConstEvalDuplicateElement, templateConstEvalDuplicateKey, templateConstEvalElementImplementsEqual, templateConstEvalFailedAssertionWithMessage, templateConstEvalFreeTypeParameter, templateConstEvalInvalidType, templateConstEvalInvalidBinaryOperandType, templateConstEvalInvalidEqualsOperandType, templateConstEvalInvalidMethodInvocation, templateConstEvalInvalidPropertyGet, templateConstEvalInvalidStaticInvocation, templateConstEvalInvalidStringInterpolationOperand, templateConstEvalInvalidSymbolName, templateConstEvalKeyImplementsEqual, templateConstEvalNonConstantVariableGet, templateConstEvalZeroDivisor; import 'constant_int_folder.dart'; part 'constant_collection_builders.dart'; Component transformComponent(Component component, ConstantsBackend backend, Map<String, String> environmentDefines, ErrorReporter errorReporter, {bool keepFields: true, bool evaluateAnnotations: true, bool desugarSets: false, bool errorOnUnevaluatedConstant: false, CoreTypes coreTypes, ClassHierarchy hierarchy}) { coreTypes ??= new CoreTypes(component); hierarchy ??= new ClassHierarchy(component); final TypeEnvironment typeEnvironment = new TypeEnvironment(coreTypes, hierarchy); transformLibraries(component.libraries, backend, environmentDefines, typeEnvironment, errorReporter, keepFields: keepFields, desugarSets: desugarSets, errorOnUnevaluatedConstant: errorOnUnevaluatedConstant, evaluateAnnotations: evaluateAnnotations); return component; } void transformLibraries( List<Library> libraries, ConstantsBackend backend, Map<String, String> environmentDefines, TypeEnvironment typeEnvironment, ErrorReporter errorReporter, {bool keepFields: true, bool keepVariables: false, bool evaluateAnnotations: true, bool desugarSets: false, bool errorOnUnevaluatedConstant: false}) { final ConstantsTransformer constantsTransformer = new ConstantsTransformer( backend, environmentDefines, keepFields, keepVariables, evaluateAnnotations, desugarSets, errorOnUnevaluatedConstant, typeEnvironment, errorReporter); for (final Library library in libraries) { constantsTransformer.convertLibrary(library); } } class ConstantsTransformer extends Transformer { final ConstantsBackend backend; final ConstantEvaluator constantEvaluator; final TypeEnvironment typeEnvironment; /// Whether to preserve constant [Field]s. All use-sites will be rewritten. final bool keepFields; final bool keepVariables; final bool evaluateAnnotations; final bool desugarSets; final bool errorOnUnevaluatedConstant; ConstantsTransformer( this.backend, Map<String, String> environmentDefines, this.keepFields, this.keepVariables, this.evaluateAnnotations, this.desugarSets, this.errorOnUnevaluatedConstant, this.typeEnvironment, ErrorReporter errorReporter) : constantEvaluator = new ConstantEvaluator( backend, environmentDefines, typeEnvironment, errorReporter, desugarSets: desugarSets, errorOnUnevaluatedConstant: errorOnUnevaluatedConstant); // Transform the library/class members: void convertLibrary(Library library) { transformAnnotations(library.annotations, library); transformList(library.dependencies, this, library); transformList(library.parts, this, library); transformList(library.typedefs, this, library); transformList(library.classes, this, library); transformList(library.procedures, this, library); transformList(library.fields, this, library); if (!keepFields) { // The transformer API does not iterate over `Library.additionalExports`, // so we manually delete the references to shaken nodes. library.additionalExports.removeWhere((Reference reference) { return reference.node is Field && reference.canonicalName == null; }); } } @override LibraryPart visitLibraryPart(LibraryPart node) { constantEvaluator.withNewEnvironment(() { transformAnnotations(node.annotations, node); }); return node; } @override LibraryDependency visitLibraryDependency(LibraryDependency node) { constantEvaluator.withNewEnvironment(() { transformAnnotations(node.annotations, node); }); return node; } @override Class visitClass(Class node) { constantEvaluator.withNewEnvironment(() { transformAnnotations(node.annotations, node); transformList(node.fields, this, node); transformList(node.typeParameters, this, node); transformList(node.constructors, this, node); transformList(node.procedures, this, node); transformList(node.redirectingFactoryConstructors, this, node); }); return node; } @override Procedure visitProcedure(Procedure node) { constantEvaluator.withNewEnvironment(() { transformAnnotations(node.annotations, node); node.function = node.function.accept<TreeNode>(this)..parent = node; }); return node; } @override Constructor visitConstructor(Constructor node) { constantEvaluator.withNewEnvironment(() { transformAnnotations(node.annotations, node); transformList(node.initializers, this, node); node.function = node.function.accept<TreeNode>(this)..parent = node; }); return node; } @override Typedef visitTypedef(Typedef node) { constantEvaluator.withNewEnvironment(() { transformAnnotations(node.annotations, node); transformList(node.typeParameters, this, node); transformList(node.typeParametersOfFunctionType, this, node); transformList(node.positionalParameters, this, node); transformList(node.namedParameters, this, node); }); return node; } @override RedirectingFactoryConstructor visitRedirectingFactoryConstructor( RedirectingFactoryConstructor node) { constantEvaluator.withNewEnvironment(() { transformAnnotations(node.annotations, node); transformList(node.typeParameters, this, node); transformList(node.positionalParameters, this, node); transformList(node.namedParameters, this, node); }); return node; } @override TypeParameter visitTypeParameter(TypeParameter node) { transformAnnotations(node.annotations, node); return node; } void transformAnnotations(List<Expression> nodes, TreeNode parent) { if (evaluateAnnotations && nodes.length > 0) { transformExpressions(nodes, parent); } } void transformExpressions(List<Expression> nodes, TreeNode parent) { constantEvaluator.withNewEnvironment(() { for (int i = 0; i < nodes.length; ++i) { nodes[i] = evaluateAndTransformWithContext(parent, nodes[i]) ..parent = parent; } }); } // Handle definition of constants: @override FunctionNode visitFunctionNode(FunctionNode node) { final int positionalParameterCount = node.positionalParameters.length; for (int i = 0; i < positionalParameterCount; ++i) { final VariableDeclaration variable = node.positionalParameters[i]; transformAnnotations(variable.annotations, variable); if (variable.initializer != null) { variable.initializer = evaluateAndTransformWithContext(variable, variable.initializer) ..parent = variable; } } for (final VariableDeclaration variable in node.namedParameters) { transformAnnotations(variable.annotations, variable); if (variable.initializer != null) { variable.initializer = evaluateAndTransformWithContext(variable, variable.initializer) ..parent = variable; } } if (node.body != null) { node.body = node.body.accept<TreeNode>(this)..parent = node; } return node; } @override VariableDeclaration visitVariableDeclaration(VariableDeclaration node) { transformAnnotations(node.annotations, node); if (node.initializer != null) { if (node.isConst) { final Constant constant = evaluateWithContext(node, node.initializer); constantEvaluator.env.addVariableValue(node, constant); node.initializer = makeConstantExpression(constant, node.initializer) ..parent = node; // If this constant is inlined, remove it. if (!keepVariables && shouldInline(node.initializer)) { if (constant is! UnevaluatedConstant) { // If the constant is unevaluated we need to keep the expression, // so that, in the case the constant contains error but the local // is unused, the error will still be reported. return null; } } } else { node.initializer = node.initializer.accept<TreeNode>(this) ..parent = node; } } return node; } @override Field visitField(Field node) { return constantEvaluator.withNewEnvironment(() { if (node.isConst) { transformAnnotations(node.annotations, node); node.initializer = evaluateAndTransformWithContext(node, node.initializer) ..parent = node; // If this constant is inlined, remove it. if (!keepFields && shouldInline(node.initializer)) { return null; } } else { transformAnnotations(node.annotations, node); if (node.initializer != null) { node.initializer = node.initializer.accept<TreeNode>(this) ..parent = node; } } return node; }); } // Handle use-sites of constants (and "inline" constant expressions): @override Expression visitSymbolLiteral(SymbolLiteral node) { return makeConstantExpression(constantEvaluator.evaluate(node), node); } @override Expression visitStaticGet(StaticGet node) { final Member target = node.target; if (target is Field && target.isConst) { // Make sure the initializer is evaluated first. target.initializer = evaluateAndTransformWithContext(target, target.initializer) ..parent = target; if (shouldInline(target.initializer)) { return evaluateAndTransformWithContext(node, node); } } else if (target is Procedure && target.kind == ProcedureKind.Method) { return evaluateAndTransformWithContext(node, node); } return super.visitStaticGet(node); } @override SwitchCase visitSwitchCase(SwitchCase node) { transformExpressions(node.expressions, node); return super.visitSwitchCase(node); } @override Expression visitVariableGet(VariableGet node) { final VariableDeclaration variable = node.variable; if (variable.isConst) { variable.initializer = evaluateAndTransformWithContext(variable, variable.initializer) ..parent = variable; if (shouldInline(variable.initializer)) { return evaluateAndTransformWithContext(node, node); } } return super.visitVariableGet(node); } @override Expression visitListLiteral(ListLiteral node) { if (node.isConst) { return evaluateAndTransformWithContext(node, node); } return super.visitListLiteral(node); } @override Expression visitListConcatenation(ListConcatenation node) { return evaluateAndTransformWithContext(node, node); } @override Expression visitSetLiteral(SetLiteral node) { if (node.isConst) { return evaluateAndTransformWithContext(node, node); } return super.visitSetLiteral(node); } @override Expression visitSetConcatenation(SetConcatenation node) { return evaluateAndTransformWithContext(node, node); } @override Expression visitMapLiteral(MapLiteral node) { if (node.isConst) { return evaluateAndTransformWithContext(node, node); } return super.visitMapLiteral(node); } @override Expression visitMapConcatenation(MapConcatenation node) { return evaluateAndTransformWithContext(node, node); } @override Expression visitConstructorInvocation(ConstructorInvocation node) { if (node.isConst) { return evaluateAndTransformWithContext(node, node); } return super.visitConstructorInvocation(node); } @override Expression visitStaticInvocation(StaticInvocation node) { if (node.isConst) { return evaluateAndTransformWithContext(node, node); } return super.visitStaticInvocation(node); } @override Expression visitConstantExpression(ConstantExpression node) { Constant constant = node.constant; if (constant is UnevaluatedConstant) { Expression expression = constant.expression; return evaluateAndTransformWithContext(expression, expression); } else { node.constant = constantEvaluator.canonicalize(constant); return node; } } Expression evaluateAndTransformWithContext( TreeNode treeContext, Expression node) { return makeConstantExpression(evaluateWithContext(treeContext, node), node); } Constant evaluateWithContext(TreeNode treeContext, Expression node) { if (treeContext == node) { return constantEvaluator.evaluate(node); } return constantEvaluator.runInsideContext(treeContext, () { return constantEvaluator.evaluate(node); }); } Expression makeConstantExpression(Constant constant, Expression node) { if (constant is UnevaluatedConstant && constant.expression is InvalidExpression) { return constant.expression; } return new ConstantExpression(constant, node.getStaticType(typeEnvironment)) ..fileOffset = node.fileOffset; } bool shouldInline(Expression initializer) { if (initializer is ConstantExpression) { return backend.shouldInlineConstant(initializer); } return true; } } class ConstantEvaluator extends RecursiveVisitor<Constant> { final ConstantsBackend backend; final NumberSemantics numberSemantics; ConstantIntFolder intFolder; Map<String, String> environmentDefines; final bool errorOnUnevaluatedConstant; final CoreTypes coreTypes; final TypeEnvironment typeEnvironment; final ErrorReporter errorReporter; final bool desugarSets; final Field unmodifiableSetMap; final bool Function(DartType) isInstantiated = new IsInstantiatedVisitor().isInstantiated; final Map<Constant, Constant> canonicalizationCache; final Map<Node, Object> nodeCache; final CloneVisitor cloner = new CloneVisitor(); Map<Class, bool> primitiveEqualCache; final NullConstant nullConstant = new NullConstant(); final BoolConstant trueConstant = new BoolConstant(true); final BoolConstant falseConstant = new BoolConstant(false); final List<TreeNode> contextChain = []; InstanceBuilder instanceBuilder; EvaluationEnvironment env; Set<Expression> replacementNodes = new Set<Expression>.identity(); Map<Constant, Constant> lowered = new Map<Constant, Constant>.identity(); bool seenUnevaluatedChild; // Any children that were left unevaluated? int lazyDepth; // Current nesting depth of lazy regions. bool get shouldBeUnevaluated => seenUnevaluatedChild || lazyDepth != 0; bool get targetingJavaScript => numberSemantics == NumberSemantics.js; ConstantEvaluator(this.backend, this.environmentDefines, this.typeEnvironment, this.errorReporter, {this.desugarSets = false, this.errorOnUnevaluatedConstant = false}) : numberSemantics = backend.numberSemantics, coreTypes = typeEnvironment.coreTypes, canonicalizationCache = <Constant, Constant>{}, nodeCache = <Node, Constant>{}, env = new EvaluationEnvironment(), unmodifiableSetMap = desugarSets ? typeEnvironment.coreTypes.index .getMember('dart:collection', '_UnmodifiableSet', '_map') : null { if (environmentDefines == null && !backend.supportsUnevaluatedConstants) { throw new ArgumentError( "No 'environmentDefines' passed to the constant evaluator but the " "ConstantsBackend does not support unevaluated constants."); } intFolder = new ConstantIntFolder.forSemantics(this, numberSemantics); primitiveEqualCache = <Class, bool>{ coreTypes.boolClass: true, coreTypes.doubleClass: false, coreTypes.intClass: true, coreTypes.internalSymbolClass: true, coreTypes.listClass: true, coreTypes.mapClass: true, coreTypes.nullClass: true, coreTypes.objectClass: true, coreTypes.setClass: true, coreTypes.stringClass: true, coreTypes.symbolClass: true, coreTypes.typeClass: true, }; } Uri getFileUri(TreeNode node) { while (node != null && node is! FileUriNode) { node = node.parent; } return (node as FileUriNode)?.fileUri; } int getFileOffset(Uri uri, TreeNode node) { if (uri == null) return TreeNode.noOffset; while (node != null && node.fileOffset == TreeNode.noOffset) { node = node.parent; } return node == null ? TreeNode.noOffset : node.fileOffset; } /// Evaluate [node] and possibly cache the evaluation result. /// Returns UnevaluatedConstant if the constant could not be evaluated. /// If the expression in the UnevaluatedConstant is an InvalidExpression, /// an error occurred during constant evaluation. Constant evaluate(Expression node) { seenUnevaluatedChild = false; lazyDepth = 0; try { Constant result = _evaluateSubexpression(node); if (result is UnevaluatedConstant) { if (errorOnUnevaluatedConstant) { return report(node, messageConstEvalUnevaluated); } return new UnevaluatedConstant( removeRedundantFileUriExpressions(result.expression)); } return result; } on _AbortDueToError catch (e) { final Uri uri = getFileUri(e.node); final int fileOffset = getFileOffset(uri, e.node); final LocatedMessage locatedMessageActualError = e.message.withLocation(uri, fileOffset, noLength); final List<LocatedMessage> contextMessages = <LocatedMessage>[ locatedMessageActualError ]; if (e.context != null) contextMessages.addAll(e.context); for (final TreeNode node in contextChain) { if (node == e.node) continue; final Uri uri = getFileUri(node); final int fileOffset = getFileOffset(uri, node); contextMessages.add( messageConstEvalContext.withLocation(uri, fileOffset, noLength)); } { final Uri uri = getFileUri(node); final int fileOffset = getFileOffset(uri, node); final LocatedMessage locatedMessage = messageConstEvalStartingPoint .withLocation(uri, fileOffset, noLength); errorReporter.report(locatedMessage, contextMessages); } return new UnevaluatedConstant(new InvalidExpression(e.message.message)); } on _AbortDueToInvalidExpression catch (e) { InvalidExpression invalid = new InvalidExpression(e.message) ..fileOffset = node.fileOffset; errorReporter.reportInvalidExpression(invalid); return new UnevaluatedConstant(invalid); } } /// Report an error that has been detected during constant evaluation. Null report(TreeNode node, Message message, {List<LocatedMessage> context}) { throw new _AbortDueToError(node, message, context: context); } /// Report a construct that should not occur inside a potentially constant /// expression. It is assumed that an error has already been reported. Null reportInvalid(TreeNode node, String message) { throw new _AbortDueToInvalidExpression(node, message); } /// Produce an unevaluated constant node for an expression. Constant unevaluated(Expression original, Expression replacement) { replacement.fileOffset = original.fileOffset; return new UnevaluatedConstant( new FileUriExpression(replacement, getFileUri(original)) ..fileOffset = original.fileOffset); } Expression removeRedundantFileUriExpressions(Expression node) { return node.accept(new RedundantFileUriExpressionRemover()) as Expression; } /// Extract an expression from a (possibly unevaluated) constant to become /// part of the expression tree of another unevaluated constant. /// Makes sure a particular expression occurs only once in the tree by /// cloning further instances. Expression extract(Constant constant) { Expression expression = constant.asExpression(); if (!replacementNodes.add(expression)) { expression = cloner.clone(expression); replacementNodes.add(expression); } return expression; } /// Enter a region of lazy evaluation. All leaf nodes are evaluated normally /// (to ensure inlining of referenced local variables), but composite nodes /// always treat their children as unevaluated, resulting in a partially /// evaluated clone of the original expression tree. /// Lazy evaluation is used for the subtrees of lazy operations with /// unevaluated conditions to ensure no errors are reported for problems /// in the subtree as long as the subtree is potentially constant. void enterLazy() => lazyDepth++; /// Leave a (possibly nested) region of lazy evaluation. void leaveLazy() => lazyDepth--; Constant lower(Constant original, Constant replacement) { if (!identical(original, replacement)) { original = canonicalize(original); replacement = canonicalize(replacement); lowered[replacement] = original; return replacement; } return canonicalize(replacement); } Constant unlower(Constant constant) { return lowered[constant] ?? constant; } Constant lowerListConstant(ListConstant constant) { if (shouldBeUnevaluated) return constant; return lower(constant, backend.lowerListConstant(constant)); } Constant lowerSetConstant(SetConstant constant) { if (shouldBeUnevaluated) return constant; return lower(constant, backend.lowerSetConstant(constant)); } Constant lowerMapConstant(MapConstant constant) { if (shouldBeUnevaluated) return constant; return lower(constant, backend.lowerMapConstant(constant)); } /// Evaluate [node] and possibly cache the evaluation result. /// @throws _AbortDueToError or _AbortDueToInvalidExpression if expression /// can't be evaluated. Constant _evaluateSubexpression(Expression node) { bool wasUnevaluated = seenUnevaluatedChild; seenUnevaluatedChild = false; Constant result; if (env.isEmpty) { // We only try to evaluate the same [node] *once* within an empty // environment. if (nodeCache.containsKey(node)) { result = nodeCache[node] ?? report(node, messageConstEvalCircularity); } else { nodeCache[node] = null; try { result = nodeCache[node] = node.accept(this); } catch (e) { nodeCache.remove(node); rethrow; } } } else { result = node.accept(this); } seenUnevaluatedChild = wasUnevaluated || result is UnevaluatedConstant; return result; } Constant _evaluateNullableSubexpression(Expression node) { if (node == null) return nullConstant; return _evaluateSubexpression(node); } T runInsideContext<T>(TreeNode node, T fun()) { try { pushContext(node); return fun(); } finally { popContext(node); } } T runInsideContextIfNoContext<T>(TreeNode node, T fun()) { if (contextChain.isEmpty) { return runInsideContext(node, fun); } else { return fun(); } } void pushContext(TreeNode contextNode) { contextChain.add(contextNode); } void popContext(TreeNode contextNode) { assert(contextChain.last == contextNode); contextChain.length = contextChain.length - 1; } @override Constant defaultTreeNode(Node node) { // Only a subset of the expression language is valid for constant // evaluation. return reportInvalid( node, 'Constant evaluation has no support for ${node.runtimeType}!'); } @override Constant visitFileUriExpression(FileUriExpression node) { return _evaluateSubexpression(node.expression); } @override Constant visitNullLiteral(NullLiteral node) => nullConstant; @override Constant visitBoolLiteral(BoolLiteral node) { return makeBoolConstant(node.value); } @override Constant visitIntLiteral(IntLiteral node) { // The frontend ensures that integer literals are valid according to the // target representation. return canonicalize(intFolder.makeIntConstant(node.value, unsigned: true)); } @override Constant visitDoubleLiteral(DoubleLiteral node) { return canonicalize(new DoubleConstant(node.value)); } @override Constant visitStringLiteral(StringLiteral node) { return canonicalize(new StringConstant(node.value)); } @override Constant visitTypeLiteral(TypeLiteral node) { final DartType type = evaluateDartType(node, node.type); return canonicalize(new TypeLiteralConstant(type)); } @override Constant visitConstantExpression(ConstantExpression node) { Constant constant = node.constant; Constant result = constant; if (constant is UnevaluatedConstant) { result = runInsideContext(constant.expression, () { return _evaluateSubexpression(constant.expression); }); } // If there were already constants in the AST then we make sure we // re-canonicalize them. After running the transformer we will therefore // have a fully-canonicalized constant DAG with roots coming from the // [ConstantExpression] nodes in the AST. return canonicalize(result); } @override Constant visitListLiteral(ListLiteral node) { if (!node.isConst) { return reportInvalid(node, "Non-constant list literal"); } final ListConstantBuilder builder = new ListConstantBuilder(node, node.typeArgument, this); for (Expression element in node.expressions) { builder.add(element); } return builder.build(); } @override Constant visitListConcatenation(ListConcatenation node) { final ListConstantBuilder builder = new ListConstantBuilder(node, node.typeArgument, this); for (Expression list in node.lists) { builder.addSpread(list); } return builder.build(); } @override Constant visitSetLiteral(SetLiteral node) { if (!node.isConst) { return reportInvalid(node, "Non-constant set literal"); } final SetConstantBuilder builder = new SetConstantBuilder(node, node.typeArgument, this); for (Expression element in node.expressions) { builder.add(element); } return builder.build(); } @override Constant visitSetConcatenation(SetConcatenation node) { final SetConstantBuilder builder = new SetConstantBuilder(node, node.typeArgument, this); for (Expression set_ in node.sets) { builder.addSpread(set_); } return builder.build(); } @override Constant visitMapLiteral(MapLiteral node) { if (!node.isConst) { return reportInvalid(node, "Non-constant map literal"); } final MapConstantBuilder builder = new MapConstantBuilder(node, node.keyType, node.valueType, this); for (MapEntry element in node.entries) { builder.add(element); } return builder.build(); } @override Constant visitMapConcatenation(MapConcatenation node) { final MapConstantBuilder builder = new MapConstantBuilder(node, node.keyType, node.valueType, this); for (Expression map in node.maps) { builder.addSpread(map); } return builder.build(); } @override Constant visitFunctionExpression(FunctionExpression node) { return reportInvalid(node, "Function literal"); } @override Constant visitConstructorInvocation(ConstructorInvocation node) { final Constructor constructor = node.target; final Class klass = constructor.enclosingClass; bool isSymbol = klass == coreTypes.internalSymbolClass; if (!constructor.isConst) { return reportInvalid(node, 'Non-const constructor invocation.'); } if (constructor.function.body != null && constructor.function.body is! EmptyStatement) { return reportInvalid( node, 'Constructor "$node" has non-trivial body ' '"${constructor.function.body.runtimeType}".'); } if (klass.isAbstract) { return reportInvalid( node, 'Constructor "$node" belongs to abstract class "${klass}".'); } final List<Constant> positionals = evaluatePositionalArguments(node.arguments); final Map<String, Constant> named = evaluateNamedArguments(node.arguments); if (isSymbol && shouldBeUnevaluated) { return unevaluated( node, new ConstructorInvocation(constructor, unevaluatedArguments(positionals, named, node.arguments.types), isConst: true)); } // Special case the dart:core's Symbol class here and convert it to a // [SymbolConstant]. For invalid values we report a compile-time error. if (isSymbol) { final Constant nameValue = positionals.single; if (nameValue is StringConstant && isValidSymbolName(nameValue.value)) { return canonicalize(new SymbolConstant(nameValue.value, null)); } return report(node.arguments.positional.first, templateConstEvalInvalidSymbolName.withArguments(nameValue)); } final List<DartType> typeArguments = evaluateTypeArguments(node, node.arguments); // Fill in any missing type arguments with "dynamic". for (int i = typeArguments.length; i < klass.typeParameters.length; i++) { typeArguments.add(const DynamicType()); } // Start building a new instance. return withNewInstanceBuilder(klass, typeArguments, () { return runInsideContextIfNoContext(node, () { // "Run" the constructor (and any super constructor calls), which will // initialize the fields of the new instance. if (shouldBeUnevaluated) { enterLazy(); handleConstructorInvocation( constructor, typeArguments, positionals, named); leaveLazy(); return unevaluated(node, instanceBuilder.buildUnevaluatedInstance()); } handleConstructorInvocation( constructor, typeArguments, positionals, named); if (shouldBeUnevaluated) { return unevaluated(node, instanceBuilder.buildUnevaluatedInstance()); } return canonicalize(instanceBuilder.buildInstance()); }); }); } @override Constant visitInstanceCreation(InstanceCreation node) { return withNewInstanceBuilder(node.classNode, node.typeArguments, () { for (AssertStatement statement in node.asserts) { checkAssert(statement); } node.fieldValues.forEach((Reference fieldRef, Expression value) { instanceBuilder.setFieldValue( fieldRef.asField, _evaluateSubexpression(value)); }); node.unusedArguments.forEach((Expression value) { Constant constant = _evaluateSubexpression(value); if (constant is UnevaluatedConstant) { instanceBuilder.unusedArguments.add(extract(constant)); } }); if (shouldBeUnevaluated) { return unevaluated(node, instanceBuilder.buildUnevaluatedInstance()); } return canonicalize(instanceBuilder.buildInstance()); }); } bool isValidSymbolName(String name) { // See https://api.dartlang.org/stable/2.0.0/dart-core/Symbol/Symbol.html: // // A qualified name is a valid name preceded by a public identifier name // and a '.', e.g., foo.bar.baz= is a qualified version of baz=. // // That means that the content of the name String must be either // - a valid public Dart identifier (that is, an identifier not // starting with "_"), // - such an identifier followed by "=" (a setter name), // - the name of a declarable operator, // - any of the above preceded by any number of qualifiers, where a // qualifier is a non-private identifier followed by '.', // - or the empty string (the default name of a library with no library // name declaration). const List<String> operatorNames = const <String>[ '+', '-', '*', '/', '%', '~/', '&', '|', '^', '~', '<<', '>>', '<', '<=', '>', '>=', '==', '[]', '[]=', 'unary-' ]; if (name == null) return false; if (name == '') return true; final List<String> parts = name.split('.'); // Each qualifier must be a public identifier. for (int i = 0; i < parts.length - 1; ++i) { if (!isValidPublicIdentifier(parts[i])) return false; } String last = parts.last; if (operatorNames.contains(last)) { return true; } if (last.endsWith('=')) { last = last.substring(0, last.length - 1); } if (!isValidPublicIdentifier(last)) return false; return true; } /// From the Dart Language specification: /// /// IDENTIFIER: /// IDENTIFIER_START IDENTIFIER_PART* /// /// IDENTIFIER_START: /// IDENTIFIER_START_NO_DOLLAR | ‘$’ /// /// IDENTIFIER_PART: /// IDENTIFIER_START | DIGIT /// /// IDENTIFIER_NO_DOLLAR: /// IDENTIFIER_START_NO_DOLLAR IDENTIFIER_PART_NO_DOLLAR* /// /// IDENTIFIER_START_NO_DOLLAR: /// LETTER | '_' /// /// IDENTIFIER_PART_NO_DOLLAR: /// IDENTIFIER_START_NO_DOLLAR | DIGIT /// static final RegExp publicIdentifierRegExp = new RegExp(r'^[a-zA-Z$][a-zA-Z0-9_$]*$'); static const List<String> nonUsableKeywords = const <String>[ 'assert', 'break', 'case', 'catch', 'class', 'const', 'continue', 'default', 'do', 'else', 'enum', 'extends', 'false', 'final', 'finally', 'for', 'if', 'in', 'is', 'new', 'null', 'rethrow', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'var', 'while', 'with', ]; bool isValidPublicIdentifier(String name) { return publicIdentifierRegExp.hasMatch(name) && !nonUsableKeywords.contains(name); } void handleConstructorInvocation( Constructor constructor, List<DartType> typeArguments, List<Constant> positionalArguments, Map<String, Constant> namedArguments) { return runInsideContext(constructor, () { return withNewEnvironment(() { final Class klass = constructor.enclosingClass; final FunctionNode function = constructor.function; // We simulate now the constructor invocation. // Step 1) Map type arguments and normal arguments from caller to // callee. for (int i = 0; i < klass.typeParameters.length; i++) { env.addTypeParameterValue(klass.typeParameters[i], typeArguments[i]); } for (int i = 0; i < function.positionalParameters.length; i++) { final VariableDeclaration parameter = function.positionalParameters[i]; final Constant value = (i < positionalArguments.length) ? positionalArguments[i] : _evaluateNullableSubexpression(parameter.initializer); env.addVariableValue(parameter, value); } for (final VariableDeclaration parameter in function.namedParameters) { final Constant value = namedArguments[parameter.name] ?? _evaluateNullableSubexpression(parameter.initializer); env.addVariableValue(parameter, value); } // Step 2) Run all initializers (including super calls) with environment // setup. for (final Field field in klass.fields) { if (!field.isStatic) { instanceBuilder.setFieldValue( field, _evaluateNullableSubexpression(field.initializer)); } } for (final Initializer init in constructor.initializers) { if (init is FieldInitializer) { instanceBuilder.setFieldValue( init.field, _evaluateSubexpression(init.value)); } else if (init is LocalInitializer) { final VariableDeclaration variable = init.variable; env.addVariableValue( variable, _evaluateSubexpression(variable.initializer)); } else if (init is SuperInitializer) { handleConstructorInvocation( init.target, evaluateSuperTypeArguments( init, constructor.enclosingClass.supertype), evaluatePositionalArguments(init.arguments), evaluateNamedArguments(init.arguments)); } else if (init is RedirectingInitializer) { // Since a redirecting constructor targets a constructor of the same // class, we pass the same [typeArguments]. handleConstructorInvocation( init.target, typeArguments, evaluatePositionalArguments(init.arguments), evaluateNamedArguments(init.arguments)); } else if (init is AssertInitializer) { checkAssert(init.statement); } else { return reportInvalid( constructor, 'No support for handling initializer of type ' '"${init.runtimeType}".'); } } for (UnevaluatedConstant constant in env.unevaluatedUnreadConstants) { instanceBuilder.unusedArguments.add(extract(constant)); } }); }); } void checkAssert(AssertStatement statement) { final Constant condition = _evaluateSubexpression(statement.condition); if (shouldBeUnevaluated) { Expression message = null; if (statement.message != null) { enterLazy(); message = extract(_evaluateSubexpression(statement.message)); leaveLazy(); } instanceBuilder.asserts.add(new AssertStatement(extract(condition), message: message, conditionStartOffset: statement.conditionStartOffset, conditionEndOffset: statement.conditionEndOffset)); } else if (condition is BoolConstant) { if (!condition.value) { if (statement.message == null) { report(statement.condition, messageConstEvalFailedAssertion); } final Constant message = _evaluateSubexpression(statement.message); if (shouldBeUnevaluated) { instanceBuilder.asserts.add(new AssertStatement(extract(condition), message: extract(message), conditionStartOffset: statement.conditionStartOffset, conditionEndOffset: statement.conditionEndOffset)); } else if (message is StringConstant) { report( statement.condition, templateConstEvalFailedAssertionWithMessage .withArguments(message.value)); } else { report( statement.message, templateConstEvalInvalidType.withArguments( message, typeEnvironment.coreTypes.stringLegacyRawType, message.getType(typeEnvironment))); } } } else { report( statement.condition, templateConstEvalInvalidType.withArguments( condition, typeEnvironment.coreTypes.boolLegacyRawType, condition.getType(typeEnvironment))); } } @override Constant visitInvalidExpression(InvalidExpression node) { return reportInvalid(node, node.message); } @override Constant visitMethodInvocation(MethodInvocation node) { // We have no support for generic method invocation atm. assert(node.arguments.named.isEmpty); final Constant receiver = _evaluateSubexpression(node.receiver); final List<Constant> arguments = evaluatePositionalArguments(node.arguments); if (shouldBeUnevaluated) { return unevaluated( node, new MethodInvocation(extract(receiver), node.name, unevaluatedArguments(arguments, {}, node.arguments.types))); } final String op = node.name.name; // Handle == and != first (it's common between all types). Since `a != b` is // parsed as `!(a == b)` it is handled implicitly through ==. if (arguments.length == 1 && op == '==') { final Constant right = arguments[0]; if (receiver is NullConstant || receiver is BoolConstant || receiver is IntConstant || receiver is DoubleConstant || receiver is StringConstant || right is NullConstant) { // [DoubleConstant] uses [identical] to determine equality, so we need // to take the special cases into account. return doubleSpecialCases(receiver, right) ?? makeBoolConstant(receiver == right); } else { return report( node, templateConstEvalInvalidEqualsOperandType.withArguments( receiver, receiver.getType(typeEnvironment))); } } // This is a white-listed set of methods we need to support on constants. if (receiver is StringConstant) { if (arguments.length == 1) { switch (op) { case '+': final Constant other = arguments[0]; if (other is StringConstant) { return canonicalize( new StringConstant(receiver.value + other.value)); } return report( node, templateConstEvalInvalidBinaryOperandType.withArguments( '+', receiver, typeEnvironment.coreTypes.stringLegacyRawType, other.getType(typeEnvironment))); } } } else if (intFolder.isInt(receiver)) { if (arguments.length == 0) { return canonicalize(intFolder.foldUnaryOperator(node, op, receiver)); } else if (arguments.length == 1) { final Constant other = arguments[0]; if (intFolder.isInt(other)) { return canonicalize( intFolder.foldBinaryOperator(node, op, receiver, other)); } else if (other is DoubleConstant) { if ((op == '|' || op == '&' || op == '^') || (op == '<<' || op == '>>' || op == '>>>')) { return report( node, templateConstEvalInvalidBinaryOperandType.withArguments( op, other, typeEnvironment.coreTypes.intLegacyRawType, other.getType(typeEnvironment))); } num receiverValue = (receiver as PrimitiveConstant<num>).value; return canonicalize(evaluateBinaryNumericOperation( op, receiverValue, other.value, node)); } return report( node, templateConstEvalInvalidBinaryOperandType.withArguments( op, receiver, typeEnvironment.coreTypes.numLegacyRawType, other.getType(typeEnvironment))); } } else if (receiver is DoubleConstant) { if ((op == '|' || op == '&' || op == '^') || (op == '<<' || op == '>>' || op == '>>>')) { return report( node, templateConstEvalInvalidBinaryOperandType.withArguments( op, receiver, typeEnvironment.coreTypes.intLegacyRawType, receiver.getType(typeEnvironment))); } if (arguments.length == 0) { switch (op) { case 'unary-': return canonicalize(new DoubleConstant(-receiver.value)); } } else if (arguments.length == 1) { final Constant other = arguments[0]; if (other is IntConstant || other is DoubleConstant) { final num value = (other as PrimitiveConstant<num>).value; return canonicalize( evaluateBinaryNumericOperation(op, receiver.value, value, node)); } return report( node, templateConstEvalInvalidBinaryOperandType.withArguments( op, receiver, typeEnvironment.coreTypes.numLegacyRawType, other.getType(typeEnvironment))); } } else if (receiver is BoolConstant) { if (arguments.length == 1) { final Constant other = arguments[0]; if (other is BoolConstant) { switch (op) { case '|': return canonicalize( new BoolConstant(receiver.value || other.value)); case '&': return canonicalize( new BoolConstant(receiver.value && other.value)); case '^': return canonicalize( new BoolConstant(receiver.value != other.value)); } } } } else if (receiver is NullConstant) { return report(node, messageConstEvalNullValue); } return report(node, templateConstEvalInvalidMethodInvocation.withArguments(op, receiver)); } @override Constant visitLogicalExpression(LogicalExpression node) { final Constant left = _evaluateSubexpression(node.left); if (shouldBeUnevaluated) { enterLazy(); Constant right = _evaluateSubexpression(node.right); leaveLazy(); return unevaluated(node, new LogicalExpression(extract(left), node.operator, extract(right))); } switch (node.operator) { case '||': if (left is BoolConstant) { if (left.value) return trueConstant; final Constant right = _evaluateSubexpression(node.right); if (right is BoolConstant || right is UnevaluatedConstant) { return right; } return report( node, templateConstEvalInvalidBinaryOperandType.withArguments( node.operator, left, typeEnvironment.coreTypes.boolLegacyRawType, right.getType(typeEnvironment))); } return report( node, templateConstEvalInvalidMethodInvocation.withArguments( node.operator, left)); case '&&': if (left is BoolConstant) { if (!left.value) return falseConstant; final Constant right = _evaluateSubexpression(node.right); if (right is BoolConstant || right is UnevaluatedConstant) { return right; } return report( node, templateConstEvalInvalidBinaryOperandType.withArguments( node.operator, left, typeEnvironment.coreTypes.boolLegacyRawType, right.getType(typeEnvironment))); } return report( node, templateConstEvalInvalidMethodInvocation.withArguments( node.operator, left)); case '??': return (left is! NullConstant) ? left : _evaluateSubexpression(node.right); default: return report( node, templateConstEvalInvalidMethodInvocation.withArguments( node.operator, left)); } } @override Constant visitConditionalExpression(ConditionalExpression node) { final Constant condition = _evaluateSubexpression(node.condition); if (condition == trueConstant) { return _evaluateSubexpression(node.then); } else if (condition == falseConstant) { return _evaluateSubexpression(node.otherwise); } else if (shouldBeUnevaluated) { enterLazy(); Constant then = _evaluateSubexpression(node.then); Constant otherwise = _evaluateSubexpression(node.otherwise); leaveLazy(); return unevaluated( node, new ConditionalExpression(extract(condition), extract(then), extract(otherwise), node.staticType)); } else { return report( node.condition, templateConstEvalInvalidType.withArguments( condition, typeEnvironment.coreTypes.boolLegacyRawType, condition.getType(typeEnvironment))); } } @override Constant visitPropertyGet(PropertyGet node) { if (node.receiver is ThisExpression) { // Access "this" during instance creation. if (instanceBuilder == null) { return reportInvalid(node, 'Instance field access outside constructor'); } for (final Field field in instanceBuilder.fields.keys) { if (field.name == node.name) { return instanceBuilder.fields[field]; } } return reportInvalid(node, 'Could not evaluate field get ${node.name} on incomplete instance'); } final Constant receiver = _evaluateSubexpression(node.receiver); if (receiver is StringConstant && node.name.name == 'length') { return canonicalize(intFolder.makeIntConstant(receiver.value.length)); } else if (shouldBeUnevaluated) { return unevaluated(node, new PropertyGet(extract(receiver), node.name, node.interfaceTarget)); } else if (receiver is NullConstant) { return report(node, messageConstEvalNullValue); } return report( node, templateConstEvalInvalidPropertyGet.withArguments( node.name.name, receiver)); } @override Constant visitLet(Let node) { env.addVariableValue( node.variable, _evaluateSubexpression(node.variable.initializer)); return _evaluateSubexpression(node.body); } @override Constant visitVariableGet(VariableGet node) { // Not every variable which a [VariableGet] refers to must be marked as // constant. For example function parameters as well as constructs // desugared to [Let] expressions are ok. // // TODO(kustermann): The heuristic of allowing all [VariableGet]s on [Let] // variables might allow more than it should. final VariableDeclaration variable = node.variable; if (variable.parent is Let || _isFormalParameter(variable)) { return env.lookupVariable(node.variable) ?? report( node, templateConstEvalNonConstantVariableGet .withArguments(variable.name)); } if (variable.isConst) { return _evaluateSubexpression(variable.initializer); } return reportInvalid(node, 'Variable get of a non-const variable.'); } @override Constant visitStaticGet(StaticGet node) { return withNewEnvironment(() { final Member target = node.target; if (target is Field) { if (target.isConst) { return runInsideContext(target, () { return _evaluateSubexpression(target.initializer); }); } return report( node, templateConstEvalInvalidStaticInvocation .withArguments(target.name.name)); } else if (target is Procedure) { if (target.kind == ProcedureKind.Method) { return canonicalize(new TearOffConstant(target)); } return report( node, templateConstEvalInvalidStaticInvocation .withArguments(target.name.name)); } else { reportInvalid( node, 'No support for ${target.runtimeType} in a static-get.'); return null; } }); } @override Constant visitStringConcatenation(StringConcatenation node) { final List<Object> concatenated = <Object>[new StringBuffer()]; for (int i = 0; i < node.expressions.length; i++) { Constant constant = _evaluateSubexpression(node.expressions[i]); if (constant is PrimitiveConstant<Object>) { String value; if (constant is DoubleConstant && intFolder.isInt(constant)) { value = new BigInt.from(constant.value).toString(); } else { value = constant.toString(); } Object last = concatenated.last; if (last is StringBuffer) { last.write(value); } else { concatenated.add(new StringBuffer(value)); } } else if (shouldBeUnevaluated) { // The constant is either unevaluated or a non-primitive in an // unevaluated context. In both cases we defer the evaluation and/or // error reporting till later. concatenated.add(constant); } else { return report( node, templateConstEvalInvalidStringInterpolationOperand .withArguments(constant)); } } if (concatenated.length > 1) { final List<Expression> expressions = new List<Expression>(concatenated.length); for (int i = 0; i < concatenated.length; i++) { Object value = concatenated[i]; if (value is StringBuffer) { expressions[i] = new ConstantExpression( canonicalize(new StringConstant(value.toString()))); } else { // The value is either unevaluated constant or a non-primitive // constant in an unevaluated expression. expressions[i] = extract(value); } } return unevaluated(node, new StringConcatenation(expressions)); } return canonicalize(new StringConstant(concatenated.single.toString())); } @override Constant visitStaticInvocation(StaticInvocation node) { final Procedure target = node.target; final Arguments arguments = node.arguments; final List<Constant> positionals = evaluatePositionalArguments(arguments); final Map<String, Constant> named = evaluateNamedArguments(arguments); if (shouldBeUnevaluated) { return unevaluated( node, new StaticInvocation( target, unevaluatedArguments(positionals, named, arguments.types), isConst: true)); } if (target.kind == ProcedureKind.Factory) { if (target.isConst && target.name.name == "fromEnvironment" && target.enclosingLibrary == coreTypes.coreLibrary && positionals.length == 1) { if (environmentDefines != null) { // Evaluate environment constant. Constant name = positionals.single; if (name is StringConstant) { String value = environmentDefines[name.value]; Constant defaultValue = named["defaultValue"]; if (target.enclosingClass == coreTypes.boolClass) { Constant boolConstant = value == "true" ? trueConstant : value == "false" ? falseConstant : defaultValue is BoolConstant ? makeBoolConstant(defaultValue.value) : defaultValue is NullConstant ? nullConstant : falseConstant; return boolConstant; } else if (target.enclosingClass == coreTypes.intClass) { int intValue = value != null ? int.tryParse(value) : null; Constant intConstant; if (intValue != null) { bool negated = value.startsWith('-'); intConstant = intFolder.makeIntConstant(intValue, unsigned: !negated); } else if (intFolder.isInt(defaultValue)) { intConstant = defaultValue; } else { intConstant = nullConstant; } return canonicalize(intConstant); } else if (target.enclosingClass == coreTypes.stringClass) { value ??= defaultValue is StringConstant ? defaultValue.value : null; if (value == null) return nullConstant; return canonicalize(new StringConstant(value)); } } else if (name is NullConstant) { return report(node, messageConstEvalNullValue); } } else { // Leave environment constant unevaluated. return unevaluated( node, new StaticInvocation(target, unevaluatedArguments(positionals, named, arguments.types), isConst: true)); } } } else if (target.name.name == 'identical') { // Ensure the "identical()" function comes from dart:core. final TreeNode parent = target.parent; if (parent is Library && parent == coreTypes.coreLibrary) { final Constant left = positionals[0]; final Constant right = positionals[1]; if (targetingJavaScript) { // In JavaScript, we lower [identical] to `===`, so we need to take // the double special cases into account. return doubleSpecialCases(left, right) ?? makeBoolConstant(identical(left, right)); } // Since we canonicalize constants during the evaluation, we can use // identical here. return makeBoolConstant(identical(left, right)); } } String name = target.name.name; if (target is Procedure && target.isFactory) { if (name.isEmpty) { name = target.enclosingClass.name; } else { name = '${target.enclosingClass.name}.${name}'; } } return reportInvalid(node, "Invocation of $name"); } @override Constant visitAsExpression(AsExpression node) { final Constant constant = _evaluateSubexpression(node.operand); if (shouldBeUnevaluated) { return unevaluated(node, new AsExpression(extract(constant), env.substituteType(node.type))); } return ensureIsSubtype(constant, evaluateDartType(node, node.type), node); } @override Constant visitIsExpression(IsExpression node) { final Constant constant = node.operand.accept(this); if (shouldBeUnevaluated) { return unevaluated(node, new IsExpression(extract(constant), node.type)); } if (constant is NullConstant) { return makeBoolConstant(node.type == typeEnvironment.nullType || node.type == typeEnvironment.coreTypes.objectLegacyRawType || node.type is DynamicType); } return makeBoolConstant( isSubtype(constant, evaluateDartType(node, node.type))); } @override Constant visitNot(Not node) { final Constant constant = _evaluateSubexpression(node.operand); if (constant is BoolConstant) { return makeBoolConstant(constant != trueConstant); } if (shouldBeUnevaluated) { return unevaluated(node, new Not(extract(constant))); } return report( node, templateConstEvalInvalidType.withArguments( constant, typeEnvironment.coreTypes.boolLegacyRawType, constant.getType(typeEnvironment))); } @override Constant visitSymbolLiteral(SymbolLiteral node) { final Reference libraryReference = node.value.startsWith('_') ? libraryOf(node).reference : null; return canonicalize(new SymbolConstant(node.value, libraryReference)); } @override Constant visitInstantiation(Instantiation node) { final Constant constant = _evaluateSubexpression(node.expression); if (shouldBeUnevaluated) { return unevaluated( node, new Instantiation(extract(constant), node.typeArguments.map((t) => env.substituteType(t)).toList())); } if (constant is TearOffConstant) { if (node.typeArguments.length == constant.procedure.function.typeParameters.length) { final List<DartType> typeArguments = evaluateDartTypes(node, node.typeArguments); return canonicalize( new PartialInstantiationConstant(constant, typeArguments)); } return reportInvalid( node, 'The number of type arguments supplied in the partial instantiation ' 'does not match the number of type arguments of the $constant.'); } // The inner expression in an instantiation can never be null, since // instantiations are only inferred on direct references to declarations. return reportInvalid( node, 'Only tear-off constants can be partially instantiated.'); } @override Constant visitCheckLibraryIsLoaded(CheckLibraryIsLoaded node) { return report( node, templateConstEvalDeferredLibrary.withArguments(node.import.name)); } // Helper methods: /// If both constants are DoubleConstant whose values would give different /// results from == and [identical], return the result of ==. Otherwise /// return null. Constant doubleSpecialCases(Constant a, Constant b) { if (a is DoubleConstant && b is DoubleConstant) { if (a.value.isNaN && b.value.isNaN) return falseConstant; if (a.value == 0.0 && b.value == 0.0) return trueConstant; } return null; } bool hasPrimitiveEqual(Constant constant) { if (intFolder.isInt(constant)) return true; DartType type = constant.getType(typeEnvironment); return !(type is InterfaceType && !classHasPrimitiveEqual(type.classNode)); } bool classHasPrimitiveEqual(Class klass) { bool cached = primitiveEqualCache[klass]; if (cached != null) return cached; for (Procedure procedure in klass.procedures) { if (procedure.kind == ProcedureKind.Operator && procedure.name.name == '==' && !procedure.isAbstract && !procedure.isForwardingStub) { return primitiveEqualCache[klass] = false; } } if (klass.supertype == null) return true; // To be on the safe side return primitiveEqualCache[klass] = classHasPrimitiveEqual(klass.supertype.classNode); } BoolConstant makeBoolConstant(bool value) => value ? trueConstant : falseConstant; bool isSubtype(Constant constant, DartType type) { DartType constantType = constant.getType(typeEnvironment); if (targetingJavaScript) { if (constantType == typeEnvironment.coreTypes.intLegacyRawType && type == typeEnvironment.coreTypes.doubleLegacyRawType) { // With JS semantics, an integer is also a double. return true; } if (constantType == typeEnvironment.coreTypes.doubleLegacyRawType && type == typeEnvironment.coreTypes.intLegacyRawType) { double value = (constant as DoubleConstant).value; if (value.isFinite && value == value.truncateToDouble()) { return true; } } } return typeEnvironment.isSubtypeOf( constantType, type, SubtypeCheckMode.ignoringNullabilities); } Constant ensureIsSubtype(Constant constant, DartType type, TreeNode node) { if (!isSubtype(constant, type)) { return report( node, templateConstEvalInvalidType.withArguments( constant, type, constant.getType(typeEnvironment))); } return constant; } List<DartType> evaluateTypeArguments(TreeNode node, Arguments arguments) { return evaluateDartTypes(node, arguments.types); } List<DartType> evaluateSuperTypeArguments(TreeNode node, Supertype type) { return evaluateDartTypes(node, type.typeArguments); } List<DartType> evaluateDartTypes(TreeNode node, List<DartType> types) { // TODO: Once the frontend guarantees that there are no free type variables // left over after substitution, we can enable this shortcut again: // if (env.isEmpty) return types; return types.map((t) => evaluateDartType(node, t)).toList(); } DartType evaluateDartType(TreeNode node, DartType type) { final DartType result = env.substituteType(type); if (!isInstantiated(result)) { return report( node, templateConstEvalFreeTypeParameter.withArguments(type)); } return result; } List<Constant> evaluatePositionalArguments(Arguments arguments) { return arguments.positional.map((Expression node) { return _evaluateSubexpression(node); }).toList(); } Map<String, Constant> evaluateNamedArguments(Arguments arguments) { if (arguments.named.isEmpty) return const <String, Constant>{}; final Map<String, Constant> named = {}; arguments.named.forEach((NamedExpression pair) { named[pair.name] = _evaluateSubexpression(pair.value); }); return named; } Arguments unevaluatedArguments(List<Constant> positionalArgs, Map<String, Constant> namedArgs, List<DartType> types) { final List<Expression> positional = new List<Expression>(positionalArgs.length); final List<NamedExpression> named = new List<NamedExpression>(namedArgs.length); for (int i = 0; i < positionalArgs.length; ++i) { positional[i] = extract(positionalArgs[i]); } int i = 0; namedArgs.forEach((String name, Constant value) { named[i++] = new NamedExpression(name, extract(value)); }); return new Arguments(positional, named: named, types: types); } Constant canonicalize(Constant constant) { return canonicalizationCache.putIfAbsent(constant, () => constant); } T withNewInstanceBuilder<T>( Class klass, List<DartType> typeArguments, T fn()) { InstanceBuilder old = instanceBuilder; try { instanceBuilder = new InstanceBuilder(this, klass, typeArguments); return fn(); } finally { instanceBuilder = old; } } T withNewEnvironment<T>(T fn()) { final EvaluationEnvironment oldEnv = env; try { env = new EvaluationEnvironment(); return fn(); } finally { env = oldEnv; } } /// Binary operation between two operands, at least one of which is a double. Constant evaluateBinaryNumericOperation( String op, num a, num b, TreeNode node) { switch (op) { case '+': return new DoubleConstant(a + b); case '-': return new DoubleConstant(a - b); case '*': return new DoubleConstant(a * b); case '/': return new DoubleConstant(a / b); case '~/': if (b == 0) { return report( node, templateConstEvalZeroDivisor.withArguments(op, '$a')); } return intFolder.truncatingDivide(a, b); case '%': return new DoubleConstant(a % b); } switch (op) { case '<': return makeBoolConstant(a < b); case '<=': return makeBoolConstant(a <= b); case '>=': return makeBoolConstant(a >= b); case '>': return makeBoolConstant(a > b); } return reportInvalid(node, "Unexpected binary numeric operation '$op'."); } Library libraryOf(TreeNode node) { // The tree structure of the kernel AST ensures we always have an enclosing // library. while (true) { if (node is Library) return node; node = node.parent; } } } /// Holds the necessary information for a constant object, namely /// * the [klass] being instantiated /// * the [typeArguments] used for the instantiation /// * the [fields] the instance will obtain (all fields from the /// instantiated [klass] up to the [Object] klass). class InstanceBuilder { ConstantEvaluator evaluator; /// The class of the new instance. final Class klass; /// The values of the type parameters of the new instance. final List<DartType> typeArguments; /// The field values of the new instance. final Map<Field, Constant> fields = <Field, Constant>{}; final List<AssertStatement> asserts = <AssertStatement>[]; final List<Expression> unusedArguments = <Expression>[]; InstanceBuilder(this.evaluator, this.klass, this.typeArguments); void setFieldValue(Field field, Constant constant) { fields[field] = constant; } InstanceConstant buildInstance() { assert(asserts.isEmpty); final Map<Reference, Constant> fieldValues = <Reference, Constant>{}; fields.forEach((Field field, Constant value) { assert(value is! UnevaluatedConstant); fieldValues[field.reference] = value; }); assert(unusedArguments.isEmpty); return new InstanceConstant(klass.reference, typeArguments, fieldValues); } InstanceCreation buildUnevaluatedInstance() { final Map<Reference, Expression> fieldValues = <Reference, Expression>{}; fields.forEach((Field field, Constant value) { fieldValues[field.reference] = evaluator.extract(value); }); return new InstanceCreation( klass.reference, typeArguments, fieldValues, asserts, unusedArguments); } } /// Holds an environment of type parameters, parameters and variables. class EvaluationEnvironment { /// The values of the type parameters in scope. final Map<TypeParameter, DartType> _typeVariables = <TypeParameter, DartType>{}; /// The values of the parameters/variables in scope. final Map<VariableDeclaration, Constant> _variables = <VariableDeclaration, Constant>{}; /// The variables that hold unevaluated constants. /// /// Variables are removed from this set when looked up, leaving only the /// unread variables at the end. final Set<VariableDeclaration> _unreadUnevaluatedVariables = new Set<VariableDeclaration>(); /// Whether the current environment is empty. bool get isEmpty => _typeVariables.isEmpty && _variables.isEmpty; void addTypeParameterValue(TypeParameter parameter, DartType value) { assert(!_typeVariables.containsKey(parameter)); _typeVariables[parameter] = value; } void addVariableValue(VariableDeclaration variable, Constant value) { _variables[variable] = value; if (value is UnevaluatedConstant) { _unreadUnevaluatedVariables.add(variable); } } DartType lookupParameterValue(TypeParameter parameter) { final DartType value = _typeVariables[parameter]; assert(value != null); return value; } Constant lookupVariable(VariableDeclaration variable) { Constant value = _variables[variable]; if (value is UnevaluatedConstant) { _unreadUnevaluatedVariables.remove(variable); } return value; } /// The unevaluated constants of variables that were never read. Iterable<UnevaluatedConstant> get unevaluatedUnreadConstants { if (_unreadUnevaluatedVariables.isEmpty) return const []; return _unreadUnevaluatedVariables.map<UnevaluatedConstant>( (VariableDeclaration variable) => _variables[variable]); } DartType substituteType(DartType type) { if (_typeVariables.isEmpty) return type; return substitute(type, _typeVariables); } } class RedundantFileUriExpressionRemover extends Transformer { Uri currentFileUri = null; TreeNode visitFileUriExpression(FileUriExpression node) { if (node.fileUri == currentFileUri) { return node.expression.accept(this); } else { Uri oldFileUri = currentFileUri; currentFileUri = node.fileUri; node.expression = node.expression.accept(this) as Expression ..parent = node; currentFileUri = oldFileUri; return node; } } } // Used as control-flow to abort the current evaluation. class _AbortDueToError { final TreeNode node; final Message message; final List<LocatedMessage> context; _AbortDueToError(this.node, this.message, {this.context}); } class _AbortDueToInvalidExpression { final TreeNode node; final String message; _AbortDueToInvalidExpression(this.node, this.message); } abstract class ErrorReporter { const ErrorReporter(); void report(LocatedMessage message, List<LocatedMessage> context); void reportInvalidExpression(InvalidExpression node); } class SimpleErrorReporter implements ErrorReporter { const SimpleErrorReporter(); @override void report(LocatedMessage message, List<LocatedMessage> context) { _report(message); for (LocatedMessage contextMessage in context) { _report(contextMessage); } } @override void reportInvalidExpression(InvalidExpression node) { // Ignored } void _report(LocatedMessage message) { reportMessage(message.uri, message.charOffset, message.message); } void reportMessage(Uri uri, int offset, String message) { io.exitCode = 42; io.stderr.writeln('$uri:$offset Constant evaluation error: $message'); } } class IsInstantiatedVisitor extends DartTypeVisitor<bool> { final _availableVariables = new Set<TypeParameter>(); bool isInstantiated(DartType type) { return type.accept(this); } @override bool defaultDartType(DartType node) { throw 'A visitor method seems to be unimplemented!'; } @override bool visitInvalidType(InvalidType node) => true; @override bool visitDynamicType(DynamicType node) => true; @override bool visitVoidType(VoidType node) => true; @override bool visitBottomType(BottomType node) => true; @override bool visitTypeParameterType(TypeParameterType node) { return _availableVariables.contains(node.parameter); } @override bool visitInterfaceType(InterfaceType node) { return node.typeArguments .every((DartType typeArgument) => typeArgument.accept(this)); } @override bool visitFunctionType(FunctionType node) { final List<TypeParameter> parameters = node.typeParameters; _availableVariables.addAll(parameters); final bool result = node.returnType.accept(this) && node.positionalParameters.every((p) => p.accept(this)) && node.namedParameters.every((p) => p.type.accept(this)); _availableVariables.removeAll(parameters); return result; } @override bool visitTypedefType(TypedefType node) { return node.unalias.accept(this); } } bool _isFormalParameter(VariableDeclaration variable) { final TreeNode parent = variable.parent; if (parent is FunctionNode) { return parent.positionalParameters.contains(variable) || parent.namedParameters.contains(variable); } 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/kernel/implicit_field_type.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.implicit_type; import 'package:kernel/ast.dart' show DartType, DartTypeVisitor, DartTypeVisitor1, Nullability, Visitor; import '../../scanner/token.dart' show Token; import '../problems.dart' show unsupported; import 'kernel_builder.dart' show MemberBuilder; class ImplicitFieldType extends DartType { final MemberBuilder member; Token initializerToken; bool isStarted = false; ImplicitFieldType(this.member, this.initializerToken); Nullability get nullability => unsupported("nullability", member.charOffset, member.fileUri); R accept<R>(DartTypeVisitor<R> v) { throw unsupported("accept", member.charOffset, member.fileUri); } R accept1<R, A>(DartTypeVisitor1<R, A> v, arg) { throw unsupported("accept1", member.charOffset, member.fileUri); } visitChildren(Visitor<Object> v) { unsupported("visitChildren", member.charOffset, member.fileUri); } ImplicitFieldType withNullability(Nullability nullability) { return unsupported("withNullability", member.charOffset, member.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/kernel/inference_visitor.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. part of "kernel_shadow_ast.dart"; class InferenceVisitor implements ExpressionVisitor1<ExpressionInferenceResult, DartType>, StatementVisitor<void>, InitializerVisitor<void> { final ShadowTypeInferrer inferrer; Class mapEntryClass; // Stores the offset of the map entry found by inferMapEntry. int mapEntryOffset = null; // Stores the offset of the map spread found by inferMapEntry. int mapSpreadOffset = null; // Stores the offset of the iterable spread found by inferMapEntry. int iterableSpreadOffset = null; // Stores the type of the iterable spread found by inferMapEntry. DartType iterableSpreadType = null; InferenceVisitor(this.inferrer); ExpressionInferenceResult _unhandledExpression( Expression node, DartType typeContext) { unhandled("${node.runtimeType}", "InferenceVisitor", node.fileOffset, inferrer.helper.uri); return const ExpressionInferenceResult(const InvalidType()); } @override ExpressionInferenceResult defaultExpression( Expression node, DartType typeContext) { if (node is InternalExpression) { switch (node.kind) { case InternalExpressionKind.Cascade: return visitCascade(node, typeContext); case InternalExpressionKind.CompoundExtensionIndexSet: return visitCompoundExtensionIndexSet(node, typeContext); case InternalExpressionKind.CompoundIndexSet: return visitCompoundIndexSet(node, typeContext); case InternalExpressionKind.CompoundPropertySet: return visitCompoundPropertySet(node, typeContext); case InternalExpressionKind.CompoundSuperIndexSet: return visitCompoundSuperIndexSet(node, typeContext); case InternalExpressionKind.DeferredCheck: return visitDeferredCheck(node, typeContext); case InternalExpressionKind.ExtensionIndexSet: return visitExtensionIndexSet(node, typeContext); case InternalExpressionKind.ExtensionTearOff: return visitExtensionTearOff(node, typeContext); case InternalExpressionKind.ExtensionSet: return visitExtensionSet(node, typeContext); case InternalExpressionKind.IfNull: return visitIfNull(node, typeContext); case InternalExpressionKind.IfNullExtensionIndexSet: return visitIfNullExtensionIndexSet(node, typeContext); case InternalExpressionKind.IfNullIndexSet: return visitIfNullIndexSet(node, typeContext); case InternalExpressionKind.IfNullPropertySet: return visitIfNullPropertySet(node, typeContext); case InternalExpressionKind.IfNullSet: return visitIfNullSet(node, typeContext); case InternalExpressionKind.IfNullSuperIndexSet: return visitIfNullSuperIndexSet(node, typeContext); case InternalExpressionKind.IndexSet: return visitIndexSet(node, typeContext); case InternalExpressionKind.LoadLibraryTearOff: return visitLoadLibraryTearOff(node, typeContext); case InternalExpressionKind.LocalPostIncDec: return visitLocalPostIncDec(node, typeContext); case InternalExpressionKind.NullAwareCompoundSet: return visitNullAwareCompoundSet(node, typeContext); case InternalExpressionKind.NullAwareExtension: return visitNullAwareExtension(node, typeContext); case InternalExpressionKind.NullAwareIfNullSet: return visitNullAwareIfNullSet(node, typeContext); case InternalExpressionKind.NullAwareMethodInvocation: return visitNullAwareMethodInvocation(node, typeContext); case InternalExpressionKind.NullAwarePropertyGet: return visitNullAwarePropertyGet(node, typeContext); case InternalExpressionKind.NullAwarePropertySet: return visitNullAwarePropertySet(node, typeContext); case InternalExpressionKind.PropertyPostIncDec: return visitPropertyPostIncDec(node, typeContext); case InternalExpressionKind.StaticPostIncDec: return visitStaticPostIncDec(node, typeContext); case InternalExpressionKind.SuperIndexSet: return visitSuperIndexSet(node, typeContext); case InternalExpressionKind.SuperPostIncDec: return visitSuperPostIncDec(node, typeContext); } } return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult defaultBasicLiteral( BasicLiteral node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitBlockExpression( BlockExpression node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitConstantExpression( ConstantExpression node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitDirectMethodInvocation( DirectMethodInvocation node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitDirectPropertyGet( DirectPropertyGet node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitDirectPropertySet( DirectPropertySet node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitFileUriExpression( FileUriExpression node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitInstanceCreation( InstanceCreation node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitInstantiation( Instantiation node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitListConcatenation( ListConcatenation node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitMapConcatenation( MapConcatenation node, DartType typeContext) { return _unhandledExpression(node, typeContext); } @override ExpressionInferenceResult visitSetConcatenation( SetConcatenation node, DartType typeContext) { return _unhandledExpression(node, typeContext); } void _unhandledStatement(Statement node) { unhandled("${node.runtimeType}", "InferenceVisitor", node.fileOffset, inferrer.helper.uri); } @override void defaultStatement(Statement node) { _unhandledStatement(node); } @override void visitAssertBlock(AssertBlock node) { _unhandledStatement(node); } void _unhandledInitializer(Initializer node) { unhandled("${node.runtimeType}", "InferenceVisitor", node.fileOffset, node.location.file); } @override void defaultInitializer(Initializer node) { _unhandledInitializer(node); } @override void visitInvalidInitializer(Initializer node) { _unhandledInitializer(node); } @override void visitLocalInitializer(LocalInitializer node) { _unhandledInitializer(node); } @override ExpressionInferenceResult visitInvalidExpression( InvalidExpression node, DartType typeContext) { // TODO(johnniwinther): The inferred type should be an InvalidType. Using // BottomType leads to cascading errors so we use DynamicType for now. return const ExpressionInferenceResult(const DynamicType()); } @override ExpressionInferenceResult visitIntLiteral( IntLiteral node, DartType typeContext) { return new ExpressionInferenceResult( inferrer.coreTypes.intRawType(inferrer.library.nonNullable)); } @override ExpressionInferenceResult visitAsExpression( AsExpression node, DartType typeContext) { inferrer.inferExpression( node.operand, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: true); return new ExpressionInferenceResult(node.type); } @override void visitAssertInitializer(AssertInitializer node) { inferrer.inferStatement(node.statement); } @override void visitAssertStatement(AssertStatement node) { InterfaceType expectedType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType conditionType = inferrer .inferExpression(node.condition, expectedType, !inferrer.isTopLevel, isVoidAllowed: true) .inferredType; inferrer.ensureAssignable( expectedType, conditionType, node.condition, node.condition.fileOffset); if (node.message != null) { inferrer.inferExpression( node.message, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: true); } } @override ExpressionInferenceResult visitAwaitExpression( AwaitExpression node, DartType typeContext) { if (!inferrer.typeSchemaEnvironment.isEmptyContext(typeContext)) { typeContext = inferrer.wrapFutureOrType(typeContext); } DartType operandType = inferrer .inferExpression(node.operand, typeContext, true, isVoidAllowed: true) .inferredType; DartType inferredType = inferrer.typeSchemaEnvironment.unfutureType(operandType); return new ExpressionInferenceResult(inferredType); } @override void visitBlock(Block node) { for (Statement statement in node.statements) { inferrer.inferStatement(statement); } } @override ExpressionInferenceResult visitBoolLiteral( BoolLiteral node, DartType typeContext) { return new ExpressionInferenceResult( inferrer.coreTypes.boolRawType(inferrer.library.nonNullable)); } @override void visitBreakStatement(BreakStatement node) { // No inference needs to be done. } ExpressionInferenceResult visitCascade(Cascade node, DartType typeContext) { ExpressionInferenceResult result = inferrer.inferExpression( node.expression, typeContext, true, isVoidAllowed: false); node.variable.type = result.inferredType; for (Expression judgment in node.cascades) { inferrer.inferExpression( judgment, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: true); } Expression replacement = node.replace(); return new ExpressionInferenceResult(result.inferredType, replacement); } @override ExpressionInferenceResult visitConditionalExpression( ConditionalExpression node, DartType typeContext) { InterfaceType expectedType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType conditionType = inferrer .inferExpression(node.condition, expectedType, !inferrer.isTopLevel, isVoidAllowed: true) .inferredType; inferrer.ensureAssignable( expectedType, conditionType, node.condition, node.condition.fileOffset); DartType thenType = inferrer .inferExpression(node.then, typeContext, true, isVoidAllowed: true) .inferredType; DartType otherwiseType = inferrer .inferExpression(node.otherwise, typeContext, true, isVoidAllowed: true) .inferredType; DartType inferredType = inferrer.typeSchemaEnvironment .getStandardUpperBound(thenType, otherwiseType); node.staticType = inferredType; return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitConstructorInvocation( ConstructorInvocation node, DartType typeContext) { LibraryBuilder library = inferrer.engine.beingInferred[node.target]; if (library != null) { // There is a cyclic dependency where inferring the types of the // initializing formals of a constructor required us to infer the // corresponding field type which required us to know the type of the // constructor. String name = node.target.enclosingClass.name; if (node.target.name.name.isNotEmpty) { // TODO(ahe): Use `inferrer.helper.constructorNameForDiagnostics` // instead. However, `inferrer.helper` may be null. name += ".${node.target.name.name}"; } library.addProblem( templateCantInferTypeDueToCircularity.withArguments(name), node.target.fileOffset, name.length, node.target.fileUri); for (VariableDeclaration declaration in node.target.function.positionalParameters) { declaration.type ??= const InvalidType(); } for (VariableDeclaration declaration in node.target.function.namedParameters) { declaration.type ??= const InvalidType(); } } else if ((library = inferrer.engine.toBeInferred[node.target]) != null) { inferrer.engine.toBeInferred.remove(node.target); inferrer.engine.beingInferred[node.target] = library; for (VariableDeclaration declaration in node.target.function.positionalParameters) { inferrer.engine.inferInitializingFormal(declaration, node.target); } for (VariableDeclaration declaration in node.target.function.namedParameters) { inferrer.engine.inferInitializingFormal(declaration, node.target); } inferrer.engine.beingInferred.remove(node.target); } bool hasExplicitTypeArguments = getExplicitTypeArguments(node.arguments) != null; DartType inferredType = inferrer.inferInvocation(typeContext, node.fileOffset, node.target.function.thisFunctionType, node.arguments, returnType: computeConstructorReturnType(node.target), isConst: node.isConst); if (!inferrer.isTopLevel) { SourceLibraryBuilder library = inferrer.library; if (!hasExplicitTypeArguments) { library.checkBoundsInConstructorInvocation( node, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } } return new ExpressionInferenceResult(inferredType); } @override void visitContinueSwitchStatement(ContinueSwitchStatement node) { // No inference needs to be done. } ExpressionInferenceResult visitExtensionTearOff( ExtensionTearOff node, DartType typeContext) { FunctionType calleeType = node.target != null ? node.target.function.functionType : new FunctionType([], const DynamicType()); bool hadExplicitTypeArguments = getExplicitTypeArguments(node.arguments) != null; DartType inferredType = inferrer.inferInvocation( typeContext, node.fileOffset, calleeType, node.arguments); Expression replacement = new StaticInvocation(node.target, node.arguments); if (!inferrer.isTopLevel && !hadExplicitTypeArguments && node.target != null) { inferrer.library.checkBoundsInStaticInvocation( replacement, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } node.replaceWith(replacement); inferredType = inferrer.instantiateTearOff(inferredType, typeContext, replacement); return new ExpressionInferenceResult(inferredType); } ExpressionInferenceResult visitExtensionSet( ExtensionSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: false); List<DartType> extensionTypeArguments = inferrer.computeExtensionTypeArgument(node.extension, node.explicitTypeArguments, receiverResult.inferredType); DartType receiverType = inferrer.getExtensionReceiverType( node.extension, extensionTypeArguments); inferrer.ensureAssignable(receiverType, receiverResult.inferredType, node.receiver, node.receiver.fileOffset); ObjectAccessTarget target = new ExtensionAccessTarget( node.target, null, ProcedureKind.Setter, extensionTypeArguments); DartType valueType = inferrer.getSetterType(target, receiverResult.inferredType); ExpressionInferenceResult valueResult = inferrer.inferExpression( node.value, const UnknownType(), true, isVoidAllowed: false); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); Expression value; VariableDeclaration valueVariable; if (node.forEffect) { value = node.value; } else { valueVariable = createVariable(node.value, valueResult.inferredType); value = createVariableGet(valueVariable); } VariableDeclaration receiverVariable; Expression receiver; if (node.forEffect || node.readOnlyReceiver) { receiver = node.receiver; } else { receiverVariable = createVariable(node.receiver, receiverResult.inferredType); receiver = createVariableGet(receiverVariable); } Expression assignment = new StaticInvocation( node.target, new Arguments(<Expression>[receiver, value], types: extensionTypeArguments) ..fileOffset = node.fileOffset) ..fileOffset = node.fileOffset; Expression replacement; if (node.forEffect) { assert(receiverVariable == null); assert(valueVariable == null); replacement = assignment; } else { assert(valueVariable != null); VariableDeclaration assignmentVariable = createVariable(assignment, const VoidType()); replacement = createLet(valueVariable, createLet(assignmentVariable, createVariableGet(valueVariable))); if (receiverVariable != null) { replacement = createLet(receiverVariable, replacement); } } replacement.fileOffset = node.fileOffset; node.replaceWith(replacement); return new ExpressionInferenceResult(valueResult.inferredType, replacement); } ExpressionInferenceResult visitDeferredCheck( DeferredCheck node, DartType typeContext) { // Since the variable is not used in the body we don't need to type infer // it. We can just type infer the body. ExpressionInferenceResult result = inferrer.inferExpression( node.expression, typeContext, true, isVoidAllowed: true); Expression replacement = node.replace(); return new ExpressionInferenceResult(result.inferredType, replacement); } @override void visitDoStatement(DoStatement node) { inferrer.inferStatement(node.body); InterfaceType boolType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType conditionType = inferrer .inferExpression(node.condition, boolType, !inferrer.isTopLevel, isVoidAllowed: true) .inferredType; inferrer.ensureAssignable( boolType, conditionType, node.condition, node.condition.fileOffset); } ExpressionInferenceResult visitDoubleLiteral( DoubleLiteral node, DartType typeContext) { return new ExpressionInferenceResult( inferrer.coreTypes.doubleRawType(inferrer.library.nonNullable)); } @override void visitEmptyStatement(EmptyStatement node) { // No inference needs to be done. } @override void visitExpressionStatement(ExpressionStatement node) { inferrer.inferExpression( node.expression, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: true); } ExpressionInferenceResult visitFactoryConstructorInvocationJudgment( FactoryConstructorInvocationJudgment node, DartType typeContext) { bool hadExplicitTypeArguments = getExplicitTypeArguments(node.arguments) != null; DartType inferredType = inferrer.inferInvocation(typeContext, node.fileOffset, node.target.function.thisFunctionType, node.arguments, returnType: computeConstructorReturnType(node.target), isConst: node.isConst); node.hasBeenInferred = true; if (!inferrer.isTopLevel) { SourceLibraryBuilder library = inferrer.library; if (!hadExplicitTypeArguments) { library.checkBoundsInFactoryInvocation( node, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } } return new ExpressionInferenceResult(inferredType); } @override void visitFieldInitializer(FieldInitializer node) { ExpressionInferenceResult initializerResult = inferrer.inferExpression(node.value, node.field.type, true); DartType initializerType = initializerResult.inferredType; inferrer.ensureAssignable( node.field.type, initializerType, node.value, node.fileOffset); } void handleForInDeclaringVariable( VariableDeclaration variable, Expression iterable, Statement body, {bool isAsync: false}) { DartType elementType; bool typeNeeded = false; bool typeChecksNeeded = !inferrer.isTopLevel; if (VariableDeclarationImpl.isImplicitlyTyped(variable)) { typeNeeded = true; elementType = const UnknownType(); } else { elementType = variable.type; } DartType inferredType = inferForInIterable( iterable, elementType, typeNeeded || typeChecksNeeded, isAsync: isAsync); if (typeNeeded) { inferrer.instrumentation?.record(inferrer.uri, variable.fileOffset, 'type', new InstrumentationValueForType(inferredType)); variable.type = inferredType; } if (body != null) inferrer.inferStatement(body); VariableDeclaration tempVar = new VariableDeclaration(null, type: inferredType, isFinal: true); VariableGet variableGet = new VariableGet(tempVar) ..fileOffset = variable.fileOffset; TreeNode parent = variable.parent; Expression implicitDowncast = inferrer.ensureAssignable( variable.type, inferredType, variableGet, parent.fileOffset, template: templateForInLoopElementTypeNotAssignable); if (implicitDowncast != null) { parent.replaceChild(variable, tempVar); variable.initializer = implicitDowncast..parent = variable; if (body == null) { if (parent is ForInElement) { parent.prologue = variable; } else if (parent is ForInMapEntry) { parent.prologue = variable; } else { unhandled("${parent.runtimeType}", "handleForInDeclaringVariable", variable.fileOffset, variable.location.file); } } else { parent.replaceChild(body, combineStatements(variable, body)); } } } DartType inferForInIterable( Expression iterable, DartType elementType, bool typeNeeded, {bool isAsync: false}) { Class iterableClass = isAsync ? inferrer.coreTypes.streamClass : inferrer.coreTypes.iterableClass; DartType context = inferrer.wrapType(elementType, iterableClass); ExpressionInferenceResult iterableResult = inferrer .inferExpression(iterable, context, typeNeeded, isVoidAllowed: false); DartType iterableType = iterableResult.inferredType; if (iterableResult.replacement != null) { iterable = iterableResult.replacement; } DartType inferredExpressionType = inferrer.resolveTypeParameter(iterableType); inferrer.ensureAssignable( inferrer.wrapType(const DynamicType(), iterableClass), inferredExpressionType, iterable, iterable.fileOffset, template: templateForInLoopTypeNotIterable); DartType inferredType; if (typeNeeded) { inferredType = const DynamicType(); if (inferredExpressionType is InterfaceType) { InterfaceType supertype = inferrer.classHierarchy .getTypeAsInstanceOf(inferredExpressionType, iterableClass); if (supertype != null) { inferredType = supertype.typeArguments[0]; } } } return inferredType; } void handleForInWithoutVariable( VariableDeclaration variable, Expression iterable, Statement body, {bool isAsync: false}) { DartType elementType; bool typeChecksNeeded = !inferrer.isTopLevel; DartType syntheticWriteType; Expression rhs; // If `true`, the synthetic statement should not be visited. bool skipStatement = false; ExpressionStatement syntheticStatement = body is Block ? body.statements.first : body; Expression statementExpression = syntheticStatement.expression; Expression syntheticAssignment = statementExpression; if (syntheticAssignment is VariableSet) { syntheticWriteType = elementType = syntheticAssignment.variable.type; rhs = syntheticAssignment.value; // This expression is fully handled in this method so we should not // visit the synthetic statement. skipStatement = true; } else if (syntheticAssignment is PropertySet || syntheticAssignment is SuperPropertySet) { DartType receiverType = inferrer.thisType; ObjectAccessTarget writeTarget = inferrer.findPropertySetMember(receiverType, syntheticAssignment); syntheticWriteType = elementType = inferrer.getSetterType(writeTarget, receiverType); if (syntheticAssignment is PropertySet) { rhs = syntheticAssignment.value; } else if (syntheticAssignment is SuperPropertySet) { rhs = syntheticAssignment.value; } } else if (syntheticAssignment is StaticSet) { syntheticWriteType = elementType = syntheticAssignment.target.setterType; rhs = syntheticAssignment.value; } else if (syntheticAssignment is InvalidExpression) { elementType = const UnknownType(); } else { unhandled( "${syntheticAssignment.runtimeType}", "handleForInStatementWithoutVariable", syntheticAssignment.fileOffset, inferrer.helper.uri); } DartType inferredType = inferForInIterable( iterable, elementType, typeChecksNeeded, isAsync: isAsync); if (typeChecksNeeded) { variable.type = inferredType; } if (body is Block) { for (Statement statement in body.statements) { if (!skipStatement || statement != syntheticStatement) { inferrer.inferStatement(statement); } } } else { if (!skipStatement) { inferrer.inferStatement(body); } } if (syntheticWriteType != null) { inferrer.ensureAssignable( greatestClosure(inferrer.coreTypes, syntheticWriteType), variable.type, rhs, rhs.fileOffset, template: templateForInLoopElementTypeNotAssignable, isVoidAllowed: true); } } @override void visitForInStatement(ForInStatement node) { if (node.variable.name == null) { handleForInWithoutVariable(node.variable, node.iterable, node.body, isAsync: node.isAsync); } else { handleForInDeclaringVariable(node.variable, node.iterable, node.body, isAsync: node.isAsync); } } @override void visitForStatement(ForStatement node) { for (VariableDeclaration variable in node.variables) { if (variable.name == null) { if (variable.initializer != null) { ExpressionInferenceResult result = inferrer.inferExpression( variable.initializer, const UnknownType(), true, isVoidAllowed: true); variable.type = result.inferredType; } } else { inferrer.inferStatement(variable); } } if (node.condition != null) { InterfaceType expectedType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType conditionType = inferrer .inferExpression(node.condition, expectedType, !inferrer.isTopLevel, isVoidAllowed: true) .inferredType; inferrer.ensureAssignable(expectedType, conditionType, node.condition, node.condition.fileOffset); } for (Expression update in node.updates) { inferrer.inferExpression( update, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: true); } inferrer.inferStatement(node.body); } DartType visitFunctionNode(FunctionNode node, DartType typeContext, DartType returnContext, int returnTypeInstrumentationOffset) { return inferrer.inferLocalFunction( node, typeContext, returnTypeInstrumentationOffset, returnContext); } @override void visitFunctionDeclaration(covariant FunctionDeclarationImpl node) { inferrer.inferMetadataKeepingHelper(node.variable.annotations); DartType returnContext = node._hasImplicitReturnType ? null : node.function.returnType; DartType inferredType = visitFunctionNode(node.function, null, returnContext, node.fileOffset); node.variable.type = inferredType; } @override ExpressionInferenceResult visitFunctionExpression( FunctionExpression node, DartType typeContext) { DartType inferredType = visitFunctionNode(node.function, typeContext, null, node.fileOffset); return new ExpressionInferenceResult(inferredType); } void visitInvalidSuperInitializerJudgment( InvalidSuperInitializerJudgment node) { Substitution substitution = Substitution.fromSupertype( inferrer.classHierarchy.getClassAsInstanceOf( inferrer.thisType.classNode, node.target.enclosingClass)); inferrer.inferInvocation( null, node.fileOffset, substitution.substituteType( node.target.function.thisFunctionType.withoutTypeParameters), node.argumentsJudgment, returnType: inferrer.thisType, skipTypeArgumentInference: true); } ExpressionInferenceResult visitIfNull( IfNullExpression node, DartType typeContext) { // To infer `e0 ?? e1` in context K: // - Infer e0 in context K to get T0 DartType lhsType = inferrer .inferExpression(node.left, typeContext, true, isVoidAllowed: false) .inferredType; Member equalsMember = inferrer .findInterfaceMember(lhsType, equalsName, node.fileOffset) .member; // - Let J = T0 if K is `?` else K. // - Infer e1 in context J to get T1 DartType rhsType; if (typeContext is UnknownType) { rhsType = inferrer .inferExpression(node.right, lhsType, true, isVoidAllowed: true) .inferredType; } else { rhsType = inferrer .inferExpression(node.right, typeContext, true, isVoidAllowed: true) .inferredType; } // - Let T = greatest closure of K with respect to `?` if K is not `_`, else // UP(t0, t1) // - Then the inferred type is T. DartType inferredType = inferrer.typeSchemaEnvironment.getStandardUpperBound(lhsType, rhsType); VariableDeclaration variable = createVariable(node.left, lhsType); MethodInvocation equalsNull = createEqualsNull( node.left.fileOffset, createVariableGet(variable), equalsMember); ConditionalExpression conditional = new ConditionalExpression( equalsNull, node.right, createVariableGet(variable), inferredType); Expression replacement = new Let(variable, conditional) ..fileOffset = node.fileOffset; node.replaceWith(replacement); return new ExpressionInferenceResult(inferredType, replacement); } @override void visitIfStatement(IfStatement node) { InterfaceType expectedType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType conditionType = inferrer .inferExpression(node.condition, expectedType, !inferrer.isTopLevel, isVoidAllowed: true) .inferredType; inferrer.ensureAssignable( expectedType, conditionType, node.condition, node.condition.fileOffset); inferrer.inferStatement(node.then); if (node.otherwise != null) { inferrer.inferStatement(node.otherwise); } } ExpressionInferenceResult visitIntJudgment( IntJudgment node, DartType typeContext) { if (inferrer.isDoubleContext(typeContext)) { double doubleValue = node.asDouble(); if (doubleValue != null) { node.parent.replaceChild( node, new DoubleLiteral(doubleValue)..fileOffset = node.fileOffset); DartType inferredType = inferrer.coreTypes.doubleRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } } Expression error = checkWebIntLiteralsErrorIfUnexact( inferrer, node.value, node.literal, node.fileOffset); if (error != null) { node.parent.replaceChild(node, error); return const ExpressionInferenceResult(const BottomType()); } DartType inferredType = inferrer.coreTypes.intRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } ExpressionInferenceResult visitShadowLargeIntLiteral( ShadowLargeIntLiteral node, DartType typeContext) { if (inferrer.isDoubleContext(typeContext)) { double doubleValue = node.asDouble(); if (doubleValue != null) { node.parent.replaceChild( node, new DoubleLiteral(doubleValue)..fileOffset = node.fileOffset); DartType inferredType = inferrer.coreTypes.doubleRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } } int intValue = node.asInt64(); if (intValue == null) { Expression replacement = inferrer.helper.buildProblem( templateIntegerLiteralIsOutOfRange.withArguments(node.literal), node.fileOffset, node.literal.length); node.parent.replaceChild(node, replacement); return const ExpressionInferenceResult(const BottomType()); } Expression error = checkWebIntLiteralsErrorIfUnexact( inferrer, intValue, node.literal, node.fileOffset); if (error != null) { node.parent.replaceChild(node, error); return const ExpressionInferenceResult(const BottomType()); } node.parent.replaceChild( node, new IntLiteral(intValue)..fileOffset = node.fileOffset); DartType inferredType = inferrer.coreTypes.intRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } void visitShadowInvalidInitializer(ShadowInvalidInitializer node) { inferrer.inferExpression( node.variable.initializer, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: false); } void visitShadowInvalidFieldInitializer(ShadowInvalidFieldInitializer node) { inferrer.inferExpression(node.value, node.field.type, !inferrer.isTopLevel, isVoidAllowed: false); } @override ExpressionInferenceResult visitIsExpression( IsExpression node, DartType typeContext) { inferrer.inferExpression( node.operand, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: false); return new ExpressionInferenceResult( inferrer.coreTypes.boolRawType(inferrer.library.nonNullable)); } @override void visitLabeledStatement(LabeledStatement node) { inferrer.inferStatement(node.body); } DartType getSpreadElementType(DartType spreadType, bool isNullAware) { if (spreadType is InterfaceType) { InterfaceType supertype = inferrer.typeSchemaEnvironment .getTypeAsInstanceOf(spreadType, inferrer.coreTypes.iterableClass); if (supertype != null) return supertype.typeArguments[0]; if (spreadType.classNode == inferrer.coreTypes.nullClass && isNullAware) { return spreadType; } return null; } if (spreadType is DynamicType) return const DynamicType(); return null; } DartType inferElement( Expression element, TreeNode parent, DartType inferredTypeArgument, Map<TreeNode, DartType> inferredSpreadTypes, Map<Expression, DartType> inferredConditionTypes, bool inferenceNeeded, bool typeChecksNeeded) { if (element is SpreadElement) { ExpressionInferenceResult spreadResult = inferrer.inferExpression( element.expression, new InterfaceType(inferrer.coreTypes.iterableClass, <DartType>[inferredTypeArgument]), inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); DartType spreadType = spreadResult.inferredType; inferredSpreadTypes[element.expression] = spreadType; if (typeChecksNeeded) { DartType spreadElementType = getSpreadElementType(spreadType, element.isNullAware); if (spreadElementType == null) { if (spreadType is InterfaceType && spreadType.classNode == inferrer.coreTypes.nullClass && !element.isNullAware) { parent.replaceChild( element, inferrer.helper.buildProblem(messageNonNullAwareSpreadIsNull, element.expression.fileOffset, 1)); } else { parent.replaceChild( element, inferrer.helper.buildProblem( templateSpreadTypeMismatch.withArguments(spreadType), element.expression.fileOffset, 1)); } } else if (spreadType is InterfaceType) { if (!inferrer.isAssignable(inferredTypeArgument, spreadElementType)) { parent.replaceChild( element, inferrer.helper.buildProblem( templateSpreadElementTypeMismatch.withArguments( spreadElementType, inferredTypeArgument), element.expression.fileOffset, 1)); } } } // Use 'dynamic' for error recovery. return element.elementType = getSpreadElementType(spreadType, element.isNullAware) ?? const DynamicType(); } else if (element is IfElement) { DartType boolType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); ExpressionInferenceResult conditionResult = inferrer.inferExpression( element.condition, boolType, typeChecksNeeded, isVoidAllowed: false); DartType conditionType = conditionResult.inferredType; inferrer.ensureAssignable(boolType, conditionType, element.condition, element.condition.fileOffset); DartType thenType = inferElement( element.then, element, inferredTypeArgument, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); DartType otherwiseType; if (element.otherwise != null) { otherwiseType = inferElement( element.otherwise, element, inferredTypeArgument, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); } return otherwiseType == null ? thenType : inferrer.typeSchemaEnvironment .getStandardUpperBound(thenType, otherwiseType); } else if (element is ForElement) { for (VariableDeclaration declaration in element.variables) { if (declaration.name == null) { if (declaration.initializer != null) { ExpressionInferenceResult initializerResult = inferrer.inferExpression(declaration.initializer, declaration.type, inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); declaration.type = initializerResult.inferredType; } } else { inferrer.inferStatement(declaration); } } if (element.condition != null) { inferredConditionTypes[element.condition] = inferrer .inferExpression( element.condition, inferrer.coreTypes.boolRawType(inferrer.library.nonNullable), inferenceNeeded || typeChecksNeeded, isVoidAllowed: false) .inferredType; } for (Expression expression in element.updates) { inferrer.inferExpression(expression, const UnknownType(), inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); } return inferElement( element.body, element, inferredTypeArgument, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); } else if (element is ForInElement) { if (element.variable.name == null) { handleForInWithoutVariable( element.variable, element.iterable, element.prologue, isAsync: element.isAsync); } else { handleForInDeclaringVariable( element.variable, element.iterable, element.prologue, isAsync: element.isAsync); } if (element.problem != null) { inferrer.inferExpression(element.problem, const UnknownType(), inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); } return inferElement( element.body, element, inferredTypeArgument, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); } else { ExpressionInferenceResult result = inferrer.inferExpression( element, inferredTypeArgument, inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); if (result.replacement != null) { element = result.replacement; } DartType inferredType = result.inferredType; if (inferredTypeArgument is! UnknownType) { inferrer.ensureAssignable( inferredTypeArgument, inferredType, element, element.fileOffset, isVoidAllowed: inferredTypeArgument is VoidType); } return inferredType; } } void checkElement( Expression item, Expression parent, DartType typeArgument, Map<TreeNode, DartType> inferredSpreadTypes, Map<Expression, DartType> inferredConditionTypes) { if (item is SpreadElement) { DartType spreadType = inferredSpreadTypes[item.expression]; if (spreadType is DynamicType) { inferrer.ensureAssignable( inferrer.coreTypes.iterableRawType( inferrer.library.nullableIfTrue(item.isNullAware)), spreadType, item.expression, item.expression.fileOffset); } } else if (item is IfElement) { checkElement(item.then, item, typeArgument, inferredSpreadTypes, inferredConditionTypes); if (item.otherwise != null) { checkElement(item.otherwise, item, typeArgument, inferredSpreadTypes, inferredConditionTypes); } } else if (item is ForElement) { if (item.condition != null) { DartType conditionType = inferredConditionTypes[item.condition]; inferrer.ensureAssignable( inferrer.coreTypes.boolRawType(inferrer.library.nonNullable), conditionType, item.condition, item.condition.fileOffset); } checkElement(item.body, item, typeArgument, inferredSpreadTypes, inferredConditionTypes); } else if (item is ForInElement) { checkElement(item.body, item, typeArgument, inferredSpreadTypes, inferredConditionTypes); } else { // Do nothing. Assignability checks are done during type inference. } } @override ExpressionInferenceResult visitListLiteral( ListLiteral node, DartType typeContext) { Class listClass = inferrer.coreTypes.listClass; InterfaceType listType = listClass.thisType; List<DartType> inferredTypes; DartType inferredTypeArgument; List<DartType> formalTypes; List<DartType> actualTypes; bool inferenceNeeded = node.typeArgument is ImplicitTypeArgument; bool typeChecksNeeded = !inferrer.isTopLevel; Map<TreeNode, DartType> inferredSpreadTypes; Map<Expression, DartType> inferredConditionTypes; if (inferenceNeeded || typeChecksNeeded) { formalTypes = []; actualTypes = []; inferredSpreadTypes = new Map<TreeNode, DartType>.identity(); inferredConditionTypes = new Map<Expression, DartType>.identity(); } if (inferenceNeeded) { inferredTypes = [const UnknownType()]; inferrer.typeSchemaEnvironment.inferGenericFunctionOrType(listType, listClass.typeParameters, null, null, typeContext, inferredTypes, isConst: node.isConst); inferredTypeArgument = inferredTypes[0]; } else { inferredTypeArgument = node.typeArgument; } if (inferenceNeeded || typeChecksNeeded) { for (int i = 0; i < node.expressions.length; ++i) { DartType type = inferElement( node.expressions[i], node, inferredTypeArgument, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); actualTypes.add(type); if (inferenceNeeded) { formalTypes.add(listType.typeArguments[0]); } } } if (inferenceNeeded) { inferrer.typeSchemaEnvironment.inferGenericFunctionOrType( listType, listClass.typeParameters, formalTypes, actualTypes, typeContext, inferredTypes); inferredTypeArgument = inferredTypes[0]; inferrer.instrumentation?.record( inferrer.uri, node.fileOffset, 'typeArgs', new InstrumentationValueForTypeArgs([inferredTypeArgument])); node.typeArgument = inferredTypeArgument; } if (typeChecksNeeded) { for (int i = 0; i < node.expressions.length; i++) { checkElement(node.expressions[i], node, node.typeArgument, inferredSpreadTypes, inferredConditionTypes); } } DartType inferredType = new InterfaceType(listClass, [inferredTypeArgument]); if (!inferrer.isTopLevel) { SourceLibraryBuilder library = inferrer.library; if (inferenceNeeded) { library.checkBoundsInListLiteral( node, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } } return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitLogicalExpression( LogicalExpression node, DartType typeContext) { InterfaceType boolType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType leftType = inferrer .inferExpression(node.left, boolType, !inferrer.isTopLevel, isVoidAllowed: false) .inferredType; DartType rightType = inferrer .inferExpression(node.right, boolType, !inferrer.isTopLevel, isVoidAllowed: false) .inferredType; inferrer.ensureAssignable( boolType, leftType, node.left, node.left.fileOffset); inferrer.ensureAssignable( boolType, rightType, node.right, node.right.fileOffset); return new ExpressionInferenceResult(boolType); } // Calculates the key and the value type of a spread map entry of type // spreadMapEntryType and stores them in output in positions offset and offset // + 1. If the types can't be calculated, for example, if spreadMapEntryType // is a function type, the original values in output are preserved. void storeSpreadMapEntryElementTypes(DartType spreadMapEntryType, bool isNullAware, List<DartType> output, int offset) { if (spreadMapEntryType is InterfaceType) { InterfaceType supertype = inferrer.typeSchemaEnvironment .getTypeAsInstanceOf(spreadMapEntryType, inferrer.coreTypes.mapClass); if (supertype != null) { output[offset] = supertype.typeArguments[0]; output[offset + 1] = supertype.typeArguments[1]; } else if (spreadMapEntryType.classNode == inferrer.coreTypes.nullClass && isNullAware) { output[offset] = output[offset + 1] = spreadMapEntryType; } } if (spreadMapEntryType is DynamicType) { output[offset] = output[offset + 1] = const DynamicType(); } } // Note that inferMapEntry adds exactly two elements to actualTypes -- the // actual types of the key and the value. The same technique is used for // actualTypesForSet, only inferMapEntry adds exactly one element to that // list: the actual type of the iterable spread elements in case the map // literal will be disambiguated as a set literal later. void inferMapEntry( MapEntry entry, TreeNode parent, DartType inferredKeyType, DartType inferredValueType, DartType spreadContext, List<DartType> actualTypes, List<DartType> actualTypesForSet, Map<TreeNode, DartType> inferredSpreadTypes, Map<Expression, DartType> inferredConditionTypes, bool inferenceNeeded, bool typeChecksNeeded) { if (entry is SpreadMapEntry) { ExpressionInferenceResult spreadResult = inferrer.inferExpression( entry.expression, spreadContext, inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); DartType spreadType = spreadResult.inferredType; inferredSpreadTypes[entry.expression] = spreadType; int length = actualTypes.length; actualTypes.add(null); actualTypes.add(null); storeSpreadMapEntryElementTypes( spreadType, entry.isNullAware, actualTypes, length); DartType actualKeyType = actualTypes[length]; DartType actualValueType = actualTypes[length + 1]; DartType actualElementType = getSpreadElementType(spreadType, entry.isNullAware); if (typeChecksNeeded) { if (actualKeyType == null) { if (spreadType is InterfaceType && spreadType.classNode == inferrer.coreTypes.nullClass && !entry.isNullAware) { parent.replaceChild( entry, new MapEntry( inferrer.helper.buildProblem( messageNonNullAwareSpreadIsNull, entry.expression.fileOffset, 1), new NullLiteral()) ..fileOffset = entry.fileOffset); } else if (actualElementType != null) { // Don't report the error here, it might be an ambiguous Set. The // error is reported in checkMapEntry if it's disambiguated as map. iterableSpreadType = spreadType; } else { parent.replaceChild( entry, new MapEntry( inferrer.helper.buildProblem( templateSpreadMapEntryTypeMismatch .withArguments(spreadType), entry.expression.fileOffset, 1), new NullLiteral()) ..fileOffset = entry.fileOffset); } } else if (spreadType is InterfaceType) { Expression keyError; Expression valueError; if (!inferrer.isAssignable(inferredKeyType, actualKeyType)) { keyError = inferrer.helper.buildProblem( templateSpreadMapEntryElementKeyTypeMismatch.withArguments( actualKeyType, inferredKeyType), entry.expression.fileOffset, 1); } if (!inferrer.isAssignable(inferredValueType, actualValueType)) { valueError = inferrer.helper.buildProblem( templateSpreadMapEntryElementValueTypeMismatch.withArguments( actualValueType, inferredValueType), entry.expression.fileOffset, 1); } if (keyError != null || valueError != null) { keyError ??= new NullLiteral(); valueError ??= new NullLiteral(); parent.replaceChild( entry, new MapEntry(keyError, valueError) ..fileOffset = entry.fileOffset); } } } // Use 'dynamic' for error recovery. if (actualKeyType == null) { actualKeyType = actualTypes[length] = const DynamicType(); actualValueType = actualTypes[length + 1] = const DynamicType(); } // Store the type in case of an ambiguous Set. Use 'dynamic' for error // recovery. actualTypesForSet.add(actualElementType ?? const DynamicType()); mapEntryClass ??= inferrer.coreTypes.index.getClass('dart:core', 'MapEntry'); // TODO(dmitryas): Handle the case of an ambiguous Set. entry.entryType = new InterfaceType( mapEntryClass, <DartType>[actualKeyType, actualValueType]); bool isMap = inferrer.typeSchemaEnvironment.isSubtypeOf( spreadType, inferrer.coreTypes.mapRawType(inferrer.library.nullable), SubtypeCheckMode.ignoringNullabilities); bool isIterable = inferrer.typeSchemaEnvironment.isSubtypeOf( spreadType, inferrer.coreTypes.iterableRawType(inferrer.library.nullable), SubtypeCheckMode.ignoringNullabilities); if (isMap && !isIterable) { mapSpreadOffset = entry.fileOffset; } if (!isMap && isIterable) { iterableSpreadOffset = entry.expression.fileOffset; } return; } else if (entry is IfMapEntry) { DartType boolType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); ExpressionInferenceResult conditionResult = inferrer.inferExpression( entry.condition, boolType, typeChecksNeeded, isVoidAllowed: false); DartType conditionType = conditionResult.inferredType; inferrer.ensureAssignable( boolType, conditionType, entry.condition, entry.condition.fileOffset); // Note that this recursive invocation of inferMapEntry will add two types // to actualTypes; they are the actual types of the current invocation if // the 'else' branch is empty. inferMapEntry( entry.then, entry, inferredKeyType, inferredValueType, spreadContext, actualTypes, actualTypesForSet, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); if (entry.otherwise != null) { // We need to modify the actual types added in the recursive call to // inferMapEntry. DartType actualValueType = actualTypes.removeLast(); DartType actualKeyType = actualTypes.removeLast(); DartType actualTypeForSet = actualTypesForSet.removeLast(); inferMapEntry( entry.otherwise, entry, inferredKeyType, inferredValueType, spreadContext, actualTypes, actualTypesForSet, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); int length = actualTypes.length; actualTypes[length - 2] = inferrer.typeSchemaEnvironment .getStandardUpperBound(actualKeyType, actualTypes[length - 2]); actualTypes[length - 1] = inferrer.typeSchemaEnvironment .getStandardUpperBound(actualValueType, actualTypes[length - 1]); int lengthForSet = actualTypesForSet.length; actualTypesForSet[lengthForSet - 1] = inferrer.typeSchemaEnvironment .getStandardUpperBound( actualTypeForSet, actualTypesForSet[lengthForSet - 1]); } return; } else if (entry is ForMapEntry) { for (VariableDeclaration declaration in entry.variables) { if (declaration.name == null) { if (declaration.initializer != null) { ExpressionInferenceResult result = inferrer.inferExpression( declaration.initializer, declaration.type, inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); declaration.type = result.inferredType; } } else { inferrer.inferStatement(declaration); } } if (entry.condition != null) { inferredConditionTypes[entry.condition] = inferrer .inferExpression( entry.condition, inferrer.coreTypes.boolRawType(inferrer.library.nonNullable), inferenceNeeded || typeChecksNeeded, isVoidAllowed: false) .inferredType; } for (Expression expression in entry.updates) { inferrer.inferExpression(expression, const UnknownType(), inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); } // Actual types are added by the recursive call. return inferMapEntry( entry.body, entry, inferredKeyType, inferredValueType, spreadContext, actualTypes, actualTypesForSet, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); } else if (entry is ForInMapEntry) { if (entry.variable.name == null) { handleForInWithoutVariable( entry.variable, entry.iterable, entry.prologue, isAsync: entry.isAsync); } else { handleForInDeclaringVariable( entry.variable, entry.iterable, entry.prologue, isAsync: entry.isAsync); } if (entry.problem != null) { inferrer.inferExpression(entry.problem, const UnknownType(), inferenceNeeded || typeChecksNeeded, isVoidAllowed: true); } // Actual types are added by the recursive call. inferMapEntry( entry.body, entry, inferredKeyType, inferredValueType, spreadContext, actualTypes, actualTypesForSet, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); } else { ExpressionInferenceResult keyResult = inferrer.inferExpression( entry.key, inferredKeyType, true, isVoidAllowed: true); DartType keyType = keyResult.inferredType; ExpressionInferenceResult valueResult = inferrer.inferExpression( entry.value, inferredValueType, true, isVoidAllowed: true); DartType valueType = valueResult.inferredType; inferrer.ensureAssignable( inferredKeyType, keyType, entry.key, entry.key.fileOffset, isVoidAllowed: inferredKeyType is VoidType); inferrer.ensureAssignable( inferredValueType, valueType, entry.value, entry.value.fileOffset, isVoidAllowed: inferredValueType is VoidType); actualTypes.add(keyType); actualTypes.add(valueType); // Use 'dynamic' for error recovery. actualTypesForSet.add(const DynamicType()); mapEntryOffset = entry.fileOffset; return; } } void checkMapEntry( MapEntry entry, TreeNode parent, Expression cachedKey, Expression cachedValue, DartType keyType, DartType valueType, Map<TreeNode, DartType> inferredSpreadTypes, Map<Expression, DartType> inferredConditionTypes) { // It's disambiguated as a map literal. if (iterableSpreadOffset != null) { parent.replaceChild( entry, new MapEntry( inferrer.helper.buildProblem( templateSpreadMapEntryTypeMismatch .withArguments(iterableSpreadType), iterableSpreadOffset, 1), new NullLiteral())); } if (entry is SpreadMapEntry) { DartType spreadType = inferredSpreadTypes[entry.expression]; if (spreadType is DynamicType) { inferrer.ensureAssignable( inferrer.coreTypes .mapRawType(inferrer.library.nullableIfTrue(entry.isNullAware)), spreadType, entry.expression, entry.expression.fileOffset); } } else if (entry is IfMapEntry) { checkMapEntry(entry.then, entry, cachedKey, cachedValue, keyType, valueType, inferredSpreadTypes, inferredConditionTypes); if (entry.otherwise != null) { checkMapEntry(entry.otherwise, entry, cachedKey, cachedValue, keyType, valueType, inferredSpreadTypes, inferredConditionTypes); } } else if (entry is ForMapEntry) { if (entry.condition != null) { DartType conditionType = inferredConditionTypes[entry.condition]; inferrer.ensureAssignable( inferrer.coreTypes.boolRawType(inferrer.library.nonNullable), conditionType, entry.condition, entry.condition.fileOffset); } checkMapEntry(entry.body, entry, cachedKey, cachedValue, keyType, valueType, inferredSpreadTypes, inferredConditionTypes); } else if (entry is ForInMapEntry) { checkMapEntry(entry.body, entry, cachedKey, cachedValue, keyType, valueType, inferredSpreadTypes, inferredConditionTypes); } else { // Do nothing. Assignability checks are done during type inference. } } @override ExpressionInferenceResult visitMapLiteral( MapLiteral node, DartType typeContext) { Class mapClass = inferrer.coreTypes.mapClass; InterfaceType mapType = mapClass.thisType; List<DartType> inferredTypes; DartType inferredKeyType; DartType inferredValueType; List<DartType> formalTypes; List<DartType> actualTypes; List<DartType> actualTypesForSet; assert((node.keyType is ImplicitTypeArgument) == (node.valueType is ImplicitTypeArgument)); bool inferenceNeeded = node.keyType is ImplicitTypeArgument; bool typeContextIsMap = node.keyType is! ImplicitTypeArgument; bool typeContextIsIterable = false; if (!inferrer.isTopLevel && inferenceNeeded) { // Ambiguous set/map literal DartType context = inferrer.typeSchemaEnvironment.unfutureType(typeContext); if (context is InterfaceType) { typeContextIsMap = typeContextIsMap || inferrer.classHierarchy .isSubtypeOf(context.classNode, inferrer.coreTypes.mapClass); typeContextIsIterable = typeContextIsIterable || inferrer.classHierarchy.isSubtypeOf( context.classNode, inferrer.coreTypes.iterableClass); if (node.entries.isEmpty && typeContextIsIterable && !typeContextIsMap) { // Set literal SetLiteral setLiteral = new SetLiteral([], typeArgument: const ImplicitTypeArgument(), isConst: node.isConst) ..fileOffset = node.fileOffset; node.parent.replaceChild(node, setLiteral); ExpressionInferenceResult setLiteralResult = visitSetLiteral(setLiteral, typeContext); DartType inferredType = setLiteralResult.inferredType; return new ExpressionInferenceResult(inferredType); } } } bool typeChecksNeeded = !inferrer.isTopLevel; Map<TreeNode, DartType> inferredSpreadTypes; Map<Expression, DartType> inferredConditionTypes; if (inferenceNeeded || typeChecksNeeded) { formalTypes = []; actualTypes = []; actualTypesForSet = []; inferredSpreadTypes = new Map<TreeNode, DartType>.identity(); inferredConditionTypes = new Map<Expression, DartType>.identity(); } if (inferenceNeeded) { inferredTypes = [const UnknownType(), const UnknownType()]; inferrer.typeSchemaEnvironment.inferGenericFunctionOrType(mapType, mapClass.typeParameters, null, null, typeContext, inferredTypes, isConst: node.isConst); inferredKeyType = inferredTypes[0]; inferredValueType = inferredTypes[1]; } else { inferredKeyType = node.keyType; inferredValueType = node.valueType; } List<Expression> cachedKeys = new List(node.entries.length); List<Expression> cachedValues = new List(node.entries.length); for (int i = 0; i < node.entries.length; i++) { MapEntry entry = node.entries[i]; if (entry is! ControlFlowMapEntry) { cachedKeys[i] = node.entries[i].key; cachedValues[i] = node.entries[i].value; } } bool hasMapEntry = false; bool hasMapSpread = false; bool hasIterableSpread = false; if (inferenceNeeded || typeChecksNeeded) { mapEntryOffset = null; mapSpreadOffset = null; iterableSpreadOffset = null; iterableSpreadType = null; DartType spreadTypeContext = const UnknownType(); if (typeContextIsIterable && !typeContextIsMap) { spreadTypeContext = inferrer.typeSchemaEnvironment .getTypeAsInstanceOf(typeContext, inferrer.coreTypes.iterableClass); } else if (!typeContextIsIterable && typeContextIsMap) { spreadTypeContext = new InterfaceType(inferrer.coreTypes.mapClass, <DartType>[inferredKeyType, inferredValueType]); } for (int i = 0; i < node.entries.length; ++i) { MapEntry entry = node.entries[i]; inferMapEntry( entry, node, inferredKeyType, inferredValueType, spreadTypeContext, actualTypes, actualTypesForSet, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); if (inferenceNeeded) { formalTypes.add(mapType.typeArguments[0]); formalTypes.add(mapType.typeArguments[1]); } } hasMapEntry = mapEntryOffset != null; hasMapSpread = mapSpreadOffset != null; hasIterableSpread = iterableSpreadOffset != null; } if (inferenceNeeded) { bool canBeSet = !hasMapSpread && !hasMapEntry && !typeContextIsMap; bool canBeMap = !hasIterableSpread && !typeContextIsIterable; if (canBeSet && !canBeMap) { List<Expression> setElements = <Expression>[]; List<DartType> formalTypesForSet = <DartType>[]; InterfaceType setType = inferrer.coreTypes.setClass.thisType; for (int i = 0; i < node.entries.length; ++i) { setElements.add(convertToElement(node.entries[i], inferrer.helper)); formalTypesForSet.add(setType.typeArguments[0]); } List<DartType> inferredTypesForSet = <DartType>[const UnknownType()]; inferrer.typeSchemaEnvironment.inferGenericFunctionOrType( setType, inferrer.coreTypes.setClass.typeParameters, null, null, typeContext, inferredTypesForSet, isConst: node.isConst); inferrer.typeSchemaEnvironment.inferGenericFunctionOrType( inferrer.coreTypes.setClass.thisType, inferrer.coreTypes.setClass.typeParameters, formalTypesForSet, actualTypesForSet, typeContext, inferredTypesForSet); DartType inferredTypeArgument = inferredTypesForSet[0]; inferrer.instrumentation?.record( inferrer.uri, node.fileOffset, 'typeArgs', new InstrumentationValueForTypeArgs([inferredTypeArgument])); SetLiteral setLiteral = new SetLiteral(setElements, typeArgument: inferredTypeArgument, isConst: node.isConst) ..fileOffset = node.fileOffset; node.parent.replaceChild(node, setLiteral); if (typeChecksNeeded) { for (int i = 0; i < setLiteral.expressions.length; i++) { checkElement( setLiteral.expressions[i], setLiteral, setLiteral.typeArgument, inferredSpreadTypes, inferredConditionTypes); } } DartType inferredType = new InterfaceType(inferrer.coreTypes.setClass, inferredTypesForSet); return new ExpressionInferenceResult(inferredType); } if (canBeSet && canBeMap && node.entries.isNotEmpty) { node.parent.replaceChild( node, inferrer.helper.buildProblem( messageCantDisambiguateNotEnoughInformation, node.fileOffset, 1)); return const ExpressionInferenceResult(const BottomType()); } if (!canBeSet && !canBeMap) { if (!inferrer.isTopLevel) { node.parent.replaceChild( node, inferrer.helper.buildProblem( messageCantDisambiguateAmbiguousInformation, node.fileOffset, 1)); } return const ExpressionInferenceResult(const BottomType()); } inferrer.typeSchemaEnvironment.inferGenericFunctionOrType( mapType, mapClass.typeParameters, formalTypes, actualTypes, typeContext, inferredTypes); inferredKeyType = inferredTypes[0]; inferredValueType = inferredTypes[1]; inferrer.instrumentation?.record( inferrer.uri, node.fileOffset, 'typeArgs', new InstrumentationValueForTypeArgs( [inferredKeyType, inferredValueType])); node.keyType = inferredKeyType; node.valueType = inferredValueType; } if (typeChecksNeeded) { for (int i = 0; i < node.entries.length; ++i) { checkMapEntry( node.entries[i], node, cachedKeys[i], cachedValues[i], node.keyType, node.valueType, inferredSpreadTypes, inferredConditionTypes); } } DartType inferredType = new InterfaceType(mapClass, [inferredKeyType, inferredValueType]); if (!inferrer.isTopLevel) { SourceLibraryBuilder library = inferrer.library; // Either both [_declaredKeyType] and [_declaredValueType] are omitted or // none of them, so we may just check one. if (inferenceNeeded) { library.checkBoundsInMapLiteral( node, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } } return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitMethodInvocation( covariant MethodInvocationImpl node, DartType typeContext) { if (node.name.name == 'unary-' && node.arguments.types.isEmpty && node.arguments.positional.isEmpty && node.arguments.named.isEmpty) { // Replace integer literals in a double context with the corresponding // double literal if it's exact. For double literals, the negation is // folded away. In any non-double context, or if there is no exact // double value, then the corresponding integer literal is left. The // negation is not folded away so that platforms with web literals can // distinguish between (non-negated) 0x8000000000000000 represented as // integer literal -9223372036854775808 which should be a positive number, // and negated 9223372036854775808 represented as // -9223372036854775808.unary-() which should be a negative number. if (node.receiver is IntJudgment) { IntJudgment receiver = node.receiver; if (inferrer.isDoubleContext(typeContext)) { double doubleValue = receiver.asDouble(negated: true); if (doubleValue != null) { node.parent.replaceChild(node, new DoubleLiteral(doubleValue)..fileOffset = node.fileOffset); DartType inferredType = inferrer.coreTypes.doubleRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } } Expression error = checkWebIntLiteralsErrorIfUnexact( inferrer, receiver.value, receiver.literal, receiver.fileOffset); if (error != null) { node.parent.replaceChild(node, error); return const ExpressionInferenceResult(const BottomType()); } } else if (node.receiver is ShadowLargeIntLiteral) { ShadowLargeIntLiteral receiver = node.receiver; if (!receiver.isParenthesized) { if (inferrer.isDoubleContext(typeContext)) { double doubleValue = receiver.asDouble(negated: true); if (doubleValue != null) { node.parent.replaceChild(node, new DoubleLiteral(doubleValue)..fileOffset = node.fileOffset); DartType inferredType = inferrer.coreTypes .doubleRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } } int intValue = receiver.asInt64(negated: true); if (intValue == null) { Expression error = inferrer.helper.buildProblem( templateIntegerLiteralIsOutOfRange .withArguments(receiver.literal), receiver.fileOffset, receiver.literal.length); node.parent.replaceChild(node, error); return const ExpressionInferenceResult(const BottomType()); } if (intValue != null) { Expression error = checkWebIntLiteralsErrorIfUnexact( inferrer, intValue, receiver.literal, receiver.fileOffset); if (error != null) { node.parent.replaceChild(node, error); return const ExpressionInferenceResult(const BottomType()); } node.receiver = new IntLiteral(-intValue) ..fileOffset = node.receiver.fileOffset ..parent = node; } } } } ExpressionInferenceResult result = inferrer.inferMethodInvocation(node, typeContext); return new ExpressionInferenceResult( result.inferredType, result.replacement); } ExpressionInferenceResult visitNamedFunctionExpressionJudgment( NamedFunctionExpressionJudgment node, DartType typeContext) { DartType inferredType = inferrer .inferExpression(node.variable.initializer, typeContext, true) .inferredType; node.variable.type = inferredType; return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitNot(Not node, DartType typeContext) { InterfaceType boolType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType inferredType = inferrer .inferExpression(node.operand, boolType, !inferrer.isTopLevel) .inferredType; inferrer.ensureAssignable( boolType, inferredType, node.operand, node.fileOffset); return new ExpressionInferenceResult(boolType); } @override ExpressionInferenceResult visitNullCheck( NullCheck node, DartType typeContext) { // TODO(johnniwinther): Should the typeContext for the operand be // `Nullable(typeContext)`? DartType inferredType = inferrer .inferExpression(node.operand, typeContext, !inferrer.isTopLevel) .inferredType; // TODO(johnniwinther): Check that the inferred type is potentially // nullable. // TODO(johnniwinther): Return `NonNull(inferredType)`. return new ExpressionInferenceResult(inferredType); } ExpressionInferenceResult visitNullAwareMethodInvocation( NullAwareMethodInvocation node, DartType typeContext) { inferrer.inferStatement(node.variable); ExpressionInferenceResult readResult = inferrer.inferExpression( node.invocation, typeContext, true, isVoidAllowed: true); Member equalsMember = inferrer .findInterfaceMember(node.variable.type, equalsName, node.fileOffset) .member; DartType inferredType = readResult.inferredType; Expression replacement; MethodInvocation equalsNull = createEqualsNull( node.fileOffset, new VariableGet(node.variable)..fileOffset = node.fileOffset, equalsMember); ConditionalExpression condition = new ConditionalExpression( equalsNull, new NullLiteral()..fileOffset = node.fileOffset, node.invocation, inferredType); node.replaceWith(replacement = new Let(node.variable, condition) ..fileOffset = node.fileOffset); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitNullAwarePropertyGet( NullAwarePropertyGet node, DartType typeContext) { inferrer.inferStatement(node.variable); ExpressionInferenceResult readResult = inferrer.inferExpression(node.read, const UnknownType(), true); Member equalsMember = inferrer .findInterfaceMember(node.variable.type, equalsName, node.fileOffset) .member; DartType inferredType = readResult.inferredType; Expression replacement; MethodInvocation equalsNull = createEqualsNull( node.fileOffset, new VariableGet(node.variable)..fileOffset = node.fileOffset, equalsMember); ConditionalExpression condition = new ConditionalExpression( equalsNull, new NullLiteral()..fileOffset = node.fileOffset, node.read, inferredType); node.replaceWith(replacement = new Let(node.variable, condition) ..fileOffset = node.fileOffset); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitNullAwarePropertySet( NullAwarePropertySet node, DartType typeContext) { inferrer.inferStatement(node.variable); ExpressionInferenceResult writeResult = inferrer.inferExpression(node.write, typeContext, true); Member equalsMember = inferrer .findInterfaceMember(node.variable.type, equalsName, node.fileOffset) .member; DartType inferredType = writeResult.inferredType; Expression replacement; MethodInvocation equalsNull = createEqualsNull( node.fileOffset, new VariableGet(node.variable)..fileOffset = node.fileOffset, equalsMember); ConditionalExpression condition = new ConditionalExpression( equalsNull, new NullLiteral()..fileOffset = node.fileOffset, node.write, inferredType); node.replaceWith(replacement = new Let(node.variable, condition) ..fileOffset = node.fileOffset); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitNullAwareExtension( NullAwareExtension node, DartType typeContext) { inferrer.inferStatement(node.variable); ExpressionInferenceResult expressionResult = inferrer.inferExpression(node.expression, const UnknownType(), true); Member equalsMember = inferrer .findInterfaceMember(node.variable.type, equalsName, node.fileOffset) .member; DartType inferredType = expressionResult.inferredType; Expression replacement; MethodInvocation equalsNull = createEqualsNull( node.fileOffset, new VariableGet(node.variable)..fileOffset = node.fileOffset, equalsMember); ConditionalExpression condition = new ConditionalExpression( equalsNull, new NullLiteral()..fileOffset = node.fileOffset, node.expression, inferredType); node.replaceWith(replacement = new Let(node.variable, condition) ..fileOffset = node.fileOffset); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitStaticPostIncDec( StaticPostIncDec node, DartType typeContext) { inferrer.inferStatement(node.read); inferrer.inferStatement(node.write); DartType inferredType = node.read.type; Expression replacement = node.replace(); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitSuperPostIncDec( SuperPostIncDec node, DartType typeContext) { inferrer.inferStatement(node.read); inferrer.inferStatement(node.write); DartType inferredType = node.read.type; Expression replacement = node.replace(); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitLocalPostIncDec( LocalPostIncDec node, DartType typeContext) { inferrer.inferStatement(node.read); inferrer.inferStatement(node.write); DartType inferredType = node.read.type; Expression replacement = node.replace(); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitPropertyPostIncDec( PropertyPostIncDec node, DartType typeContext) { inferrer.inferStatement(node.variable); inferrer.inferStatement(node.read); inferrer.inferStatement(node.write); DartType inferredType = node.read.type; Expression replacement = node.replace(); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitCompoundPropertySet( CompoundPropertySet node, DartType typeContext) { inferrer.inferStatement(node.variable); ExpressionInferenceResult writeResult = inferrer .inferExpression(node.write, typeContext, true, isVoidAllowed: true); Expression replacement = node.replace(); return new ExpressionInferenceResult(writeResult.inferredType, replacement); } ExpressionInferenceResult visitIfNullPropertySet( IfNullPropertySet node, DartType typeContext) { inferrer.inferStatement(node.variable); ExpressionInferenceResult readResult = inferrer.inferExpression( node.read, const UnknownType(), true, isVoidAllowed: true); ExpressionInferenceResult writeResult = inferrer .inferExpression(node.write, typeContext, true, isVoidAllowed: true); Member equalsMember = inferrer .findInterfaceMember( readResult.inferredType, equalsName, node.fileOffset) .member; DartType inferredType = inferrer.typeSchemaEnvironment .getStandardUpperBound( readResult.inferredType, writeResult.inferredType); Expression replacement; if (node.forEffect) { // Encode `o.a ??= b` as: // // let v1 = o in v1.a == null ? v1.a = b : null // MethodInvocation equalsNull = createEqualsNull(node.fileOffset, node.read, equalsMember); ConditionalExpression conditional = new ConditionalExpression( equalsNull, node.write, new NullLiteral()..fileOffset = node.fileOffset, inferredType) ..fileOffset = node.fileOffset; node.replaceWith(replacement = new Let(node.variable, conditional..fileOffset = node.fileOffset)); } else { // Encode `o.a ??= b` as: // // let v1 = o in let v2 = v1.a in v2 == null ? v1.a = b : v2 // VariableDeclaration readVariable = createVariable(node.read, readResult.inferredType); MethodInvocation equalsNull = createEqualsNull( node.fileOffset, createVariableGet(readVariable), equalsMember); ConditionalExpression conditional = new ConditionalExpression( equalsNull, node.write, createVariableGet(readVariable), inferredType) ..fileOffset = node.fileOffset; node.replaceWith(replacement = new Let(node.variable, createLet(readVariable, conditional)) ..fileOffset = node.fileOffset); } return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitIfNullSet( IfNullSet node, DartType typeContext) { ExpressionInferenceResult readResult = inferrer.inferExpression(node.read, const UnknownType(), true); ExpressionInferenceResult writeResult = inferrer .inferExpression(node.write, typeContext, true, isVoidAllowed: true); Member equalsMember = inferrer .findInterfaceMember( readResult.inferredType, equalsName, node.fileOffset) .member; DartType inferredType = inferrer.typeSchemaEnvironment .getStandardUpperBound( readResult.inferredType, writeResult.inferredType); Expression replacement; if (node.forEffect) { // Encode `a ??= b` as: // // a == null ? a = b : null // MethodInvocation equalsNull = createEqualsNull(node.fileOffset, node.read, equalsMember); node.replaceWith(replacement = new ConditionalExpression( equalsNull, node.write, new NullLiteral()..fileOffset = node.fileOffset, inferredType) ..fileOffset = node.fileOffset); } else { // Encode `a ??= b` as: // // let v1 = a in v1 == null ? a = b : v1 // VariableDeclaration readVariable = createVariable(node.read, readResult.inferredType); MethodInvocation equalsNull = createEqualsNull( node.fileOffset, createVariableGet(readVariable), equalsMember); ConditionalExpression conditional = new ConditionalExpression( equalsNull, node.write, createVariableGet(readVariable), inferredType) ..fileOffset = node.fileOffset; node.replaceWith(replacement = new Let(readVariable, conditional) ..fileOffset = node.fileOffset); } return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitIndexSet(IndexSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: true); DartType receiverType = receiverResult.inferredType; VariableDeclaration receiverVariable = createVariable(node.receiver, receiverType); ObjectAccessTarget indexSetTarget = inferrer.findInterfaceMember( receiverType, indexSetName, node.fileOffset, includeExtensionMethods: true); DartType indexType = inferrer.getIndexKeyType(indexSetTarget, receiverType); DartType valueType = inferrer.getIndexSetValueType(indexSetTarget, receiverType); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, indexType, true, isVoidAllowed: true); inferrer.ensureAssignable( indexType, indexResult.inferredType, node.index, node.index.fileOffset); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); ExpressionInferenceResult valueResult = inferrer .inferExpression(node.value, valueType, true, isVoidAllowed: true); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); VariableDeclaration valueVariable = createVariable(node.value, valueResult.inferredType); // The inferred type is that inferred type of the value expression and not // the type of the value parameter. DartType inferredType = valueResult.inferredType; Expression replacement; Expression assignment; if (indexSetTarget.isMissing) { assignment = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments('[]=', receiverType), node.fileOffset, '[]='.length); } else if (indexSetTarget.isExtensionMember) { assert(indexSetTarget.extensionMethodKind != ProcedureKind.Setter); assignment = new StaticInvocation( indexSetTarget.member, new Arguments(<Expression>[ createVariableGet(receiverVariable), createVariableGet(indexVariable), createVariableGet(valueVariable) ], types: indexSetTarget.inferredExtensionTypeArguments) ..fileOffset = node.fileOffset) ..fileOffset = node.fileOffset; } else { assignment = new MethodInvocation( createVariableGet(receiverVariable), indexSetName, new Arguments(<Expression>[ createVariableGet(indexVariable), createVariableGet(valueVariable) ]) ..fileOffset = node.fileOffset, indexSetTarget.member) ..fileOffset = node.fileOffset; } VariableDeclaration assignmentVariable = createVariable(assignment, const VoidType()); node.replaceWith(replacement = new Let( receiverVariable, createLet( indexVariable, createLet( valueVariable, createLet( assignmentVariable, createVariableGet(valueVariable)))) ..fileOffset = node.fileOffset)); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitSuperIndexSet( SuperIndexSet node, DartType typeContext) { ObjectAccessTarget indexSetTarget = node.setter != null ? new ObjectAccessTarget.interfaceMember(node.setter) : const ObjectAccessTarget.missing(); DartType indexType = inferrer.getIndexKeyType(indexSetTarget, inferrer.thisType); DartType valueType = inferrer.getIndexSetValueType(indexSetTarget, inferrer.thisType); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, indexType, true, isVoidAllowed: true); inferrer.ensureAssignable( indexType, indexResult.inferredType, node.index, node.index.fileOffset); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); ExpressionInferenceResult valueResult = inferrer .inferExpression(node.value, valueType, true, isVoidAllowed: true); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); VariableDeclaration valueVariable = createVariable(node.value, valueResult.inferredType); // The inferred type is that inferred type of the value expression and not // the type of the value parameter. DartType inferredType = valueResult.inferredType; Expression replacement; Expression assignment; if (indexSetTarget.isMissing) { assignment = inferrer.helper.buildProblem( templateSuperclassHasNoMethod.withArguments(indexSetName.name), node.fileOffset, noLength); } else { assert(indexSetTarget.isInstanceMember); inferrer.instrumentation?.record(inferrer.uri, node.fileOffset, 'target', new InstrumentationValueForMember(node.setter)); assignment = new SuperMethodInvocation( indexSetName, new Arguments(<Expression>[ createVariableGet(indexVariable), createVariableGet(valueVariable) ]) ..fileOffset = node.fileOffset, indexSetTarget.member) ..fileOffset = node.fileOffset; } VariableDeclaration assignmentVariable = createVariable(assignment, const VoidType()); node.replaceWith(replacement = new Let( indexVariable, createLet(valueVariable, createLet(assignmentVariable, createVariableGet(valueVariable)))) ..fileOffset = node.fileOffset); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitExtensionIndexSet( ExtensionIndexSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: false); List<DartType> extensionTypeArguments = inferrer.computeExtensionTypeArgument(node.extension, node.explicitTypeArguments, receiverResult.inferredType); DartType receiverType = inferrer.getExtensionReceiverType( node.extension, extensionTypeArguments); inferrer.ensureAssignable(receiverType, receiverResult.inferredType, node.receiver, node.receiver.fileOffset); VariableDeclaration receiverVariable = createVariable(node.receiver, receiverType); ObjectAccessTarget target = new ExtensionAccessTarget( node.setter, null, ProcedureKind.Operator, extensionTypeArguments); DartType indexType = inferrer.getIndexKeyType(target, receiverType); DartType valueType = inferrer.getIndexSetValueType(target, receiverType); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, indexType, true, isVoidAllowed: true); inferrer.ensureAssignable( indexType, indexResult.inferredType, node.index, node.index.fileOffset); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); ExpressionInferenceResult valueResult = inferrer .inferExpression(node.value, valueType, true, isVoidAllowed: true); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); VariableDeclaration valueVariable = createVariable(node.value, valueResult.inferredType); // The inferred type is that inferred type of the value expression and not // the type of the value parameter. DartType inferredType = valueResult.inferredType; Expression replacement; Expression assignment; if (target.isMissing) { assignment = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments( indexSetName.name, receiverType), node.fileOffset, noLength); } else { assert(target.isExtensionMember); assignment = new StaticInvocation( target.member, new Arguments(<Expression>[ createVariableGet(receiverVariable), createVariableGet(indexVariable), createVariableGet(valueVariable) ], types: target.inferredExtensionTypeArguments) ..fileOffset = node.fileOffset) ..fileOffset = node.fileOffset; } VariableDeclaration assignmentVariable = createVariable(assignment, const VoidType()); node.replaceWith(replacement = new Let( receiverVariable, createLet( indexVariable, createLet( valueVariable, createLet( assignmentVariable, createVariableGet(valueVariable))))) ..fileOffset = node.fileOffset); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitIfNullIndexSet( IfNullIndexSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: true); DartType receiverType = receiverResult.inferredType; VariableDeclaration receiverVariable; Expression readReceiver; Expression writeReceiver; if (node.readOnlyReceiver) { readReceiver = node.receiver; writeReceiver = readReceiver.accept<TreeNode>(new CloneVisitor()); } else { receiverVariable = createVariable(node.receiver, receiverType); readReceiver = createVariableGet(receiverVariable); writeReceiver = createVariableGet(receiverVariable); } ObjectAccessTarget readTarget = inferrer.findInterfaceMember( receiverType, indexGetName, node.readOffset, includeExtensionMethods: true); MethodContravarianceCheckKind checkKind = inferrer.preCheckInvocationContravariance(receiverType, readTarget, isThisReceiver: node.receiver is ThisExpression); DartType readType = inferrer.getReturnType(readTarget, receiverType); DartType readIndexType = inferrer.getIndexKeyType(readTarget, receiverType); Member equalsMember = inferrer .findInterfaceMember(readType, equalsName, node.testOffset) .member; ObjectAccessTarget writeTarget = inferrer.findInterfaceMember( receiverType, indexSetName, node.writeOffset, includeExtensionMethods: true); DartType writeIndexType = inferrer.getIndexKeyType(writeTarget, receiverType); DartType valueType = inferrer.getIndexSetValueType(writeTarget, receiverType); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, readIndexType, true, isVoidAllowed: true); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); Expression readIndex = createVariableGet(indexVariable); readIndex = inferrer.ensureAssignable(readIndexType, indexResult.inferredType, readIndex, readIndex.fileOffset) ?? readIndex; Expression writeIndex = createVariableGet(indexVariable); writeIndex = inferrer.ensureAssignable(writeIndexType, indexResult.inferredType, writeIndex, writeIndex.fileOffset) ?? writeIndex; ExpressionInferenceResult valueResult = inferrer .inferExpression(node.value, valueType, true, isVoidAllowed: true); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); DartType inferredType = inferrer.typeSchemaEnvironment .getStandardUpperBound(readType, valueResult.inferredType); Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments('[]', receiverType), node.readOffset, '[]'.length); } else if (readTarget.isExtensionMember) { read = new StaticInvocation( readTarget.member, new Arguments(<Expression>[ readReceiver, readIndex, ], types: readTarget.inferredExtensionTypeArguments) ..fileOffset = node.readOffset) ..fileOffset = node.readOffset; } else { read = new MethodInvocation( readReceiver, indexGetName, new Arguments(<Expression>[ readIndex, ]) ..fileOffset = node.readOffset, readTarget.member) ..fileOffset = node.readOffset; if (checkKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.readOffset, 'checkReturn', new InstrumentationValueForType(readType)); } read = new AsExpression(read, readType) ..isTypeError = true ..fileOffset = node.readOffset; } } VariableDeclaration valueVariable; Expression valueExpression; if (node.forEffect) { valueExpression = node.value; } else { valueVariable = createVariable(node.value, valueResult.inferredType); valueExpression = createVariableGet(valueVariable); } Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments('[]=', receiverType), node.writeOffset, '[]='.length); } else if (writeTarget.isExtensionMember) { assert(writeTarget.extensionMethodKind != ProcedureKind.Setter); write = new StaticInvocation( writeTarget.member, new Arguments( <Expression>[writeReceiver, writeIndex, valueExpression], types: writeTarget.inferredExtensionTypeArguments) ..fileOffset = node.writeOffset) ..fileOffset = node.writeOffset; } else { write = new MethodInvocation( writeReceiver, indexSetName, new Arguments(<Expression>[writeIndex, valueExpression]) ..fileOffset = node.writeOffset, writeTarget.member) ..fileOffset = node.writeOffset; } Expression inner; if (node.forEffect) { // Encode `Extension(o)[a] ??= b`, if `node.readOnlyReceiver` is false, // as: // // let receiverVariable = o in // let indexVariable = a in // receiverVariable[indexVariable] == null // ? receiverVariable.[]=(indexVariable, b) : null // // and if `node.readOnlyReceiver` is true as: // // let indexVariable = a in // o[indexVariable] == null ? o.[]=(indexVariable, b) : null // MethodInvocation equalsNull = createEqualsNull(node.testOffset, read, equalsMember); ConditionalExpression conditional = new ConditionalExpression(equalsNull, write, new NullLiteral()..fileOffset = node.testOffset, inferredType) ..fileOffset = node.testOffset; inner = createLet(indexVariable, conditional); } else { // Encode `Extension(o)[a] ??= b` as, if `node.readOnlyReceiver` is false, // as: // // let receiverVariable = o in // let indexVariable = a in // let readVariable = receiverVariable[indexVariable] in // readVariable == null // ? (let valueVariable = b in // let writeVariable = // receiverVariable.[]=(indexVariable, valueVariable) in // valueVariable) // : readVariable // // and if `node.readOnlyReceiver` is true as: // // let indexVariable = a in // let readVariable = o[indexVariable] in // readVariable == null // ? (let valueVariable = b in // let writeVariable = o.[]=(indexVariable, valueVariable) in // valueVariable) // : readVariable // // assert(valueVariable != null); VariableDeclaration readVariable = createVariable(read, readType); MethodInvocation equalsNull = createEqualsNull( node.testOffset, createVariableGet(readVariable), equalsMember); VariableDeclaration writeVariable = createVariable(write, const VoidType()); ConditionalExpression conditional = new ConditionalExpression( equalsNull, createLet(valueVariable, createLet(writeVariable, createVariableGet(valueVariable))), createVariableGet(readVariable), inferredType) ..fileOffset = node.fileOffset; inner = createLet(indexVariable, createLet(readVariable, conditional)); } Expression replacement; if (receiverVariable != null) { node.replaceWith(replacement = new Let(receiverVariable, inner) ..fileOffset = node.fileOffset); } else { node.replaceWith(replacement = inner); } return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitIfNullSuperIndexSet( IfNullSuperIndexSet node, DartType typeContext) { ObjectAccessTarget readTarget = node.getter != null ? new ObjectAccessTarget.interfaceMember(node.getter) : const ObjectAccessTarget.missing(); DartType readType = inferrer.getReturnType(readTarget, inferrer.thisType); DartType readIndexType = inferrer.getIndexKeyType(readTarget, inferrer.thisType); Member equalsMember = inferrer .findInterfaceMember(readType, equalsName, node.testOffset) .member; ObjectAccessTarget writeTarget = node.setter != null ? new ObjectAccessTarget.interfaceMember(node.setter) : const ObjectAccessTarget.missing(); DartType writeIndexType = inferrer.getIndexKeyType(writeTarget, inferrer.thisType); DartType valueType = inferrer.getIndexSetValueType(writeTarget, inferrer.thisType); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, readIndexType, true, isVoidAllowed: true); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); VariableGet readIndex = createVariableGet(indexVariable); inferrer.ensureAssignable(readIndexType, indexResult.inferredType, readIndex, readIndex.fileOffset); VariableGet writeIndex = createVariableGet(indexVariable); inferrer.ensureAssignable(writeIndexType, indexResult.inferredType, writeIndex, writeIndex.fileOffset); ExpressionInferenceResult valueResult = inferrer .inferExpression(node.value, valueType, true, isVoidAllowed: true); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); DartType inferredType = inferrer.typeSchemaEnvironment .getStandardUpperBound(readType, valueResult.inferredType); Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateSuperclassHasNoMethod.withArguments('[]'), node.readOffset, '[]'.length); } else { assert(readTarget.isInstanceMember); inferrer.instrumentation?.record(inferrer.uri, node.readOffset, 'target', new InstrumentationValueForMember(node.getter)); read = new SuperMethodInvocation( indexGetName, new Arguments(<Expression>[ readIndex, ]) ..fileOffset = node.readOffset, readTarget.member) ..fileOffset = node.readOffset; } VariableDeclaration valueVariable; Expression valueExpression; if (node.forEffect) { valueExpression = node.value; } else { valueVariable = createVariable(node.value, valueResult.inferredType); valueExpression = createVariableGet(valueVariable); } Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateSuperclassHasNoMethod.withArguments('[]='), node.writeOffset, '[]='.length); } else { assert(writeTarget.isInstanceMember); inferrer.instrumentation?.record(inferrer.uri, node.writeOffset, 'target', new InstrumentationValueForMember(node.setter)); write = new SuperMethodInvocation( indexSetName, new Arguments( <Expression>[createVariableGet(indexVariable), valueExpression]) ..fileOffset = node.writeOffset, writeTarget.member) ..fileOffset = node.writeOffset; } Expression replacement; if (node.forEffect) { // Encode `o[a] ??= b` as: // // let v1 = a in // super[v1] == null ? super.[]=(v1, b) : null // MethodInvocation equalsNull = createEqualsNull(node.testOffset, read, equalsMember); ConditionalExpression conditional = new ConditionalExpression(equalsNull, write, new NullLiteral()..fileOffset = node.testOffset, inferredType) ..fileOffset = node.testOffset; replacement = createLet(indexVariable, conditional); } else { // Encode `o[a] ??= b` as: // // let v1 = a in // let v2 = super[v1] in // v2 == null // ? (let v3 = b in // let _ = super.[]=(v1, v3) in // v3) // : v2 // assert(valueVariable != null); VariableDeclaration readVariable = createVariable(read, readType); MethodInvocation equalsNull = createEqualsNull( node.testOffset, createVariableGet(readVariable), equalsMember); VariableDeclaration writeVariable = createVariable(write, const VoidType()); ConditionalExpression conditional = new ConditionalExpression( equalsNull, createLet(valueVariable, createLet(writeVariable, createVariableGet(valueVariable))), createVariableGet(readVariable), inferredType) ..fileOffset = node.fileOffset; replacement = createLet(indexVariable, createLet(readVariable, conditional)); } node.replaceWith(replacement); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitIfNullExtensionIndexSet( IfNullExtensionIndexSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: false); List<DartType> extensionTypeArguments = inferrer.computeExtensionTypeArgument(node.extension, node.explicitTypeArguments, receiverResult.inferredType); DartType receiverType = inferrer.getExtensionReceiverType( node.extension, extensionTypeArguments); inferrer.ensureAssignable(receiverType, receiverResult.inferredType, node.receiver, node.receiver.fileOffset); VariableDeclaration receiverVariable = createVariable(node.receiver, receiverType); ObjectAccessTarget readTarget = node.getter != null ? new ExtensionAccessTarget( node.getter, null, ProcedureKind.Operator, extensionTypeArguments) : const ObjectAccessTarget.missing(); DartType readType = inferrer.getReturnType(readTarget, receiverType); DartType readIndexType = inferrer.getIndexKeyType(readTarget, receiverType); Member equalsMember = inferrer .findInterfaceMember(readType, equalsName, node.testOffset) .member; ObjectAccessTarget writeTarget = node.setter != null ? new ExtensionAccessTarget( node.setter, null, ProcedureKind.Operator, extensionTypeArguments) : const ObjectAccessTarget.missing(); DartType writeIndexType = inferrer.getIndexKeyType(writeTarget, receiverType); DartType valueType = inferrer.getIndexSetValueType(writeTarget, receiverType); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, readIndexType, true, isVoidAllowed: true); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); VariableGet readIndex = createVariableGet(indexVariable); inferrer.ensureAssignable(readIndexType, indexResult.inferredType, readIndex, readIndex.fileOffset); VariableGet writeIndex = createVariableGet(indexVariable); inferrer.ensureAssignable(writeIndexType, indexResult.inferredType, writeIndex, writeIndex.fileOffset); ExpressionInferenceResult valueResult = inferrer .inferExpression(node.value, valueType, true, isVoidAllowed: true); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); DartType inferredType = inferrer.typeSchemaEnvironment .getStandardUpperBound(readType, valueResult.inferredType); Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments( indexGetName.name, receiverType), node.readOffset, noLength); } else { assert(readTarget.isExtensionMember); read = new StaticInvocation( readTarget.member, new Arguments(<Expression>[ createVariableGet(receiverVariable), readIndex, ], types: readTarget.inferredExtensionTypeArguments) ..fileOffset = node.readOffset) ..fileOffset = node.readOffset; } VariableDeclaration valueVariable; Expression valueExpression; if (node.forEffect) { valueExpression = node.value; } else { valueVariable = createVariable(node.value, valueResult.inferredType); valueExpression = createVariableGet(valueVariable); } Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments( indexSetName.name, receiverType), node.writeOffset, noLength); } else { assert(writeTarget.isExtensionMember); write = new StaticInvocation( writeTarget.member, new Arguments(<Expression>[ createVariableGet(receiverVariable), writeIndex, valueExpression ], types: writeTarget.inferredExtensionTypeArguments) ..fileOffset = node.writeOffset) ..fileOffset = node.writeOffset; } Expression inner; if (node.forEffect) { // Encode `Extension(o)[a] ??= b` as: // // let receiverVariable = o; // let indexVariable = a in // receiverVariable[indexVariable] == null // ? receiverVariable.[]=(indexVariable, b) : null // MethodInvocation equalsNull = createEqualsNull(node.testOffset, read, equalsMember); ConditionalExpression conditional = new ConditionalExpression(equalsNull, write, new NullLiteral()..fileOffset = node.testOffset, inferredType) ..fileOffset = node.testOffset; inner = createLet(indexVariable, conditional); } else { // Encode `Extension(o)[a] ??= b` as: // // let receiverVariable = o; // let indexVariable = a in // let readVariable = receiverVariable[indexVariable] in // readVariable == null // ? (let valueVariable = b in // let writeVariable = // receiverVariable.[]=(indexVariable, valueVariable) in // valueVariable) // : readVariable // assert(valueVariable != null); VariableDeclaration readVariable = createVariable(read, readType); MethodInvocation equalsNull = createEqualsNull( node.testOffset, createVariableGet(readVariable), equalsMember); VariableDeclaration writeVariable = createVariable(write, const VoidType()); ConditionalExpression conditional = new ConditionalExpression( equalsNull, createLet(valueVariable, createLet(writeVariable, createVariableGet(valueVariable))), createVariableGet(readVariable), inferredType) ..fileOffset = node.fileOffset; inner = createLet(indexVariable, createLet(readVariable, conditional)); } Expression replacement = new Let(receiverVariable, inner) ..fileOffset = node.fileOffset; node.replaceWith(replacement); return new ExpressionInferenceResult(inferredType, replacement); } ExpressionInferenceResult visitCompoundIndexSet( CompoundIndexSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: true); DartType receiverType = receiverResult.inferredType; VariableDeclaration receiverVariable; Expression readReceiver; Expression writeReceiver; if (node.readOnlyReceiver) { readReceiver = node.receiver; writeReceiver = readReceiver.accept<TreeNode>(new CloneVisitor()); } else { receiverVariable = createVariable(node.receiver, receiverType); readReceiver = createVariableGet(receiverVariable); writeReceiver = createVariableGet(receiverVariable); } ObjectAccessTarget readTarget = inferrer.findInterfaceMember( receiverType, indexGetName, node.readOffset, includeExtensionMethods: true); MethodContravarianceCheckKind readCheckKind = inferrer.preCheckInvocationContravariance(receiverType, readTarget, isThisReceiver: node.receiver is ThisExpression); DartType readType = inferrer.getReturnType(readTarget, receiverType); DartType readIndexType = inferrer.getPositionalParameterTypeForTarget( readTarget, receiverType, 0); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, readIndexType, true, isVoidAllowed: true); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); Expression readIndex = createVariableGet(indexVariable); Expression readIndexReplacement = inferrer.ensureAssignable(readIndexType, indexResult.inferredType, readIndex, readIndex.fileOffset); if (readIndexReplacement != null) { readIndex = readIndexReplacement; } Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments('[]', receiverType), node.readOffset, '[]'.length); } else if (readTarget.isExtensionMember) { read = new StaticInvocation( readTarget.member, new Arguments(<Expression>[ readReceiver, readIndex, ], types: readTarget.inferredExtensionTypeArguments) ..fileOffset = node.readOffset) ..fileOffset = node.readOffset; } else { read = new MethodInvocation( readReceiver, indexGetName, new Arguments(<Expression>[ readIndex, ]) ..fileOffset = node.readOffset, readTarget.member) ..fileOffset = node.readOffset; if (readCheckKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.readOffset, 'checkReturn', new InstrumentationValueForType(readType)); } read = new AsExpression(read, readType) ..isTypeError = true ..fileOffset = node.readOffset; } } VariableDeclaration leftVariable; Expression left; if (node.forEffect) { left = read; } else if (node.forPostIncDec) { leftVariable = createVariable(read, readType); left = createVariableGet(leftVariable); } else { left = read; } ObjectAccessTarget binaryTarget = inferrer.findInterfaceMember( readType, node.binaryName, node.binaryOffset, includeExtensionMethods: true); MethodContravarianceCheckKind binaryCheckKind = inferrer.preCheckInvocationContravariance(readType, binaryTarget, isThisReceiver: false); DartType binaryType = inferrer.getReturnType(binaryTarget, readType); DartType rhsType = inferrer.getPositionalParameterTypeForTarget(binaryTarget, readType, 0); ExpressionInferenceResult rhsResult = inferrer.inferExpression(node.rhs, rhsType, true, isVoidAllowed: true); inferrer.ensureAssignable( rhsType, rhsResult.inferredType, node.rhs, node.rhs.fileOffset); if (inferrer.isOverloadedArithmeticOperatorAndType( binaryTarget, readType)) { binaryType = inferrer.typeSchemaEnvironment .getTypeOfOverloadedArithmetic(readType, rhsResult.inferredType); } Expression binary; if (binaryTarget.isMissing) { binary = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments(node.binaryName.name, readType), node.binaryOffset, node.binaryName.name.length); } else if (binaryTarget.isExtensionMember) { assert(binaryTarget.extensionMethodKind != ProcedureKind.Setter); binary = new StaticInvocation( binaryTarget.member, new Arguments(<Expression>[ left, node.rhs, ], types: binaryTarget.inferredExtensionTypeArguments) ..fileOffset = node.binaryOffset) ..fileOffset = node.binaryOffset; } else { binary = new MethodInvocation( left, node.binaryName, new Arguments(<Expression>[ node.rhs, ]) ..fileOffset = node.binaryOffset, binaryTarget.member) ..fileOffset = node.binaryOffset; if (binaryCheckKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.binaryOffset, 'checkReturn', new InstrumentationValueForType(readType)); } binary = new AsExpression(binary, binaryType) ..isTypeError = true ..fileOffset = node.binaryOffset; } } ObjectAccessTarget writeTarget = inferrer.findInterfaceMember( receiverType, indexSetName, node.writeOffset, includeExtensionMethods: true); DartType writeIndexType = inferrer.getPositionalParameterTypeForTarget( writeTarget, receiverType, 0); Expression writeIndex = createVariableGet(indexVariable); Expression writeIndexReplacement = inferrer.ensureAssignable(writeIndexType, indexResult.inferredType, writeIndex, writeIndex.fileOffset); if (writeIndexReplacement != null) { writeIndex = writeIndexReplacement; } DartType valueType = inferrer.getIndexSetValueType(writeTarget, receiverType); Expression binaryReplacement = inferrer.ensureAssignable( valueType, binaryType, binary, node.fileOffset); if (binaryReplacement != null) { binary = binaryReplacement; } VariableDeclaration valueVariable; Expression valueExpression; if (node.forEffect || node.forPostIncDec) { valueExpression = binary; } else { valueVariable = createVariable(binary, binaryType); valueExpression = createVariableGet(valueVariable); } Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments('[]=', receiverType), node.writeOffset, '[]='.length); } else if (writeTarget.isExtensionMember) { assert(writeTarget.extensionMethodKind != ProcedureKind.Setter); write = new StaticInvocation( writeTarget.member, new Arguments( <Expression>[writeReceiver, writeIndex, valueExpression], types: writeTarget.inferredExtensionTypeArguments) ..fileOffset = node.writeOffset) ..fileOffset = node.writeOffset; } else { write = new MethodInvocation( writeReceiver, indexSetName, new Arguments(<Expression>[writeIndex, valueExpression]) ..fileOffset = node.writeOffset, writeTarget.member) ..fileOffset = node.writeOffset; } Expression inner; if (node.forEffect) { assert(leftVariable == null); assert(valueVariable == null); // Encode `o[a] += b` as: // // let v1 = o in let v2 = a in v1.[]=(v2, v1.[](v2) + b) // inner = createLet(indexVariable, write); } else if (node.forPostIncDec) { // Encode `o[a]++` as: // // let v1 = o in // let v2 = a in // let v3 = v1.[](v2) // let v4 = v1.[]=(v2, c3 + b) in v3 // assert(leftVariable != null); assert(valueVariable == null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); inner = createLet( indexVariable, createLet(leftVariable, createLet(writeVariable, createVariableGet(leftVariable)))); } else { // Encode `o[a] += b` as: // // let v1 = o in // let v2 = a in // let v3 = v1.[](v2) + b // let v4 = v1.[]=(v2, c3) in v3 // assert(leftVariable == null); assert(valueVariable != null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); inner = createLet( indexVariable, createLet(valueVariable, createLet(writeVariable, createVariableGet(valueVariable)))); } Expression replacement; if (receiverVariable != null) { node.replaceWith(replacement = new Let(receiverVariable, inner) ..fileOffset = node.fileOffset); } else { node.replaceWith(replacement = inner); } return new ExpressionInferenceResult( node.forPostIncDec ? readType : binaryType, replacement); } ExpressionInferenceResult visitNullAwareCompoundSet( NullAwareCompoundSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: true); DartType receiverType = receiverResult.inferredType; VariableDeclaration receiverVariable = createVariable(node.receiver, receiverType); Expression readReceiver = createVariableGet(receiverVariable); Expression writeReceiver = createVariableGet(receiverVariable); Member equalsMember = inferrer .findInterfaceMember(receiverType, equalsName, node.receiver.fileOffset) .member; ObjectAccessTarget readTarget = inferrer.findInterfaceMember( receiverType, node.propertyName, node.readOffset, includeExtensionMethods: true); MethodContravarianceCheckKind readCheckKind = inferrer.preCheckInvocationContravariance(receiverType, readTarget, isThisReceiver: node.receiver is ThisExpression); DartType readType = inferrer.getGetterType(readTarget, receiverType); Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments( node.propertyName.name, receiverType), node.readOffset, node.propertyName.name.length); } else if (readTarget.isExtensionMember) { read = new StaticInvocation( readTarget.member, new Arguments(<Expression>[ readReceiver, ], types: readTarget.inferredExtensionTypeArguments) ..fileOffset = node.readOffset) ..fileOffset = node.readOffset; } else { read = new PropertyGet(readReceiver, node.propertyName, readTarget.member) ..fileOffset = node.readOffset; if (readCheckKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.readOffset, 'checkReturn', new InstrumentationValueForType(readType)); } read = new AsExpression(read, readType) ..isTypeError = true ..fileOffset = node.readOffset; } } VariableDeclaration leftVariable; Expression left; if (node.forEffect) { left = read; } else if (node.forPostIncDec) { leftVariable = createVariable(read, readType); left = createVariableGet(leftVariable); } else { left = read; } ObjectAccessTarget binaryTarget = inferrer.findInterfaceMember( readType, node.binaryName, node.binaryOffset, includeExtensionMethods: true); MethodContravarianceCheckKind binaryCheckKind = inferrer.preCheckInvocationContravariance(readType, binaryTarget, isThisReceiver: false); DartType binaryType = inferrer.getReturnType(binaryTarget, readType); DartType rhsType = inferrer.getPositionalParameterTypeForTarget(binaryTarget, readType, 0); ExpressionInferenceResult rhsResult = inferrer.inferExpression(node.rhs, rhsType, true, isVoidAllowed: true); inferrer.ensureAssignable( rhsType, rhsResult.inferredType, node.rhs, node.rhs.fileOffset); if (inferrer.isOverloadedArithmeticOperatorAndType( binaryTarget, readType)) { binaryType = inferrer.typeSchemaEnvironment .getTypeOfOverloadedArithmetic(readType, rhsResult.inferredType); } Expression binary; if (binaryTarget.isMissing) { binary = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments(node.binaryName.name, readType), node.binaryOffset, node.binaryName.name.length); } else if (binaryTarget.isExtensionMember) { binary = new StaticInvocation( binaryTarget.member, new Arguments(<Expression>[ left, node.rhs, ], types: binaryTarget.inferredExtensionTypeArguments) ..fileOffset = node.binaryOffset) ..fileOffset = node.binaryOffset; } else { binary = new MethodInvocation( left, node.binaryName, new Arguments(<Expression>[ node.rhs, ]) ..fileOffset = node.binaryOffset, binaryTarget.member) ..fileOffset = node.binaryOffset; if (binaryCheckKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.binaryOffset, 'checkReturn', new InstrumentationValueForType(readType)); } binary = new AsExpression(binary, binaryType) ..isTypeError = true ..fileOffset = node.binaryOffset; } } ObjectAccessTarget writeTarget = inferrer.findInterfaceMember( receiverType, node.propertyName, node.writeOffset, setter: true, includeExtensionMethods: true); DartType valueType = inferrer.getSetterType(writeTarget, receiverType); Expression binaryReplacement = inferrer.ensureAssignable( valueType, binaryType, binary, node.fileOffset); if (binaryReplacement != null) { binary = binaryReplacement; } VariableDeclaration valueVariable; Expression valueExpression; if (node.forEffect || node.forPostIncDec) { valueExpression = binary; } else { valueVariable = createVariable(binary, binaryType); valueExpression = createVariableGet(valueVariable); } Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments( node.propertyName.name, receiverType), node.writeOffset, node.propertyName.name.length); } else if (writeTarget.isExtensionMember) { write = new StaticInvocation( writeTarget.member, new Arguments(<Expression>[writeReceiver, valueExpression], types: writeTarget.inferredExtensionTypeArguments) ..fileOffset = node.writeOffset) ..fileOffset = node.writeOffset; } else { write = new PropertySet( writeReceiver, node.propertyName, valueExpression, writeTarget.member) ..fileOffset = node.writeOffset; } DartType resultType = node.forPostIncDec ? readType : binaryType; Expression replacement; if (node.forEffect) { assert(leftVariable == null); assert(valueVariable == null); // Encode `receiver?.propertyName binaryName= rhs` as: // // let receiverVariable = receiver in // receiverVariable == null ? null : // receiverVariable.propertyName = // receiverVariable.propertyName + rhs // MethodInvocation equalsNull = createEqualsNull( receiverVariable.fileOffset, createVariableGet(receiverVariable), equalsMember); ConditionalExpression condition = new ConditionalExpression(equalsNull, new NullLiteral()..fileOffset = node.readOffset, write, resultType); replacement = createLet(receiverVariable, condition); } else if (node.forPostIncDec) { // Encode `receiver?.propertyName binaryName= rhs` from a postfix // expression like `o?.a++` as: // // let receiverVariable = receiver in // receiverVariable == null ? null : // let leftVariable = receiverVariable.propertyName in // let writeVariable = // receiverVariable.propertyName = // leftVariable binaryName rhs in // leftVariable // assert(leftVariable != null); assert(valueVariable == null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); MethodInvocation equalsNull = createEqualsNull( receiverVariable.fileOffset, createVariableGet(receiverVariable), equalsMember); ConditionalExpression condition = new ConditionalExpression( equalsNull, new NullLiteral()..fileOffset = node.readOffset, createLet(leftVariable, createLet(writeVariable, createVariableGet(leftVariable))), resultType); replacement = createLet(receiverVariable, condition); } else { // Encode `receiver?.propertyName binaryName= rhs` as: // // let receiverVariable = receiver in // receiverVariable == null ? null : // let leftVariable = receiverVariable.propertyName in // let valueVariable = leftVariable binaryName rhs in // let writeVariable = // receiverVariable.propertyName = valueVariable in // valueVariable // // TODO(johnniwinther): Do we need the `leftVariable` in this case? assert(leftVariable == null); assert(valueVariable != null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); MethodInvocation equalsNull = createEqualsNull( receiverVariable.fileOffset, createVariableGet(receiverVariable), equalsMember); ConditionalExpression condition = new ConditionalExpression( equalsNull, new NullLiteral()..fileOffset = node.readOffset, createLet(valueVariable, createLet(writeVariable, createVariableGet(valueVariable))), resultType); replacement = createLet(receiverVariable, condition); } node.replaceWith(replacement); return new ExpressionInferenceResult(resultType, replacement); } ExpressionInferenceResult visitCompoundSuperIndexSet( CompoundSuperIndexSet node, DartType typeContext) { ObjectAccessTarget readTarget = node.getter != null ? new ObjectAccessTarget.interfaceMember(node.getter) : const ObjectAccessTarget.missing(); DartType readType = inferrer.getReturnType(readTarget, inferrer.thisType); DartType readIndexType = inferrer.getPositionalParameterTypeForTarget( readTarget, inferrer.thisType, 0); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, readIndexType, true, isVoidAllowed: true); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); Expression readIndex = createVariableGet(indexVariable); Expression readIndexReplacement = inferrer.ensureAssignable(readIndexType, indexResult.inferredType, readIndex, readIndex.fileOffset); if (readIndexReplacement != null) { readIndex = readIndexReplacement; } Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateSuperclassHasNoMethod.withArguments('[]'), node.readOffset, '[]'.length); } else { assert(readTarget.isInstanceMember); inferrer.instrumentation?.record(inferrer.uri, node.readOffset, 'target', new InstrumentationValueForMember(node.getter)); read = new SuperMethodInvocation( indexGetName, new Arguments(<Expression>[ readIndex, ]) ..fileOffset = node.readOffset, readTarget.member) ..fileOffset = node.readOffset; } VariableDeclaration leftVariable; Expression left; if (node.forEffect) { left = read; } else if (node.forPostIncDec) { leftVariable = createVariable(read, readType); left = createVariableGet(leftVariable); } else { left = read; } ObjectAccessTarget binaryTarget = inferrer.findInterfaceMember( readType, node.binaryName, node.binaryOffset, includeExtensionMethods: true); MethodContravarianceCheckKind binaryCheckKind = inferrer.preCheckInvocationContravariance(readType, binaryTarget, isThisReceiver: false); DartType binaryType = inferrer.getReturnType(binaryTarget, readType); DartType rhsType = inferrer.getPositionalParameterTypeForTarget(binaryTarget, readType, 0); ExpressionInferenceResult rhsResult = inferrer.inferExpression(node.rhs, rhsType, true, isVoidAllowed: true); inferrer.ensureAssignable( rhsType, rhsResult.inferredType, node.rhs, node.rhs.fileOffset); if (inferrer.isOverloadedArithmeticOperatorAndType( binaryTarget, readType)) { binaryType = inferrer.typeSchemaEnvironment .getTypeOfOverloadedArithmetic(readType, rhsResult.inferredType); } Expression binary; if (binaryTarget.isMissing) { binary = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments(node.binaryName.name, readType), node.binaryOffset, node.binaryName.name.length); } else if (binaryTarget.isExtensionMember) { binary = new StaticInvocation( binaryTarget.member, new Arguments(<Expression>[ left, node.rhs, ], types: binaryTarget.inferredExtensionTypeArguments) ..fileOffset = node.binaryOffset) ..fileOffset = node.binaryOffset; } else { binary = new MethodInvocation( left, node.binaryName, new Arguments(<Expression>[ node.rhs, ]) ..fileOffset = node.binaryOffset, binaryTarget.member) ..fileOffset = node.binaryOffset; if (binaryCheckKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.binaryOffset, 'checkReturn', new InstrumentationValueForType(readType)); } binary = new AsExpression(binary, binaryType) ..isTypeError = true ..fileOffset = node.binaryOffset; } } ObjectAccessTarget writeTarget = node.setter != null ? new ObjectAccessTarget.interfaceMember(node.setter) : const ObjectAccessTarget.missing(); DartType writeIndexType = inferrer.getPositionalParameterTypeForTarget( writeTarget, inferrer.thisType, 0); Expression writeIndex = createVariableGet(indexVariable); Expression writeIndexReplacement = inferrer.ensureAssignable(writeIndexType, indexResult.inferredType, writeIndex, writeIndex.fileOffset); if (writeIndexReplacement != null) { writeIndex = writeIndexReplacement; } DartType valueType = inferrer.getIndexSetValueType(writeTarget, inferrer.thisType); Expression binaryReplacement = inferrer.ensureAssignable( valueType, binaryType, binary, node.fileOffset); if (binaryReplacement != null) { binary = binaryReplacement; } VariableDeclaration valueVariable; Expression valueExpression; if (node.forEffect || node.forPostIncDec) { valueExpression = binary; } else { valueVariable = createVariable(binary, binaryType); valueExpression = createVariableGet(valueVariable); } Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateSuperclassHasNoMethod.withArguments('[]='), node.writeOffset, '[]='.length); } else { assert(writeTarget.isInstanceMember); inferrer.instrumentation?.record(inferrer.uri, node.writeOffset, 'target', new InstrumentationValueForMember(node.setter)); write = new SuperMethodInvocation( indexSetName, new Arguments(<Expression>[writeIndex, valueExpression]) ..fileOffset = node.writeOffset, writeTarget.member) ..fileOffset = node.writeOffset; } Expression replacement; if (node.forEffect) { assert(leftVariable == null); assert(valueVariable == null); // Encode `super[a] += b` as: // // let v1 = a in super.[]=(v1, super.[](v1) + b) // replacement = createLet(indexVariable, write); } else if (node.forPostIncDec) { // Encode `super[a]++` as: // // let v2 = a in // let v3 = v1.[](v2) // let v4 = v1.[]=(v2, v3 + 1) in v3 // assert(leftVariable != null); assert(valueVariable == null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); replacement = createLet( indexVariable, createLet(leftVariable, createLet(writeVariable, createVariableGet(leftVariable)))); } else { // Encode `super[a] += b` as: // // let v1 = o in // let v2 = a in // let v3 = v1.[](v2) + b // let v4 = v1.[]=(v2, c3) in v3 // assert(leftVariable == null); assert(valueVariable != null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); replacement = createLet( indexVariable, createLet(valueVariable, createLet(writeVariable, createVariableGet(valueVariable)))); } node.replaceWith(replacement); return new ExpressionInferenceResult( node.forPostIncDec ? readType : binaryType, replacement); } ExpressionInferenceResult visitCompoundExtensionIndexSet( CompoundExtensionIndexSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: false); List<DartType> extensionTypeArguments = inferrer.computeExtensionTypeArgument(node.extension, node.explicitTypeArguments, receiverResult.inferredType); ObjectAccessTarget readTarget = node.getter != null ? new ExtensionAccessTarget( node.getter, null, ProcedureKind.Operator, extensionTypeArguments) : const ObjectAccessTarget.missing(); DartType receiverType = inferrer.getPositionalParameterTypeForTarget( readTarget, receiverResult.inferredType, 0); inferrer.ensureAssignable(receiverType, receiverResult.inferredType, node.receiver, node.receiver.fileOffset); VariableDeclaration receiverVariable = createVariable(node.receiver, receiverType); DartType readType = inferrer.getReturnType(readTarget, receiverType); DartType readIndexType = inferrer.getPositionalParameterTypeForTarget( readTarget, receiverType, 0); ExpressionInferenceResult indexResult = inferrer .inferExpression(node.index, readIndexType, true, isVoidAllowed: true); VariableDeclaration indexVariable = createVariable(node.index, indexResult.inferredType); Expression readIndex = createVariableGet(indexVariable); Expression readIndexReplacement = inferrer.ensureAssignable(readIndexType, indexResult.inferredType, readIndex, readIndex.fileOffset); if (readIndexReplacement != null) { readIndex = readIndexReplacement; } Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments( indexGetName.name, receiverType), node.readOffset, noLength); } else { assert(readTarget.isExtensionMember); read = new StaticInvocation( readTarget.member, new Arguments(<Expression>[ createVariableGet(receiverVariable), readIndex, ], types: readTarget.inferredExtensionTypeArguments) ..fileOffset = node.readOffset) ..fileOffset = node.readOffset; } VariableDeclaration leftVariable; Expression left; if (node.forEffect) { left = read; } else if (node.forPostIncDec) { leftVariable = createVariable(read, readType); left = createVariableGet(leftVariable); } else { left = read; } ObjectAccessTarget binaryTarget = inferrer.findInterfaceMember( readType, node.binaryName, node.binaryOffset, includeExtensionMethods: true); MethodContravarianceCheckKind binaryCheckKind = inferrer.preCheckInvocationContravariance(readType, binaryTarget, isThisReceiver: false); DartType binaryType = inferrer.getReturnType(binaryTarget, readType); DartType rhsType = inferrer.getPositionalParameterTypeForTarget(binaryTarget, readType, 0); ExpressionInferenceResult rhsResult = inferrer.inferExpression(node.rhs, rhsType, true, isVoidAllowed: true); inferrer.ensureAssignable( rhsType, rhsResult.inferredType, node.rhs, node.rhs.fileOffset); if (inferrer.isOverloadedArithmeticOperatorAndType( binaryTarget, readType)) { binaryType = inferrer.typeSchemaEnvironment .getTypeOfOverloadedArithmetic(readType, rhsResult.inferredType); } Expression binary; if (binaryTarget.isMissing) { binary = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments(node.binaryName.name, readType), node.binaryOffset, node.binaryName.name.length); } else if (binaryTarget.isExtensionMember) { binary = new StaticInvocation( binaryTarget.member, new Arguments(<Expression>[ left, node.rhs, ], types: binaryTarget.inferredExtensionTypeArguments) ..fileOffset = node.binaryOffset) ..fileOffset = node.binaryOffset; } else { binary = new MethodInvocation( left, node.binaryName, new Arguments(<Expression>[ node.rhs, ]) ..fileOffset = node.binaryOffset, binaryTarget.member) ..fileOffset = node.binaryOffset; if (binaryCheckKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.binaryOffset, 'checkReturn', new InstrumentationValueForType(readType)); } binary = new AsExpression(binary, binaryType) ..isTypeError = true ..fileOffset = node.binaryOffset; } } ObjectAccessTarget writeTarget = node.setter != null ? new ExtensionAccessTarget( node.setter, null, ProcedureKind.Operator, extensionTypeArguments) : const ObjectAccessTarget.missing(); DartType writeIndexType = inferrer.getPositionalParameterTypeForTarget( writeTarget, receiverType, 0); Expression writeIndex = createVariableGet(indexVariable); Expression writeIndexReplacement = inferrer.ensureAssignable(writeIndexType, indexResult.inferredType, writeIndex, writeIndex.fileOffset); if (writeIndexReplacement != null) { writeIndex = writeIndexReplacement; } DartType valueType = inferrer.getIndexSetValueType(writeTarget, inferrer.thisType); Expression binaryReplacement = inferrer.ensureAssignable( valueType, binaryType, binary, node.fileOffset); if (binaryReplacement != null) { binary = binaryReplacement; } VariableDeclaration valueVariable; Expression valueExpression; if (node.forEffect || node.forPostIncDec) { valueExpression = binary; } else { valueVariable = createVariable(binary, binaryType); valueExpression = createVariableGet(valueVariable); } Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments( indexSetName.name, receiverType), node.writeOffset, noLength); } else { assert(writeTarget.isExtensionMember); write = new StaticInvocation( writeTarget.member, new Arguments(<Expression>[ createVariableGet(receiverVariable), writeIndex, valueExpression ], types: writeTarget.inferredExtensionTypeArguments) ..fileOffset = node.writeOffset) ..fileOffset = node.writeOffset; } Expression inner; if (node.forEffect) { assert(leftVariable == null); assert(valueVariable == null); // Encode `Extension(o)[a] += b` as: // // let receiverVariable = o in // let indexVariable = a in // receiverVariable.[]=(receiverVariable, o.[](indexVariable) + b) // inner = createLet(indexVariable, write); } else if (node.forPostIncDec) { // Encode `Extension(o)[a]++` as: // // let receiverVariable = o in // let indexVariable = a in // let leftVariable = receiverVariable.[](indexVariable) // let writeVariable = // receiverVariable.[]=(indexVariable, leftVariable + 1) in // leftVariable // assert(leftVariable != null); assert(valueVariable == null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); inner = createLet( indexVariable, createLet(leftVariable, createLet(writeVariable, createVariableGet(leftVariable)))); } else { // Encode `Extension(o)[a] += b` as: // // let receiverVariable = o in // let indexVariable = a in // let valueVariable = receiverVariable.[](indexVariable) + b // let writeVariable = // receiverVariable.[]=(indexVariable, valueVariable) in // valueVariable // assert(leftVariable == null); assert(valueVariable != null); VariableDeclaration writeVariable = createVariable(write, const VoidType()); inner = createLet( indexVariable, createLet(valueVariable, createLet(writeVariable, createVariableGet(valueVariable)))); } Expression replacement = new Let(receiverVariable, inner) ..fileOffset = node.fileOffset; node.replaceWith(replacement); return new ExpressionInferenceResult( node.forPostIncDec ? readType : binaryType, replacement); } @override ExpressionInferenceResult visitNullLiteral( NullLiteral node, DartType typeContext) { return new ExpressionInferenceResult(inferrer.coreTypes.nullType); } @override ExpressionInferenceResult visitLet(Let node, DartType typeContext) { DartType variableType = node.variable.type; inferrer.inferExpression(node.variable.initializer, variableType, true, isVoidAllowed: true); ExpressionInferenceResult result = inferrer .inferExpression(node.body, typeContext, true, isVoidAllowed: true); DartType inferredType = result.inferredType; return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitPropertySet( covariant PropertySetImpl node, DartType typeContext) { DartType receiverType = inferrer .inferExpression(node.receiver, const UnknownType(), true, isVoidAllowed: false) .inferredType; ObjectAccessTarget target = inferrer.findPropertySetMember(receiverType, node); DartType writeContext = inferrer.getSetterType(target, receiverType); ExpressionInferenceResult rhsResult = inferrer.inferExpression( node.value, writeContext ?? const UnknownType(), true, isVoidAllowed: true); DartType rhsType = rhsResult.inferredType; inferrer.ensureAssignable( writeContext, rhsType, node.value, node.fileOffset, isVoidAllowed: writeContext is VoidType); Expression replacement; if (target.isExtensionMember) { if (node.forEffect) { replacement = new StaticInvocation( target.member, new Arguments(<Expression>[node.receiver, node.value], types: target.inferredExtensionTypeArguments) ..fileOffset = node.fileOffset) ..fileOffset = node.fileOffset; } else { Expression receiver; VariableDeclaration receiverVariable; if (node.readOnlyReceiver) { receiver = node.receiver; } else { receiverVariable = createVariable(node.receiver, receiverType); receiver = createVariableGet(receiverVariable); } VariableDeclaration valueVariable = createVariable(node.value, rhsType); VariableDeclaration assignmentVariable = createVariable( new StaticInvocation( target.member, new Arguments( <Expression>[receiver, createVariableGet(valueVariable)], types: target.inferredExtensionTypeArguments) ..fileOffset = node.fileOffset) ..fileOffset = node.fileOffset, const VoidType()); replacement = createLet(valueVariable, createLet(assignmentVariable, createVariableGet(valueVariable))); if (receiverVariable != null) { replacement = createLet(receiverVariable, replacement); } replacement..fileOffset = node.fileOffset; } node.replaceWith(replacement); } return new ExpressionInferenceResult(rhsType, replacement); } ExpressionInferenceResult visitNullAwareIfNullSet( NullAwareIfNullSet node, DartType typeContext) { ExpressionInferenceResult receiverResult = inferrer.inferExpression( node.receiver, const UnknownType(), true, isVoidAllowed: false); DartType receiverType = receiverResult.inferredType; VariableDeclaration receiverVariable = createVariable(node.receiver, receiverType); Expression readReceiver = createVariableGet(receiverVariable); Expression writeReceiver = createVariableGet(receiverVariable); Member receiverEqualsMember = inferrer .findInterfaceMember(receiverType, equalsName, node.receiver.fileOffset) .member; ObjectAccessTarget readTarget = inferrer.findInterfaceMember( receiverType, node.name, node.readOffset, includeExtensionMethods: true); MethodContravarianceCheckKind readCheckKind = inferrer.preCheckInvocationContravariance(receiverType, readTarget, isThisReceiver: node.receiver is ThisExpression); DartType readType = inferrer.getGetterType(readTarget, receiverType); Member readEqualsMember = inferrer .findInterfaceMember(readType, equalsName, node.testOffset) .member; Expression read; if (readTarget.isMissing) { read = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments(node.name.name, receiverType), node.readOffset, node.name.name.length); } else if (readTarget.isExtensionMember) { read = new StaticInvocation( readTarget.member, new Arguments(<Expression>[ readReceiver, ], types: readTarget.inferredExtensionTypeArguments) ..fileOffset = node.readOffset) ..fileOffset = node.readOffset; } else { read = new PropertyGet(readReceiver, node.name, readTarget.member) ..fileOffset = node.readOffset; if (readCheckKind == MethodContravarianceCheckKind.checkMethodReturn) { if (inferrer.instrumentation != null) { inferrer.instrumentation.record(inferrer.uri, node.readOffset, 'checkReturn', new InstrumentationValueForType(readType)); } read = new AsExpression(read, readType) ..isTypeError = true ..fileOffset = node.readOffset; } } VariableDeclaration readVariable; if (!node.forEffect) { readVariable = createVariable(read, readType); read = createVariableGet(readVariable); } ObjectAccessTarget writeTarget = inferrer.findInterfaceMember( receiverType, node.name, node.writeOffset, setter: true, includeExtensionMethods: true); DartType valueType = inferrer.getSetterType(writeTarget, receiverType); ExpressionInferenceResult valueResult = inferrer .inferExpression(node.value, valueType, true, isVoidAllowed: true); inferrer.ensureAssignable( valueType, valueResult.inferredType, node.value, node.value.fileOffset); Expression write; if (writeTarget.isMissing) { write = inferrer.helper.buildProblem( templateUndefinedMethod.withArguments(node.name.name, receiverType), node.writeOffset, node.name.name.length); } else if (writeTarget.isExtensionMember) { if (node.forEffect) { write = new StaticInvocation( writeTarget.member, new Arguments(<Expression>[writeReceiver, node.value], types: writeTarget.inferredExtensionTypeArguments) ..fileOffset = node.writeOffset) ..fileOffset = node.writeOffset; } else { VariableDeclaration valueVariable = createVariable(node.value, valueResult.inferredType); VariableDeclaration assignmentVariable = createVariable( new StaticInvocation( writeTarget.member, new Arguments(<Expression>[ writeReceiver, createVariableGet(valueVariable) ], types: writeTarget.inferredExtensionTypeArguments) ..fileOffset = node.writeOffset) ..fileOffset = node.writeOffset, const VoidType()); write = createLet(valueVariable, createLet(assignmentVariable, createVariableGet(valueVariable))) ..fileOffset = node.writeOffset; } } else { write = new PropertySet( writeReceiver, node.name, node.value, writeTarget.member) ..fileOffset = node.writeOffset; } DartType inferredType = inferrer.typeSchemaEnvironment .getStandardUpperBound(readType, valueResult.inferredType); Expression replacement; if (node.forEffect) { assert(readVariable == null); // Encode `receiver?.name ??= value` as: // // let receiverVariable = receiver in // receiverVariable == null ? null : // (receiverVariable.name == null ? // receiverVariable.name = value : null) // MethodInvocation receiverEqualsNull = createEqualsNull( receiverVariable.fileOffset, createVariableGet(receiverVariable), receiverEqualsMember); MethodInvocation readEqualsNull = createEqualsNull(node.readOffset, read, readEqualsMember); ConditionalExpression innerCondition = new ConditionalExpression( readEqualsNull, write, new NullLiteral()..fileOffset = node.writeOffset, inferredType); ConditionalExpression outerCondition = new ConditionalExpression( receiverEqualsNull, new NullLiteral()..fileOffset = node.readOffset, innerCondition, inferredType); replacement = createLet(receiverVariable, outerCondition); } else { // Encode `receiver?.name ??= value` as: // // let receiverVariable = receiver in // receiverVariable == null ? null : // (let readVariable = receiverVariable.name in // readVariable == null ? // receiverVariable.name = value : readVariable) // assert(readVariable != null); MethodInvocation receiverEqualsNull = createEqualsNull( receiverVariable.fileOffset, createVariableGet(receiverVariable), receiverEqualsMember); MethodInvocation readEqualsNull = createEqualsNull(receiverVariable.fileOffset, read, readEqualsMember); ConditionalExpression innerCondition = new ConditionalExpression( readEqualsNull, write, createVariableGet(readVariable), inferredType); ConditionalExpression outerCondition = new ConditionalExpression( receiverEqualsNull, new NullLiteral()..fileOffset = node.readOffset, createLet(readVariable, innerCondition), inferredType); replacement = createLet(receiverVariable, outerCondition); } node.replaceWith(replacement); return new ExpressionInferenceResult(inferredType, replacement); } @override ExpressionInferenceResult visitPropertyGet( PropertyGet node, DartType typeContext) { return inferrer.inferPropertyGet( node, node.receiver, node.fileOffset, typeContext, node); } @override void visitRedirectingInitializer(RedirectingInitializer node) { List<TypeParameter> classTypeParameters = node.target.enclosingClass.typeParameters; List<DartType> typeArguments = new List<DartType>(classTypeParameters.length); for (int i = 0; i < typeArguments.length; i++) { typeArguments[i] = new TypeParameterType(classTypeParameters[i]); } ArgumentsImpl.setNonInferrableArgumentTypes(node.arguments, typeArguments); inferrer.inferInvocation(null, node.fileOffset, node.target.function.thisFunctionType, node.arguments, returnType: node.target.enclosingClass.thisType, skipTypeArgumentInference: true); ArgumentsImpl.removeNonInferrableArgumentTypes(node.arguments); } @override ExpressionInferenceResult visitRethrow(Rethrow node, DartType typeContext) { return const ExpressionInferenceResult(const BottomType()); } @override void visitReturnStatement(covariant ReturnStatementImpl node) { ClosureContext closureContext = inferrer.closureContext; DartType typeContext = !closureContext.isGenerator ? closureContext.returnOrYieldContext : const UnknownType(); DartType inferredType; if (node.expression != null) { inferredType = inferrer .inferExpression(node.expression, typeContext, true, isVoidAllowed: true) .inferredType; } else { inferredType = inferrer.coreTypes.nullType; } closureContext.handleReturn(inferrer, node, inferredType, node.isArrow); } @override ExpressionInferenceResult visitSetLiteral( SetLiteral node, DartType typeContext) { Class setClass = inferrer.coreTypes.setClass; InterfaceType setType = setClass.thisType; List<DartType> inferredTypes; DartType inferredTypeArgument; List<DartType> formalTypes; List<DartType> actualTypes; bool inferenceNeeded = node.typeArgument is ImplicitTypeArgument; bool typeChecksNeeded = !inferrer.isTopLevel; Map<TreeNode, DartType> inferredSpreadTypes; Map<Expression, DartType> inferredConditionTypes; if (inferenceNeeded || typeChecksNeeded) { formalTypes = []; actualTypes = []; inferredSpreadTypes = new Map<TreeNode, DartType>.identity(); inferredConditionTypes = new Map<Expression, DartType>.identity(); } if (inferenceNeeded) { inferredTypes = [const UnknownType()]; inferrer.typeSchemaEnvironment.inferGenericFunctionOrType(setType, setClass.typeParameters, null, null, typeContext, inferredTypes, isConst: node.isConst); inferredTypeArgument = inferredTypes[0]; } else { inferredTypeArgument = node.typeArgument; } if (inferenceNeeded || typeChecksNeeded) { for (int i = 0; i < node.expressions.length; ++i) { DartType type = inferElement( node.expressions[i], node, inferredTypeArgument, inferredSpreadTypes, inferredConditionTypes, inferenceNeeded, typeChecksNeeded); actualTypes.add(type); if (inferenceNeeded) { formalTypes.add(setType.typeArguments[0]); } } } if (inferenceNeeded) { inferrer.typeSchemaEnvironment.inferGenericFunctionOrType( setType, setClass.typeParameters, formalTypes, actualTypes, typeContext, inferredTypes); inferredTypeArgument = inferredTypes[0]; inferrer.instrumentation?.record( inferrer.uri, node.fileOffset, 'typeArgs', new InstrumentationValueForTypeArgs([inferredTypeArgument])); node.typeArgument = inferredTypeArgument; } if (typeChecksNeeded) { for (int i = 0; i < node.expressions.length; i++) { checkElement(node.expressions[i], node, node.typeArgument, inferredSpreadTypes, inferredConditionTypes); } } DartType inferredType = new InterfaceType(setClass, [inferredTypeArgument]); if (!inferrer.isTopLevel) { SourceLibraryBuilder library = inferrer.library; if (inferenceNeeded) { library.checkBoundsInSetLiteral( node, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } if (!library.loader.target.backendTarget.supportsSetLiterals) { inferrer.helper.transformSetLiterals = true; } } return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitStaticSet( StaticSet node, DartType typeContext) { Member writeMember = node.target; DartType writeContext = writeMember.setterType; TypeInferenceEngine.resolveInferenceNode(writeMember); ExpressionInferenceResult rhsResult = inferrer.inferExpression( node.value, writeContext ?? const UnknownType(), true, isVoidAllowed: true); DartType rhsType = rhsResult.inferredType; inferrer.ensureAssignable( writeContext, rhsType, node.value, node.fileOffset, isVoidAllowed: writeContext is VoidType); return new ExpressionInferenceResult(rhsType); } @override ExpressionInferenceResult visitStaticGet( StaticGet node, DartType typeContext) { Member target = node.target; TypeInferenceEngine.resolveInferenceNode(target); DartType type = target.getterType; if (target is Procedure && target.kind == ProcedureKind.Method) { type = inferrer.instantiateTearOff(type, typeContext, node); } return new ExpressionInferenceResult(type); } @override ExpressionInferenceResult visitStaticInvocation( StaticInvocation node, DartType typeContext) { FunctionType calleeType = node.target != null ? node.target.function.functionType : new FunctionType([], const DynamicType()); bool hadExplicitTypeArguments = getExplicitTypeArguments(node.arguments) != null; DartType inferredType = inferrer.inferInvocation( typeContext, node.fileOffset, calleeType, node.arguments); if (!inferrer.isTopLevel && !hadExplicitTypeArguments && node.target != null) { inferrer.library.checkBoundsInStaticInvocation( node, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitStringConcatenation( StringConcatenation node, DartType typeContext) { if (!inferrer.isTopLevel) { for (Expression expression in node.expressions) { inferrer.inferExpression( expression, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: false); } } return new ExpressionInferenceResult( inferrer.coreTypes.stringRawType(inferrer.library.nonNullable)); } @override ExpressionInferenceResult visitStringLiteral( StringLiteral node, DartType typeContext) { return new ExpressionInferenceResult( inferrer.coreTypes.stringRawType(inferrer.library.nonNullable)); } @override void visitSuperInitializer(SuperInitializer node) { Substitution substitution = Substitution.fromSupertype( inferrer.classHierarchy.getClassAsInstanceOf( inferrer.thisType.classNode, node.target.enclosingClass)); inferrer.inferInvocation( null, node.fileOffset, substitution.substituteType( node.target.function.thisFunctionType.withoutTypeParameters), node.arguments, returnType: inferrer.thisType, skipTypeArgumentInference: true); } @override ExpressionInferenceResult visitSuperMethodInvocation( SuperMethodInvocation node, DartType typeContext) { if (node.interfaceTarget != null) { inferrer.instrumentation?.record(inferrer.uri, node.fileOffset, 'target', new InstrumentationValueForMember(node.interfaceTarget)); } ExpressionInferenceResult result = inferrer.inferSuperMethodInvocation( node, typeContext, node.interfaceTarget != null ? new ObjectAccessTarget.interfaceMember(node.interfaceTarget) : const ObjectAccessTarget.unresolved()); return new ExpressionInferenceResult(result.inferredType); } @override ExpressionInferenceResult visitSuperPropertyGet( SuperPropertyGet node, DartType typeContext) { if (node.interfaceTarget != null) { inferrer.instrumentation?.record(inferrer.uri, node.fileOffset, 'target', new InstrumentationValueForMember(node.interfaceTarget)); } return inferrer.inferSuperPropertyGet( node, typeContext, node.interfaceTarget != null ? new ObjectAccessTarget.interfaceMember(node.interfaceTarget) : const ObjectAccessTarget.unresolved()); } @override ExpressionInferenceResult visitSuperPropertySet( SuperPropertySet node, DartType typeContext) { DartType receiverType = inferrer.classHierarchy.getTypeAsInstanceOf( inferrer.thisType, inferrer.thisType.classNode.supertype.classNode); ObjectAccessTarget writeTarget = inferrer.findInterfaceMember( receiverType, node.name, node.fileOffset, setter: true, instrumented: true); if (writeTarget.isInstanceMember) { node.interfaceTarget = writeTarget.member; } DartType writeContext = inferrer.getSetterType(writeTarget, receiverType); ExpressionInferenceResult rhsResult = inferrer.inferExpression( node.value, writeContext ?? const UnknownType(), true, isVoidAllowed: true); DartType rhsType = rhsResult.inferredType; inferrer.ensureAssignable( writeContext, rhsType, node.value, node.fileOffset, isVoidAllowed: writeContext is VoidType); return new ExpressionInferenceResult(rhsType); } @override void visitSwitchStatement(SwitchStatement node) { DartType expressionType = inferrer .inferExpression(node.expression, const UnknownType(), true, isVoidAllowed: false) .inferredType; for (SwitchCase switchCase in node.cases) { for (Expression caseExpression in switchCase.expressions) { ExpressionInferenceResult caseExpressionResult = inferrer.inferExpression(caseExpression, expressionType, true, isVoidAllowed: false); if (caseExpressionResult.replacement != null) { caseExpression = caseExpressionResult.replacement; } DartType caseExpressionType = caseExpressionResult.inferredType; // Check whether the expression type is assignable to the case // expression type. if (!inferrer.isAssignable(expressionType, caseExpressionType)) { inferrer.helper.addProblem( templateSwitchExpressionNotAssignable.withArguments( expressionType, caseExpressionType), caseExpression.fileOffset, noLength, context: [ messageSwitchExpressionNotAssignableCause.withLocation( inferrer.uri, node.expression.fileOffset, noLength) ]); } } inferrer.inferStatement(switchCase.body); } } @override ExpressionInferenceResult visitSymbolLiteral( SymbolLiteral node, DartType typeContext) { DartType inferredType = inferrer.coreTypes.symbolRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } ExpressionInferenceResult visitThisExpression( ThisExpression node, DartType typeContext) { return new ExpressionInferenceResult(inferrer.thisType); } @override ExpressionInferenceResult visitThrow(Throw node, DartType typeContext) { inferrer.inferExpression( node.expression, const UnknownType(), !inferrer.isTopLevel, isVoidAllowed: false); return const ExpressionInferenceResult(const BottomType()); } void visitCatch(Catch node) { inferrer.inferStatement(node.body); } @override void visitTryCatch(TryCatch node) { inferrer.inferStatement(node.body); for (Catch catch_ in node.catches) { visitCatch(catch_); } } @override void visitTryFinally(TryFinally node) { inferrer.inferStatement(node.body); inferrer.inferStatement(node.finalizer); } @override ExpressionInferenceResult visitTypeLiteral( TypeLiteral node, DartType typeContext) { DartType inferredType = inferrer.coreTypes.typeRawType(inferrer.library.nonNullable); return new ExpressionInferenceResult(inferredType); } @override ExpressionInferenceResult visitVariableSet( VariableSet node, DartType typeContext) { DartType writeContext = node.variable.type; ExpressionInferenceResult rhsResult = inferrer.inferExpression( node.value, writeContext ?? const UnknownType(), true, isVoidAllowed: true); DartType rhsType = rhsResult.inferredType; inferrer.ensureAssignable( writeContext, rhsType, node.value, node.fileOffset, isVoidAllowed: writeContext is VoidType); return new ExpressionInferenceResult(rhsType); } @override void visitVariableDeclaration(covariant VariableDeclarationImpl node) { DartType declaredType = node._implicitlyTyped ? const UnknownType() : node.type; DartType inferredType; DartType initializerType; if (node.initializer != null) { ExpressionInferenceResult initializerResult = inferrer.inferExpression( node.initializer, declaredType, !inferrer.isTopLevel || node._implicitlyTyped, isVoidAllowed: true); initializerType = initializerResult.inferredType; inferredType = inferrer.inferDeclarationType(initializerType); } else { inferredType = const DynamicType(); } if (node._implicitlyTyped) { inferrer.instrumentation?.record(inferrer.uri, node.fileOffset, 'type', new InstrumentationValueForType(inferredType)); node.type = inferredType; } if (node.initializer != null) { Expression replacedInitializer = inferrer.ensureAssignable( node.type, initializerType, node.initializer, node.fileOffset, isVoidAllowed: node.type is VoidType); if (replacedInitializer != null) { node.initializer = replacedInitializer; } } if (!inferrer.isTopLevel) { SourceLibraryBuilder library = inferrer.library; if (node._implicitlyTyped) { library.checkBoundsInVariableDeclaration( node, inferrer.typeSchemaEnvironment, inferrer.helper.uri, inferred: true); } } } @override ExpressionInferenceResult visitVariableGet( covariant VariableGetImpl node, DartType typeContext) { VariableDeclarationImpl variable = node.variable; bool mutatedInClosure = variable._mutatedInClosure; DartType declaredOrInferredType = variable.type; DartType promotedType = inferrer.typePromoter .computePromotedType(node._fact, node._scope, mutatedInClosure); if (promotedType != null) { inferrer.instrumentation?.record(inferrer.uri, node.fileOffset, 'promotedType', new InstrumentationValueForType(promotedType)); } node.promotedType = promotedType; DartType type = promotedType ?? declaredOrInferredType; if (variable._isLocalFunction) { type = inferrer.instantiateTearOff(type, typeContext, node); } return new ExpressionInferenceResult(type); } @override void visitWhileStatement(WhileStatement node) { InterfaceType expectedType = inferrer.coreTypes.boolRawType(inferrer.library.nonNullable); DartType conditionType = inferrer .inferExpression(node.condition, expectedType, !inferrer.isTopLevel, isVoidAllowed: false) .inferredType; inferrer.ensureAssignable( expectedType, conditionType, node.condition, node.condition.fileOffset); inferrer.inferStatement(node.body); } @override void visitYieldStatement(YieldStatement node) { ClosureContext closureContext = inferrer.closureContext; DartType inferredType; if (closureContext.isGenerator) { DartType typeContext = closureContext.returnOrYieldContext; if (node.isYieldStar && typeContext != null) { typeContext = inferrer.wrapType( typeContext, closureContext.isAsync ? inferrer.coreTypes.streamClass : inferrer.coreTypes.iterableClass); } inferredType = inferrer .inferExpression(node.expression, typeContext, true, isVoidAllowed: true) .inferredType; } else { inferredType = inferrer .inferExpression(node.expression, const UnknownType(), true, isVoidAllowed: true) .inferredType; } closureContext.handleYield(inferrer, node.isYieldStar, inferredType, node.expression, node.fileOffset); } @override ExpressionInferenceResult visitLoadLibrary( covariant LoadLibraryImpl node, DartType typeContext) { DartType inferredType = inferrer.typeSchemaEnvironment.futureType(const DynamicType()); if (node.arguments != null) { FunctionType calleeType = new FunctionType([], inferredType); inferrer.inferInvocation( typeContext, node.fileOffset, calleeType, node.arguments); } return new ExpressionInferenceResult(inferredType); } ExpressionInferenceResult visitLoadLibraryTearOff( LoadLibraryTearOff node, DartType typeContext) { DartType inferredType = new FunctionType( [], inferrer.typeSchemaEnvironment.futureType(const DynamicType())); Expression replacement = node.replace(); return new ExpressionInferenceResult(inferredType, replacement); } @override ExpressionInferenceResult visitCheckLibraryIsLoaded( CheckLibraryIsLoaded node, DartType typeContext) { // TODO(dmitryas): Figure out the suitable nullability for that. return new ExpressionInferenceResult( inferrer.coreTypes.objectRawType(inferrer.library.nullable)); } }
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/kernel/expression_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. /// A library to help generate expression. library fasta.expression_generator; import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart'; import '../../scanner/token.dart' show Token; import '../constant_context.dart' show ConstantContext; import '../builder/builder.dart' show NullabilityBuilder, PrefixBuilder, TypeDeclarationBuilder; import '../builder/declaration_builder.dart'; import '../builder/extension_builder.dart'; import '../builder/member_builder.dart'; import '../fasta_codes.dart'; import '../names.dart' show ampersandName, barName, callName, caretName, divisionName, equalsName, indexGetName, indexSetName, leftShiftName, lengthName, minusName, multiplyName, mustacheName, percentName, plusName, rightShiftName, tripleShiftName; import '../parser.dart' show lengthForToken, lengthOfSpan, offsetForToken; import '../problems.dart'; import '../scope.dart'; import 'body_builder.dart' show noLocation; import 'constness.dart' show Constness; import 'expression_generator_helper.dart' show ExpressionGeneratorHelper; import 'forest.dart'; import 'kernel_api.dart' show NameSystem, printNodeOn, printQualifiedNameOn; import 'kernel_ast_api.dart' show Arguments, DartType, DynamicType, Expression, Initializer, Member, Name, Procedure, VariableDeclaration; import 'kernel_builder.dart' show AccessErrorBuilder, Builder, InvalidTypeBuilder, LoadLibraryBuilder, NamedTypeBuilder, TypeBuilder, UnlinkedDeclaration, UnresolvedType; import 'kernel_shadow_ast.dart'; /// A generator represents a subexpression for which we can't yet build an /// expression because we don't yet know the context in which it's used. /// /// Once the context is known, a generator can be converted into an expression /// by calling a `build` method. /// /// For example, when building a kernel representation for `a[x] = b`, after /// parsing `a[x]` but before parsing `= b`, we don't yet know whether to /// generate an invocation of `operator[]` or `operator[]=`, so we create a /// [Generator] object. Later, after `= b` is parsed, [buildAssignment] will /// be called. abstract class Generator { /// Helper that provides access to contextual information. final ExpressionGeneratorHelper _helper; /// A token that defines a position subexpression that being built. final Token token; final int fileOffset; Generator(this._helper, this.token) : fileOffset = offsetForToken(token); /// Easy access to the [Forest] factory object. Forest get _forest => _helper.forest; // TODO(johnniwinther): Improve the semantic precision of this property or // remove it. It's unclear if the semantics is inconsistent. It's for instance // used both for the name of a variable in [VariableUseGenerator] and for // `[]` in [IndexedAccessGenerator], and while the former text occurs in the // underlying source code, the latter doesn't. String get _plainNameForRead; /// Internal name used for debugging. String get _debugName; /// The source uri for use in error messaging. Uri get _uri => _helper.uri; /// Builds a [Expression] representing a read from the generator. /// /// The read of this subexpression does _not_ need to support a simultaneous /// write of the same subexpression. Expression buildSimpleRead(); /// Builds a [Expression] representing an assignment with the generator on /// the LHS and [value] on the RHS. /// /// The returned expression evaluates to the assigned value, unless /// [voidContext] is true, in which case it may evaluate to anything. Expression buildAssignment(Expression value, {bool voidContext: false}); /// Returns a [Expression] representing a null-aware assignment (`??=`) with /// the generator on the LHS and [value] on the RHS. /// /// The returned expression evaluates to the assigned value, unless /// [voidContext] is true, in which case it may evaluate to anything. /// /// [type] is the static type of the RHS. Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}); /// Returns a [Expression] representing a compound assignment (e.g. `+=`) /// with the generator on the LHS and [value] on the RHS. Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}); /// Returns a [Expression] representing a pre-increment or pre-decrement of /// the generator. Expression buildPrefixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return buildCompoundAssignment( binaryOperator, _forest.createIntLiteral(offset, 1), offset: offset, // TODO(johnniwinther): We are missing some void contexts here. For // instance `++a?.b;` is not providing a void context making it default // `true`. voidContext: voidContext, interfaceTarget: interfaceTarget, isPreIncDec: true); } /// Returns a [Expression] representing a post-increment or post-decrement of /// the generator. Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}); /// Returns a [Generator] or [Expression] representing an index access /// (e.g. `a[b]`) with the generator on the receiver and [index] as the /// index expression. Generator buildIndexedAccess(Expression index, Token token); /// Returns a [Expression] representing a compile-time error. /// /// At runtime, an exception will be thrown. Expression _makeInvalidRead() { return _helper.throwNoSuchMethodError(_forest.createNullLiteral(fileOffset), _plainNameForRead, _forest.createArgumentsEmpty(noLocation), fileOffset, isGetter: true); } /// Returns a [Expression] representing a compile-time error wrapping /// [value]. /// /// At runtime, [value] will be evaluated before throwing an exception. Expression _makeInvalidWrite(Expression value) { return _helper.throwNoSuchMethodError( _forest.createNullLiteral(fileOffset), _plainNameForRead, _forest.createArguments(noLocation, <Expression>[value]), fileOffset, isSetter: true); } Expression buildForEffect() => buildSimpleRead(); Initializer buildFieldInitializer(Map<String, int> initializedFields) { return _helper.buildInvalidInitializer( _helper.buildProblem( messageInvalidInitializer, fileOffset, lengthForToken(token)), fileOffset); } /// Returns an expression, generator or initializer for an invocation of this /// subexpression with [arguments] at [offset]. /// /// For instance: /// * If this is a [PropertyAccessGenerator] for `a.b`, this will create /// a [MethodInvocation] for `a.b(...)`. /// * If this is a [ThisAccessGenerator] for `this` in an initializer list, /// this will create a [RedirectingInitializer] for `this(...)`. /// * If this is an [IncompleteErrorGenerator], this will return the error /// generator itself. /// /// If the invocation has explicit type arguments /// [buildTypeWithResolvedArguments] called instead. /* Expression | Generator | Initializer */ doInvocation( int offset, Arguments arguments); /* Expression | Generator */ buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { if (send is SendAccessGenerator) { return _helper.buildMethodInvocation(buildSimpleRead(), send.name, send.arguments, offsetForToken(send.token), isNullAware: isNullAware); } else { if (_helper.constantContext != ConstantContext.none && send.name != lengthName) { _helper.addProblem( messageNotAConstantExpression, fileOffset, token.length); } return PropertyAccessGenerator.make(_helper, send.token, buildSimpleRead(), send.name, null, null, isNullAware); } } /// Returns a [TypeBuilder] for this subexpression instantiated with the /// type [arguments]. If no type arguments are provided [arguments] is `null`. /// /// The type arguments have not been resolved and should be resolved to /// create a [TypeBuilder] for a valid type. TypeBuilder buildTypeWithResolvedArguments( NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) { NamedTypeBuilder result = new NamedTypeBuilder(token.lexeme, nullabilityBuilder, null); Message message = templateNotAType.withArguments(token.lexeme); _helper.libraryBuilder .addProblem(message, fileOffset, lengthForToken(token), _uri); result.bind(result.buildInvalidType( message.withLocation(_uri, fileOffset, lengthForToken(token)))); return result; } /* Expression | Generator */ Object qualifiedLookup(Token name) { return new UnexpectedQualifiedUseGenerator(_helper, name, this, false); } Expression invokeConstructor( List<UnresolvedType> typeArguments, String name, Arguments arguments, Token nameToken, Token nameLastToken, Constness constness) { if (typeArguments != null) { assert(_forest.argumentsTypeArguments(arguments).isEmpty); _forest.argumentsSetTypeArguments( arguments, _helper.buildDartTypeArguments(typeArguments)); } return _helper.throwNoSuchMethodError( _forest.createNullLiteral(fileOffset), _helper.constructorNameForDiagnostics(name, className: _plainNameForRead), arguments, nameToken.charOffset); } void printOn(StringSink sink); String toString() { StringBuffer buffer = new StringBuffer(); buffer.write(_debugName); buffer.write("(offset: "); buffer.write("${fileOffset}"); printOn(buffer); buffer.write(")"); return "$buffer"; } } /// [VariableUseGenerator] represents the subexpression whose prefix is a /// local variable or parameter name. /// /// For instance: /// /// method(a) { /// var b; /// a; // a VariableUseGenerator is created for `a`. /// b = a[]; // a VariableUseGenerator is created for `a` and `b`. /// b(); // a VariableUseGenerator is created for `b`. /// b.c = a.d; // a VariableUseGenerator is created for `a` and `b`. /// } /// /// If the variable is final or read-only (like a parameter in a catch clause) a /// [ReadOnlyAccessGenerator] is created instead. class VariableUseGenerator extends Generator { final VariableDeclaration variable; final DartType promotedType; VariableUseGenerator( ExpressionGeneratorHelper helper, Token token, this.variable, [this.promotedType]) : super(helper, token); @override String get _debugName => "VariableUseGenerator"; @override String get _plainNameForRead => variable.name; @override Expression buildSimpleRead() { return _createRead(); } Expression _createRead() { return _helper.createVariableGet(variable, fileOffset); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _createWrite(fileOffset, value); } Expression _createWrite(int offset, Expression value) { _helper.typePromoter ?.mutateVariable(variable, _helper.functionNestingLevel); Expression write; if (variable.isFinal || variable.isConst) { write = _makeInvalidWrite(value); } else { write = new VariableSet(variable, value)..fileOffset = offset; } return write; } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { Expression read = _createRead(); Expression write = _createWrite(fileOffset, value); return new IfNullSet(read, write, forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _createRead(), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); return _createWrite(fileOffset, binary); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } VariableDeclaration read = _helper.forest.createVariableDeclarationForValue(_createRead()); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue(_createWrite(offset, binary)); return new LocalPostIncDec(read, write)..fileOffset = offset; } @override Expression doInvocation(int offset, Arguments arguments) { return _helper.buildMethodInvocation(buildSimpleRead(), callName, arguments, adjustForImplicitCall(_plainNameForRead, offset), isImplicitCall: true); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", variable: "); printNodeOn(variable, sink, syntheticNames: syntheticNames); sink.write(", promotedType: "); printNodeOn(promotedType, sink, syntheticNames: syntheticNames); } } /// A [PropertyAccessGenerator] represents a subexpression whose prefix is /// an explicit property access. /// /// For instance /// /// method(a) { /// a.b; // a PropertyAccessGenerator is created for `a.b`. /// a.b(); // a PropertyAccessGenerator is created for `a.b`. /// a.b = c; // a PropertyAccessGenerator is created for `a.b`. /// a.b += c; // a PropertyAccessGenerator is created for `a.b`. /// } /// /// If the receiver is `this`, a [ThisPropertyAccessGenerator] is created /// instead. If the access is null-aware, e.g. `a?.b`, a /// [NullAwarePropertyAccessGenerator] is created instead. class PropertyAccessGenerator extends Generator { /// The receiver expression. `a` in the examples in the class documentation. final Expression receiver; /// The name for the accessed property. `b` in the examples in the class /// documentation. final Name name; // TODO(johnniwinther): Remove [getter] and [setter]? These are never // passed. final Member getter; final Member setter; PropertyAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.receiver, this.name, this.getter, this.setter) : super(helper, token); @override String get _debugName => "PropertyAccessGenerator"; @override String get _plainNameForRead => name.name; @override Expression doInvocation(int offset, Arguments arguments) { return _helper.buildMethodInvocation(receiver, name, arguments, offset); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", receiver: "); printNodeOn(receiver, sink, syntheticNames: syntheticNames); sink.write(", name: "); sink.write(name.name); sink.write(", getter: "); printQualifiedNameOn(getter, sink, syntheticNames: syntheticNames); sink.write(", setter: "); printQualifiedNameOn(setter, sink, syntheticNames: syntheticNames); } @override Expression buildSimpleRead() { return new PropertyGet(receiver, name, getter)..fileOffset = fileOffset; } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _helper.forest.createPropertySet(fileOffset, receiver, name, value, interfaceTarget: setter, forEffect: voidContext); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext = false}) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); PropertyGet read = new PropertyGet( _helper.createVariableGet(variable, receiver.fileOffset), name) ..fileOffset = fileOffset; PropertySet write = _helper.forest.createPropertySet(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), name, value, forEffect: voidContext); return new IfNullPropertySet(variable, read, write, forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, new PropertyGet( _helper.createVariableGet(variable, receiver.fileOffset), name) ..fileOffset = fileOffset, binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); PropertySet write = _helper.forest.createPropertySet(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), name, binary, forEffect: voidContext); return new CompoundPropertySet(variable, write)..fileOffset = offset; } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); VariableDeclaration read = _helper.forest.createVariableDeclarationForValue( new PropertyGet( _helper.createVariableGet(variable, receiver.fileOffset), name) ..fileOffset = fileOffset); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue(_helper.forest.createPropertySet( fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), name, binary, forEffect: true)); return new PropertyPostIncDec(variable, read, write)..fileOffset = offset; } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } /// Creates a [Generator] for the access of property [name] on [receiver]. static Generator make( ExpressionGeneratorHelper helper, Token token, Expression receiver, Name name, // TODO(johnniwinther): Remove [getter] and [setter]? These are never // passed. Member getter, Member setter, bool isNullAware) { if (helper.forest.isThisExpression(receiver)) { getter ??= helper.lookupInstanceMember(name); setter ??= helper.lookupInstanceMember(name, isSetter: true); return new ThisPropertyAccessGenerator( helper, token, name, getter, setter); } else { return isNullAware ? new NullAwarePropertyAccessGenerator( helper, token, receiver, name, getter, setter, null) : new PropertyAccessGenerator( helper, token, receiver, name, getter, setter); } } } /// A [ThisPropertyAccessGenerator] represents a subexpression whose prefix is /// an implicit or explicit access on `this`. /// /// For instance /// /// class C { /// var b; /// method() { /// b; // a ThisPropertyAccessGenerator is created for `b`. /// b(); // a ThisPropertyAccessGenerator is created for `b`. /// b = c; // a ThisPropertyAccessGenerator is created for `b`. /// b += c; // a ThisPropertyAccessGenerator is created for `b`. /// this.b; // a ThisPropertyAccessGenerator is created for `this.b`. /// this.b(); // a ThisPropertyAccessGenerator is created for `this.b`. /// this.b = c; // a ThisPropertyAccessGenerator is created for `this.b`. /// this.b += c; // a ThisPropertyAccessGenerator is created for `this.b`. /// } /// } /// /// This is a special case of [PropertyAccessGenerator] to avoid creating an /// indirect access to 'this' in for instance `this.b += c` which by /// [PropertyAccessGenerator] would have been created as /// /// let #1 = this in #.b = #.b + c /// /// instead of /// /// this.b = this.b + c /// class ThisPropertyAccessGenerator extends Generator { /// The name for the accessed property. `b` in the examples in the class /// documentation. final Name name; /// The member accessed if this subexpression has a read. /// /// This is `null` if the `this` class does not have a readable property named /// [name]. final Member getter; /// The member accessed if this subexpression has a write. /// /// This is `null` if the `this` class does not have a writable property named /// [name]. final Member setter; ThisPropertyAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.name, this.getter, this.setter) : super(helper, token); @override String get _debugName => "ThisPropertyAccessGenerator"; @override String get _plainNameForRead => name.name; @override Expression buildSimpleRead() { return _createRead(); } Expression _createRead() { return new PropertyGet( _forest.createThisExpression(fileOffset), name, getter) ..fileOffset = fileOffset; } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _createWrite(fileOffset, value, forEffect: voidContext); } Expression _createWrite(int offset, Expression value, {bool forEffect}) { return _helper.forest.createPropertySet( fileOffset, _forest.createThisExpression(fileOffset), name, value, interfaceTarget: setter, forEffect: forEffect); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new IfNullSet( _createRead(), _createWrite(offset, value, forEffect: voidContext), forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { MethodInvocation binary = _helper.forest.createMethodInvocation( offset, new PropertyGet(_forest.createThisExpression(fileOffset), name) ..fileOffset = fileOffset, binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); return _createWrite(fileOffset, binary, forEffect: voidContext); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } VariableDeclaration read = _helper.forest.createVariableDeclarationForValue( new PropertyGet(_forest.createThisExpression(fileOffset), name) ..fileOffset = fileOffset); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue( _createWrite(fileOffset, binary, forEffect: true)); return new PropertyPostIncDec.onReadOnly(read, write)..fileOffset = offset; } @override Expression doInvocation(int offset, Arguments arguments) { Member interfaceTarget = getter; if (interfaceTarget is Field) { // TODO(ahe): In strong mode we should probably rewrite this to // `this.name.call(arguments)`. interfaceTarget = null; } return _helper.buildMethodInvocation( _forest.createThisExpression(fileOffset), name, arguments, offset, interfaceTarget: interfaceTarget); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", name: "); sink.write(name.name); sink.write(", getter: "); printQualifiedNameOn(getter, sink, syntheticNames: syntheticNames); sink.write(", setter: "); printQualifiedNameOn(setter, sink, syntheticNames: syntheticNames); } } class NullAwarePropertyAccessGenerator extends Generator { final VariableDeclaration receiver; final Expression receiverExpression; final Name name; final Member getter; final Member setter; final DartType type; NullAwarePropertyAccessGenerator( ExpressionGeneratorHelper helper, Token token, this.receiverExpression, this.name, this.getter, this.setter, this.type) : this.receiver = makeOrReuseVariable(receiverExpression), super(helper, token); @override String get _debugName => "NullAwarePropertyAccessGenerator"; Expression receiverAccess() => new VariableGet(receiver); @override String get _plainNameForRead => name.name; @override Expression buildSimpleRead() { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiverExpression); PropertyGet read = new PropertyGet( _helper.createVariableGet(variable, receiverExpression.fileOffset), name) ..fileOffset = fileOffset; return new NullAwarePropertyGet(variable, read) ..fileOffset = receiverExpression.fileOffset; } @override Expression buildAssignment(Expression value, {bool voidContext = false}) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiverExpression); PropertySet read = _helper.forest.createPropertySet( fileOffset, _helper.createVariableGet(variable, receiverExpression.fileOffset), name, value, forEffect: voidContext, readOnlyReceiver: true); return new NullAwarePropertySet(variable, read) ..fileOffset = receiverExpression.fileOffset; } Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new NullAwareIfNullSet(receiverExpression, name, value, forEffect: voidContext, readOffset: fileOffset, testOffset: offset, writeOffset: fileOffset) ..fileOffset = offset; } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return new NullAwareCompoundSet( receiverExpression, name, binaryOperator, value, readOffset: fileOffset, binaryOffset: offset, writeOffset: fileOffset, forEffect: voidContext, forPostIncDec: isPostIncDec); } Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return buildCompoundAssignment( binaryOperator, _forest.createIntLiteral(offset, 1), offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } @override Expression doInvocation(int offset, Arguments arguments) { return unsupported("doInvocation", offset, _uri); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", receiver: "); printNodeOn(receiver, sink, syntheticNames: syntheticNames); sink.write(", receiverExpression: "); printNodeOn(receiverExpression, sink, syntheticNames: syntheticNames); sink.write(", name: "); sink.write(name.name); sink.write(", getter: "); printQualifiedNameOn(getter, sink, syntheticNames: syntheticNames); sink.write(", setter: "); printQualifiedNameOn(setter, sink, syntheticNames: syntheticNames); sink.write(", type: "); printNodeOn(type, sink, syntheticNames: syntheticNames); } } class SuperPropertyAccessGenerator extends Generator { final Name name; final Member getter; final Member setter; SuperPropertyAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.name, this.getter, this.setter) : super(helper, token); @override String get _debugName => "SuperPropertyAccessGenerator"; @override String get _plainNameForRead => name.name; @override Expression buildSimpleRead() { return _createRead(); } Expression _createRead() { if (getter == null) { _helper.warnUnresolvedGet(name, fileOffset, isSuper: true); } return new SuperPropertyGet(name, getter)..fileOffset = fileOffset; } @override Expression buildAssignment(Expression value, {bool voidContext = false}) { return _createWrite(fileOffset, value); } Expression _createWrite(int offset, Expression value) { if (setter == null) { _helper.warnUnresolvedSet(name, offset, isSuper: true); } SuperPropertySet write = new SuperPropertySet(name, value, setter) ..fileOffset = offset; return write; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget, bool isPreIncDec = false, bool isPostIncDec = false}) { MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _createRead(), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); return _createWrite(fileOffset, binary); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } VariableDeclaration read = _helper.forest.createVariableDeclarationForValue(_createRead()); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue(_createWrite(fileOffset, binary)); return new StaticPostIncDec(read, write)..fileOffset = offset; } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new IfNullSet(_createRead(), _createWrite(fileOffset, value), forEffect: voidContext) ..fileOffset = offset; } @override Expression doInvocation(int offset, Arguments arguments) { if (_helper.constantContext != ConstantContext.none) { // TODO(brianwilkerson) Fix the length _helper.addProblem(messageNotAConstantExpression, offset, 1); } if (getter == null || isFieldOrGetter(getter)) { return _helper.buildMethodInvocation( buildSimpleRead(), callName, arguments, offset, // This isn't a constant expression, but we have checked if a // constant expression error should be emitted already. isConstantExpression: true, isImplicitCall: true); } else { // TODO(ahe): This could be something like "super.property(...)" where // property is a setter. return unhandled("${getter.runtimeType}", "doInvocation", offset, _uri); } } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", name: "); sink.write(name.name); sink.write(", getter: "); printQualifiedNameOn(getter, sink, syntheticNames: syntheticNames); sink.write(", setter: "); printQualifiedNameOn(setter, sink, syntheticNames: syntheticNames); } } class IndexedAccessGenerator extends Generator { final Expression receiver; final Expression index; final Procedure getter; final Procedure setter; IndexedAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.receiver, this.index, this.getter, this.setter) : super(helper, token); @override String get _plainNameForRead => "[]"; @override String get _debugName => "IndexedAccessGenerator"; @override Expression buildSimpleRead() { return _helper.buildMethodInvocation( receiver, indexGetName, _helper.forest.createArguments(fileOffset, <Expression>[index]), fileOffset, interfaceTarget: getter); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { if (voidContext) { return _helper.buildMethodInvocation( receiver, indexSetName, _helper.forest .createArguments(fileOffset, <Expression>[index, value]), fileOffset, interfaceTarget: setter); } else { return new IndexSet(receiver, index, value)..fileOffset = fileOffset; } } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new IfNullIndexSet(receiver, index, value, readOffset: fileOffset, testOffset: offset, writeOffset: fileOffset, forEffect: voidContext) ..fileOffset = offset; } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return new CompoundIndexSet(receiver, index, binaryOperator, value, readOffset: fileOffset, binaryOffset: offset, writeOffset: fileOffset, forEffect: voidContext, forPostIncDec: isPostIncDec); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } @override Expression doInvocation(int offset, Arguments arguments) { return _helper.buildMethodInvocation( buildSimpleRead(), callName, arguments, arguments.fileOffset, isImplicitCall: true); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", receiver: "); printNodeOn(receiver, sink, syntheticNames: syntheticNames); sink.write(", index: "); printNodeOn(index, sink, syntheticNames: syntheticNames); sink.write(", getter: "); printQualifiedNameOn(getter, sink, syntheticNames: syntheticNames); sink.write(", setter: "); printQualifiedNameOn(setter, sink, syntheticNames: syntheticNames); } static Generator make( ExpressionGeneratorHelper helper, Token token, Expression receiver, Expression index, Procedure getter, Procedure setter) { if (helper.forest.isThisExpression(receiver)) { return new ThisIndexedAccessGenerator( helper, token, index, getter, setter); } else { return new IndexedAccessGenerator( helper, token, receiver, index, getter, setter); } } } /// Special case of [IndexedAccessGenerator] to avoid creating an indirect /// access to 'this'. class ThisIndexedAccessGenerator extends Generator { final Expression index; final Procedure getter; final Procedure setter; ThisIndexedAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.index, this.getter, this.setter) : super(helper, token); @override String get _plainNameForRead => "[]"; @override String get _debugName => "ThisIndexedAccessGenerator"; @override Expression buildSimpleRead() { Expression receiver = _helper.forest.createThisExpression(fileOffset); return _helper.buildMethodInvocation( receiver, indexGetName, _helper.forest.createArguments(fileOffset, <Expression>[index]), fileOffset, interfaceTarget: getter); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { Expression receiver = _helper.forest.createThisExpression(fileOffset); if (voidContext) { return _helper.buildMethodInvocation( receiver, indexSetName, _helper.forest .createArguments(fileOffset, <Expression>[index, value]), fileOffset, interfaceTarget: setter); } else { return new IndexSet(receiver, index, value)..fileOffset = fileOffset; } } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { Expression receiver = _helper.forest.createThisExpression(fileOffset); return new IfNullIndexSet(receiver, index, value, readOffset: fileOffset, testOffset: offset, writeOffset: fileOffset, forEffect: voidContext, readOnlyReceiver: true) ..fileOffset = offset; } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { Expression receiver = _helper.forest.createThisExpression(fileOffset); return new CompoundIndexSet(receiver, index, binaryOperator, value, readOffset: fileOffset, binaryOffset: offset, writeOffset: fileOffset, forEffect: voidContext, forPostIncDec: isPostIncDec, readOnlyReceiver: true); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } @override Expression doInvocation(int offset, Arguments arguments) { return _helper.buildMethodInvocation( buildSimpleRead(), callName, arguments, offset, isImplicitCall: true); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", index: "); printNodeOn(index, sink, syntheticNames: syntheticNames); sink.write(", getter: "); printQualifiedNameOn(getter, sink, syntheticNames: syntheticNames); sink.write(", setter: "); printQualifiedNameOn(setter, sink, syntheticNames: syntheticNames); } } class SuperIndexedAccessGenerator extends Generator { final Expression index; final Member getter; final Member setter; SuperIndexedAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.index, this.getter, this.setter) : super(helper, token); String get _plainNameForRead => "[]"; String get _debugName => "SuperIndexedAccessGenerator"; @override Expression buildSimpleRead() { if (getter == null) { _helper.warnUnresolvedMethod(indexGetName, fileOffset, isSuper: true); } return _helper.forest.createSuperMethodInvocation( fileOffset, indexGetName, getter, _helper.forest.createArguments(fileOffset, <Expression>[index])); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { if (voidContext) { if (setter == null) { _helper.warnUnresolvedMethod(indexSetName, fileOffset, isSuper: true); } return _helper.forest.createSuperMethodInvocation( fileOffset, indexSetName, setter, _helper.forest .createArguments(fileOffset, <Expression>[index, value])); } else { return new SuperIndexSet(setter, index, value)..fileOffset = fileOffset; } } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new IfNullSuperIndexSet(getter, setter, index, value, readOffset: fileOffset, testOffset: offset, writeOffset: fileOffset, forEffect: voidContext) ..fileOffset = offset; } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return new CompoundSuperIndexSet( getter, setter, index, binaryOperator, value, readOffset: fileOffset, binaryOffset: offset, writeOffset: fileOffset, forEffect: voidContext, forPostIncDec: isPostIncDec); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } @override Expression doInvocation(int offset, Arguments arguments) { return _helper.buildMethodInvocation( buildSimpleRead(), callName, arguments, offset, isImplicitCall: true); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", index: "); printNodeOn(index, sink, syntheticNames: syntheticNames); sink.write(", getter: "); printQualifiedNameOn(getter, sink, syntheticNames: syntheticNames); sink.write(", setter: "); printQualifiedNameOn(setter, sink, syntheticNames: syntheticNames); } } /// A [StaticAccessGenerator] represents a subexpression whose prefix is /// a static or top-level member, including static extension members. /// /// For instance /// /// get property => 0; /// set property(_) {} /// var field; /// method() {} /// /// main() { /// property; // a StaticAccessGenerator is created for `property`. /// property = 0; // a StaticAccessGenerator is created for `property`. /// field = 0; // a StaticAccessGenerator is created for `field`. /// method; // a StaticAccessGenerator is created for `method`. /// method(); // a StaticAccessGenerator is created for `method`. /// } /// /// class A {} /// extension B on A { /// static get property => 0; /// static set property(_) {} /// static var field; /// static method() { /// property; // this StaticAccessGenerator is created for `property`. /// property = 0; // this StaticAccessGenerator is created for `property`. /// field = 0; // this StaticAccessGenerator is created for `field`. /// method; // this StaticAccessGenerator is created for `method`. /// method(); // this StaticAccessGenerator is created for `method`. /// } /// } /// class StaticAccessGenerator extends Generator { /// The name of the original target; final String targetName; /// The static [Member] used for performing a read or invocation on this /// subexpression. /// /// This can be `null` if the subexpression doesn't have a readable target. /// For instance if the subexpression is a setter without a corresponding /// getter. final Member readTarget; /// The static [Member] used for performing a write on this subexpression. /// /// This can be `null` if the subexpression doesn't have a writable target. /// For instance if the subexpression is a final field, a method, or a getter /// without a corresponding setter. final Member writeTarget; StaticAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.targetName, this.readTarget, this.writeTarget) : assert(targetName != null), assert(readTarget != null || writeTarget != null), super(helper, token); factory StaticAccessGenerator.fromBuilder( ExpressionGeneratorHelper helper, String targetName, Builder declaration, Token token, Builder builderSetter) { if (declaration is AccessErrorBuilder) { AccessErrorBuilder error = declaration; declaration = error.builder; // We should only see an access error here if we've looked up a setter // when not explicitly looking for a setter. assert(declaration.isSetter); } else if (declaration.target == null) { return unhandled( "${declaration.runtimeType}", "StaticAccessGenerator.fromBuilder", offsetForToken(token), helper.uri); } Member getter = declaration.target.hasGetter ? declaration.target : null; Member setter = declaration.target.hasSetter ? declaration.target : null; if (setter == null) { if (builderSetter?.target?.hasSetter ?? false) { setter = builderSetter.target; } } return new StaticAccessGenerator(helper, token, targetName, getter, setter); } @override String get _debugName => "StaticAccessGenerator"; @override String get _plainNameForRead => targetName; @override Expression buildSimpleRead() { return _createRead(); } Expression _createRead() { Expression read; if (readTarget == null) { read = _makeInvalidRead(); } else { read = _helper.makeStaticGet(readTarget, token); } return read; } @override Expression buildAssignment(Expression value, {bool voidContext = false}) { return _createWrite(fileOffset, value); } Expression _createWrite(int offset, Expression value) { Expression write; if (writeTarget == null) { write = _makeInvalidWrite(value); } else { write = new StaticSet(writeTarget, value)..fileOffset = offset; } return write; } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new IfNullSet(_createRead(), _createWrite(offset, value), forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget, bool isPreIncDec = false, bool isPostIncDec = false}) { MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _createRead(), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); return _createWrite(fileOffset, binary); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } VariableDeclaration read = _helper.forest.createVariableDeclarationForValue(_createRead()); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue(_createWrite(offset, binary)); return new StaticPostIncDec(read, write)..fileOffset = offset; } @override Expression doInvocation(int offset, Arguments arguments) { if (_helper.constantContext != ConstantContext.none && !_helper.isIdentical(readTarget)) { return _helper.buildProblem( templateNotConstantExpression.withArguments('Method invocation'), offset, readTarget?.name?.name?.length ?? 0); } if (readTarget == null || isFieldOrGetter(readTarget)) { return _helper.buildMethodInvocation(buildSimpleRead(), callName, arguments, offset + (readTarget?.name?.name?.length ?? 0), // This isn't a constant expression, but we have checked if a // constant expression error should be emitted already. isConstantExpression: true, isImplicitCall: true); } else { return _helper.buildStaticInvocation(readTarget, arguments, charOffset: offset); } } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", targetName: "); sink.write(targetName); sink.write(", readTarget: "); printQualifiedNameOn(readTarget, sink, syntheticNames: syntheticNames); sink.write(", writeTarget: "); printQualifiedNameOn(writeTarget, sink, syntheticNames: syntheticNames); } } /// An [ExtensionInstanceAccessGenerator] represents a subexpression whose /// prefix is an extension instance member. /// /// For instance /// /// class A {} /// extension B on A { /// get property => 0; /// set property(_) {} /// method() { /// property; // this generator is created for `property`. /// property = 0; // this generator is created for `property`. /// method; // this generator is created for `method`. /// method(); // this generator is created for `method`. /// } /// } /// /// These can only occur within an extension instance member. class ExtensionInstanceAccessGenerator extends Generator { final Extension extension; /// The original name of the target. final String targetName; /// The static [Member] generated for an instance extension member which is /// used for performing a read on this subexpression. /// /// This can be `null` if the subexpression doesn't have a readable target. /// For instance if the subexpression is a setter without a corresponding /// getter. final Procedure readTarget; /// The static [Member] generated for an instance extension member which is /// used for performing an invocation on this subexpression. /// /// This can be `null` if the subexpression doesn't have an invokable target. /// For instance if the subexpression is a getter or setter. final Procedure invokeTarget; /// The static [Member] generated for an instance extension member which is /// used for performing a write on this subexpression. /// /// This can be `null` if the subexpression doesn't have a writable target. /// For instance if the subexpression is a final field, a method, or a getter /// without a corresponding setter. final Procedure writeTarget; /// The parameter holding the value for `this` within the current extension /// instance method. // TODO(johnniwinther): Handle static access to extension instance members, // in which case the access is erroneous and [extensionThis] is `null`. final VariableDeclaration extensionThis; /// The type parameters synthetically added to the current extension /// instance method. final List<TypeParameter> extensionTypeParameters; ExtensionInstanceAccessGenerator( ExpressionGeneratorHelper helper, Token token, this.extension, this.targetName, this.readTarget, this.invokeTarget, this.writeTarget, this.extensionThis, this.extensionTypeParameters) : assert(targetName != null), assert(readTarget != null || writeTarget != null), assert(extensionThis != null), super(helper, token); factory ExtensionInstanceAccessGenerator.fromBuilder( ExpressionGeneratorHelper helper, Extension extension, String targetName, VariableDeclaration extensionThis, List<TypeParameter> extensionTypeParameters, Builder declaration, Token token, Builder builderSetter) { if (declaration is AccessErrorBuilder) { AccessErrorBuilder error = declaration; declaration = error.builder; // We should only see an access error here if we've looked up a setter // when not explicitly looking for a setter. assert(declaration.isSetter); } else if (declaration.target == null) { return unhandled( "${declaration.runtimeType}", "InstanceExtensionAccessGenerator.fromBuilder", offsetForToken(token), helper.uri); } Procedure readTarget; Procedure invokeTarget; if (declaration.isGetter) { readTarget = declaration.target; } else if (declaration.isRegularMethod) { MemberBuilder procedureBuilder = declaration; readTarget = procedureBuilder.extensionTearOff; invokeTarget = procedureBuilder.procedure; } Procedure writeTarget; if (builderSetter != null && builderSetter.isSetter) { writeTarget = builderSetter.target; } return new ExtensionInstanceAccessGenerator( helper, token, extension, targetName, readTarget, invokeTarget, writeTarget, extensionThis, extensionTypeParameters); } @override String get _debugName => "InstanceExtensionAccessGenerator"; @override String get _plainNameForRead => targetName; int get _extensionTypeParameterCount => extensionTypeParameters?.length ?? 0; List<DartType> _createExtensionTypeArguments() { List<DartType> extensionTypeArguments = const <DartType>[]; if (extensionTypeParameters != null) { extensionTypeArguments = []; for (TypeParameter typeParameter in extensionTypeParameters) { extensionTypeArguments .add(_forest.createTypeParameterType(typeParameter)); } } return extensionTypeArguments; } @override Expression buildSimpleRead() { return _createRead(); } Expression _createRead() { Expression read; if (readTarget == null) { read = _makeInvalidRead(); } else { read = _helper.buildExtensionMethodInvocation( fileOffset, readTarget, _helper.forest.createArgumentsForExtensionMethod( fileOffset, _extensionTypeParameterCount, 0, _helper.createVariableGet(extensionThis, fileOffset), extensionTypeArguments: _createExtensionTypeArguments()), isTearOff: invokeTarget != null); } return read; } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _createWrite(fileOffset, value, forEffect: voidContext); } Expression _createWrite(int offset, Expression value, {bool forEffect}) { Expression write; if (writeTarget == null) { write = _makeInvalidWrite(value); } else { write = new ExtensionSet( extension, _createExtensionTypeArguments(), _helper.createVariableGet(extensionThis, fileOffset), writeTarget, value, forEffect: forEffect, readOnlyReceiver: true); } write.fileOffset = offset; return write; } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new IfNullSet( _createRead(), _createWrite(fileOffset, value, forEffect: voidContext), forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _createRead(), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); return _createWrite(fileOffset, binary, forEffect: voidContext); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } VariableDeclaration read = _helper.forest.createVariableDeclarationForValue(_createRead()); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue( _createWrite(fileOffset, binary, forEffect: true)); return new PropertyPostIncDec.onReadOnly(read, write)..fileOffset = offset; } @override Expression doInvocation(int offset, Arguments arguments) { if (invokeTarget != null) { return _helper.buildExtensionMethodInvocation( offset, invokeTarget, _forest.createArgumentsForExtensionMethod( fileOffset, _extensionTypeParameterCount, invokeTarget.function.typeParameters.length - _extensionTypeParameterCount, _helper.createVariableGet(extensionThis, offset), extensionTypeArguments: _createExtensionTypeArguments(), typeArguments: arguments.types, positionalArguments: arguments.positional, namedArguments: arguments.named), isTearOff: false); } else { return _helper.buildMethodInvocation(buildSimpleRead(), callName, arguments, adjustForImplicitCall(_plainNameForRead, offset), isImplicitCall: true); } } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", targetName: "); sink.write(targetName); sink.write(", readTarget: "); printQualifiedNameOn(readTarget, sink, syntheticNames: syntheticNames); sink.write(", writeTarget: "); printQualifiedNameOn(writeTarget, sink, syntheticNames: syntheticNames); } } /// A [ExplicitExtensionInstanceAccessGenerator] represents a subexpression /// whose prefix is a forced extension instance member access. /// /// For instance /// /// class A<T> {} /// extension B on A<int> { /// method() {} /// } /// extension C<T> { /// T get field => 0; /// set field(T _) {} /// } /// /// method(A a) { /// B(a).method; // this generator is created for `B(a).method`. /// B(a).method(); // this generator is created for `B(a).method`. /// C<int>(a).field; // this generator is created for `C<int>(a).field`. /// C(a).field = 0; // this generator is created for `C(a).field`. /// } /// class ExplicitExtensionInstanceAccessGenerator extends Generator { final Extension extension; /// The name of the original target; final String targetName; /// The static [Member] generated for an instance extension member which is /// used for performing a read on this subexpression. /// /// This can be `null` if the subexpression doesn't have a readable target. /// For instance if the subexpression is a setter without a corresponding /// getter. final Procedure readTarget; /// The static [Member] generated for an instance extension member which is /// used for performing an invocation on this subexpression. /// /// This can be `null` if the subexpression doesn't have an invokable target. /// For instance if the subexpression is a getter or setter. final Procedure invokeTarget; /// The static [Member] generated for an instance extension member which is /// used for performing a write on this subexpression. /// /// This can be `null` if the subexpression doesn't have a writable target. /// For instance if the subexpression is a final field, a method, or a getter /// without a corresponding setter. final Procedure writeTarget; /// The expression holding the receiver value for the explicit extension /// access, that is, `a` in `Extension<int>(a).method<String>()`. final Expression receiver; /// The type arguments explicitly passed to the explicit extension access, /// like `<int>` in `Extension<int>(a).method<String>()`. final List<DartType> explicitTypeArguments; /// The number of type parameters declared on the extension declaration. final int extensionTypeParameterCount; /// If `true` the access is null-aware, like `Extension(c)?.foo`. final bool isNullAware; ExplicitExtensionInstanceAccessGenerator( ExpressionGeneratorHelper helper, Token token, this.extension, this.targetName, this.readTarget, this.invokeTarget, this.writeTarget, this.receiver, this.explicitTypeArguments, this.extensionTypeParameterCount, {this.isNullAware}) : assert(targetName != null), assert(readTarget != null || writeTarget != null), assert(receiver != null), assert(isNullAware != null), super(helper, token); factory ExplicitExtensionInstanceAccessGenerator.fromBuilder( ExpressionGeneratorHelper helper, Token token, Extension extension, Builder getterBuilder, Builder setterBuilder, Expression receiver, List<DartType> explicitTypeArguments, int extensionTypeParameterCount, {bool isNullAware}) { assert(getterBuilder != null || setterBuilder != null); String targetName; Procedure readTarget; Procedure invokeTarget; if (getterBuilder != null) { assert(!getterBuilder.isStatic); if (getterBuilder is AccessErrorBuilder) { AccessErrorBuilder error = getterBuilder; getterBuilder = error.builder; // We should only see an access error here if we've looked up a setter // when not explicitly looking for a setter. assert(getterBuilder.isSetter); } else if (getterBuilder.isGetter) { MemberBuilder memberBuilder = getterBuilder; readTarget = memberBuilder.member; targetName = memberBuilder.name; } else if (getterBuilder.isRegularMethod) { MemberBuilder procedureBuilder = getterBuilder; readTarget = procedureBuilder.extensionTearOff; invokeTarget = procedureBuilder.procedure; targetName = procedureBuilder.name; } else { return unhandled( "${getterBuilder.runtimeType}", "InstanceExtensionAccessGenerator.fromBuilder", offsetForToken(token), helper.uri); } } Procedure writeTarget; if (setterBuilder != null) { assert(!setterBuilder.isStatic); if (setterBuilder is AccessErrorBuilder) { targetName ??= setterBuilder.name; } else if (setterBuilder.isSetter) { MemberBuilder memberBuilder = setterBuilder; writeTarget = memberBuilder.member; targetName ??= memberBuilder.name; } else { return unhandled( "${setterBuilder.runtimeType}", "InstanceExtensionAccessGenerator.fromBuilder", offsetForToken(token), helper.uri); } } return new ExplicitExtensionInstanceAccessGenerator( helper, token, extension, targetName, readTarget, invokeTarget, writeTarget, receiver, explicitTypeArguments, extensionTypeParameterCount, isNullAware: isNullAware); } @override String get _debugName => "ExplicitExtensionIndexedAccessGenerator"; @override String get _plainNameForRead => targetName; List<DartType> _createExtensionTypeArguments() { return explicitTypeArguments ?? const <DartType>[]; } /// Returns `true` if performing a read operation is a tear off. /// /// This is the case if [invokeTarget] is non-null, since extension methods /// have both a [readTarget] and an [invokeTarget], whereas extension getters /// only have a [readTarget]. bool get isReadTearOff => invokeTarget != null; @override Expression buildSimpleRead() { if (isNullAware) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); return new NullAwareExtension(variable, _createRead(_helper.createVariableGet(variable, variable.fileOffset))) ..fileOffset = fileOffset; } else { return _createRead(receiver); } } Expression _createRead(Expression receiver) { Expression read; if (readTarget == null) { read = _makeInvalidRead(); } else { read = _helper.buildExtensionMethodInvocation( fileOffset, readTarget, _helper.forest.createArgumentsForExtensionMethod( fileOffset, extensionTypeParameterCount, 0, receiver, extensionTypeArguments: _createExtensionTypeArguments()), isTearOff: isReadTearOff); } return read; } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { if (isNullAware) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); return new NullAwareExtension( variable, _createWrite(fileOffset, _helper.createVariableGet(variable, variable.fileOffset), value, forEffect: voidContext, readOnlyReceiver: true)) ..fileOffset = fileOffset; } else { return _createWrite(fileOffset, receiver, value, forEffect: voidContext, readOnlyReceiver: false); } } Expression _createWrite(int offset, Expression receiver, Expression value, {bool readOnlyReceiver, bool forEffect}) { Expression write; if (writeTarget == null) { write = _makeInvalidWrite(value); } else { write = new ExtensionSet( extension, explicitTypeArguments, receiver, writeTarget, value, readOnlyReceiver: readOnlyReceiver, forEffect: forEffect); } write.fileOffset = offset; return write; } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { if (isNullAware) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); Expression read = _createRead(_helper.createVariableGet(variable, receiver.fileOffset)); Expression write = _createWrite(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), value, forEffect: voidContext, readOnlyReceiver: true); return new NullAwareExtension( variable, new IfNullSet(read, write, forEffect: voidContext) ..fileOffset = offset) ..fileOffset = fileOffset; } else { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); Expression read = _createRead(_helper.createVariableGet(variable, receiver.fileOffset)); Expression write = _createWrite(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), value, forEffect: voidContext, readOnlyReceiver: true); return new IfNullPropertySet(variable, read, write, forEffect: voidContext) ..fileOffset = offset; } } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { if (isNullAware) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _createRead(_helper.createVariableGet(variable, receiver.fileOffset)), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); Expression write = _createWrite(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), binary, forEffect: voidContext, readOnlyReceiver: true); return new NullAwareExtension(variable, write)..fileOffset = offset; } else { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _createRead(_helper.createVariableGet(variable, receiver.fileOffset)), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); Expression write = _createWrite(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), binary, forEffect: voidContext, readOnlyReceiver: true); return new CompoundPropertySet(variable, write)..fileOffset = offset; } } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } else if (isNullAware) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); VariableDeclaration read = _helper.forest .createVariableDeclarationForValue(_createRead( _helper.createVariableGet(variable, receiver.fileOffset))); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue(_createWrite(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), binary, forEffect: voidContext, readOnlyReceiver: true) ..fileOffset = fileOffset); return new NullAwareExtension( variable, new LocalPostIncDec(read, write)..fileOffset = offset) ..fileOffset = fileOffset; } else { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); VariableDeclaration read = _helper.forest .createVariableDeclarationForValue(_createRead( _helper.createVariableGet(variable, receiver.fileOffset))); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue(_createWrite(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), binary, forEffect: voidContext, readOnlyReceiver: true) ..fileOffset = fileOffset); return new PropertyPostIncDec(variable, read, write)..fileOffset = offset; } } @override Expression doInvocation(int offset, Arguments arguments) { VariableDeclaration receiverVariable; Expression receiverExpression = receiver; if (isNullAware) { receiverVariable = _helper.forest.createVariableDeclarationForValue(receiver); receiverExpression = _helper.createVariableGet( receiverVariable, receiverVariable.fileOffset); } Expression invocation; if (invokeTarget != null) { invocation = _helper.buildExtensionMethodInvocation( fileOffset, invokeTarget, _forest.createArgumentsForExtensionMethod( fileOffset, extensionTypeParameterCount, invokeTarget.function.typeParameters.length - extensionTypeParameterCount, receiverExpression, extensionTypeArguments: _createExtensionTypeArguments(), typeArguments: arguments.types, positionalArguments: arguments.positional, namedArguments: arguments.named), isTearOff: false); } else { invocation = _helper.buildMethodInvocation( _createRead(receiverExpression), callName, arguments, adjustForImplicitCall(_plainNameForRead, offset), isImplicitCall: true); } if (isNullAware) { assert(receiverVariable != null); return new NullAwareExtension(receiverVariable, invocation) ..fileOffset = fileOffset; } else { return invocation; } } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", targetName: "); sink.write(targetName); sink.write(", readTarget: "); printQualifiedNameOn(readTarget, sink, syntheticNames: syntheticNames); sink.write(", writeTarget: "); printQualifiedNameOn(writeTarget, sink, syntheticNames: syntheticNames); } } class ExplicitExtensionIndexedAccessGenerator extends Generator { final Extension extension; /// The static [Member] generated for the [] operation. /// /// This can be `null` if the extension doesn't have an [] method. final Procedure readTarget; /// The static [Member] generated for the []= operation. /// /// This can be `null` if the extension doesn't have an []= method. final Procedure writeTarget; /// The expression holding the receiver value for the explicit extension /// access, that is, `a` in `Extension<int>(a)[index]`. final Expression receiver; /// The index expression; final Expression index; /// The type arguments explicitly passed to the explicit extension access, /// like `<int>` in `Extension<int>(a)[b]`. final List<DartType> explicitTypeArguments; /// The number of type parameters declared on the extension declaration. final int extensionTypeParameterCount; ExplicitExtensionIndexedAccessGenerator( ExpressionGeneratorHelper helper, Token token, this.extension, this.readTarget, this.writeTarget, this.receiver, this.index, this.explicitTypeArguments, this.extensionTypeParameterCount) : assert(readTarget != null || writeTarget != null), assert(receiver != null), super(helper, token); factory ExplicitExtensionIndexedAccessGenerator.fromBuilder( ExpressionGeneratorHelper helper, Token token, Extension extension, Builder getterBuilder, Builder setterBuilder, Expression receiver, Expression index, List<DartType> explicitTypeArguments, int extensionTypeParameterCount) { Procedure readTarget; if (getterBuilder != null) { if (getterBuilder is AccessErrorBuilder) { AccessErrorBuilder error = getterBuilder; getterBuilder = error.builder; // We should only see an access error here if we've looked up a setter // when not explicitly looking for a setter. assert(getterBuilder is MemberBuilder); } else if (getterBuilder is MemberBuilder) { MemberBuilder procedureBuilder = getterBuilder; readTarget = procedureBuilder.member; } else { return unhandled( "${getterBuilder.runtimeType}", "InstanceExtensionAccessGenerator.fromBuilder", offsetForToken(token), helper.uri); } } Procedure writeTarget; if (setterBuilder is MemberBuilder) { MemberBuilder memberBuilder = setterBuilder; writeTarget = memberBuilder.member; } return new ExplicitExtensionIndexedAccessGenerator( helper, token, extension, readTarget, writeTarget, receiver, index, explicitTypeArguments, extensionTypeParameterCount); } List<DartType> _createExtensionTypeArguments() { return explicitTypeArguments ?? const <DartType>[]; } String get _plainNameForRead => "[]"; String get _debugName => "ExplicitExtensionIndexedAccessGenerator"; @override Expression buildSimpleRead() { if (readTarget == null) { return _makeInvalidRead(); } return _helper.buildExtensionMethodInvocation( fileOffset, readTarget, _forest.createArgumentsForExtensionMethod( fileOffset, extensionTypeParameterCount, 0, receiver, extensionTypeArguments: _createExtensionTypeArguments(), positionalArguments: <Expression>[index]), isTearOff: false); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { if (writeTarget == null) { return _makeInvalidWrite(value); } if (voidContext) { return _helper.buildExtensionMethodInvocation( fileOffset, writeTarget, _forest.createArgumentsForExtensionMethod( fileOffset, extensionTypeParameterCount, 0, receiver, extensionTypeArguments: _createExtensionTypeArguments(), positionalArguments: <Expression>[index, value]), isTearOff: false); } else { return new ExtensionIndexSet( extension, explicitTypeArguments, receiver, writeTarget, index, value) ..fileOffset = fileOffset; } } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return new IfNullExtensionIndexSet(extension, explicitTypeArguments, receiver, readTarget, writeTarget, index, value, readOffset: fileOffset, testOffset: offset, writeOffset: fileOffset, forEffect: voidContext) ..fileOffset = offset; } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return new CompoundExtensionIndexSet(extension, explicitTypeArguments, receiver, readTarget, writeTarget, index, binaryOperator, value, readOffset: fileOffset, binaryOffset: offset, writeOffset: fileOffset, forEffect: voidContext, forPostIncDec: isPostIncDec); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } @override Expression doInvocation(int offset, Arguments arguments) { return _helper.buildMethodInvocation( buildSimpleRead(), callName, arguments, offset, isImplicitCall: true); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", index: "); printNodeOn(index, sink, syntheticNames: syntheticNames); sink.write(", readTarget: "); printQualifiedNameOn(readTarget, sink, syntheticNames: syntheticNames); sink.write(", writeTarget: "); printQualifiedNameOn(writeTarget, sink, syntheticNames: syntheticNames); } } /// A [ExplicitExtensionAccessGenerator] represents a subexpression whose /// prefix is an explicit extension application. /// /// For instance /// /// class A<T> {} /// extension B on A<int> { /// method() {} /// } /// extension C<T> on A<T> { /// T get field => 0; /// set field(T _) {} /// } /// /// method(A a) { /// B(a).method; // this generator is created for `B(a)`. /// B(a).method(); // this generator is created for `B(a)`. /// C<int>(a).field; // this generator is created for `C<int>(a)`. /// C(a).field = 0; // this generator is created for `C(a)`. /// } /// /// When an access is performed on this generator a /// [ExplicitExtensionInstanceAccessGenerator] is created. class ExplicitExtensionAccessGenerator extends Generator { final ExtensionBuilder extensionBuilder; final Expression receiver; final List<DartType> explicitTypeArguments; ExplicitExtensionAccessGenerator( ExpressionGeneratorHelper helper, Token token, this.extensionBuilder, this.receiver, this.explicitTypeArguments) : super(helper, token); @override String get _plainNameForRead { return unsupported( "ExplicitExtensionAccessGenerator.plainNameForRead", fileOffset, _uri); } @override String get _debugName => "ExplicitExtensionAccessGenerator"; @override Expression buildSimpleRead() { return _makeInvalidRead(); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _makeInvalidWrite(value); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return _makeInvalidRead(); } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return _makeInvalidRead(); } Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return _makeInvalidRead(); } Generator _createInstanceAccess(Token token, Name name, {bool isNullAware}) { Builder getter = extensionBuilder.lookupLocalMember(name.name); if (getter != null && getter.isStatic) { getter = null; } Builder setter = extensionBuilder.lookupLocalMember(name.name, setter: true); if (setter != null && setter.isStatic) { setter = null; } if (getter == null && setter == null) { return new UnresolvedNameGenerator(_helper, token, name); } return new ExplicitExtensionInstanceAccessGenerator.fromBuilder( _helper, token, extensionBuilder.extension, getter, setter, receiver, explicitTypeArguments, extensionBuilder.typeParameters?.length ?? 0, isNullAware: isNullAware); } /* Expression | Generator */ buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { if (_helper.constantContext != ConstantContext.none) { _helper.addProblem( messageNotAConstantExpression, fileOffset, token.length); } Generator generator = _createInstanceAccess(send.token, send.name, isNullAware: isNullAware); if (send.arguments != null) { return generator.doInvocation(offsetForToken(send.token), send.arguments); } else { return generator; } } @override doInvocation(int offset, Arguments arguments) { Generator generator = _createInstanceAccess(token, callName, isNullAware: false); return generator.doInvocation(offset, arguments); } @override Expression _makeInvalidRead() { return _helper.buildProblem(messageExplicitExtensionAsExpression, fileOffset, lengthForToken(token)); } @override Expression _makeInvalidWrite(Expression value) { return _helper.buildProblem( messageExplicitExtensionAsLvalue, fileOffset, lengthForToken(token)); } @override Generator buildIndexedAccess(Expression index, Token token) { Builder getter = extensionBuilder.lookupLocalMember(indexGetName.name); Builder setter = extensionBuilder.lookupLocalMember(indexSetName.name); if (getter == null && setter == null) { return new UnresolvedNameGenerator(_helper, token, indexGetName); } return new ExplicitExtensionIndexedAccessGenerator.fromBuilder( _helper, token, extensionBuilder.extension, getter, setter, receiver, index, explicitTypeArguments, extensionBuilder.typeParameters?.length ?? 0); } @override void printOn(StringSink sink) { sink.write(", extensionBuilder: "); sink.write(extensionBuilder); sink.write(", receiver: "); sink.write(receiver); } } class LoadLibraryGenerator extends Generator { final LoadLibraryBuilder builder; LoadLibraryGenerator( ExpressionGeneratorHelper helper, Token token, this.builder) : super(helper, token); @override String get _plainNameForRead => 'loadLibrary'; @override String get _debugName => "LoadLibraryGenerator"; @override Expression buildSimpleRead() { builder.importDependency.targetLibrary; LoadLibraryTearOff read = new LoadLibraryTearOff( builder.importDependency, builder.createTearoffMethod(_helper.forest)) ..fileOffset = fileOffset; return read; } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _makeInvalidWrite(value); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { Expression read = buildSimpleRead(); Expression write = _makeInvalidWrite(value); return new IfNullSet(read, write, forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { MethodInvocation binary = _helper.forest.createMethodInvocation( offset, buildSimpleRead(), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); return _makeInvalidWrite(binary); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } @override Expression doInvocation(int offset, Arguments arguments) { if (_forest.argumentsPositional(arguments).length > 0 || _forest.argumentsNamed(arguments).length > 0) { _helper.addProblemErrorIfConst( messageLoadLibraryTakesNoArguments, offset, 'loadLibrary'.length); } return builder.createLoadLibrary(offset, _forest, arguments); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { sink.write(", builder: "); sink.write(builder); } } class DeferredAccessGenerator extends Generator { final PrefixUseGenerator prefixGenerator; final Generator suffixGenerator; DeferredAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.prefixGenerator, this.suffixGenerator) : super(helper, token); @override Expression buildSimpleRead() { return _helper.wrapInDeferredCheck(suffixGenerator.buildSimpleRead(), prefixGenerator.prefix, token.charOffset); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _helper.wrapInDeferredCheck( suffixGenerator.buildAssignment(value, voidContext: voidContext), prefixGenerator.prefix, token.charOffset); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return _helper.wrapInDeferredCheck( suffixGenerator.buildIfNullAssignment(value, type, offset, voidContext: voidContext), prefixGenerator.prefix, token.charOffset); } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return _helper.wrapInDeferredCheck( suffixGenerator.buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPreIncDec: isPreIncDec, isPostIncDec: isPostIncDec), prefixGenerator.prefix, token.charOffset); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return _helper.wrapInDeferredCheck( suffixGenerator.buildPostfixIncrement(binaryOperator, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget), prefixGenerator.prefix, token.charOffset); } @override buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { Object propertyAccess = suffixGenerator.buildPropertyAccess(send, operatorOffset, isNullAware); if (propertyAccess is Generator) { return new DeferredAccessGenerator( _helper, token, prefixGenerator, propertyAccess); } else { Expression expression = propertyAccess; return _helper.wrapInDeferredCheck( expression, prefixGenerator.prefix, token.charOffset); } } @override String get _plainNameForRead { return unsupported("deferredAccessor.plainNameForRead", fileOffset, _uri); } @override String get _debugName => "DeferredAccessGenerator"; @override TypeBuilder buildTypeWithResolvedArguments( NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) { String name = "${prefixGenerator._plainNameForRead}." "${suffixGenerator._plainNameForRead}"; TypeBuilder type = suffixGenerator.buildTypeWithResolvedArguments( nullabilityBuilder, arguments); LocatedMessage message; if (type is NamedTypeBuilder && type.declaration is InvalidTypeBuilder) { InvalidTypeBuilder declaration = type.declaration; message = declaration.message; } else { int charOffset = offsetForToken(prefixGenerator.token); message = templateDeferredTypeAnnotation .withArguments( _helper.buildDartType(new UnresolvedType(type, charOffset, _uri)), prefixGenerator._plainNameForRead) .withLocation( _uri, charOffset, lengthOfSpan(prefixGenerator.token, token)); } NamedTypeBuilder result = new NamedTypeBuilder(name, nullabilityBuilder, null); _helper.libraryBuilder.addProblem( message.messageObject, message.charOffset, message.length, message.uri); result.bind(result.buildInvalidType(message)); return result; } @override Expression doInvocation(int offset, Arguments arguments) { return _helper.wrapInDeferredCheck( suffixGenerator.doInvocation(offset, arguments), prefixGenerator.prefix, token.charOffset); } @override Expression invokeConstructor( List<UnresolvedType> typeArguments, String name, Arguments arguments, Token nameToken, Token nameLastToken, Constness constness) { return _helper.wrapInDeferredCheck( suffixGenerator.invokeConstructor(typeArguments, name, arguments, nameToken, nameLastToken, constness), prefixGenerator.prefix, offsetForToken(suffixGenerator.token)); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { sink.write(", prefixGenerator: "); sink.write(prefixGenerator); sink.write(", suffixGenerator: "); sink.write(suffixGenerator); } } /// [TypeUseGenerator] represents the subexpression whose prefix is the name of /// a class, enum, type variable, typedef, mixin declaration, extension /// declaration or built-in type, like dynamic and void. /// /// For instance: /// /// class A<T> {} /// typedef B = Function(); /// mixin C<T> on A<T> {} /// extension D<T> on A<T> {} /// /// method<T>() { /// C<B> // a TypeUseGenerator is created for `C` and `B`. /// B b; // a TypeUseGenerator is created for `B`. /// D.foo(); // a TypeUseGenerator is created for `D`. /// new A<T>(); // a TypeUseGenerator is created for `A` and `T`. /// T(); // a TypeUseGenerator is created for `T`. /// } /// class TypeUseGenerator extends ReadOnlyAccessGenerator { final TypeDeclarationBuilder declaration; TypeUseGenerator(ExpressionGeneratorHelper helper, Token token, this.declaration, String targetName) : super(helper, token, null, targetName); @override String get _debugName => "TypeUseGenerator"; @override TypeBuilder buildTypeWithResolvedArguments( NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) { if (declaration.isExtension) { // Extension declarations cannot be used as types. return super .buildTypeWithResolvedArguments(nullabilityBuilder, arguments); } if (arguments != null) { int expected = declaration.typeVariablesCount; if (arguments.length != expected) { // Build the type arguments to report any errors they may have. _helper.buildDartTypeArguments(arguments); _helper.warnTypeArgumentsMismatch( declaration.name, expected, fileOffset); // We ignore the provided arguments, which will in turn return the // raw type below. // TODO(sigmund): change to use an InvalidType and include the raw type // as a recovery node once the IR can represent it (Issue #29840). arguments = null; } } else if (declaration.typeVariablesCount != 0) { _helper.addProblem( templateMissingExplicitTypeArguments .withArguments(declaration.typeVariablesCount), fileOffset, lengthForToken(token)); } List<TypeBuilder> argumentBuilders; if (arguments != null) { argumentBuilders = new List<TypeBuilder>(arguments.length); for (int i = 0; i < argumentBuilders.length; i++) { argumentBuilders[i] = _helper.validateTypeUse(arguments[i], false).builder; } } return new NamedTypeBuilder( targetName, nullabilityBuilder, argumentBuilders) ..bind(declaration); } @override Expression invokeConstructor( List<UnresolvedType> typeArguments, String name, Arguments arguments, Token nameToken, Token nameLastToken, Constness constness) { return _helper.buildConstructorInvocation( declaration, nameToken, nameLastToken, arguments, name, typeArguments, offsetForToken(nameToken ?? token), constness); } @override void printOn(StringSink sink) { sink.write(", declaration: "); sink.write(declaration); sink.write(", plainNameForRead: "); sink.write(_plainNameForRead); } @override Expression get expression { if (super.expression == null) { if (declaration is InvalidTypeBuilder) { InvalidTypeBuilder declaration = this.declaration; super.expression = _helper.buildProblemErrorIfConst( declaration.message.messageObject, fileOffset, token.length); } else { super.expression = _forest.createTypeLiteral( offsetForToken(token), _helper.buildDartType( new UnresolvedType( buildTypeWithResolvedArguments( _helper.libraryBuilder.nonNullableBuilder, null), fileOffset, _uri), nonInstanceAccessIsError: true)); } } return super.expression; } @override buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { // `SomeType?.toString` is the same as `SomeType.toString`, not // `(SomeType).toString`. isNullAware = false; Name name = send.name; Arguments arguments = send.arguments; if (declaration is DeclarationBuilder) { DeclarationBuilder declaration = this.declaration; Builder member = declaration.findStaticBuilder( name.name, offsetForToken(send.token), _uri, _helper.libraryBuilder); Generator generator; if (member == null) { // If we find a setter, [member] is an [AccessErrorBuilder], not null. if (send is IncompletePropertyAccessGenerator) { generator = new UnresolvedNameGenerator(_helper, send.token, name); } else { return _helper.buildConstructorInvocation( declaration, send.token, send.token, arguments, name.name, null, token.charOffset, Constness.implicit); } } else if (member is AmbiguousBuilder) { return _helper.buildProblem( member.message, member.charOffset, name.name.length); } else { Builder setter; if (member.isSetter) { setter = member; } else if (member.isGetter) { setter = declaration.findStaticBuilder( name.name, fileOffset, _uri, _helper.libraryBuilder, isSetter: true); } else if (member.isField) { if (member.isFinal || member.isConst) { setter = declaration.findStaticBuilder( name.name, fileOffset, _uri, _helper.libraryBuilder, isSetter: true); } else { setter = member; } } generator = new StaticAccessGenerator.fromBuilder( _helper, name.name, member, send.token, setter); } return arguments == null ? generator : generator.doInvocation(offsetForToken(send.token), arguments); } else { return super.buildPropertyAccess(send, operatorOffset, isNullAware); } } @override doInvocation(int offset, Arguments arguments) { if (declaration.isExtension) { ExtensionBuilder extensionBuilder = declaration; if (arguments.positional.length != 1 || arguments.named.isNotEmpty) { return _helper.buildProblem(messageExplicitExtensionArgumentMismatch, fileOffset, lengthForToken(token)); } List<DartType> explicitTypeArguments = getExplicitTypeArguments(arguments); if (explicitTypeArguments != null) { int typeParameterCount = extensionBuilder.typeParameters?.length ?? 0; if (explicitTypeArguments.length != typeParameterCount) { return _helper.buildProblem( templateExplicitExtensionTypeArgumentMismatch.withArguments( extensionBuilder.name, typeParameterCount), fileOffset, lengthForToken(token)); } } // TODO(johnniwinther): Check argument and type argument count. return new ExplicitExtensionAccessGenerator(_helper, token, declaration, arguments.positional.single, explicitTypeArguments); } else { return _helper.buildConstructorInvocation(declaration, token, token, arguments, "", null, token.charOffset, Constness.implicit); } } } /// [ReadOnlyAccessGenerator] represents the subexpression whose prefix is the /// name of final local variable, final parameter, or catch clause variable or /// `this` in an instance method in an extension declaration. /// /// For instance: /// /// method(final a) { /// final b = null; /// a; // a ReadOnlyAccessGenerator is created for `a`. /// a[]; // a ReadOnlyAccessGenerator is created for `a`. /// b(); // a ReadOnlyAccessGenerator is created for `b`. /// b.c = a.d; // a ReadOnlyAccessGenerator is created for `a` and `b`. /// /// try { /// } catch (a) { /// a; // a ReadOnlyAccessGenerator is created for `a`. /// } /// } /// /// extension on Foo { /// method() { /// this; // a ReadOnlyAccessGenerator is created for `this`. /// this.a; // a ReadOnlyAccessGenerator is created for `this`. /// this.b(); // a ReadOnlyAccessGenerator is created for `this`. /// } /// } /// class ReadOnlyAccessGenerator extends Generator { final String targetName; Expression expression; VariableDeclaration value; ReadOnlyAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.expression, this.targetName) : super(helper, token); @override String get _debugName => "ReadOnlyAccessGenerator"; @override String get _plainNameForRead => targetName; @override Expression buildSimpleRead() => expression; @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _makeInvalidWrite(value); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { Expression read = buildSimpleRead(); Expression write = _makeInvalidWrite(value); return new IfNullSet(read, write, forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { MethodInvocation binary = _helper.forest.createMethodInvocation( offset, buildSimpleRead(), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); return _makeInvalidWrite(binary); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } @override doInvocation(int offset, Arguments arguments) { return _helper.buildMethodInvocation(buildSimpleRead(), callName, arguments, adjustForImplicitCall(targetName, offset), isImplicitCall: true); } @override Generator buildIndexedAccess(Expression index, Token token) { // TODO(johnniwinther): The read-only quality of the variable should be // passed on to the generator. return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { NameSystem syntheticNames = new NameSystem(); sink.write(", expression: "); printNodeOn(expression, sink, syntheticNames: syntheticNames); sink.write(", plainNameForRead: "); sink.write(targetName); sink.write(", value: "); printNodeOn(value, sink, syntheticNames: syntheticNames); } } abstract class ErroneousExpressionGenerator extends Generator { ErroneousExpressionGenerator(ExpressionGeneratorHelper helper, Token token) : super(helper, token); /// Pass [arguments] that must be evaluated before throwing an error. At /// most one of [isGetter] and [isSetter] should be true and they're passed /// to [ExpressionGeneratorHelper.throwNoSuchMethodError] if it is used. Expression buildError(Arguments arguments, {bool isGetter: false, bool isSetter: false, int offset}); Name get name => unsupported("name", fileOffset, _uri); @override String get _plainNameForRead => name.name; withReceiver(Object receiver, int operatorOffset, {bool isNullAware}) => this; @override Initializer buildFieldInitializer(Map<String, int> initializedFields) { return _helper.buildInvalidInitializer( buildError(_forest.createArgumentsEmpty(fileOffset), isSetter: true)); } @override doInvocation(int offset, Arguments arguments) { return buildError(arguments, offset: offset); } @override buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { return send.withReceiver(buildSimpleRead(), operatorOffset, isNullAware: isNullAware); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return buildError(_forest.createArguments(fileOffset, <Expression>[value]), isSetter: true); } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: -1, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return buildError(_forest.createArguments(fileOffset, <Expression>[value]), isGetter: true); } @override Expression buildPrefixIncrement(Name binaryOperator, {int offset: -1, bool voidContext: false, Procedure interfaceTarget}) { return buildError( _forest.createArguments( fileOffset, <Expression>[_forest.createIntLiteral(offset, 1)]), isGetter: true) ..fileOffset = offset; } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset: -1, bool voidContext: false, Procedure interfaceTarget}) { return buildError( _forest.createArguments( fileOffset, <Expression>[_forest.createIntLiteral(offset, 1)]), isGetter: true) ..fileOffset = offset; } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return buildError(_forest.createArguments(fileOffset, <Expression>[value]), isSetter: true); } @override Expression buildSimpleRead() { return buildError(_forest.createArgumentsEmpty(fileOffset), isGetter: true); } @override Expression _makeInvalidRead() { return buildError(_forest.createArgumentsEmpty(fileOffset), isGetter: true); } @override Expression _makeInvalidWrite(Expression value) { return buildError(_forest.createArguments(fileOffset, <Expression>[value]), isSetter: true); } @override Expression invokeConstructor( List<UnresolvedType> typeArguments, String name, Arguments arguments, Token nameToken, Token nameLastToken, Constness constness) { if (typeArguments != null) { assert(_forest.argumentsTypeArguments(arguments).isEmpty); _forest.argumentsSetTypeArguments( arguments, _helper.buildDartTypeArguments(typeArguments)); } return buildError(arguments); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } } class UnresolvedNameGenerator extends ErroneousExpressionGenerator { @override final Name name; factory UnresolvedNameGenerator( ExpressionGeneratorHelper helper, Token token, Name name) { if (name.name.isEmpty) { unhandled("empty", "name", offsetForToken(token), helper.uri); } return new UnresolvedNameGenerator.internal(helper, token, name); } UnresolvedNameGenerator.internal( ExpressionGeneratorHelper helper, Token token, this.name) : super(helper, token); @override String get _debugName => "UnresolvedNameGenerator"; @override Expression doInvocation(int charOffset, Arguments arguments) { return buildError(arguments, offset: charOffset); } @override Expression buildError(Arguments arguments, {bool isGetter: false, bool isSetter: false, int offset}) { offset ??= fileOffset; return _helper.throwNoSuchMethodError( _forest.createNullLiteral(offset), _plainNameForRead, arguments, offset, isGetter: isGetter, isSetter: isSetter); } @override /* Expression | Generator */ Object qualifiedLookup(Token name) { return new UnexpectedQualifiedUseGenerator(_helper, name, this, true); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _buildUnresolvedVariableAssignment(false, value); } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return _buildUnresolvedVariableAssignment(true, value); } @override Expression buildSimpleRead() { return buildError(_forest.createArgumentsEmpty(fileOffset), isGetter: true) ..fileOffset = fileOffset; } @override void printOn(StringSink sink) { sink.write(", name: "); sink.write(name.name); } Expression _buildUnresolvedVariableAssignment( bool isCompound, Expression value) { return buildError(_forest.createArguments(fileOffset, <Expression>[value]), isSetter: true); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } } class UnlinkedGenerator extends Generator { final UnlinkedDeclaration declaration; final Expression receiver; final Name name; UnlinkedGenerator( ExpressionGeneratorHelper helper, Token token, this.declaration) : name = new Name(declaration.name, helper.libraryBuilder.library), receiver = new InvalidExpression(declaration.name) ..fileOffset = offsetForToken(token), super(helper, token); @override String get _plainNameForRead => declaration.name; @override String get _debugName => "UnlinkedGenerator"; @override void printOn(StringSink sink) { sink.write(", name: "); sink.write(declaration.name); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _helper.forest.createPropertySet(fileOffset, receiver, name, value, forEffect: voidContext); } @override Expression buildSimpleRead() { return new PropertyGet(receiver, name)..fileOffset = fileOffset; } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); PropertyGet read = new PropertyGet( _helper.createVariableGet(variable, receiver.fileOffset), name) ..fileOffset = fileOffset; PropertySet write = _helper.forest.createPropertySet(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), name, value, forEffect: voidContext); return new IfNullPropertySet(variable, read, write, forEffect: voidContext) ..fileOffset = offset; } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, new PropertyGet( _helper.createVariableGet(variable, receiver.fileOffset), name) ..fileOffset = fileOffset, binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); PropertySet write = _helper.forest.createPropertySet(fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), name, binary, forEffect: voidContext); return new CompoundPropertySet(variable, write)..fileOffset = offset; } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { Expression value = _forest.createIntLiteral(offset, 1); if (voidContext) { return buildCompoundAssignment(binaryOperator, value, offset: offset, voidContext: voidContext, interfaceTarget: interfaceTarget, isPostIncDec: true); } VariableDeclaration variable = _helper.forest.createVariableDeclarationForValue(receiver); VariableDeclaration read = _helper.forest.createVariableDeclarationForValue( new PropertyGet( _helper.createVariableGet(variable, receiver.fileOffset), name) ..fileOffset = fileOffset); MethodInvocation binary = _helper.forest.createMethodInvocation( offset, _helper.createVariableGet(read, fileOffset), binaryOperator, _helper.forest.createArguments(offset, <Expression>[value]), interfaceTarget: interfaceTarget); VariableDeclaration write = _helper.forest .createVariableDeclarationForValue(_helper.forest.createPropertySet( fileOffset, _helper.createVariableGet(variable, receiver.fileOffset), name, binary, forEffect: true)); return new PropertyPostIncDec(variable, read, write)..fileOffset = offset; } @override Expression doInvocation(int offset, Arguments arguments) { return unsupported("doInvocation", offset, _uri); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } } abstract class ContextAwareGenerator extends Generator { final Generator generator; ContextAwareGenerator( ExpressionGeneratorHelper helper, Token token, this.generator) : super(helper, token); @override String get _plainNameForRead { return unsupported("plainNameForRead", token.charOffset, _helper.uri); } @override Expression doInvocation(int charOffset, Arguments arguments) { return unhandled("${runtimeType}", "doInvocation", charOffset, _uri); } @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _makeInvalidWrite(value); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return _makeInvalidWrite(value); } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: -1, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return _makeInvalidWrite(value); } @override Expression buildPrefixIncrement(Name binaryOperator, {int offset: -1, bool voidContext: false, Procedure interfaceTarget}) { return _makeInvalidWrite(null); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset: -1, bool voidContext: false, Procedure interfaceTarget}) { return _makeInvalidWrite(null); } @override _makeInvalidRead() { return unsupported("makeInvalidRead", token.charOffset, _helper.uri); } @override Expression _makeInvalidWrite(Expression value) { return _helper.buildProblem(messageIllegalAssignmentToNonAssignable, fileOffset, lengthForToken(token)); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } } class DelayedAssignment extends ContextAwareGenerator { final Expression value; String assignmentOperator; DelayedAssignment(ExpressionGeneratorHelper helper, Token token, Generator generator, this.value, this.assignmentOperator) : super(helper, token, generator); @override String get _debugName => "DelayedAssignment"; @override Expression buildSimpleRead() { return handleAssignment(false); } @override Expression buildForEffect() { return handleAssignment(true); } Expression handleAssignment(bool voidContext) { if (_helper.constantContext != ConstantContext.none) { return _helper.buildProblem( messageNotAConstantExpression, fileOffset, token.length); } if (identical("=", assignmentOperator)) { return generator.buildAssignment(value, voidContext: voidContext); } else if (identical("+=", assignmentOperator)) { return generator.buildCompoundAssignment(plusName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("-=", assignmentOperator)) { return generator.buildCompoundAssignment(minusName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("*=", assignmentOperator)) { return generator.buildCompoundAssignment(multiplyName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("%=", assignmentOperator)) { return generator.buildCompoundAssignment(percentName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("&=", assignmentOperator)) { return generator.buildCompoundAssignment(ampersandName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("/=", assignmentOperator)) { return generator.buildCompoundAssignment(divisionName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("<<=", assignmentOperator)) { return generator.buildCompoundAssignment(leftShiftName, value, offset: fileOffset, voidContext: voidContext); } else if (identical(">>=", assignmentOperator)) { return generator.buildCompoundAssignment(rightShiftName, value, offset: fileOffset, voidContext: voidContext); } else if (identical(">>>=", assignmentOperator)) { return generator.buildCompoundAssignment(tripleShiftName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("??=", assignmentOperator)) { return generator.buildIfNullAssignment( value, const DynamicType(), fileOffset, voidContext: voidContext); } else if (identical("^=", assignmentOperator)) { return generator.buildCompoundAssignment(caretName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("|=", assignmentOperator)) { return generator.buildCompoundAssignment(barName, value, offset: fileOffset, voidContext: voidContext); } else if (identical("~/=", assignmentOperator)) { return generator.buildCompoundAssignment(mustacheName, value, offset: fileOffset, voidContext: voidContext); } else { return unhandled(assignmentOperator, "handleAssignment", token.charOffset, _helper.uri); } } @override Initializer buildFieldInitializer(Map<String, int> initializedFields) { if (!identical("=", assignmentOperator) || generator is! ThisPropertyAccessGenerator) { return generator.buildFieldInitializer(initializedFields); } return _helper.buildFieldInitializer(false, generator._plainNameForRead, offsetForToken(generator.token), fileOffset, value); } @override void printOn(StringSink sink) { sink.write(", value: "); printNodeOn(value, sink); sink.write(", assignmentOperator: "); sink.write(assignmentOperator); } } class DelayedPostfixIncrement extends ContextAwareGenerator { final Name binaryOperator; final Procedure interfaceTarget; DelayedPostfixIncrement(ExpressionGeneratorHelper helper, Token token, Generator generator, this.binaryOperator, this.interfaceTarget) : super(helper, token, generator); @override String get _debugName => "DelayedPostfixIncrement"; @override Expression buildSimpleRead() { return generator.buildPostfixIncrement(binaryOperator, offset: fileOffset, voidContext: false, interfaceTarget: interfaceTarget); } @override Expression buildForEffect() { return generator.buildPostfixIncrement(binaryOperator, offset: fileOffset, voidContext: true, interfaceTarget: interfaceTarget); } @override void printOn(StringSink sink) { sink.write(", binaryOperator: "); sink.write(binaryOperator.name); sink.write(", interfaceTarget: "); printQualifiedNameOn(interfaceTarget, sink); } } class PrefixUseGenerator extends Generator { final PrefixBuilder prefix; PrefixUseGenerator(ExpressionGeneratorHelper helper, Token token, this.prefix) : super(helper, token); @override String get _plainNameForRead => prefix.name; @override String get _debugName => "PrefixUseGenerator"; @override Expression buildSimpleRead() => _makeInvalidRead(); @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _makeInvalidWrite(value); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return _makeInvalidRead(); } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return _makeInvalidRead(); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return _makeInvalidRead(); } @override /* Expression | Generator */ Object qualifiedLookup(Token name) { if (_helper.constantContext != ConstantContext.none && prefix.deferred) { _helper.addProblem( templateCantUseDeferredPrefixAsConstant.withArguments(token), fileOffset, lengthForToken(token)); } Object result = _helper.scopeLookup(prefix.exportScope, name.lexeme, name, isQualified: true, prefix: prefix); if (prefix.deferred) { if (result is Generator) { if (result is! LoadLibraryGenerator) { result = new DeferredAccessGenerator(_helper, name, this, result); } } else { _helper.wrapInDeferredCheck(result, prefix, fileOffset); } } return result; } @override /* Expression | Generator | Initializer */ doInvocation( int offset, Arguments arguments) { return _helper.wrapInLocatedProblem( _helper.evaluateArgumentsBefore( arguments, _forest.createNullLiteral(fileOffset)), messageCantUsePrefixAsExpression.withLocation( _helper.uri, fileOffset, lengthForToken(token))); } @override /* Expression | Generator */ buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { if (send is IncompleteSendGenerator) { assert(send.name.name == send.token.lexeme, "'${send.name.name}' != ${send.token.lexeme}"); Object result = qualifiedLookup(send.token); if (send is SendAccessGenerator) { result = _helper.finishSend(result, send.arguments, fileOffset); } if (isNullAware) { result = _helper.wrapInLocatedProblem( _helper.toValue(result), messageCantUsePrefixWithNullAware.withLocation( _helper.uri, fileOffset, lengthForToken(token))); } return result; } else { return buildSimpleRead(); } } @override Expression _makeInvalidRead() { return _helper.buildProblem( messageCantUsePrefixAsExpression, fileOffset, lengthForToken(token)); } @override Expression _makeInvalidWrite(Expression value) => _makeInvalidRead(); @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { sink.write(", prefix: "); sink.write(prefix.name); sink.write(", deferred: "); sink.write(prefix.deferred); } } class UnexpectedQualifiedUseGenerator extends Generator { final Generator prefixGenerator; final bool isUnresolved; UnexpectedQualifiedUseGenerator(ExpressionGeneratorHelper helper, Token token, this.prefixGenerator, this.isUnresolved) : super(helper, token); @override String get _plainNameForRead => "${prefixGenerator._plainNameForRead}.${token.lexeme}"; @override String get _debugName => "UnexpectedQualifiedUseGenerator"; @override Expression buildSimpleRead() => _makeInvalidRead(); @override Expression buildAssignment(Expression value, {bool voidContext: false}) { return _makeInvalidWrite(value); } @override Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return _makeInvalidRead(); } @override Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return _makeInvalidRead(); } @override Expression buildPostfixIncrement(Name binaryOperator, {int offset = TreeNode.noOffset, bool voidContext = false, Procedure interfaceTarget}) { return _makeInvalidRead(); } @override Expression doInvocation(int offset, Arguments arguments) { return _helper.throwNoSuchMethodError(_forest.createNullLiteral(offset), _plainNameForRead, arguments, fileOffset); } @override TypeBuilder buildTypeWithResolvedArguments( NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) { Template<Message Function(String, String)> template = isUnresolved ? templateUnresolvedPrefixInTypeAnnotation : templateNotAPrefixInTypeAnnotation; NamedTypeBuilder result = new NamedTypeBuilder(_plainNameForRead, nullabilityBuilder, null); Message message = template.withArguments(prefixGenerator.token.lexeme, token.lexeme); _helper.libraryBuilder.addProblem( message, offsetForToken(prefixGenerator.token), lengthOfSpan(prefixGenerator.token, token), _uri); result.bind(result.buildInvalidType(message.withLocation( _uri, offsetForToken(prefixGenerator.token), lengthOfSpan(prefixGenerator.token, token)))); return result; } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } @override void printOn(StringSink sink) { sink.write(", prefixGenerator: "); prefixGenerator.printOn(sink); } } class ParserErrorGenerator extends Generator { final Message message; ParserErrorGenerator( ExpressionGeneratorHelper helper, Token token, this.message) : super(helper, token); @override String get _plainNameForRead => "#parser-error"; @override String get _debugName => "ParserErrorGenerator"; @override void printOn(StringSink sink) {} Expression buildProblem() { return _helper.buildProblem(message, fileOffset, noLength, suppressMessage: true); } Expression buildSimpleRead() => buildProblem(); Expression buildAssignment(Expression value, {bool voidContext: false}) { return buildProblem(); } Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return buildProblem(); } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return buildProblem(); } Expression buildPrefixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return buildProblem(); } Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return buildProblem(); } Expression _makeInvalidRead() => buildProblem(); Expression _makeInvalidWrite(Expression value) => buildProblem(); Initializer buildFieldInitializer(Map<String, int> initializedFields) { return _helper.buildInvalidInitializer(buildProblem()); } Expression doInvocation(int offset, Arguments arguments) { return buildProblem(); } Expression buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { return buildProblem(); } TypeBuilder buildTypeWithResolvedArguments( NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) { NamedTypeBuilder result = new NamedTypeBuilder(token.lexeme, nullabilityBuilder, null); _helper.libraryBuilder.addProblem(message, fileOffset, noLength, _uri); result.bind(result .buildInvalidType(message.withLocation(_uri, fileOffset, noLength))); return result; } Expression qualifiedLookup(Token name) { return buildProblem(); } Expression invokeConstructor( List<UnresolvedType> typeArguments, String name, Arguments arguments, Token nameToken, Token nameLastToken, Constness constness) { return buildProblem(); } @override Generator buildIndexedAccess(Expression index, Token token) { return new IndexedAccessGenerator( _helper, token, buildSimpleRead(), index, null, null); } } /// A [ThisAccessGenerator] represents a subexpression whose prefix is `this` /// or `super`. /// /// For instance /// /// class C { /// var b = this.c; // a ThisAccessGenerator is created for `this`. /// var c; /// C(this.c) : // a ThisAccessGenerator is created for `this`. /// this.b = c; // a ThisAccessGenerator is created for `this`. /// method() { /// this.b; // a ThisAccessGenerator is created for `this`. /// super.b(); // a ThisAccessGenerator is created for `super`. /// this.b = c; // a ThisAccessGenerator is created for `this`. /// this.b += c; // a ThisAccessGenerator is created for `this`. /// } /// } /// /// If this `this` occurs in an instance member on an extension declaration, /// a [ReadOnlyAccessGenerator] is created instead. /// class ThisAccessGenerator extends Generator { /// `true` if this access is in an initializer list. /// /// For instance in `<init>` in /// /// class Class { /// Class() : <init>; /// } /// final bool isInitializer; /// `true` if this access is in a field initializer either directly or within /// an initializer list. /// /// For instance in `<init>` in /// /// var foo = <init>; /// class Class { /// var bar = <init>; /// Class() : <init>; /// } /// final bool inFieldInitializer; /// `true` if this subexpression represents a `super` prefix. final bool isSuper; ThisAccessGenerator(ExpressionGeneratorHelper helper, Token token, this.isInitializer, this.inFieldInitializer, {this.isSuper: false}) : super(helper, token); String get _plainNameForRead { return unsupported( "${isSuper ? 'super' : 'this'}.plainNameForRead", fileOffset, _uri); } String get _debugName => "ThisAccessGenerator"; Expression buildSimpleRead() { if (!isSuper) { if (inFieldInitializer) { return buildFieldInitializerError(null); } else { return _forest.createThisExpression(fileOffset); } } else { return _helper.buildProblem( messageSuperAsExpression, fileOffset, lengthForToken(token)); } } Expression buildFieldInitializerError(Map<String, int> initializedFields) { String keyword = isSuper ? "super" : "this"; return _helper.buildProblem( templateThisOrSuperAccessInFieldInitializer.withArguments(keyword), fileOffset, keyword.length); } @override Initializer buildFieldInitializer(Map<String, int> initializedFields) { Expression error = buildFieldInitializerError(initializedFields); return _helper.buildInvalidInitializer(error, error.fileOffset); } buildPropertyAccess( IncompleteSendGenerator send, int operatorOffset, bool isNullAware) { Name name = send.name; Arguments arguments = send.arguments; int offset = offsetForToken(send.token); if (isInitializer && send is SendAccessGenerator) { if (isNullAware) { _helper.addProblem( messageInvalidUseOfNullAwareAccess, operatorOffset, 2); } return buildConstructorInitializer(offset, name, arguments); } if (inFieldInitializer && !isInitializer) { return buildFieldInitializerError(null); } Member getter = _helper.lookupInstanceMember(name, isSuper: isSuper); if (send is SendAccessGenerator) { // Notice that 'this' or 'super' can't be null. So we can ignore the // value of [isNullAware]. if (getter == null) { _helper.warnUnresolvedMethod(name, offsetForToken(send.token), isSuper: isSuper); } return _helper.buildMethodInvocation( _forest.createThisExpression(fileOffset), name, send.arguments, offsetForToken(send.token), isSuper: isSuper, interfaceTarget: getter); } else { Member setter = _helper.lookupInstanceMember(name, isSuper: isSuper, isSetter: true); if (isSuper) { return new SuperPropertyAccessGenerator( _helper, // TODO(ahe): This is not the 'super' token. send.token, name, getter, setter); } else { return new ThisPropertyAccessGenerator( _helper, // TODO(ahe): This is not the 'this' token. send.token, name, getter, setter); } } } doInvocation(int offset, Arguments arguments) { if (isInitializer) { return buildConstructorInitializer(offset, new Name(""), arguments); } else if (isSuper) { return _helper.buildProblem(messageSuperAsExpression, offset, noLength); } else { return _helper.buildMethodInvocation( _forest.createThisExpression(fileOffset), callName, arguments, offset, isImplicitCall: true); } } Initializer buildConstructorInitializer( int offset, Name name, Arguments arguments) { Constructor constructor = _helper.lookupConstructor(name, isSuper: isSuper); LocatedMessage message; if (constructor != null) { message = _helper.checkArgumentsForFunction( constructor.function, arguments, offset, <TypeParameter>[]); } else { String fullName = _helper.constructorNameForDiagnostics(name.name, isSuper: isSuper); message = (isSuper ? templateSuperclassHasNoConstructor : templateConstructorNotFound) .withArguments(fullName) .withLocation(_uri, fileOffset, lengthForToken(token)); } if (message != null) { return _helper.buildInvalidInitializer( _helper.throwNoSuchMethodError( _forest.createNullLiteral(offset), _helper.constructorNameForDiagnostics(name.name, isSuper: isSuper), arguments, offset, isSuper: isSuper, message: message), offset); } else if (isSuper) { return _helper.buildSuperInitializer( false, constructor, arguments, offset); } else { return _helper.buildRedirectingInitializer( constructor, arguments, offset); } } Expression buildAssignment(Expression value, {bool voidContext: false}) { return buildAssignmentError(); } Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return buildAssignmentError(); } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return buildAssignmentError(); } Expression buildPrefixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return buildAssignmentError(); } Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return buildAssignmentError(); } @override Generator buildIndexedAccess(Expression index, Token token) { if (isSuper) { return new SuperIndexedAccessGenerator( _helper, token, index, _helper.lookupInstanceMember(indexGetName, isSuper: true), _helper.lookupInstanceMember(indexSetName, isSuper: true)); } else { return new ThisIndexedAccessGenerator(_helper, token, index, null, null); } } Expression buildAssignmentError() { return _helper.buildProblem( isSuper ? messageCannotAssignToSuper : messageNotAnLvalue, fileOffset, token.length); } @override void printOn(StringSink sink) { sink.write(", isInitializer: "); sink.write(isInitializer); sink.write(", inFieldInitializer: "); sink.write(inFieldInitializer); sink.write(", isSuper: "); sink.write(isSuper); } } abstract class IncompleteSendGenerator implements Generator { Name get name; withReceiver(Object receiver, int operatorOffset, {bool isNullAware}); Arguments get arguments => null; } class IncompleteErrorGenerator extends ErroneousExpressionGenerator with IncompleteSendGenerator { final Message message; IncompleteErrorGenerator( ExpressionGeneratorHelper helper, Token token, this.message) : super(helper, token); Name get name => null; String get _plainNameForRead => token.lexeme; String get _debugName => "IncompleteErrorGenerator"; @override Expression buildError(Arguments arguments, {bool isGetter: false, bool isSetter: false, int offset}) { int length = noLength; if (offset == null) { offset = fileOffset; length = lengthForToken(token); } return _helper.buildProblem(message, offset, length); } @override doInvocation(int offset, Arguments arguments) => this; @override Expression buildSimpleRead() { return buildError(_forest.createArgumentsEmpty(fileOffset), isGetter: true) ..fileOffset = fileOffset; } @override void printOn(StringSink sink) { sink.write(", message: "); sink.write(message.code.name); } } // TODO(ahe): Rename to SendGenerator. class SendAccessGenerator extends Generator with IncompleteSendGenerator { @override final Name name; @override final Arguments arguments; SendAccessGenerator( ExpressionGeneratorHelper helper, Token token, this.name, this.arguments) : super(helper, token) { assert(arguments != null); } String get _plainNameForRead => name.name; String get _debugName => "SendAccessGenerator"; Expression buildSimpleRead() { return unsupported("buildSimpleRead", fileOffset, _uri); } Expression buildAssignment(Expression value, {bool voidContext: false}) { return unsupported("buildAssignment", fileOffset, _uri); } withReceiver(Object receiver, int operatorOffset, {bool isNullAware: false}) { if (receiver is Generator) { return receiver.buildPropertyAccess(this, operatorOffset, isNullAware); } return _helper.buildMethodInvocation( _helper.toValue(receiver), name, arguments, fileOffset, isNullAware: isNullAware); } Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return unsupported("buildNullAwareAssignment", offset, _uri); } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return unsupported("buildCompoundAssignment", offset ?? fileOffset, _uri); } Expression buildPrefixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return unsupported("buildPrefixIncrement", offset ?? fileOffset, _uri); } Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return unsupported("buildPostfixIncrement", offset ?? fileOffset, _uri); } Expression doInvocation(int offset, Arguments arguments) { return unsupported("doInvocation", offset, _uri); } @override Generator buildIndexedAccess(Expression index, Token token) { return unsupported("buildIndexedAccess", offsetForToken(token), _uri); } @override void printOn(StringSink sink) { sink.write(", name: "); sink.write(name.name); sink.write(", arguments: "); Arguments node = arguments; if (node is Node) { printNodeOn(node, sink); } else { sink.write(node); } } } class IncompletePropertyAccessGenerator extends Generator with IncompleteSendGenerator { final Name name; IncompletePropertyAccessGenerator( ExpressionGeneratorHelper helper, Token token, this.name) : super(helper, token); String get _plainNameForRead => name.name; String get _debugName => "IncompletePropertyAccessGenerator"; Expression buildSimpleRead() { return unsupported("buildSimpleRead", fileOffset, _uri); } Expression buildAssignment(Expression value, {bool voidContext: false}) { return unsupported("buildAssignment", fileOffset, _uri); } withReceiver(Object receiver, int operatorOffset, {bool isNullAware: false}) { if (receiver is Generator) { return receiver.buildPropertyAccess(this, operatorOffset, isNullAware); } return PropertyAccessGenerator.make(_helper, token, _helper.toValue(receiver), name, null, null, isNullAware); } Expression buildIfNullAssignment(Expression value, DartType type, int offset, {bool voidContext: false}) { return unsupported("buildNullAwareAssignment", offset, _uri); } Expression buildCompoundAssignment(Name binaryOperator, Expression value, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget, bool isPreIncDec: false, bool isPostIncDec: false}) { return unsupported("buildCompoundAssignment", offset ?? fileOffset, _uri); } Expression buildPrefixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return unsupported("buildPrefixIncrement", offset ?? fileOffset, _uri); } Expression buildPostfixIncrement(Name binaryOperator, {int offset: TreeNode.noOffset, bool voidContext: false, Procedure interfaceTarget}) { return unsupported("buildPostfixIncrement", offset ?? fileOffset, _uri); } Expression doInvocation(int offset, Arguments arguments) { return unsupported("doInvocation", offset, _uri); } @override Generator buildIndexedAccess(Expression index, Token token) { return unsupported("buildIndexedAccess", offsetForToken(token), _uri); } @override void printOn(StringSink sink) { sink.write(", name: "); sink.write(name.name); } } class ParenthesizedExpressionGenerator extends ReadOnlyAccessGenerator { ParenthesizedExpressionGenerator( ExpressionGeneratorHelper helper, Token token, Expression expression) : super(helper, token, expression, null); String get _debugName => "ParenthesizedExpressionGenerator"; Expression _makeInvalidWrite(Expression value) { return _helper.buildProblem(messageCannotAssignToParenthesizedExpression, fileOffset, lengthForToken(token)); } } Expression makeLet(VariableDeclaration variable, Expression body) { if (variable == null) return body; return new Let(variable, body); } Expression makeBinary(Expression left, Name operator, Procedure interfaceTarget, Expression right, ExpressionGeneratorHelper helper, {int offset: TreeNode.noOffset}) { return new MethodInvocationImpl(left, operator, helper.forest.createArguments(offset, <Expression>[right]), interfaceTarget: interfaceTarget) ..fileOffset = offset; } Expression buildIsNull( Expression value, int offset, ExpressionGeneratorHelper helper) { return makeBinary( value, equalsName, null, helper.forest.createNullLiteral(offset), helper, offset: offset); } VariableDeclaration makeOrReuseVariable(Expression value) { // TODO: Devise a way to remember if a variable declaration was reused // or is fresh (hence needs a let binding). return new VariableDeclaration.forValue(value); } int adjustForImplicitCall(String name, int offset) { // Normally the offset is at the start of the token, but in this case, // because we insert a '.call', we want it at the end instead. return offset + (name?.length ?? 0); } bool isFieldOrGetter(Member member) { return member is Field || (member is Procedure && member.isGetter); }
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/kernel/constant_collection_builders.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. part of 'constant_evaluator.dart'; abstract class _ListOrSetConstantBuilder<L extends Expression> { final ConstantEvaluator evaluator; final Expression original; final DartType elementType; // Each element of [parts] is either a `List<Constant>` (containing fully // evaluated constants) or a `Constant` (potentially unevaluated). List<Object> parts = <Object>[<Constant>[]]; _ListOrSetConstantBuilder(this.original, this.elementType, this.evaluator); L makeLiteral(List<Expression> elements); /// Add an element to the constant list being built by this builder. void add(Expression element) { Constant constant = evaluator._evaluateSubexpression(element); if (evaluator.shouldBeUnevaluated) { parts.add(evaluator.unevaluated( element, makeLiteral([evaluator.extract(constant)]))); } else { addConstant(constant, element); } } void addSpread(Expression spreadExpression) { Constant spread = evaluator.unlower(evaluator._evaluateSubexpression(spreadExpression)); if (evaluator.shouldBeUnevaluated) { // Unevaluated spread parts.add(spread); } else if (spread == evaluator.nullConstant) { // Null spread evaluator.report(spreadExpression, messageConstEvalNullValue); } else { // Fully evaluated spread List<Constant> entries; if (spread is ListConstant) { entries = spread.entries; } else if (spread is SetConstant) { entries = spread.entries; } else { // Not list or set in spread return evaluator.report( spreadExpression, messageConstEvalNotListOrSetInSpread); } for (Constant entry in entries) { addConstant(entry, spreadExpression); } } } void addConstant(Constant constant, TreeNode context); Constant build(); } class ListConstantBuilder extends _ListOrSetConstantBuilder<ListLiteral> { ListConstantBuilder( Expression original, DartType elementType, ConstantEvaluator evaluator) : super(original, elementType, evaluator); @override ListLiteral makeLiteral(List<Expression> elements) => new ListLiteral(elements, isConst: true); @override void addConstant(Constant constant, TreeNode context) { List<Constant> lastPart; if (parts.last is List<Constant>) { lastPart = parts.last; } else { parts.add(lastPart = <Constant>[]); } lastPart.add(evaluator.ensureIsSubtype(constant, elementType, context)); } @override Constant build() { if (parts.length == 1) { // Fully evaluated return evaluator .lowerListConstant(new ListConstant(elementType, parts.single)); } List<Expression> lists = <Expression>[]; for (Object part in parts) { if (part is List<Constant>) { lists.add(new ConstantExpression(new ListConstant(elementType, part))); } else if (part is Constant) { lists.add(evaluator.extract(part)); } else { throw 'Non-constant in constant list'; } } return evaluator.unevaluated( original, new ListConcatenation(lists, typeArgument: elementType)); } } class SetConstantBuilder extends _ListOrSetConstantBuilder<SetLiteral> { final Set<Constant> seen = new Set<Constant>.identity(); SetConstantBuilder( Expression original, DartType elementType, ConstantEvaluator evaluator) : super(original, elementType, evaluator); @override SetLiteral makeLiteral(List<Expression> elements) => new SetLiteral(elements, isConst: true); @override void addConstant(Constant constant, TreeNode context) { if (!evaluator.hasPrimitiveEqual(constant)) { evaluator.report(context, templateConstEvalElementImplementsEqual.withArguments(constant)); } if (!seen.add(constant)) { evaluator.report( context, templateConstEvalDuplicateElement.withArguments(constant)); } List<Constant> lastPart; if (parts.last is List<Constant>) { lastPart = parts.last; } else { parts.add(lastPart = <Constant>[]); } lastPart.add(evaluator.ensureIsSubtype(constant, elementType, context)); } @override Constant build() { if (parts.length == 1) { // Fully evaluated List<Constant> entries = parts.single; SetConstant result = new SetConstant(elementType, entries); if (evaluator.desugarSets) { final List<ConstantMapEntry> mapEntries = new List<ConstantMapEntry>(entries.length); for (int i = 0; i < entries.length; ++i) { mapEntries[i] = new ConstantMapEntry(entries[i], evaluator.nullConstant); } Constant map = evaluator.lowerMapConstant(new MapConstant( elementType, evaluator.typeEnvironment.nullType, mapEntries)); return evaluator.lower( result, new InstanceConstant( evaluator.unmodifiableSetMap.enclosingClass.reference, [ elementType ], <Reference, Constant>{ evaluator.unmodifiableSetMap.reference: map })); } else { return evaluator.lowerSetConstant(result); } } List<Expression> sets = <Expression>[]; for (Object part in parts) { if (part is List<Constant>) { sets.add(new ConstantExpression(new SetConstant(elementType, part))); } else if (part is Constant) { sets.add(evaluator.extract(part)); } else { throw 'Non-constant in constant set'; } } return evaluator.unevaluated( original, new SetConcatenation(sets, typeArgument: elementType)); } } class MapConstantBuilder { final ConstantEvaluator evaluator; final Expression original; final DartType keyType; final DartType valueType; /// Each element of [parts] is either a `List<ConstantMapEntry>` (containing /// fully evaluated map entries) or a `Constant` (potentially unevaluated). List<Object> parts = <Object>[<ConstantMapEntry>[]]; final Set<Constant> seenKeys = new Set<Constant>.identity(); MapConstantBuilder( this.original, this.keyType, this.valueType, this.evaluator); /// Add a map entry to the constant map being built by this builder void add(MapEntry element) { Constant key = evaluator._evaluateSubexpression(element.key); Constant value = evaluator._evaluateSubexpression(element.value); if (evaluator.shouldBeUnevaluated) { parts.add(evaluator.unevaluated( element.key, new MapLiteral( [new MapEntry(evaluator.extract(key), evaluator.extract(value))], isConst: true))); } else { addConstant(key, value, element.key, element.value); } } void addSpread(Expression spreadExpression) { Constant spread = evaluator.unlower(evaluator._evaluateSubexpression(spreadExpression)); if (evaluator.shouldBeUnevaluated) { // Unevaluated spread parts.add(spread); } else if (spread == evaluator.nullConstant) { // Null spread evaluator.report(spreadExpression, messageConstEvalNullValue); } else { // Fully evaluated spread if (spread is MapConstant) { for (ConstantMapEntry entry in spread.entries) { addConstant( entry.key, entry.value, spreadExpression, spreadExpression); } } else { // Not map in spread return evaluator.report( spreadExpression, messageConstEvalNotMapInSpread); } } } void addConstant(Constant key, Constant value, TreeNode keyContext, TreeNode valueContext) { List<ConstantMapEntry> lastPart; if (parts.last is List<ConstantMapEntry>) { lastPart = parts.last; } else { parts.add(lastPart = <ConstantMapEntry>[]); } if (!evaluator.hasPrimitiveEqual(key)) { evaluator.report( keyContext, templateConstEvalKeyImplementsEqual.withArguments(key)); } if (!seenKeys.add(key)) { evaluator.report( keyContext, templateConstEvalDuplicateKey.withArguments(key)); } lastPart.add(new ConstantMapEntry( evaluator.ensureIsSubtype(key, keyType, keyContext), evaluator.ensureIsSubtype(value, valueType, valueContext))); } Constant build() { if (parts.length == 1) { // Fully evaluated return evaluator .lowerMapConstant(new MapConstant(keyType, valueType, parts.single)); } List<Expression> maps = <Expression>[]; for (Object part in parts) { if (part is List<ConstantMapEntry>) { maps.add( new ConstantExpression(new MapConstant(keyType, valueType, part))); } else if (part is Constant) { maps.add(evaluator.extract(part)); } else { throw 'Non-constant in constant map'; } } return evaluator.unevaluated(original, new MapConcatenation(maps, keyType: keyType, valueType: valueType)); } }
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/kernel/verifier.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library fasta.verifier; import 'package:kernel/ast.dart' show AsExpression, Class, Component, DartType, ExpressionStatement, Field, FunctionType, Library, Member, Procedure, StaticInvocation, SuperMethodInvocation, SuperPropertyGet, SuperPropertySet, TreeNode, TypeParameter; import 'package:kernel/transformations/flags.dart' show TransformerFlag; import 'package:kernel/verifier.dart' show VerifyingVisitor; import '../compiler_context.dart' show CompilerContext; import '../fasta_codes.dart' show LocatedMessage, noLength, templateInternalProblemVerificationError; import '../severity.dart' show Severity; import '../type_inference/type_schema.dart' show UnknownType; import 'redirecting_factory_body.dart' show RedirectingFactoryBody, getRedirectingFactoryBody; List<LocatedMessage> verifyComponent(Component component, {bool isOutline: false, bool skipPlatform: false}) { FastaVerifyingVisitor verifier = new FastaVerifyingVisitor(isOutline, skipPlatform); component.accept(verifier); return verifier.errors; } class FastaVerifyingVisitor extends VerifyingVisitor { final List<LocatedMessage> errors = <LocatedMessage>[]; Uri fileUri; final bool skipPlatform; FastaVerifyingVisitor(bool isOutline, this.skipPlatform) { this.isOutline = isOutline; } Uri checkLocation(TreeNode node, String name, Uri fileUri) { if (name == null || name.contains("#")) { // TODO(ahe): Investigate if these checks can be enabled: // if (node.fileUri != null && node is! Library) { // problem(node, "A synthetic node shouldn't have a fileUri", // context: node); // } // if (node.fileOffset != -1) { // problem(node, "A synthetic node shouldn't have a fileOffset", // context: node); // } return fileUri; } else { if (fileUri == null) { problem(node, "'$name' has no fileUri", context: node); return fileUri; } if (node.fileOffset == -1 && node is! Library) { problem(node, "'$name' has no fileOffset", context: node); } return fileUri; } } void checkSuperInvocation(TreeNode node) { Member containingMember = getContainingMember(node); if (containingMember == null) { problem(node, 'Super call outside of any member'); } else { if (containingMember.transformerFlags & TransformerFlag.superCalls == 0) { problem( node, 'Super call in a member lacking TransformerFlag.superCalls'); } } } Member getContainingMember(TreeNode node) { while (node != null) { if (node is Member) return node; node = node.parent; } return null; } @override problem(TreeNode node, String details, {TreeNode context}) { node ??= (context ?? this.context); int offset = node?.fileOffset ?? -1; Uri file = node?.location?.file ?? fileUri; Uri uri = file == null ? null : file; LocatedMessage message = templateInternalProblemVerificationError .withArguments(details) .withLocation(uri, offset, noLength); CompilerContext.current.report(message, Severity.error); errors.add(message); } @override visitAsExpression(AsExpression node) { super.visitAsExpression(node); if (node.fileOffset == -1) { TreeNode parent = node.parent; while (parent != null) { if (parent.fileOffset != -1) break; parent = parent.parent; } problem(parent, "No offset for $node", context: node); } } @override visitExpressionStatement(ExpressionStatement node) { // Bypass verification of the [StaticGet] in [RedirectingFactoryBody] as // this is a static get without a getter. if (node is! RedirectingFactoryBody) { super.visitExpressionStatement(node); } } @override visitLibrary(Library node) { // Issue(http://dartbug.com/32530) if (skipPlatform && node.importUri.scheme == 'dart') { return; } fileUri = checkLocation(node, node.name, node.fileUri); super.visitLibrary(node); } @override visitClass(Class node) { fileUri = checkLocation(node, node.name, node.fileUri); super.visitClass(node); } @override visitField(Field node) { fileUri = checkLocation(node, node.name.name, node.fileUri); super.visitField(node); } @override visitProcedure(Procedure node) { fileUri = checkLocation(node, node.name.name, node.fileUri); super.visitProcedure(node); } @override defaultDartType(DartType node) { if (node is UnknownType) { // Note: we can't pass [node] to [problem] because it's not a [TreeNode]. problem(null, "Unexpected appearance of the unknown type."); } super.defaultDartType(node); } @override visitFunctionType(FunctionType node) { if (node.typeParameters.isNotEmpty) { for (TypeParameter typeParameter in node.typeParameters) { if (typeParameter.parent != null) { problem( null, "Type parameters of function types shouldn't have parents: " "$node."); } } } } @override visitSuperMethodInvocation(SuperMethodInvocation node) { checkSuperInvocation(node); super.visitSuperMethodInvocation(node); } @override visitSuperPropertyGet(SuperPropertyGet node) { checkSuperInvocation(node); super.visitSuperPropertyGet(node); } @override visitSuperPropertySet(SuperPropertySet node) { checkSuperInvocation(node); super.visitSuperPropertySet(node); } @override visitStaticInvocation(StaticInvocation node) { super.visitStaticInvocation(node); RedirectingFactoryBody body = getRedirectingFactoryBody(node.target); if (body != null) { problem(node, "Attempt to invoke redirecting factory."); } } }
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/kernel/forwarding_node.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 "package:kernel/ast.dart" show Arguments, Class, DartType, Expression, Field, FunctionNode, Member, Name, NamedExpression, Procedure, ProcedureKind, ReturnStatement, SuperMethodInvocation, SuperPropertyGet, SuperPropertySet, TypeParameter, TypeParameterType, VariableDeclaration, VariableGet, VoidType; import 'package:kernel/transformations/flags.dart' show TransformerFlag; import "package:kernel/type_algebra.dart" show Substitution; import "../builder/class_builder.dart"; import "../problems.dart" show unhandled; import "../type_inference/type_inference_engine.dart" show IncludesTypeParametersNonCovariantly, Variance; import "../type_inference/type_inferrer.dart" show getNamedFormal; import 'class_hierarchy_builder.dart'; class ForwardingNode { final ClassHierarchyBuilder hierarchy; final ClassBuilder parent; final ClassMember combinedMemberSignatureResult; final ProcedureKind kind; /// A list containing the directly implemented and directly inherited /// procedures of the class in question. final List<ClassMember> _candidates; ForwardingNode(this.hierarchy, this.parent, this.combinedMemberSignatureResult, this._candidates, this.kind); Name get name => combinedMemberSignatureResult.member.name; Class get enclosingClass => parent.cls; /// Finishes handling of this node by propagating covariance and creating /// forwarding stubs if necessary. Member finalize() => _computeCovarianceFixes(); /// Tag the parameters of [interfaceMember] that need type checks /// /// Parameters can need type checks for calls coming from statically typed /// call sites, due to covariant generics and overrides with explicit /// `covariant` parameters. /// /// Tag parameters of [interfaceMember] that need such checks when the member /// occurs in [enclosingClass]'s interface. If parameters need checks but /// they would not be checked in an inherited implementation, a forwarding /// stub is introduced as a place to put the checks. Member _computeCovarianceFixes() { Member interfaceMember = combinedMemberSignatureResult.member; Substitution substitution = _substitutionFor(interfaceMember, enclosingClass); // We always create a forwarding stub when we've inherited a member from an // interface other than the first override candidate. This is to work // around a bug in the Kernel type checker where it chooses the first // override candidate. // // TODO(kmillikin): Fix the Kernel type checker and stop creating these // extra stubs. Member stub = interfaceMember.enclosingClass == enclosingClass || interfaceMember == getCandidateAt(0) ? interfaceMember : _createForwardingStub(substitution, interfaceMember); FunctionNode interfaceFunction = interfaceMember.function; List<VariableDeclaration> interfacePositionalParameters = getPositionalParameters(interfaceMember); List<VariableDeclaration> interfaceNamedParameters = interfaceFunction?.namedParameters ?? []; List<TypeParameter> interfaceTypeParameters = interfaceFunction?.typeParameters ?? []; void createStubIfNeeded() { if (stub != interfaceMember) return; if (interfaceMember.enclosingClass == enclosingClass) return; stub = _createForwardingStub(substitution, interfaceMember); } bool isImplCreated = false; void createImplIfNeeded() { if (isImplCreated) return; createStubIfNeeded(); _createForwardingImplIfNeeded(stub.function); isImplCreated = true; } IncludesTypeParametersNonCovariantly needsCheckVisitor = enclosingClass.typeParameters.isEmpty ? null // TODO(ahe): It may be necessary to cache this object. : new IncludesTypeParametersNonCovariantly( enclosingClass.typeParameters, // We are checking the parameter types and these are in a // contravariant position. initialVariance: Variance.contravariant); bool needsCheck(DartType type) => needsCheckVisitor == null ? false : substitution.substituteType(type).accept(needsCheckVisitor); for (int i = 0; i < interfacePositionalParameters.length; i++) { VariableDeclaration parameter = interfacePositionalParameters[i]; bool isGenericCovariantImpl = parameter.isGenericCovariantImpl || needsCheck(parameter.type); bool isCovariant = parameter.isCovariant; VariableDeclaration superParameter = parameter; for (int j = 0; j < _candidates.length; j++) { Member otherMember = getCandidateAt(j); if (otherMember is ForwardingNode) continue; List<VariableDeclaration> otherPositionalParameters = getPositionalParameters(otherMember); if (otherPositionalParameters.length <= i) continue; VariableDeclaration otherParameter = otherPositionalParameters[i]; if (j == 0) superParameter = otherParameter; if (identical(otherMember, interfaceMember)) continue; if (otherParameter.isGenericCovariantImpl) { isGenericCovariantImpl = true; } if (otherParameter.isCovariant) { isCovariant = true; } } if (isGenericCovariantImpl) { if (!superParameter.isGenericCovariantImpl) { createImplIfNeeded(); } if (!parameter.isGenericCovariantImpl) { createStubIfNeeded(); stub.function.positionalParameters[i].isGenericCovariantImpl = true; } } if (isCovariant) { if (!superParameter.isCovariant) { createImplIfNeeded(); } if (!parameter.isCovariant) { createStubIfNeeded(); stub.function.positionalParameters[i].isCovariant = true; } } } for (int i = 0; i < interfaceNamedParameters.length; i++) { VariableDeclaration parameter = interfaceNamedParameters[i]; bool isGenericCovariantImpl = parameter.isGenericCovariantImpl || needsCheck(parameter.type); bool isCovariant = parameter.isCovariant; VariableDeclaration superParameter = parameter; for (int j = 0; j < _candidates.length; j++) { Member otherMember = getCandidateAt(j); if (otherMember is ForwardingNode) continue; VariableDeclaration otherParameter = getNamedFormal(otherMember.function, parameter.name); if (otherParameter == null) continue; if (j == 0) superParameter = otherParameter; if (identical(otherMember, interfaceMember)) continue; if (otherParameter.isGenericCovariantImpl) { isGenericCovariantImpl = true; } if (otherParameter.isCovariant) { isCovariant = true; } } if (isGenericCovariantImpl) { if (!superParameter.isGenericCovariantImpl) { createImplIfNeeded(); } if (!parameter.isGenericCovariantImpl) { createStubIfNeeded(); stub.function.namedParameters[i].isGenericCovariantImpl = true; } } if (isCovariant) { if (!superParameter.isCovariant) { createImplIfNeeded(); } if (!parameter.isCovariant) { createStubIfNeeded(); stub.function.namedParameters[i].isCovariant = true; } } } for (int i = 0; i < interfaceTypeParameters.length; i++) { TypeParameter typeParameter = interfaceTypeParameters[i]; bool isGenericCovariantImpl = typeParameter.isGenericCovariantImpl || needsCheck(typeParameter.bound); TypeParameter superTypeParameter = typeParameter; for (int j = 0; j < _candidates.length; j++) { Member otherMember = getCandidateAt(j); if (otherMember is ForwardingNode) continue; List<TypeParameter> otherTypeParameters = otherMember.function.typeParameters; if (otherTypeParameters.length <= i) continue; TypeParameter otherTypeParameter = otherTypeParameters[i]; if (j == 0) superTypeParameter = otherTypeParameter; if (identical(otherMember, interfaceMember)) continue; if (otherTypeParameter.isGenericCovariantImpl) { isGenericCovariantImpl = true; } } if (isGenericCovariantImpl) { if (!superTypeParameter.isGenericCovariantImpl) { createImplIfNeeded(); } if (!typeParameter.isGenericCovariantImpl) { createStubIfNeeded(); stub.function.typeParameters[i].isGenericCovariantImpl = true; } } } return stub; } void _createForwardingImplIfNeeded(FunctionNode function) { if (function.body != null) { // There is already an implementation; nothing further needs to be done. return; } // Find the concrete implementation in the superclass; this is what we need // to forward to. If we can't find one, then the method is fully abstract // and we don't need to do anything. Class superclass = enclosingClass.superclass; if (superclass == null) return; Procedure procedure = function.parent; Member superTarget = hierarchy.getDispatchTargetKernel( superclass, procedure.name, kind == ProcedureKind.Setter); if (superTarget == null) return; if (superTarget is Procedure && superTarget.isForwardingStub) { superTarget = _getForwardingStubSuperTarget(superTarget); } procedure.isAbstract = false; if (!procedure.isForwardingStub) { // This procedure exists abstractly in the source code; we need to make it // concrete and give it a body that is a forwarding stub. This situation // is called a "forwarding semi-stub". procedure.isForwardingStub = true; procedure.isForwardingSemiStub = true; } List<Expression> positionalArguments = function.positionalParameters .map<Expression>((parameter) => new VariableGet(parameter)) .toList(); List<NamedExpression> namedArguments = function.namedParameters .map((parameter) => new NamedExpression(parameter.name, new VariableGet(parameter))) .toList(); List<DartType> typeArguments = function.typeParameters .map<DartType>((typeParameter) => new TypeParameterType(typeParameter)) .toList(); Arguments arguments = new Arguments(positionalArguments, types: typeArguments, named: namedArguments); Expression superCall; switch (kind) { case ProcedureKind.Method: case ProcedureKind.Operator: superCall = new SuperMethodInvocation(name, arguments, superTarget); break; case ProcedureKind.Getter: superCall = new SuperPropertyGet(name, superTarget); break; case ProcedureKind.Setter: superCall = new SuperPropertySet(name, positionalArguments[0], superTarget); break; default: unhandled('$kind', '_createForwardingImplIfNeeded', -1, null); break; } function.body = new ReturnStatement(superCall)..parent = function; procedure.transformerFlags |= TransformerFlag.superCalls; procedure.forwardingStubSuperTarget = superTarget; } /// Creates a forwarding stub based on the given [target]. Procedure _createForwardingStub(Substitution substitution, Member target) { VariableDeclaration copyParameter(VariableDeclaration parameter) { return new VariableDeclaration(parameter.name, type: substitution.substituteType(parameter.type), isCovariant: parameter.isCovariant) ..isGenericCovariantImpl = parameter.isGenericCovariantImpl; } List<TypeParameter> targetTypeParameters = target.function?.typeParameters ?? []; List<TypeParameter> typeParameters; if (targetTypeParameters.isNotEmpty) { typeParameters = new List<TypeParameter>.filled(targetTypeParameters.length, null); Map<TypeParameter, DartType> additionalSubstitution = <TypeParameter, DartType>{}; for (int i = 0; i < targetTypeParameters.length; i++) { TypeParameter targetTypeParameter = targetTypeParameters[i]; TypeParameter typeParameter = new TypeParameter( targetTypeParameter.name, null) ..isGenericCovariantImpl = targetTypeParameter.isGenericCovariantImpl; typeParameters[i] = typeParameter; additionalSubstitution[targetTypeParameter] = new TypeParameterType(typeParameter); } substitution = Substitution.combine( substitution, Substitution.fromMap(additionalSubstitution)); for (int i = 0; i < typeParameters.length; i++) { typeParameters[i].bound = substitution.substituteType(targetTypeParameters[i].bound); } } List<VariableDeclaration> positionalParameters = getPositionalParameters(target).map(copyParameter).toList(); List<VariableDeclaration> namedParameters = target.function?.namedParameters?.map(copyParameter)?.toList() ?? []; FunctionNode function = new FunctionNode(null, positionalParameters: positionalParameters, namedParameters: namedParameters, typeParameters: typeParameters, requiredParameterCount: getRequiredParameterCount(target), returnType: substitution.substituteType(getReturnType(target))); Member finalTarget; if (target is Procedure && target.isForwardingStub) { finalTarget = target.forwardingStubInterfaceTarget; } else { finalTarget = target; } return new Procedure(name, kind, function, isAbstract: true, isForwardingStub: true, fileUri: enclosingClass.fileUri, forwardingStubInterfaceTarget: finalTarget) ..startFileOffset = enclosingClass.fileOffset ..fileOffset = enclosingClass.fileOffset ..parent = enclosingClass; } /// Returns the [i]th element of [_candidates], finalizing it if necessary. Member getCandidateAt(int i) { ClassMember candidate = _candidates[i]; assert(candidate is! DelayedMember); return candidate.member; } static Member _getForwardingStubSuperTarget(Procedure forwardingStub) { // TODO(paulberry): when dartbug.com/31562 is fixed, this should become // easier. ReturnStatement body = forwardingStub.function.body; Expression expression = body.expression; if (expression is SuperMethodInvocation) { return expression.interfaceTarget; } else if (expression is SuperPropertySet) { return expression.interfaceTarget; } else { return unhandled('${expression.runtimeType}', '_getForwardingStubSuperTarget', -1, null); } } Substitution _substitutionFor(Member candidate, Class class_) { return Substitution.fromInterfaceType(hierarchy.getKernelTypeAsInstanceOf( class_.thisType, candidate.enclosingClass)); } List<VariableDeclaration> getPositionalParameters(Member member) { if (member is Field) { if (kind == ProcedureKind.Setter) { return <VariableDeclaration>[ new VariableDeclaration("_", type: member.type, isCovariant: member.isCovariant) ..isGenericCovariantImpl = member.isGenericCovariantImpl ]; } else { return <VariableDeclaration>[]; } } else { return member.function.positionalParameters; } } int getRequiredParameterCount(Member member) { switch (kind) { case ProcedureKind.Getter: return 0; case ProcedureKind.Setter: return 1; default: return member.function.requiredParameterCount; } } DartType getReturnType(Member member) { switch (kind) { case ProcedureKind.Getter: return member is Field ? member.type : member.function.returnType; case ProcedureKind.Setter: return const VoidType(); default: return member.function.returnType; } } }
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/kernel/load_library_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. import 'package:kernel/ast.dart' show Arguments, DartType, DynamicType, FunctionNode, InterfaceType, LibraryDependency, LoadLibrary, Member, Name, Procedure, ProcedureKind, ReturnStatement; import '../source/source_library_builder.dart' show SourceLibraryBuilder; import '../builder/declaration.dart'; import 'forest.dart' show Forest; /// Builder to represent the `deferLibrary.loadLibrary` calls and tear-offs. class LoadLibraryBuilder extends BuilderImpl { final SourceLibraryBuilder parent; final LibraryDependency importDependency; /// Offset of the import prefix. final int charOffset; /// Synthetic static method to represent the tear-off of 'loadLibrary'. If /// null, no tear-offs were seen in the code and no method is generated. Member tearoff; LoadLibraryBuilder(this.parent, this.importDependency, this.charOffset); Uri get fileUri => parent.fileUri; LoadLibrary createLoadLibrary( int charOffset, Forest forest, Arguments arguments) { return forest.createLoadLibrary(charOffset, importDependency, arguments); } Procedure createTearoffMethod(Forest forest) { if (tearoff != null) return tearoff; LoadLibrary expression = createLoadLibrary(charOffset, forest, null); String prefix = expression.import.name; tearoff = new Procedure( new Name('__loadLibrary_$prefix', parent.library), ProcedureKind.Method, new FunctionNode(new ReturnStatement(expression), returnType: new InterfaceType(parent.loader.coreTypes.futureClass, <DartType>[const DynamicType()])), fileUri: parent.library.fileUri, isStatic: true) ..startFileOffset = charOffset ..fileOffset = charOffset; return tearoff; } @override String get fullNameForErrors => 'loadLibrary'; }
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/kernel/kernel_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.kernel_builder; import 'package:kernel/ast.dart' show Combinator, Constructor, Initializer, Procedure, RedirectingInitializer; import '../combinator.dart' as fasta; export '../builder/builder.dart'; export 'class_hierarchy_builder.dart' show ClassHierarchyBuilder, DelayedMember, DelayedOverrideCheck; export 'implicit_field_type.dart' show ImplicitFieldType; export 'kernel_variable_builder.dart' show VariableBuilder; export 'load_library_builder.dart' show LoadLibraryBuilder; export 'unlinked_scope.dart' show UnlinkedDeclaration; int compareProcedures(Procedure a, Procedure b) { int i = "${a.fileUri}".compareTo("${b.fileUri}"); if (i != 0) return i; return a.fileOffset.compareTo(b.fileOffset); } bool isRedirectingGenerativeConstructorImplementation(Constructor constructor) { List<Initializer> initializers = constructor.initializers; return initializers.length == 1 && initializers.single is RedirectingInitializer; } List<Combinator> toKernelCombinators(List<fasta.Combinator> fastaCombinators) { if (fastaCombinators == null) { // Note: it's safe to return null here as Kernel's LibraryDependency will // convert null to an empty list. return null; } List<Combinator> result = new List<Combinator>.filled( fastaCombinators.length, null, growable: true); for (int i = 0; i < fastaCombinators.length; i++) { fasta.Combinator combinator = fastaCombinators[i]; List<String> nameList = combinator.names.toList(); result[i] = combinator.isShow ? new Combinator.show(nameList) : new Combinator.hide(nameList); } 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/kernel/utils.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 'dart:io' show BytesBuilder, File, IOSink; import 'dart:typed_data' show Uint8List; import 'package:kernel/clone.dart' show CloneVisitor; import 'package:kernel/ast.dart' show Class, Component, DartType, Library, Procedure, Supertype, TreeNode, TypeParameter, TypeParameterType; import 'package:kernel/binary/ast_to_binary.dart' show BinaryPrinter; import 'package:kernel/binary/limited_ast_to_binary.dart' show LimitedBinaryPrinter; import 'package:kernel/text/ast_to_text.dart' show Printer; /// Print the given [component]. Do nothing if it is `null`. If the /// [libraryFilter] is provided, then only libraries that satisfy it are /// printed. void printComponentText(Component component, {bool libraryFilter(Library library)}) { if (component == null) return; StringBuffer sb = new StringBuffer(); Printer printer = new Printer(sb); printer.writeComponentProblems(component); for (Library library in component.libraries) { if (libraryFilter != null && !libraryFilter(library)) continue; printer.writeLibraryFile(library); } printer.writeConstantTable(component); print(sb); } /// Write [component] to file only including libraries that match [filter]. Future<Null> writeComponentToFile(Component component, Uri uri, {bool filter(Library library)}) async { File output = new File.fromUri(uri); IOSink sink = output.openWrite(); try { BinaryPrinter printer = filter == null ? new BinaryPrinter(sink) : new LimitedBinaryPrinter(sink, filter ?? (_) => true, false); printer.writeComponentFile(component); } finally { await sink.close(); } } /// Serialize the libraries in [component] that match [filter]. Uint8List serializeComponent(Component component, {bool filter(Library library), bool includeSources: true, bool includeOffsets: true}) { ByteSink byteSink = new ByteSink(); BinaryPrinter printer = filter == null ? new BinaryPrinter(byteSink, includeSources: includeSources, includeOffsets: includeOffsets) : new LimitedBinaryPrinter(byteSink, filter, !includeSources, includeOffsets: includeOffsets); printer.writeComponentFile(component); return byteSink.builder.takeBytes(); } const String kDebugClassName = "#DebugClass"; Component createExpressionEvaluationComponent(Procedure procedure) { Library realLibrary = procedure.enclosingLibrary; Library fakeLibrary = new Library(new Uri(scheme: 'evaluate', path: 'source')) ..setLanguageVersion( realLibrary.languageVersionMajor, realLibrary.languageVersionMinor); if (procedure.parent is Class) { Class realClass = procedure.parent; Class fakeClass = new Class(name: kDebugClassName)..parent = fakeLibrary; Map<TypeParameter, TypeParameter> typeParams = <TypeParameter, TypeParameter>{}; Map<TypeParameter, DartType> typeSubstitution = <TypeParameter, DartType>{}; for (TypeParameter typeParam in realClass.typeParameters) { TypeParameter newNode = new TypeParameter(typeParam.name) ..parent = fakeClass; typeParams[typeParam] = newNode; typeSubstitution[typeParam] = new TypeParameterType(newNode); } CloneVisitor cloner = new CloneVisitor( typeSubstitution: typeSubstitution, typeParams: typeParams); for (TypeParameter typeParam in realClass.typeParameters) { fakeClass.typeParameters.add(typeParam.accept<TreeNode>(cloner)); } if (realClass.supertype != null) { // supertype is null for Object. fakeClass.supertype = new Supertype.byReference( realClass.supertype.className, realClass.supertype.typeArguments.map(cloner.visitType).toList()); } // Rebind the type parameters in the procedure. procedure = procedure.accept<TreeNode>(cloner); procedure.parent = fakeClass; fakeClass.procedures.add(procedure); fakeLibrary.classes.add(fakeClass); } else { fakeLibrary.procedures.add(procedure); procedure.parent = fakeLibrary; } // TODO(vegorov) find a way to preserve metadata. return new Component(libraries: [fakeLibrary]); } List<int> serializeProcedure(Procedure procedure) { return serializeComponent(createExpressionEvaluationComponent(procedure)); } /// A [Sink] that directly writes data into a byte builder. class ByteSink implements Sink<List<int>> { final BytesBuilder builder = new BytesBuilder(); void add(List<int> data) { builder.add(data); } void close() {} }
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/kernel/types.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 fasta.types; import 'package:kernel/ast.dart' show BottomType, Class, DartType, DynamicType, FunctionType, InterfaceType, InvalidType, NamedType, Nullability, TypeParameter, TypeParameterType, TypedefType, VoidType; import 'package:kernel/type_algebra.dart' show Substitution; import 'package:kernel/type_environment.dart'; import 'kernel_builder.dart' show ClassHierarchyBuilder; class Types { final ClassHierarchyBuilder hierarchy; Types(this.hierarchy); /// Returns true if [s] is a subtype of [t]. bool isSubtypeOfKernel(DartType s, DartType t, SubtypeCheckMode mode) { if (s is InvalidType) { // InvalidType is a bottom type. return true; } if (t is InvalidType) { return false; } return isSubtypeOfKernelNullability(s, s.nullability, t, t.nullability); } bool isSubtypeOfKernelNullability( DartType s, Nullability sNullability, DartType t, tNullability) { if (s is BottomType) { return true; // Rule 3. } if (t is DynamicType) { return true; // Rule 2. } if (t is VoidType) { return true; // Rule 2. } if (t is BottomType) { return false; } if (t is InterfaceType) { Class cls = t.classNode; if (cls == hierarchy.objectClass) { return true; // Rule 2. } if (cls == hierarchy.futureOrClass) { const IsFutureOrSubtypeOf relation = const IsFutureOrSubtypeOf(); if (s is DynamicType) { return relation.isDynamicRelated( s, sNullability, t, tNullability, this); } else if (s is VoidType) { return relation.isVoidRelated(s, sNullability, t, tNullability, this); } else if (s is InterfaceType) { return s.classNode == hierarchy.futureOrClass ? relation.isFutureOrRelated( s, sNullability, t, tNullability, this) : relation.isInterfaceRelated( s, sNullability, t, tNullability, this); } else if (s is FunctionType) { return relation.isFunctionRelated( s, sNullability, t, tNullability, this); } else if (s is TypeParameterType) { return s.promotedBound == null ? relation.isTypeParameterRelated( s, sNullability, t, tNullability, this) : relation.isIntersectionRelated( s, sNullability, t, tNullability, this); } else if (s is TypedefType) { return relation.isTypedefRelated( s, sNullability, t, tNullability, this); } } else { const IsInterfaceSubtypeOf relation = const IsInterfaceSubtypeOf(); if (s is DynamicType) { return relation.isDynamicRelated( s, sNullability, t, tNullability, this); } else if (s is VoidType) { return relation.isVoidRelated(s, sNullability, t, tNullability, this); } else if (s is InterfaceType) { return s.classNode == hierarchy.futureOrClass ? relation.isFutureOrRelated( s, sNullability, t, tNullability, this) : relation.isInterfaceRelated( s, sNullability, t, tNullability, this); } else if (s is FunctionType) { return relation.isFunctionRelated( s, sNullability, t, tNullability, this); } else if (s is TypeParameterType) { return s.promotedBound == null ? relation.isTypeParameterRelated( s, sNullability, t, tNullability, this) : relation.isIntersectionRelated( s, sNullability, t, tNullability, this); } else if (s is TypedefType) { return relation.isTypedefRelated( s, sNullability, t, tNullability, this); } } } else if (t is FunctionType) { const IsFunctionSubtypeOf relation = const IsFunctionSubtypeOf(); if (s is DynamicType) { return relation.isDynamicRelated( s, sNullability, t, tNullability, this); } else if (s is VoidType) { return relation.isVoidRelated(s, sNullability, t, tNullability, this); } else if (s is InterfaceType) { return s.classNode == hierarchy.futureOrClass ? relation.isFutureOrRelated(s, sNullability, t, tNullability, this) : relation.isInterfaceRelated( s, sNullability, t, tNullability, this); } else if (s is FunctionType) { return relation.isFunctionRelated( s, sNullability, t, tNullability, this); } else if (s is TypeParameterType) { return s.promotedBound == null ? relation.isTypeParameterRelated( s, sNullability, t, tNullability, this) : relation.isIntersectionRelated( s, sNullability, t, tNullability, this); } else if (s is TypedefType) { return relation.isTypedefRelated( s, sNullability, t, tNullability, this); } } else if (t is TypeParameterType) { if (t.promotedBound == null) { const IsTypeParameterSubtypeOf relation = const IsTypeParameterSubtypeOf(); if (s is DynamicType) { return relation.isDynamicRelated( s, sNullability, t, tNullability, this); } else if (s is VoidType) { return relation.isVoidRelated(s, sNullability, t, tNullability, this); } else if (s is InterfaceType) { return s.classNode == hierarchy.futureOrClass ? relation.isFutureOrRelated( s, sNullability, t, tNullability, this) : relation.isInterfaceRelated( s, sNullability, t, tNullability, this); } else if (s is FunctionType) { return relation.isFunctionRelated( s, sNullability, t, tNullability, this); } else if (s is TypeParameterType) { return s.promotedBound == null ? relation.isTypeParameterRelated( s, sNullability, t, tNullability, this) : relation.isIntersectionRelated( s, sNullability, t, tNullability, this); } else if (s is TypedefType) { return relation.isTypedefRelated( s, sNullability, t, tNullability, this); } } else { const IsIntersectionSubtypeOf relation = const IsIntersectionSubtypeOf(); if (s is DynamicType) { return relation.isDynamicRelated( s, sNullability, t, tNullability, this); } else if (s is VoidType) { return relation.isVoidRelated(s, sNullability, t, tNullability, this); } else if (s is InterfaceType) { return s.classNode == hierarchy.futureOrClass ? relation.isFutureOrRelated( s, sNullability, t, tNullability, this) : relation.isInterfaceRelated( s, sNullability, t, tNullability, this); } else if (s is FunctionType) { return relation.isFunctionRelated( s, sNullability, t, tNullability, this); } else if (s is TypeParameterType) { return s.promotedBound == null ? relation.isTypeParameterRelated( s, sNullability, t, tNullability, this) : relation.isIntersectionRelated( s, sNullability, t, tNullability, this); } else if (s is TypedefType) { return relation.isTypedefRelated( s, sNullability, t, tNullability, this); } } } else if (t is TypedefType) { const IsTypedefSubtypeOf relation = const IsTypedefSubtypeOf(); if (s is DynamicType) { return relation.isDynamicRelated( s, sNullability, t, tNullability, this); } else if (s is VoidType) { return relation.isVoidRelated(s, sNullability, t, tNullability, this); } else if (s is InterfaceType) { return s.classNode == hierarchy.futureOrClass ? relation.isFutureOrRelated(s, sNullability, t, tNullability, this) : relation.isInterfaceRelated( s, sNullability, t, tNullability, this); } else if (s is FunctionType) { return relation.isFunctionRelated( s, sNullability, t, tNullability, this); } else if (s is TypeParameterType) { return s.promotedBound == null ? relation.isTypeParameterRelated( s, sNullability, t, tNullability, this) : relation.isIntersectionRelated( s, sNullability, t, tNullability, this); } else if (s is TypedefType) { return relation.isTypedefRelated( s, sNullability, t, tNullability, this); } } else { throw "Unhandled type: ${t.runtimeType}"; } throw "Unhandled type combination: ${t.runtimeType} ${s.runtimeType}"; } /// Returns true if all types in [s] and [t] pairwise are subtypes. bool areSubtypesOfKernel(List<DartType> s, List<DartType> t) { if (s.length != t.length) { throw "Numbers of type arguments don't match $s $t."; } for (int i = 0; i < s.length; i++) { if (!isSubtypeOfKernel( s[i], t[i], SubtypeCheckMode.ignoringNullabilities)) return false; } return true; } bool isSameTypeKernel(DartType s, DartType t) { return isSubtypeOfKernel(s, t, SubtypeCheckMode.ignoringNullabilities) && isSubtypeOfKernel(t, s, SubtypeCheckMode.ignoringNullabilities); } } abstract class TypeRelation<T extends DartType> { const TypeRelation(); bool isDynamicRelated(DynamicType s, Nullability sNullability, T t, Nullability tNullability, Types types); bool isVoidRelated(VoidType s, Nullability sNullability, T t, Nullability tNullability, Types types); bool isInterfaceRelated(InterfaceType s, Nullability sNullability, T t, Nullability tNullability, Types types); bool isIntersectionRelated( TypeParameterType intersection, Nullability intersectionNullability, T t, Nullability tNullability, Types types); bool isFunctionRelated(FunctionType s, Nullability sNullability, T t, Nullability tNullability, Types types); bool isFutureOrRelated( InterfaceType futureOr, Nullability futureOrNullability, T t, Nullability tNullability, Types types); bool isTypeParameterRelated(TypeParameterType s, Nullability sNullability, T t, Nullability tNullability, Types types); bool isTypedefRelated(TypedefType s, Nullability sNullability, T t, Nullability tNullability, Types types); } class IsInterfaceSubtypeOf extends TypeRelation<InterfaceType> { const IsInterfaceSubtypeOf(); @override bool isInterfaceRelated(InterfaceType s, Nullability sNullability, InterfaceType t, Nullability tNullability, Types types) { if (s.classNode == types.hierarchy.nullClass) { // This is an optimization, to avoid instantiating unnecessary type // arguments in getKernelTypeAsInstanceOf. return true; } InterfaceType asSupertype = types.hierarchy.getKernelTypeAsInstanceOf(s, t.classNode); if (asSupertype == null) { return false; } else { return types.areSubtypesOfKernel( asSupertype.typeArguments, t.typeArguments); } } @override bool isTypeParameterRelated(TypeParameterType s, Nullability sNullability, InterfaceType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s.parameter.bound, t, SubtypeCheckMode.ignoringNullabilities); } @override bool isFutureOrRelated( InterfaceType futureOr, Nullability futureOrNullability, InterfaceType t, Nullability tNullability, Types types) { List<DartType> arguments = futureOr.typeArguments; if (!types.isSubtypeOfKernel( arguments.single, t, SubtypeCheckMode.ignoringNullabilities)) { return false; // Rule 7.1 } if (!types.isSubtypeOfKernel( new InterfaceType(types.hierarchy.futureClass, arguments), t, SubtypeCheckMode.ignoringNullabilities)) { return false; // Rule 7.2 } return true; } @override bool isIntersectionRelated( TypeParameterType intersection, Nullability intersectionNullability, InterfaceType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel(intersection.promotedBound, t, SubtypeCheckMode.ignoringNullabilities); // Rule 12. } @override bool isDynamicRelated(DynamicType s, Nullability sNullability, InterfaceType t, Nullability tNullability, Types types) { return false; } @override bool isFunctionRelated(FunctionType s, Nullability sNullability, InterfaceType t, Nullability tNullability, Types types) { return t.classNode == types.hierarchy.functionClass; // Rule 14. } @override bool isTypedefRelated(TypedefType s, Nullability sNullability, InterfaceType t, Nullability tNullability, Types types) { // Rule 5. return types.isSubtypeOfKernel( s.unalias, t, SubtypeCheckMode.ignoringNullabilities); } @override bool isVoidRelated(VoidType s, Nullability sNullability, InterfaceType t, Nullability tNullability, Types types) { return false; } } class IsFunctionSubtypeOf extends TypeRelation<FunctionType> { const IsFunctionSubtypeOf(); @override bool isFunctionRelated(FunctionType s, Nullability sNullability, FunctionType t, Nullability tNullability, Types types) { List<TypeParameter> sTypeVariables = s.typeParameters; List<TypeParameter> tTypeVariables = t.typeParameters; if (sTypeVariables.length != tTypeVariables.length) return false; if (sTypeVariables.isNotEmpty) { // If the function types have type variables, we alpha-rename the type // variables of [s] to use those of [t]. List<DartType> typeVariableSubstitution = <DartType>[]; bool secondBoundsCheckNeeded = false; for (int i = 0; i < sTypeVariables.length; i++) { TypeParameter sTypeVariable = sTypeVariables[i]; TypeParameter tTypeVariable = tTypeVariables[i]; if (!types.isSameTypeKernel(sTypeVariable.bound, tTypeVariable.bound)) { // If the bounds aren't the same, we need to try again after // computing the substitution of type variables. secondBoundsCheckNeeded = true; } typeVariableSubstitution.add(new TypeParameterType(tTypeVariable)); } Substitution substitution = Substitution.fromPairs(sTypeVariables, typeVariableSubstitution); if (secondBoundsCheckNeeded) { for (int i = 0; i < sTypeVariables.length; i++) { TypeParameter sTypeVariable = sTypeVariables[i]; TypeParameter tTypeVariable = tTypeVariables[i]; if (!types.isSameTypeKernel( substitution.substituteType(sTypeVariable.bound), tTypeVariable.bound)) { return false; } } } s = substitution.substituteType(s.withoutTypeParameters); } if (!types.isSubtypeOfKernel( s.returnType, t.returnType, SubtypeCheckMode.ignoringNullabilities)) { return false; } List<DartType> sPositional = s.positionalParameters; List<DartType> tPositional = t.positionalParameters; if (s.requiredParameterCount > t.requiredParameterCount) { // Rule 15, n1 <= n2. return false; } if (sPositional.length < tPositional.length) { // Rule 15, n1 + k1 >= n2 + k2. return false; } for (int i = 0; i < tPositional.length; i++) { if (!types.isSubtypeOfKernel(tPositional[i], sPositional[i], SubtypeCheckMode.ignoringNullabilities)) { // Rule 15, Tj <: Sj. return false; } } List<NamedType> sNamed = s.namedParameters; List<NamedType> tNamed = t.namedParameters; if (sNamed.isNotEmpty || tNamed.isNotEmpty) { // Rule 16, the number of positional parameters must be the same. if (sPositional.length != tPositional.length) return false; if (s.requiredParameterCount != t.requiredParameterCount) return false; // Rule 16, the parameter names of [t] must be a subset of those of // [s]. Also, for the intersection, the type of the parameter of [t] must // be a subtype of the type of the parameter of [s]. int sCount = 0; for (int tCount = 0; tCount < tNamed.length; tCount++) { String name = tNamed[tCount].name; for (; sCount < sNamed.length; sCount++) { if (sNamed[sCount].name == name) break; } if (sCount == sNamed.length) return false; if (!types.isSubtypeOfKernel(tNamed[tCount].type, sNamed[sCount].type, SubtypeCheckMode.ignoringNullabilities)) { return false; } } } return true; } @override bool isInterfaceRelated(InterfaceType s, Nullability sNullability, FunctionType t, Nullability tNullability, Types types) { return s.classNode == types.hierarchy.nullClass; // Rule 4. } @override bool isDynamicRelated(DynamicType s, Nullability sNullability, FunctionType t, Nullability tNullability, Types types) { return false; } @override bool isFutureOrRelated( InterfaceType futureOr, Nullability futureOrNullability, FunctionType t, Nullability tNullability, Types types) { return false; } @override bool isIntersectionRelated( TypeParameterType intersection, Nullability intersectionNullability, FunctionType t, Nullability tNullability, Types types) { // Rule 12. return types.isSubtypeOfKernel( intersection.promotedBound, t, SubtypeCheckMode.ignoringNullabilities); } @override bool isTypeParameterRelated(TypeParameterType s, Nullability sNullability, FunctionType t, Nullability tNullability, Types types) { // Rule 13. return types.isSubtypeOfKernel( s.parameter.bound, t, SubtypeCheckMode.ignoringNullabilities); } @override bool isTypedefRelated(TypedefType s, Nullability sNullability, FunctionType t, Nullability tNullability, Types types) { // Rule 5. return types.isSubtypeOfKernel( s.unalias, t, SubtypeCheckMode.ignoringNullabilities); } @override bool isVoidRelated(VoidType s, Nullability sNullability, FunctionType t, Nullability tNullability, Types types) { return false; } } class IsTypeParameterSubtypeOf extends TypeRelation<TypeParameterType> { const IsTypeParameterSubtypeOf(); @override bool isTypeParameterRelated(TypeParameterType s, Nullability sNullability, TypeParameterType t, Nullability tNullability, Types types) { return s.parameter == t.parameter || // Rule 13. types.isSubtypeOfKernel( s.bound, t, SubtypeCheckMode.ignoringNullabilities); } @override bool isIntersectionRelated( TypeParameterType intersection, Nullability intersectionNullability, TypeParameterType t, Nullability tNullability, Types types) { return intersection.parameter == t.parameter; // Rule 8. } @override bool isInterfaceRelated(InterfaceType s, Nullability sNullability, TypeParameterType t, Nullability tNullability, Types types) { return s.classNode == types.hierarchy.nullClass; // Rule 4. } @override bool isDynamicRelated(DynamicType s, Nullability sNullability, TypeParameterType t, Nullability tNullability, Types types) { return false; } @override bool isFunctionRelated(FunctionType s, Nullability sNullability, TypeParameterType t, Nullability tNullability, Types types) { return false; } @override bool isFutureOrRelated( InterfaceType futureOr, Nullability futureOrNullability, TypeParameterType t, Nullability tNullability, Types types) { return false; } @override bool isTypedefRelated(TypedefType s, Nullability sNullability, TypeParameterType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s.unalias, t, SubtypeCheckMode.ignoringNullabilities); } @override bool isVoidRelated(VoidType s, Nullability sNullability, TypeParameterType t, Nullability tNullability, Types types) { return false; } } class IsTypedefSubtypeOf extends TypeRelation<TypedefType> { const IsTypedefSubtypeOf(); @override bool isInterfaceRelated(InterfaceType s, Nullability sNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s, t.unalias, SubtypeCheckMode.ignoringNullabilities); } @override bool isDynamicRelated(DynamicType s, Nullability sNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s, t.unalias, SubtypeCheckMode.ignoringNullabilities); } @override bool isFunctionRelated(FunctionType s, Nullability sNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s, t.unalias, SubtypeCheckMode.ignoringNullabilities); } @override bool isFutureOrRelated( InterfaceType futureOr, Nullability futureOrNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( futureOr, t.unalias, SubtypeCheckMode.ignoringNullabilities); } @override bool isIntersectionRelated( TypeParameterType intersection, Nullability intersectionNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( intersection, t.unalias, SubtypeCheckMode.ignoringNullabilities); } @override bool isTypeParameterRelated(TypeParameterType s, Nullability sNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s, t.unalias, SubtypeCheckMode.ignoringNullabilities); } @override bool isTypedefRelated(TypedefType s, Nullability sNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s.unalias, t.unalias, SubtypeCheckMode.ignoringNullabilities); } @override bool isVoidRelated(VoidType s, Nullability sNullability, TypedefType t, Nullability tNullability, Types types) { return types.isSubtypeOfKernel( s, t.unalias, SubtypeCheckMode.ignoringNullabilities); } } class IsFutureOrSubtypeOf extends TypeRelation<InterfaceType> { const IsFutureOrSubtypeOf(); @override bool isInterfaceRelated(InterfaceType s, Nullability sNullability, InterfaceType futureOr, Nullability futureOrNullability, Types types) { List<DartType> arguments = futureOr.typeArguments; if (types.isSubtypeOfKernel( s, arguments.single, SubtypeCheckMode.ignoringNullabilities)) { return true; // Rule 11. } // Rule 10. return types.isSubtypeOfKernel( s, new InterfaceType(types.hierarchy.futureClass, arguments), SubtypeCheckMode.ignoringNullabilities); } @override bool isFutureOrRelated( InterfaceType sFutureOr, Nullability sFutureOrNullability, InterfaceType tFutureOr, Nullability tFutureOrNullability, Types types) { // This follows from combining rules 7, 10, and 11. return types.isSubtypeOfKernel(sFutureOr.typeArguments.single, tFutureOr.typeArguments.single, SubtypeCheckMode.ignoringNullabilities); } @override bool isDynamicRelated(DynamicType s, Nullability sNullability, InterfaceType futureOr, Nullability futureOrNullability, Types types) { // Rule 11. return types.isSubtypeOfKernel(s, futureOr.typeArguments.single, SubtypeCheckMode.ignoringNullabilities); } @override bool isVoidRelated(VoidType s, Nullability sNullability, InterfaceType futureOr, Nullability futureOrNullability, Types types) { // Rule 11. return types.isSubtypeOfKernel(s, futureOr.typeArguments.single, SubtypeCheckMode.ignoringNullabilities); } @override bool isTypeParameterRelated(TypeParameterType s, Nullability sNullability, InterfaceType futureOr, Nullability futureOrNullability, Types types) { List<DartType> arguments = futureOr.typeArguments; if (types.isSubtypeOfKernel( s, arguments.single, SubtypeCheckMode.ignoringNullabilities)) { // Rule 11. return true; } if (types.isSubtypeOfKernel( s.parameter.bound, futureOr, SubtypeCheckMode.ignoringNullabilities)) { // Rule 13. return true; } // Rule 10. return types.isSubtypeOfKernel( s, new InterfaceType(types.hierarchy.futureClass, arguments), SubtypeCheckMode.ignoringNullabilities); } @override bool isFunctionRelated(FunctionType s, Nullability sNullability, InterfaceType futureOr, Nullability futureOrNullability, Types types) { // Rule 11. return types.isSubtypeOfKernel(s, futureOr.typeArguments.single, SubtypeCheckMode.ignoringNullabilities); } @override bool isIntersectionRelated( TypeParameterType intersection, Nullability intersectionNullability, InterfaceType futureOr, Nullability futureOrNullability, Types types) { if (isTypeParameterRelated(intersection, intersectionNullability, futureOr, futureOrNullability, types)) { // Rule 8. return true; } // Rule 12. return types.isSubtypeOfKernel(intersection.promotedBound, futureOr, SubtypeCheckMode.ignoringNullabilities); } @override bool isTypedefRelated(TypedefType s, Nullability sNullability, InterfaceType futureOr, Nullability futureOrNullability, Types types) { return types.isSubtypeOfKernel( s.unalias, futureOr, SubtypeCheckMode.ignoringNullabilities); } } class IsIntersectionSubtypeOf extends TypeRelation<TypeParameterType> { const IsIntersectionSubtypeOf(); @override bool isIntersectionRelated( TypeParameterType sIntersection, Nullability sIntersectionNullability, TypeParameterType tIntersection, Nullability tIntersectionNullability, Types types) { // Rule 9. return const IsTypeParameterSubtypeOf().isIntersectionRelated( sIntersection, sIntersectionNullability, tIntersection, tIntersectionNullability, types) && types.isSubtypeOfKernel(sIntersection, tIntersection.promotedBound, SubtypeCheckMode.ignoringNullabilities); } @override bool isTypeParameterRelated( TypeParameterType s, Nullability sNullability, TypeParameterType intersection, Nullability intersectionNullability, Types types) { // Rule 9. return const IsTypeParameterSubtypeOf().isTypeParameterRelated( s, sNullability, intersection, intersectionNullability, types) && types.isSubtypeOfKernel(s, intersection.promotedBound, SubtypeCheckMode.ignoringNullabilities); } @override bool isInterfaceRelated( InterfaceType s, Nullability sNullability, TypeParameterType intersection, Nullability intersectionNullability, Types types) { return s.classNode == types.hierarchy.nullClass; // Rule 4. } @override bool isDynamicRelated( DynamicType s, Nullability sNullability, TypeParameterType intersection, Nullability intersectionNullability, Types types) { return false; } @override bool isFunctionRelated( FunctionType s, Nullability sNullability, TypeParameterType intersection, Nullability intersectionNullability, Types types) { return false; } @override bool isFutureOrRelated( InterfaceType futureOr, Nullability futureOrNullability, TypeParameterType intersection, Nullability intersectionNullability, Types types) { return false; } @override bool isTypedefRelated( TypedefType s, Nullability sNullability, TypeParameterType intersection, Nullability intersectionNullability, Types types) { // Rule 5. return types.isSubtypeOfKernel( s.unalias, intersection, SubtypeCheckMode.ignoringNullabilities); } @override bool isVoidRelated( VoidType s, Nullability sNullability, TypeParameterType intersection, Nullability intersectionNullability, Types types) { 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/kernel/kernel_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.kernel_variable_builder; import 'package:kernel/ast.dart' show VariableDeclaration; import '../builder/declaration.dart'; class VariableBuilder extends BuilderImpl { @override final Builder parent; @override final Uri fileUri; final VariableDeclaration variable; VariableBuilder(this.variable, this.parent, this.fileUri); @override int get charOffset => variable.fileOffset; bool get isLocal => true; bool get isConst => variable.isConst; bool get isFinal => variable.isFinal; VariableDeclaration get target => variable; @override String get fullNameForErrors => variable.name ?? "<unnamed>"; }
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/kernel/class_hierarchy_builder.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.class_hierarchy_builder; import 'package:kernel/ast.dart' show Class, DartType, Field, FunctionNode, InterfaceType, InvalidType, Member, Name, Procedure, ProcedureKind, Supertype, TypeParameter, TypeParameterType, VariableDeclaration; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy; import 'package:kernel/core_types.dart' show CoreTypes; import 'package:kernel/type_algebra.dart' show Substitution; import 'package:kernel/type_environment.dart'; import '../dill/dill_member_builder.dart' show DillMemberBuilder; import '../loader.dart' show Loader; import '../messages.dart' show LocatedMessage, Message, messageDeclaredMemberConflictsWithInheritedMember, messageDeclaredMemberConflictsWithInheritedMemberCause, messageInheritedMembersConflict, messageInheritedMembersConflictCause1, messageInheritedMembersConflictCause2, messageStaticAndInstanceConflict, messageStaticAndInstanceConflictCause, templateCantInferReturnTypeDueToInconsistentOverrides, templateCantInferTypeDueToInconsistentOverrides, templateCombinedMemberSignatureFailed, templateDuplicatedDeclaration, templateDuplicatedDeclarationCause, templateDuplicatedDeclarationUse, templateMissingImplementationCause, templateMissingImplementationNotAbstract; import '../names.dart' show noSuchMethodName; import '../problems.dart' show unhandled; import '../scope.dart' show Scope; import '../source/source_library_builder.dart' show SourceLibraryBuilder; import '../source/source_loader.dart' show SourceLoader; import '../type_inference/standard_bounds.dart' show StandardBounds; import '../type_inference/type_constraint_gatherer.dart' show TypeConstraintGatherer; import '../type_inference/type_inferrer.dart' show MixinInferrer; import '../type_inference/type_schema.dart' show UnknownType; import '../type_inference/type_schema_environment.dart' show TypeConstraint; import 'forwarding_node.dart' show ForwardingNode; import 'kernel_builder.dart' show Builder, FormalParameterBuilder, ImplicitFieldType, ClassBuilder, FieldBuilder, NamedTypeBuilder, ProcedureBuilder, LibraryBuilder, MemberBuilder, NullabilityBuilder, TypeBuilder, TypeVariableBuilder; import 'types.dart' show Types; const DebugLogger debug = const bool.fromEnvironment("debug.hierarchy") ? const DebugLogger() : null; class DebugLogger { const DebugLogger(); void log(Object message) => print(message); } int compareDeclarations(ClassMember a, ClassMember b) { return ClassHierarchy.compareMembers(a.member, b.member); } ProcedureKind memberKind(Member member) { return member is Procedure ? member.kind : null; } bool isNameVisibleIn(Name name, LibraryBuilder libraryBuilder) { return !name.isPrivate || name.library == libraryBuilder.library; } abstract class ClassMember { bool get isStatic; bool get isField; bool get isSetter; bool get isGetter; bool get isFinal; bool get isConst; Member get member; bool get isDuplicate; String get fullNameForErrors; ClassBuilder get classBuilder; Uri get fileUri; int get charOffset; } /// Returns true if [a] is a class member conflict with [b]. [a] is assumed to /// be declared in the class, [b] is assumed to be inherited. /// /// See the section named "Class Member Conflicts" in [Dart Programming /// Language Specification]( /// ../../../../../../docs/language/dartLangSpec.tex#classMemberConflicts). bool isInheritanceConflict(ClassMember a, ClassMember b) { if (a.isStatic) return true; if (memberKind(a.member) == memberKind(b.member)) return false; if (a.isField) return !(b.isField || b.isGetter || b.isSetter); if (b.isField) return !(a.isField || a.isGetter || a.isSetter); if (a.isSetter) return !(b.isGetter || b.isSetter); if (b.isSetter) return !(a.isGetter || a.isSetter); if (a is InterfaceConflict || b is InterfaceConflict) return false; return true; } bool impliesSetter(ClassMember declaration) { return declaration.isField && !(declaration.isFinal || declaration.isConst); } bool hasSameSignature(FunctionNode a, FunctionNode b) { List<TypeParameter> aTypeParameters = a.typeParameters; List<TypeParameter> bTypeParameters = b.typeParameters; int typeParameterCount = aTypeParameters.length; if (typeParameterCount != bTypeParameters.length) return false; Substitution substitution; if (typeParameterCount != 0) { List<DartType> types = new List<DartType>(typeParameterCount); for (int i = 0; i < typeParameterCount; i++) { types[i] = new TypeParameterType(aTypeParameters[i]); } substitution = Substitution.fromPairs(bTypeParameters, types); for (int i = 0; i < typeParameterCount; i++) { DartType aBound = aTypeParameters[i].bound; DartType bBound = substitution.substituteType(bTypeParameters[i].bound); if (aBound != bBound) return false; } } if (a.requiredParameterCount != b.requiredParameterCount) return false; List<VariableDeclaration> aPositionalParameters = a.positionalParameters; List<VariableDeclaration> bPositionalParameters = b.positionalParameters; if (aPositionalParameters.length != bPositionalParameters.length) { return false; } for (int i = 0; i < aPositionalParameters.length; i++) { VariableDeclaration aParameter = aPositionalParameters[i]; VariableDeclaration bParameter = bPositionalParameters[i]; if (aParameter.isCovariant != bParameter.isCovariant) return false; DartType aType = aParameter.type; DartType bType = bParameter.type; if (substitution != null) { bType = substitution.substituteType(bType); } if (aType != bType) return false; } List<VariableDeclaration> aNamedParameters = a.namedParameters; List<VariableDeclaration> bNamedParameters = b.namedParameters; if (aNamedParameters.length != bNamedParameters.length) return false; for (int i = 0; i < aNamedParameters.length; i++) { VariableDeclaration aParameter = aNamedParameters[i]; VariableDeclaration bParameter = bNamedParameters[i]; if (aParameter.isCovariant != bParameter.isCovariant) return false; if (aParameter.name != bParameter.name) return false; DartType aType = aParameter.type; DartType bType = bParameter.type; if (substitution != null) { bType = substitution.substituteType(bType); } if (aType != bType) return false; } DartType aReturnType = a.returnType; DartType bReturnType = b.returnType; if (substitution != null) { bReturnType = substitution.substituteType(bReturnType); } return aReturnType == bReturnType; } class ClassHierarchyBuilder { final Map<Class, ClassHierarchyNode> nodes = <Class, ClassHierarchyNode>{}; final ClassBuilder objectClassBuilder; final Loader loader; final Class objectClass; final Class futureClass; final Class futureOrClass; final Class functionClass; final Class nullClass; final List<DelayedOverrideCheck> overrideChecks = <DelayedOverrideCheck>[]; final List<DelayedMember> delayedMemberChecks = <DelayedMember>[]; // TODO(dmitryas): Consider removing this. final CoreTypes coreTypes; Types types; ClassHierarchyBuilder(this.objectClassBuilder, this.loader, this.coreTypes) : objectClass = objectClassBuilder.cls, futureClass = coreTypes.futureClass, futureOrClass = coreTypes.futureOrClass, functionClass = coreTypes.functionClass, nullClass = coreTypes.nullClass { types = new Types(this); } ClassHierarchyNode getNodeFromClass(ClassBuilder classBuilder) { return nodes[classBuilder.cls] ??= new ClassHierarchyNodeBuilder(this, classBuilder).build(); } ClassHierarchyNode getNodeFromType(TypeBuilder type) { ClassBuilder cls = getClass(type); return cls == null ? null : getNodeFromClass(cls); } ClassHierarchyNode getNodeFromKernelClass(Class cls) { return nodes[cls] ?? getNodeFromClass(loader.computeClassBuilderFromTargetClass(cls)); } TypeBuilder asSupertypeOf(Class cls, Class supertype) { ClassHierarchyNode clsNode = getNodeFromKernelClass(cls); if (cls == supertype) { return new NamedTypeBuilder( clsNode.classBuilder.name, const NullabilityBuilder.omitted(), null) ..bind(clsNode.classBuilder); } ClassHierarchyNode supertypeNode = getNodeFromKernelClass(supertype); List<TypeBuilder> supertypes = clsNode.superclasses; int depth = supertypeNode.depth; Builder supertypeDeclaration = supertypeNode.classBuilder; if (depth < supertypes.length) { TypeBuilder asSupertypeOf = supertypes[depth]; if (asSupertypeOf.declaration == supertypeDeclaration) { return asSupertypeOf; } } supertypes = clsNode.interfaces; for (int i = 0; i < supertypes.length; i++) { TypeBuilder type = supertypes[i]; if (type.declaration == supertypeDeclaration) return type; } return null; } InterfaceType getKernelTypeAsInstanceOf( InterfaceType type, Class superclass) { Class kernelClass = type.classNode; if (kernelClass == superclass) return type; if (kernelClass == nullClass) { if (superclass.typeParameters.isEmpty) { return coreTypes.legacyRawType(superclass); } else { // This is a safe fall-back for dealing with `Null`. It will likely be // faster to check for `Null` before calling this method. return new InterfaceType( superclass, new List<DartType>.filled( superclass.typeParameters.length, coreTypes.nullType)); } } NamedTypeBuilder supertype = asSupertypeOf(kernelClass, superclass); if (supertype == null) return null; if (supertype.arguments == null && superclass.typeParameters.isEmpty) { return coreTypes.legacyRawType(superclass); } return Substitution.fromInterfaceType(type) .substituteType(supertype.build(null)); } InterfaceType getKernelLegacyLeastUpperBound( InterfaceType type1, InterfaceType type2) { if (type1 == type2) return type1; ClassHierarchyNode node1 = getNodeFromKernelClass(type1.classNode); ClassHierarchyNode node2 = getNodeFromKernelClass(type2.classNode); Set<ClassHierarchyNode> nodes1 = node1.computeAllSuperNodes(this).toSet(); List<ClassHierarchyNode> nodes2 = node2.computeAllSuperNodes(this); List<ClassHierarchyNode> common = <ClassHierarchyNode>[]; for (int i = 0; i < nodes2.length; i++) { ClassHierarchyNode node = nodes2[i]; if (node == null) continue; if (nodes1.contains(node)) { DartType candidate1 = getKernelTypeAsInstanceOf(type1, node.classBuilder.cls); DartType candidate2 = getKernelTypeAsInstanceOf(type2, node.classBuilder.cls); if (candidate1 == candidate2) { common.add(node); } } } if (common.length == 1) return coreTypes.objectLegacyRawType; common.sort(ClassHierarchyNode.compareMaxInheritancePath); for (int i = 0; i < common.length - 1; i++) { ClassHierarchyNode node = common[i]; if (node.maxInheritancePath != common[i + 1].maxInheritancePath) { return getKernelTypeAsInstanceOf(type1, node.classBuilder.cls); } else { do { i++; } while (node.maxInheritancePath == common[i + 1].maxInheritancePath); } } return coreTypes.objectLegacyRawType; } Member getInterfaceMemberKernel(Class cls, Name name, bool isSetter) { return getNodeFromKernelClass(cls) .getInterfaceMember(name, isSetter) ?.member; } Member getDispatchTargetKernel(Class cls, Name name, bool isSetter) { return getNodeFromKernelClass(cls) .getDispatchTarget(name, isSetter) ?.member; } Member getCombinedMemberSignatureKernel(Class cls, Name name, bool isSetter, int charOffset, SourceLibraryBuilder library) { ClassMember declaration = getNodeFromKernelClass(cls).getInterfaceMember(name, isSetter); if (declaration?.isStatic ?? true) return null; if (declaration.isDuplicate) { library?.addProblem( templateDuplicatedDeclarationUse.withArguments(name.name), charOffset, name.name.length, library.fileUri); return null; } if (declaration is DelayedMember) { return declaration.check(this); } else { return declaration.member; } } static ClassHierarchyBuilder build(ClassBuilder objectClass, List<ClassBuilder> classes, SourceLoader loader, CoreTypes coreTypes) { ClassHierarchyBuilder hierarchy = new ClassHierarchyBuilder(objectClass, loader, coreTypes); for (int i = 0; i < classes.length; i++) { ClassBuilder classBuilder = classes[i]; if (!classBuilder.isPatch) { hierarchy.nodes[classBuilder.cls] = new ClassHierarchyNodeBuilder(hierarchy, classBuilder).build(); } else { // TODO(ahe): Merge the injected members of patch into the hierarchy // node of `cls.origin`. } } return hierarchy; } } class ClassHierarchyNodeBuilder { final ClassHierarchyBuilder hierarchy; final ClassBuilder classBuilder; bool hasNoSuchMethod = false; List<ClassMember> abstractMembers = null; ClassHierarchyNodeBuilder(this.hierarchy, this.classBuilder); ClassBuilder get objectClass => hierarchy.objectClassBuilder; final Map<Class, Substitution> substitutions = <Class, Substitution>{}; /// When merging `aList` and `bList`, [a] (from `aList`) and [b] (from /// `bList`) each have the same name. /// /// If [mergeKind] is `MergeKind.superclass`, [a] should override [b]. /// /// If [mergeKind] is `MergeKind.interfaces`, we need to record them and /// solve the conflict later. /// /// If [mergeKind] is `MergeKind.supertypes`, [a] should implement [b], and /// [b] is implicitly abstract. ClassMember handleMergeConflict( ClassMember a, ClassMember b, MergeKind mergeKind) { debug?.log( "handleMergeConflict: ${fullName(a)} ${fullName(b)} ${mergeKind}"); // TODO(ahe): Enable this optimization, but be careful about abstract // methods overriding concrete methods. // if (cls is DillClassBuilder) return a; if (a == b) return a; if (a.isDuplicate || b.isDuplicate) { // Don't check overrides involving duplicated members. return a; } ClassMember result = checkInheritanceConflict(a, b); if (result != null) return result; result = a; switch (mergeKind) { case MergeKind.superclassMembers: case MergeKind.superclassSetters: // [a] is a method declared in [cls]. This means it defines the // interface of this class regardless if its abstract. debug?.log("superclass: checkValidOverride(" "${classBuilder.fullNameForErrors}, " "${fullName(a)}, ${fullName(b)})"); checkValidOverride( a, AbstractMemberOverridingImplementation.selectAbstract(b)); if (isAbstract(a)) { if (isAbstract(b)) { recordAbstractMember(a); } else { if (!classBuilder.isAbstract) { // The interface of this class is [a]. But the implementation is // [b]. So [b] must implement [a], unless [cls] is abstract. checkValidOverride(b, a); } result = new AbstractMemberOverridingImplementation( classBuilder, a, AbstractMemberOverridingImplementation.selectConcrete(b), mergeKind == MergeKind.superclassSetters, classBuilder.library.loader == hierarchy.loader); hierarchy.delayedMemberChecks.add(result); } } else if (classBuilder.isMixinApplication && a.classBuilder != classBuilder) { result = InheritedImplementationInterfaceConflict.combined( classBuilder, a, b, mergeKind == MergeKind.superclassSetters, classBuilder.library.loader == hierarchy.loader, isInheritableConflict: false); if (result is DelayedMember) { hierarchy.delayedMemberChecks.add(result); } } Member target = result.member; if (target.enclosingClass != objectClass.cls && target.name == noSuchMethodName) { hasNoSuchMethod = true; } break; case MergeKind.membersWithSetters: case MergeKind.settersWithMembers: if (a.classBuilder == classBuilder && b.classBuilder != classBuilder) { if (a is FieldBuilder) { if (a.isFinal && b.isSetter) { hierarchy.overrideChecks .add(new DelayedOverrideCheck(classBuilder, a, b)); } else { if (!inferFieldTypes(a, b)) { hierarchy.overrideChecks .add(new DelayedOverrideCheck(classBuilder, a, b)); } } } else if (a is ProcedureBuilder) { if (!inferMethodTypes(a, b)) { hierarchy.overrideChecks .add(new DelayedOverrideCheck(classBuilder, a, b)); } } } break; case MergeKind.interfacesMembers: result = InterfaceConflict.combined(classBuilder, a, b, false, classBuilder.library.loader == hierarchy.loader); break; case MergeKind.interfacesSetters: result = InterfaceConflict.combined(classBuilder, a, b, true, classBuilder.library.loader == hierarchy.loader); break; case MergeKind.supertypesMembers: case MergeKind.supertypesSetters: // [b] is inherited from an interface so it is implicitly abstract. a = AbstractMemberOverridingImplementation.selectAbstract(a); b = AbstractMemberOverridingImplementation.selectAbstract(b); // If [a] is declared in this class, it defines the interface. if (a.classBuilder == classBuilder) { debug?.log("supertypes: checkValidOverride(" "${classBuilder.fullNameForErrors}, " "${fullName(a)}, ${fullName(b)})"); checkValidOverride(a, b); if (a is DelayedMember && !a.isInheritableConflict) { if (b is DelayedMember) { b.addAllDeclarationsTo(a.declarations); } else { addDeclarationIfDifferent(b, a.declarations); } } } else { if (isAbstract(a)) { result = InterfaceConflict.combined( classBuilder, a, b, mergeKind == MergeKind.supertypesSetters, classBuilder.library.loader == hierarchy.loader); } else { result = InheritedImplementationInterfaceConflict.combined( classBuilder, a, b, mergeKind == MergeKind.supertypesSetters, classBuilder.library.loader == hierarchy.loader); } debug?.log("supertypes: ${result}"); if (result is DelayedMember) { hierarchy.delayedMemberChecks.add(result); } } break; } return result; } ClassMember checkInheritanceConflict(ClassMember a, ClassMember b) { if (a is DelayedMember) { ClassMember result; for (int i = 0; i < a.declarations.length; i++) { ClassMember d = checkInheritanceConflict(a.declarations[i], b); result ??= d; } return result; } if (b is DelayedMember) { ClassMember result; for (int i = 0; i < b.declarations.length; i++) { ClassMember d = checkInheritanceConflict(a, b.declarations[i]); result ??= d; } return result; } if (isInheritanceConflict(a, b)) { reportInheritanceConflict(a, b); return a; } return null; } bool inferMethodTypes(ProcedureBuilder a, ClassMember b) { debug?.log( "Trying to infer types for ${fullName(a)} based on ${fullName(b)}"); if (b is DelayedMember) { bool hasSameSignature = true; List<ClassMember> declarations = b.declarations; for (int i = 0; i < declarations.length; i++) { if (!inferMethodTypes(a, declarations[i])) { hasSameSignature = false; } } return hasSameSignature; } if (a.isGetter) { return inferGetterType(a, b); } else if (a.isSetter) { return inferSetterType(a, b); } bool hadTypesInferred = a.hadTypesInferred; ClassBuilder aClassBuilder = a.parent; Substitution aSubstitution; if (classBuilder != aClassBuilder) { assert( substitutions.containsKey(aClassBuilder.cls), "${classBuilder.fullNameForErrors} " "${aClassBuilder.fullNameForErrors}"); aSubstitution = substitutions[aClassBuilder.cls]; debug?.log("${classBuilder.fullNameForErrors} -> " "${aClassBuilder.fullNameForErrors} $aSubstitution"); } ClassBuilder bClassBuilder = b.classBuilder; Substitution bSubstitution; if (classBuilder != bClassBuilder) { assert( substitutions.containsKey(bClassBuilder.cls), "${classBuilder.fullNameForErrors} " "${bClassBuilder.fullNameForErrors}"); bSubstitution = substitutions[bClassBuilder.cls]; debug?.log("${classBuilder.fullNameForErrors} -> " "${bClassBuilder.fullNameForErrors} $bSubstitution"); } Procedure aProcedure = a.procedure; if (b.member is! Procedure) { debug?.log("Giving up 1"); return false; } Procedure bProcedure = b.member; FunctionNode aFunction = aProcedure.function; FunctionNode bFunction = bProcedure.function; List<TypeParameter> aTypeParameters = aFunction.typeParameters; List<TypeParameter> bTypeParameters = bFunction.typeParameters; int typeParameterCount = aTypeParameters.length; if (typeParameterCount != bTypeParameters.length) { debug?.log("Giving up 2"); return false; } Substitution substitution; if (typeParameterCount != 0) { for (int i = 0; i < typeParameterCount; i++) { copyTypeParameterCovariance( a.parent, aTypeParameters[i], bTypeParameters[i]); } List<DartType> types = new List<DartType>(typeParameterCount); for (int i = 0; i < typeParameterCount; i++) { types[i] = new TypeParameterType(aTypeParameters[i]); } substitution = Substitution.fromPairs(bTypeParameters, types); for (int i = 0; i < typeParameterCount; i++) { DartType aBound = aTypeParameters[i].bound; DartType bBound = substitution.substituteType(bTypeParameters[i].bound); if (aBound != bBound) { debug?.log("Giving up 3"); return false; } } } DartType aReturnType = aFunction.returnType; if (aSubstitution != null) { aReturnType = aSubstitution.substituteType(aReturnType); } DartType bReturnType = bFunction.returnType; if (bSubstitution != null) { bReturnType = bSubstitution.substituteType(bReturnType); } if (substitution != null) { bReturnType = substitution.substituteType(bReturnType); } bool result = true; if (aFunction.requiredParameterCount > bFunction.requiredParameterCount) { debug?.log("Giving up 4"); return false; } List<VariableDeclaration> aPositional = aFunction.positionalParameters; List<VariableDeclaration> bPositional = bFunction.positionalParameters; if (aPositional.length < bPositional.length) { debug?.log("Giving up 5"); return false; } if (aReturnType != bReturnType) { if (a.parent == classBuilder && a.returnType == null) { result = inferReturnType( classBuilder, a, bReturnType, hadTypesInferred, hierarchy); } else { debug?.log("Giving up 6"); result = false; } } for (int i = 0; i < bPositional.length; i++) { VariableDeclaration aParameter = aPositional[i]; VariableDeclaration bParameter = bPositional[i]; copyParameterCovariance(a.parent, aParameter, bParameter); DartType aType = aParameter.type; if (aSubstitution != null) { aType = aSubstitution.substituteType(aType); } DartType bType = bParameter.type; if (bSubstitution != null) { bType = bSubstitution.substituteType(bType); } if (substitution != null) { bType = substitution.substituteType(bType); } if (aType != bType) { if (a.parent == classBuilder && a.formals[i].type == null) { result = inferParameterType(classBuilder, a, a.formals[i], bType, hadTypesInferred, hierarchy); } else { debug?.log("Giving up 8"); result = false; } } } List<VariableDeclaration> aNamed = aFunction.namedParameters; List<VariableDeclaration> bNamed = bFunction.namedParameters; named: if (aNamed.isNotEmpty || bNamed.isNotEmpty) { if (aPositional.length != bPositional.length) { debug?.log("Giving up 9"); result = false; break named; } if (aFunction.requiredParameterCount != bFunction.requiredParameterCount) { debug?.log("Giving up 10"); result = false; break named; } aNamed = aNamed.toList()..sort(compareNamedParameters); bNamed = bNamed.toList()..sort(compareNamedParameters); int aCount = 0; for (int bCount = 0; bCount < bNamed.length; bCount++) { String name = bNamed[bCount].name; for (; aCount < aNamed.length; aCount++) { if (aNamed[aCount].name == name) break; } if (aCount == aNamed.length) { debug?.log("Giving up 11"); result = false; break named; } VariableDeclaration aParameter = aNamed[aCount]; VariableDeclaration bParameter = bNamed[bCount]; copyParameterCovariance(a.parent, aParameter, bParameter); DartType aType = aParameter.type; if (aSubstitution != null) { aType = aSubstitution.substituteType(aType); } DartType bType = bParameter.type; if (bSubstitution != null) { bType = bSubstitution.substituteType(bType); } if (substitution != null) { bType = substitution.substituteType(bType); } if (aType != bType) { FormalParameterBuilder parameter; for (int i = aPositional.length; i < a.formals.length; ++i) { if (a.formals[i].name == name) { parameter = a.formals[i]; break; } } if (a.parent == classBuilder && parameter.type == null) { result = inferParameterType( classBuilder, a, parameter, bType, hadTypesInferred, hierarchy); } else { debug?.log("Giving up 12"); result = false; } } } } debug?.log("Inferring types for ${fullName(a)} based on ${fullName(b)} " + (result ? "succeeded." : "failed.")); return result; } bool inferGetterType(ProcedureBuilder a, ClassMember b) { debug?.log( "Inferring getter types for ${fullName(a)} based on ${fullName(b)}"); Member bTarget = b.member; DartType bType; if (bTarget is Field) { bType = bTarget.type; } else if (bTarget is Procedure) { if (b.isSetter) { VariableDeclaration bParameter = bTarget.function.positionalParameters.single; bType = bParameter.type; if (!hasExplicitlyTypedFormalParameter(b, 0)) { debug?.log("Giving up (type may be inferred)"); return false; } } else if (b.isGetter) { bType = bTarget.function.returnType; if (!hasExplicitReturnType(b)) { debug?.log("Giving up (return type may be inferred)"); return false; } } else { debug?.log("Giving up (not accessor: ${bTarget.kind})"); return false; } } else { debug?.log("Giving up (not field/procedure: ${bTarget.runtimeType})"); return false; } return a.procedure.function.returnType == bType; } bool inferSetterType(ProcedureBuilder a, ClassMember b) { debug?.log( "Inferring setter types for ${fullName(a)} based on ${fullName(b)}"); Member bTarget = b.member; Procedure aProcedure = a.procedure; VariableDeclaration aParameter = aProcedure.function.positionalParameters.single; DartType bType; if (bTarget is Field) { bType = bTarget.type; copyParameterCovarianceFromField(a.parent, aParameter, bTarget); } if (bTarget is Procedure) { if (b.isSetter) { VariableDeclaration bParameter = bTarget.function.positionalParameters.single; bType = bParameter.type; copyParameterCovariance(a.parent, aParameter, bParameter); if (!hasExplicitlyTypedFormalParameter(b, 0) || !hasExplicitlyTypedFormalParameter(a, 0)) { debug?.log("Giving up (type may be inferred)"); return false; } } else if (b.isGetter) { bType = bTarget.function.returnType; if (!hasExplicitReturnType(b)) { debug?.log("Giving up (return type may be inferred)"); return false; } } else { debug?.log("Giving up (not accessor: ${bTarget.kind})"); return false; } } else { debug?.log("Giving up (not field/procedure: ${bTarget.runtimeType})"); return false; } return aParameter.type == bType; } void checkValidOverride(ClassMember a, ClassMember b) { debug?.log( "checkValidOverride(${fullName(a)}, ${fullName(b)}) ${a.runtimeType}"); if (a is ProcedureBuilder) { if (inferMethodTypes(a, b)) return; } else if (a.isField) { if (inferFieldTypes(a, b)) return; } Member aTarget = a.member; Member bTarget = b.member; if (aTarget is Procedure && !aTarget.isAccessor && bTarget is Procedure) { if (hasSameSignature(aTarget.function, bTarget.function)) return; } if (b is DelayedMember) { for (int i = 0; i < b.declarations.length; i++) { hierarchy.overrideChecks .add(new DelayedOverrideCheck(classBuilder, a, b.declarations[i])); } } else { hierarchy.overrideChecks .add(new DelayedOverrideCheck(classBuilder, a, b)); } } bool inferFieldTypes(MemberBuilder a, ClassMember b) { debug?.log("Trying to infer field types for ${fullName(a)} " "based on ${fullName(b)}"); if (b is DelayedMember) { bool hasSameSignature = true; List<ClassMember> declarations = b.declarations; for (int i = 0; i < declarations.length; i++) { if (!inferFieldTypes(a, declarations[i])) { hasSameSignature = false; } } return hasSameSignature; } Member bTarget = b.member; DartType inheritedType; if (bTarget is Procedure) { if (bTarget.isSetter) { VariableDeclaration parameter = bTarget.function.positionalParameters.single; // inheritedType = parameter.type; copyFieldCovarianceFromParameter(a.parent, a.member, parameter); if (!hasExplicitlyTypedFormalParameter(b, 0)) { debug?.log("Giving up (type may be inferred)"); return false; } } else if (bTarget.isGetter) { if (!hasExplicitReturnType(b)) return false; inheritedType = bTarget.function.returnType; } } else if (bTarget is Field) { copyFieldCovariance(a.parent, a.member, bTarget); inheritedType = bTarget.type; } if (inheritedType == null) { debug?.log("Giving up (inheritedType == null)\n${StackTrace.current}"); return false; } ClassBuilder aClassBuilder = a.parent; Substitution aSubstitution; if (classBuilder != aClassBuilder) { assert( substitutions.containsKey(aClassBuilder.cls), "${classBuilder.fullNameForErrors} " "${aClassBuilder.fullNameForErrors}"); aSubstitution = substitutions[aClassBuilder.cls]; debug?.log("${classBuilder.fullNameForErrors} -> " "${aClassBuilder.fullNameForErrors} $aSubstitution"); } ClassBuilder bClassBuilder = b.classBuilder; Substitution bSubstitution; if (classBuilder != bClassBuilder) { assert( substitutions.containsKey(bClassBuilder.cls), "${classBuilder.fullNameForErrors} " "${bClassBuilder.fullNameForErrors}"); bSubstitution = substitutions[bClassBuilder.cls]; debug?.log("${classBuilder.fullNameForErrors} -> " "${bClassBuilder.fullNameForErrors} $bSubstitution"); } if (bSubstitution != null && inheritedType is! ImplicitFieldType) { inheritedType = bSubstitution.substituteType(inheritedType); } Field aField = a.member; DartType declaredType = aField.type; if (aSubstitution != null) { declaredType = aSubstitution.substituteType(declaredType); } if (declaredType == inheritedType) return true; bool result = false; if (a is FieldBuilder) { if (a.parent == classBuilder && a.type == null) { if (a.hadTypesInferred) { reportCantInferFieldType(classBuilder, a); inheritedType = const InvalidType(); } else { result = true; a.hadTypesInferred = true; } if (inheritedType is ImplicitFieldType) { SourceLibraryBuilder library = classBuilder.library; (library.implicitlyTypedFields ??= <FieldBuilder>[]).add(a); } a.field.type = inheritedType; } } return result; } void copyParameterCovariance(Builder parent, VariableDeclaration aParameter, VariableDeclaration bParameter) { if (parent == classBuilder) { if (bParameter.isCovariant) { aParameter.isCovariant = true; } if (bParameter.isGenericCovariantImpl) { aParameter.isGenericCovariantImpl = true; } } } void copyParameterCovarianceFromField( Builder parent, VariableDeclaration aParameter, Field bField) { if (parent == classBuilder) { if (bField.isCovariant) { aParameter.isCovariant = true; } if (bField.isGenericCovariantImpl) { aParameter.isGenericCovariantImpl = true; } } } void copyFieldCovariance(Builder parent, Field aField, Field bField) { if (parent == classBuilder) { if (bField.isCovariant) { aField.isCovariant = true; } if (bField.isGenericCovariantImpl) { aField.isGenericCovariantImpl = true; } } } void copyFieldCovarianceFromParameter( Builder parent, Field aField, VariableDeclaration bParameter) { if (parent == classBuilder) { if (bParameter.isCovariant) { aField.isCovariant = true; } if (bParameter.isGenericCovariantImpl) { aField.isGenericCovariantImpl = true; } } } void copyTypeParameterCovariance( Builder parent, TypeParameter aParameter, TypeParameter bParameter) { if (parent == classBuilder) { if (bParameter.isGenericCovariantImpl) { aParameter.isGenericCovariantImpl = true; } } } void reportInheritanceConflict(ClassMember a, ClassMember b) { String name = a.fullNameForErrors; if (a.classBuilder != b.classBuilder) { if (a.classBuilder == classBuilder) { classBuilder.addProblem( messageDeclaredMemberConflictsWithInheritedMember, a.charOffset, name.length, context: <LocatedMessage>[ messageDeclaredMemberConflictsWithInheritedMemberCause .withLocation(b.fileUri, b.charOffset, name.length) ]); } else { classBuilder.addProblem(messageInheritedMembersConflict, classBuilder.charOffset, classBuilder.fullNameForErrors.length, context: inheritedConflictContext(a, b)); } } else if (a.isStatic != b.isStatic) { ClassMember staticMember; ClassMember instanceMember; if (a.isStatic) { staticMember = a; instanceMember = b; } else { staticMember = b; instanceMember = a; } classBuilder.library.addProblem(messageStaticAndInstanceConflict, staticMember.charOffset, name.length, staticMember.fileUri, context: <LocatedMessage>[ messageStaticAndInstanceConflictCause.withLocation( instanceMember.fileUri, instanceMember.charOffset, name.length) ]); } else { // This message can be reported twice (when merging localMembers with // classSetters, or localSetters with classMembers). By ensuring that // we always report the one with higher charOffset as the duplicate, // the message duplication logic ensures that we only report this // problem once. ClassMember existing; ClassMember duplicate; assert(a.fileUri == b.fileUri); if (a.charOffset < b.charOffset) { existing = a; duplicate = b; } else { existing = b; duplicate = a; } classBuilder.library.addProblem( templateDuplicatedDeclaration.withArguments(name), duplicate.charOffset, name.length, duplicate.fileUri, context: <LocatedMessage>[ templateDuplicatedDeclarationCause.withArguments(name).withLocation( existing.fileUri, existing.charOffset, name.length) ]); } } /// When merging `aList` and `bList`, [member] was only found in `aList`. /// /// If [mergeKind] is `MergeKind.superclass` [member] is declared in current /// class, and isn't overriding a method from the superclass. /// /// If [mergeKind] is `MergeKind.interfaces`, [member] is ignored for now. /// /// If [mergeKind] is `MergeKind.supertypes`, [member] isn't /// implementing/overriding anything. void handleOnlyA(ClassMember member, MergeKind mergeKind) { if (mergeKind == MergeKind.interfacesMembers || mergeKind == MergeKind.interfacesSetters) { return; } // TODO(ahe): Enable this optimization: // if (cls is DillClassBuilder) return; // assert(mergeKind == MergeKind.interfaces || // member is! InterfaceConflict); if ((mergeKind == MergeKind.superclassMembers || mergeKind == MergeKind.superclassSetters) && isAbstract(member)) { recordAbstractMember(member); } } /// When merging `aList` and `bList`, [member] was only found in `bList`. /// /// If [mergeKind] is `MergeKind.superclass` [member] is being inherited from /// a superclass. /// /// If [mergeKind] is `MergeKind.interfaces`, [member] is ignored for now. /// /// If [mergeKind] is `MergeKind.supertypes`, [member] is implicitly /// abstract, and not implemented. ClassMember handleOnlyB(ClassMember member, MergeKind mergeKind) { if (mergeKind == MergeKind.interfacesMembers || mergeKind == MergeKind.interfacesSetters) { return member; } // TODO(ahe): Enable this optimization: // if (cls is DillClassBuilder) return member; Member target = member.member; if ((mergeKind == MergeKind.supertypesMembers || mergeKind == MergeKind.supertypesSetters) || ((mergeKind == MergeKind.superclassMembers || mergeKind == MergeKind.superclassSetters) && target.isAbstract)) { if (isNameVisibleIn(target.name, classBuilder.library)) { recordAbstractMember(member); } } if (mergeKind == MergeKind.superclassMembers && target.enclosingClass != objectClass.cls && target.name == noSuchMethodName) { hasNoSuchMethod = true; } if (mergeKind != MergeKind.membersWithSetters && mergeKind != MergeKind.settersWithMembers && member is DelayedMember && member.isInheritableConflict) { hierarchy.delayedMemberChecks.add(member.withParent(classBuilder)); } return member; } void recordAbstractMember(ClassMember member) { abstractMembers ??= <ClassMember>[]; if (member is DelayedMember) { abstractMembers.addAll(member.declarations); } else { abstractMembers.add(member); } } ClassHierarchyNode build() { assert(!classBuilder.isPatch); ClassHierarchyNode supernode; if (objectClass != classBuilder.origin) { supernode = hierarchy.getNodeFromType(classBuilder.supertype); if (supernode == null) { supernode = hierarchy.getNodeFromClass(objectClass); } assert(supernode != null); } Scope scope = classBuilder.scope; if (classBuilder.isMixinApplication) { Builder mixin = classBuilder.mixedInType.declaration; inferMixinApplication(); // recordSupertype(cls.mixedInType); while (mixin.isNamedMixinApplication) { ClassBuilder named = mixin; // recordSupertype(named.mixedInType); mixin = named.mixedInType.declaration; } if (mixin is ClassBuilder) { scope = mixin.scope.computeMixinScope(); } } /// Members (excluding setters) declared in [cls]. List<ClassMember> localMembers = new List<ClassMember>.from(scope.local.values) ..sort(compareDeclarations); /// Setters declared in [cls]. List<ClassMember> localSetters = new List<ClassMember>.from(scope.setters.values) ..sort(compareDeclarations); // Add implied setters from fields in [localMembers]. localSetters = mergeAccessors(localMembers, localSetters); /// Members (excluding setters) declared in [cls] or its superclasses. This /// includes static methods of [cls], but not its superclasses. List<ClassMember> classMembers; /// Setters declared in [cls] or its superclasses. This includes static /// setters of [cls], but not its superclasses. List<ClassMember> classSetters; /// Members (excluding setters) inherited from interfaces. This contains no /// static members. Is null if no interfaces are implemented by this class /// or its superclasses. List<ClassMember> interfaceMembers; /// Setters inherited from interfaces. This contains no static setters. Is /// null if no interfaces are implemented by this class or its /// superclasses. List<ClassMember> interfaceSetters; List<TypeBuilder> superclasses; List<TypeBuilder> interfaces; int maxInheritancePath; if (supernode == null) { // This should be Object. classMembers = localMembers; classSetters = localSetters; superclasses = new List<TypeBuilder>(0); interfaces = new List<TypeBuilder>(0); maxInheritancePath = 0; } else { maxInheritancePath = supernode.maxInheritancePath + 1; superclasses = new List<TypeBuilder>(supernode.superclasses.length + 1); superclasses.setRange(0, superclasses.length - 1, substSupertypes(classBuilder.supertype, supernode.superclasses)); superclasses[superclasses.length - 1] = recordSupertype(classBuilder.supertype); List<TypeBuilder> directInterfaces = ignoreFunction(classBuilder.interfaces); if (classBuilder.isMixinApplication) { if (directInterfaces == null) { directInterfaces = <TypeBuilder>[classBuilder.mixedInType]; } else { directInterfaces = <TypeBuilder>[classBuilder.mixedInType] ..addAll(directInterfaces); } } if (directInterfaces != null) { for (int i = 0; i < directInterfaces.length; i++) { recordSupertype(directInterfaces[i]); } } List<TypeBuilder> superclassInterfaces = supernode.interfaces; if (superclassInterfaces != null) { superclassInterfaces = substSupertypes(classBuilder.supertype, superclassInterfaces); } classMembers = merge( localMembers, supernode.classMembers, MergeKind.superclassMembers); classSetters = merge( localSetters, supernode.classSetters, MergeKind.superclassSetters); if (directInterfaces != null) { MergeResult result = mergeInterfaces(supernode, directInterfaces); interfaceMembers = result.mergedMembers; interfaceSetters = result.mergedSetters; interfaces = <TypeBuilder>[]; if (superclassInterfaces != null) { for (int i = 0; i < superclassInterfaces.length; i++) { addInterface(interfaces, superclasses, superclassInterfaces[i]); } } for (int i = 0; i < directInterfaces.length; i++) { TypeBuilder directInterface = directInterfaces[i]; addInterface(interfaces, superclasses, directInterface); ClassHierarchyNode interfaceNode = hierarchy.getNodeFromType(directInterface); if (interfaceNode != null) { if (maxInheritancePath < interfaceNode.maxInheritancePath + 1) { maxInheritancePath = interfaceNode.maxInheritancePath + 1; } List<TypeBuilder> types = substSupertypes(directInterface, interfaceNode.superclasses); for (int i = 0; i < types.length; i++) { addInterface(interfaces, superclasses, types[i]); } if (interfaceNode.interfaces != null) { List<TypeBuilder> types = substSupertypes(directInterface, interfaceNode.interfaces); for (int i = 0; i < types.length; i++) { addInterface(interfaces, superclasses, types[i]); } } } } } else { interfaceMembers = supernode.interfaceMembers; interfaceSetters = supernode.interfaceSetters; interfaces = superclassInterfaces; } // Check if local members conflict with inherited setters. This check has // already been performed in the superclass, so we only need to check the // local members. These checks have to occur late to enable inferring // types between setters and getters, or from a setter to a final field. merge(localMembers, classSetters, MergeKind.membersWithSetters); // Check if local setters conflict with inherited members. As above, we // only need to check the local setters. merge(localSetters, classMembers, MergeKind.settersWithMembers); if (interfaceMembers != null) { interfaceMembers = merge(classMembers, interfaceMembers, MergeKind.supertypesMembers); // Check if class setters conflict with members inherited from // interfaces. merge(classSetters, interfaceMembers, MergeKind.settersWithMembers); } if (interfaceSetters != null) { interfaceSetters = merge(classSetters, interfaceSetters, MergeKind.supertypesSetters); // Check if class members conflict with setters inherited from // interfaces. merge(classMembers, interfaceSetters, MergeKind.membersWithSetters); } } if (abstractMembers != null && !classBuilder.isAbstract) { if (!hasNoSuchMethod) { reportMissingMembers(); } else { installNsmHandlers(); } } return new ClassHierarchyNode( classBuilder, classMembers, classSetters, interfaceMembers, interfaceSetters, superclasses, interfaces, maxInheritancePath, hasNoSuchMethod, ); } TypeBuilder recordSupertype(TypeBuilder supertype) { if (supertype is NamedTypeBuilder) { debug?.log("In ${this.classBuilder.fullNameForErrors} " "recordSupertype(${supertype.fullNameForErrors})"); Builder declaration = supertype.declaration; if (declaration is! ClassBuilder) return supertype; ClassBuilder classBuilder = declaration; if (classBuilder.isMixinApplication) { recordSupertype(classBuilder.mixedInType); } List<TypeVariableBuilder> typeVariableBuilders = classBuilder.typeVariables; if (typeVariableBuilders == null) { substitutions[classBuilder.cls] = Substitution.empty; assert(classBuilder.cls.typeParameters.isEmpty); } else { List<TypeBuilder> arguments = supertype.arguments ?? computeDefaultTypeArguments(supertype); if (arguments.length != typeVariableBuilders.length) { arguments = computeDefaultTypeArguments(supertype); } List<DartType> typeArguments = new List<DartType>(arguments.length); List<TypeParameter> typeParameters = new List<TypeParameter>(arguments.length); for (int i = 0; i < arguments.length; i++) { typeParameters[i] = typeVariableBuilders[i].parameter; typeArguments[i] = arguments[i].build(this.classBuilder.parent); } substitutions[classBuilder.cls] = Substitution.fromPairs(typeParameters, typeArguments); } } return supertype; } List<TypeBuilder> substSupertypes( NamedTypeBuilder supertype, List<TypeBuilder> supertypes) { Builder declaration = supertype.declaration; if (declaration is! ClassBuilder) return supertypes; ClassBuilder cls = declaration; List<TypeVariableBuilder> typeVariables = cls.typeVariables; if (typeVariables == null) { debug?.log("In ${this.classBuilder.fullNameForErrors} " "$supertypes aren't substed"); for (int i = 0; i < supertypes.length; i++) { recordSupertype(supertypes[i]); } return supertypes; } Map<TypeVariableBuilder, TypeBuilder> substitution = <TypeVariableBuilder, TypeBuilder>{}; List<TypeBuilder> arguments = supertype.arguments ?? computeDefaultTypeArguments(supertype); for (int i = 0; i < typeVariables.length; i++) { substitution[typeVariables[i]] = arguments[i]; } List<TypeBuilder> result; for (int i = 0; i < supertypes.length; i++) { TypeBuilder supertype = supertypes[i]; TypeBuilder substed = recordSupertype(supertype.subst(substitution)); if (supertype != substed) { debug?.log( "In ${this.classBuilder.fullNameForErrors} $supertype -> $substed"); result ??= supertypes.toList(); result[i] = substed; } else { debug?.log("In ${this.classBuilder.fullNameForErrors} " "$supertype isn't substed"); } } return result ?? supertypes; } List<TypeBuilder> computeDefaultTypeArguments(TypeBuilder type) { ClassBuilder cls = type.declaration; List<TypeBuilder> result = new List<TypeBuilder>(cls.typeVariables.length); for (int i = 0; i < result.length; ++i) { TypeVariableBuilder tv = cls.typeVariables[i]; result[i] = tv.defaultType ?? cls.library.loader.computeTypeBuilder(tv.parameter.defaultType); } return result; } TypeBuilder addInterface(List<TypeBuilder> interfaces, List<TypeBuilder> superclasses, TypeBuilder type) { ClassHierarchyNode node = hierarchy.getNodeFromType(type); if (node == null) return null; int depth = node.depth; int myDepth = superclasses.length; if (depth < myDepth && superclasses[depth].declaration == node.classBuilder) { // This is a potential conflict. return superclasses[depth]; } else { for (int i = 0; i < interfaces.length; i++) { // This is a quadratic algorithm, but normally, the number of // interfaces is really small. if (interfaces[i].declaration == type.declaration) { // This is a potential conflict. return interfaces[i]; } } } interfaces.add(type); return null; } MergeResult mergeInterfaces( ClassHierarchyNode supernode, List<TypeBuilder> interfaces) { debug?.log("mergeInterfaces($classBuilder (${this.classBuilder}) " "${supernode.interfaces} ${interfaces}"); List<List<ClassMember>> memberLists = new List<List<ClassMember>>(interfaces.length + 1); List<List<ClassMember>> setterLists = new List<List<ClassMember>>(interfaces.length + 1); memberLists[0] = supernode.interfaceMembers; setterLists[0] = supernode.interfaceSetters; for (int i = 0; i < interfaces.length; i++) { ClassHierarchyNode interfaceNode = hierarchy.getNodeFromType(interfaces[i]); if (interfaceNode == null) { memberLists[i + 1] = null; setterLists[i + 1] = null; } else { memberLists[i + 1] = interfaceNode.interfaceMembers ?? interfaceNode.classMembers; setterLists[i + 1] = interfaceNode.interfaceSetters ?? interfaceNode.classSetters; } } return new MergeResult(mergeLists(memberLists, MergeKind.interfacesMembers), mergeLists(setterLists, MergeKind.interfacesSetters)); } List<ClassMember> mergeLists( List<List<ClassMember>> input, MergeKind mergeKind) { // This is a k-way merge sort (where k is `input.length + 1`). We merge the // lists pairwise, which reduces the number of lists to merge by half on // each iteration. Consequently, we perform O(log k) merges. while (input.length > 1) { List<List<ClassMember>> output = <List<ClassMember>>[]; for (int i = 0; i < input.length - 1; i += 2) { List<ClassMember> first = input[i]; List<ClassMember> second = input[i + 1]; if (first == null) { output.add(second); } else if (second == null) { output.add(first); } else { output.add(merge(first, second, mergeKind)); } } if (input.length.isOdd) { output.add(input.last); } input = output; } return input.single; } /// Merge [and check] accessors. This entails copying mutable fields to /// setters to simulate implied setters, and checking that setters don't /// override regular methods. List<ClassMember> mergeAccessors( List<ClassMember> members, List<ClassMember> setters) { final List<ClassMember> mergedSetters = new List<ClassMember>.filled( members.length + setters.length, null, growable: true); int storeIndex = 0; int i = 0; int j = 0; while (i < members.length && j < setters.length) { final ClassMember member = members[i]; final ClassMember setter = setters[j]; final int compare = compareDeclarations(member, setter); if (compare == 0) { mergedSetters[storeIndex++] = setter; i++; j++; } else if (compare < 0) { if (impliesSetter(member)) { mergedSetters[storeIndex++] = member; } i++; } else { mergedSetters[storeIndex++] = setters[j]; j++; } } while (i < members.length) { final ClassMember member = members[i]; if (impliesSetter(member)) { mergedSetters[storeIndex++] = member; } i++; } while (j < setters.length) { mergedSetters[storeIndex++] = setters[j]; j++; } if (storeIndex == j) { return setters; } else { return mergedSetters..length = storeIndex; } } void reportMissingMembers() { Map<String, LocatedMessage> contextMap = <String, LocatedMessage>{}; for (int i = 0; i < abstractMembers.length; i++) { ClassMember declaration = abstractMembers[i]; Member target = declaration.member; if (isNameVisibleIn(target.name, classBuilder.library)) { String name = declaration.fullNameForErrors; String className = declaration.classBuilder?.fullNameForErrors; String displayName = declaration.isSetter ? "$className.$name=" : "$className.$name"; contextMap[displayName] = templateMissingImplementationCause .withArguments(displayName) .withLocation( declaration.fileUri, declaration.charOffset, name.length); } } if (contextMap.isEmpty) return; List<String> names = new List<String>.from(contextMap.keys)..sort(); List<LocatedMessage> context = <LocatedMessage>[]; for (int i = 0; i < names.length; i++) { context.add(contextMap[names[i]]); } classBuilder.addProblem( templateMissingImplementationNotAbstract.withArguments( classBuilder.fullNameForErrors, names), classBuilder.charOffset, classBuilder.fullNameForErrors.length, context: context); } void installNsmHandlers() { // TODO(ahe): Implement this. } List<ClassMember> merge( List<ClassMember> aList, List<ClassMember> bList, MergeKind mergeKind) { final List<ClassMember> result = new List<ClassMember>.filled( aList.length + bList.length, null, growable: true); int storeIndex = 0; int i = 0; int j = 0; while (i < aList.length && j < bList.length) { final ClassMember a = aList[i]; final ClassMember b = bList[j]; if ((mergeKind == MergeKind.interfacesMembers || mergeKind == MergeKind.interfacesSetters) && a.isStatic) { i++; continue; } if (b.isStatic) { j++; continue; } final int compare = compareDeclarations(a, b); if (compare == 0) { result[storeIndex++] = handleMergeConflict(a, b, mergeKind); i++; j++; } else if (compare < 0) { handleOnlyA(a, mergeKind); result[storeIndex++] = a; i++; } else { result[storeIndex++] = handleOnlyB(b, mergeKind); j++; } } while (i < aList.length) { final ClassMember a = aList[i]; if (!(mergeKind == MergeKind.interfacesMembers || mergeKind == MergeKind.interfacesSetters) || !a.isStatic) { handleOnlyA(a, mergeKind); result[storeIndex++] = a; } i++; } while (j < bList.length) { final ClassMember b = bList[j]; if (!b.isStatic) { result[storeIndex++] = handleOnlyB(b, mergeKind); } j++; } if (aList.isEmpty && storeIndex == bList.length) return bList; if (bList.isEmpty && storeIndex == aList.length) return aList; return result..length = storeIndex; } void inferMixinApplication() { Class cls = classBuilder.cls; Supertype mixedInType = cls.mixedInType; if (mixedInType == null) return; List<DartType> typeArguments = mixedInType.typeArguments; if (typeArguments.isEmpty || typeArguments.first is! UnknownType) return; new BuilderMixinInferrer( classBuilder, hierarchy.coreTypes, new TypeBuilderConstraintGatherer( hierarchy, mixedInType.classNode.typeParameters)) .infer(cls); List<TypeBuilder> inferredArguments = new List<TypeBuilder>(typeArguments.length); for (int i = 0; i < typeArguments.length; i++) { inferredArguments[i] = hierarchy.loader.computeTypeBuilder(typeArguments[i]); } NamedTypeBuilder mixedInTypeBuilder = classBuilder.mixedInType; mixedInTypeBuilder.arguments = inferredArguments; } /// The class Function from dart:core is supposed to be ignored when used as /// an interface. List<TypeBuilder> ignoreFunction(List<TypeBuilder> interfaces) { if (interfaces == null) return null; for (int i = 0; i < interfaces.length; i++) { ClassBuilder classBuilder = getClass(interfaces[i]); if (classBuilder != null && classBuilder.cls == hierarchy.functionClass) { if (interfaces.length == 1) { return null; } else { interfaces = interfaces.toList(); interfaces.removeAt(i); return ignoreFunction(interfaces); } } } return interfaces; } } class ClassHierarchyNode { /// The class corresponding to this hierarchy node. final ClassBuilder classBuilder; /// All the members of this class including [classMembers] of its /// superclasses. The members are sorted by [compareDeclarations]. final List<ClassMember> classMembers; /// Similar to [classMembers] but for setters. final List<ClassMember> classSetters; /// All the interface members of this class including [interfaceMembers] of /// its supertypes. The members are sorted by [compareDeclarations]. /// /// In addition to the members of [classMembers] this also contains members /// from interfaces. /// /// This may be null, in which case [classMembers] is the interface members. final List<ClassMember> interfaceMembers; /// Similar to [interfaceMembers] but for setters. /// /// This may be null, in which case [classSetters] is the interface setters. final List<ClassMember> interfaceSetters; /// All superclasses of [classBuilder] excluding itself. The classes are /// sorted by depth from the root (Object) in ascending order. final List<TypeBuilder> superclasses; /// The list of all classes implemented by [classBuilder] and its supertypes /// excluding any classes from [superclasses]. final List<TypeBuilder> interfaces; /// The longest inheritance path from [classBuilder] to `Object`. final int maxInheritancePath; int get depth => superclasses.length; final bool hasNoSuchMethod; ClassHierarchyNode( this.classBuilder, this.classMembers, this.classSetters, this.interfaceMembers, this.interfaceSetters, this.superclasses, this.interfaces, this.maxInheritancePath, this.hasNoSuchMethod); /// Returns a list of all supertypes of [classBuilder], including this node. List<ClassHierarchyNode> computeAllSuperNodes( ClassHierarchyBuilder hierarchy) { List<ClassHierarchyNode> result = new List<ClassHierarchyNode>( 1 + superclasses.length + interfaces.length); for (int i = 0; i < superclasses.length; i++) { Builder declaration = superclasses[i].declaration; if (declaration is ClassBuilder) { result[i] = hierarchy.getNodeFromClass(declaration); } } for (int i = 0; i < interfaces.length; i++) { Builder declaration = interfaces[i].declaration; if (declaration is ClassBuilder) { result[i + superclasses.length] = hierarchy.getNodeFromClass(declaration); } } return result..last = this; } String toString([StringBuffer sb]) { sb ??= new StringBuffer(); sb ..write(classBuilder.fullNameForErrors) ..writeln(":"); if (maxInheritancePath != this.depth) { sb ..write(" Longest path to Object: ") ..writeln(maxInheritancePath); } sb..writeln(" superclasses:"); int depth = 0; for (TypeBuilder superclass in superclasses) { sb.write(" " * (depth + 2)); if (depth != 0) sb.write("-> "); superclass.printOn(sb); sb.writeln(); depth++; } if (interfaces != null) { sb.write(" interfaces:"); bool first = true; for (TypeBuilder i in interfaces) { if (!first) sb.write(","); sb.write(" "); i.printOn(sb); first = false; } sb.writeln(); } printMembers(classMembers, sb, "classMembers"); printMembers(classSetters, sb, "classSetters"); if (interfaceMembers != null) { printMembers(interfaceMembers, sb, "interfaceMembers"); } if (interfaceSetters != null) { printMembers(interfaceSetters, sb, "interfaceSetters"); } return "$sb"; } void printMembers( List<ClassMember> members, StringBuffer sb, String heading) { sb.write(" "); sb.write(heading); sb.writeln(":"); for (ClassMember member in members) { sb ..write(" ") ..write(member.classBuilder.fullNameForErrors) ..write(".") ..write(member.fullNameForErrors) ..writeln(); } } ClassMember getInterfaceMember(Name name, bool isSetter) { return findMember( name, isSetter ? interfaceSetters ?? classSetters : interfaceMembers ?? classMembers); } ClassMember findMember(Name name, List<ClassMember> declarations) { // TODO(ahe): Consider creating a map or scope. The obvious choice would be // to use scopes, but they don't handle private names correctly. // This is a copy of `ClassHierarchy.findMemberByName`. int low = 0, high = declarations.length - 1; while (low <= high) { int mid = low + ((high - low) >> 1); ClassMember pivot = declarations[mid]; int comparison = ClassHierarchy.compareNames(name, pivot.member.name); if (comparison < 0) { high = mid - 1; } else if (comparison > 0) { low = mid + 1; } else if (high != mid) { // Ensure we find the first element of the given name. high = mid; } else { return pivot; } } return null; } ClassMember getDispatchTarget(Name name, bool isSetter) { return findMember(name, isSetter ? classSetters : classMembers); } static int compareMaxInheritancePath( ClassHierarchyNode a, ClassHierarchyNode b) { return b.maxInheritancePath.compareTo(a.maxInheritancePath); } } class MergeResult { final List<ClassMember> mergedMembers; final List<ClassMember> mergedSetters; MergeResult(this.mergedMembers, this.mergedSetters); } enum MergeKind { /// Merging superclass members with the current class. superclassMembers, /// Merging superclass setters with the current class. superclassSetters, /// Merging members of two interfaces. interfacesMembers, /// Merging setters of two interfaces. interfacesSetters, /// Merging class members with interface members. supertypesMembers, /// Merging class setters with interface setters. supertypesSetters, /// Merging members with inherited setters. membersWithSetters, /// Merging setters with inherited members. settersWithMembers, } List<LocatedMessage> inheritedConflictContext(ClassMember a, ClassMember b) { return inheritedConflictContextKernel( a.member, b.member, a.fullNameForErrors.length); } List<LocatedMessage> inheritedConflictContextKernel( Member a, Member b, int length) { // TODO(ahe): Delete this method when it isn't used by [InterfaceResolver]. int compare = "${a.fileUri}".compareTo("${b.fileUri}"); if (compare == 0) { compare = a.fileOffset.compareTo(b.fileOffset); } Member first; Member second; if (compare < 0) { first = a; second = b; } else { first = b; second = a; } return <LocatedMessage>[ messageInheritedMembersConflictCause1.withLocation( first.fileUri, first.fileOffset, length), messageInheritedMembersConflictCause2.withLocation( second.fileUri, second.fileOffset, length), ]; } class BuilderMixinInferrer extends MixinInferrer { final ClassBuilder cls; BuilderMixinInferrer( this.cls, CoreTypes coreTypes, TypeBuilderConstraintGatherer gatherer) : super(coreTypes, gatherer); Supertype asInstantiationOf(Supertype type, Class superclass) { InterfaceType interfaceType = gatherer.getTypeAsInstanceOf(type.asInterfaceType, superclass); if (interfaceType == null) return null; return new Supertype(interfaceType.classNode, interfaceType.typeArguments); } void reportProblem(Message message, Class kernelClass) { int length = cls.isMixinApplication ? 1 : cls.fullNameForErrors.length; cls.addProblem(message, cls.charOffset, length); } } class TypeBuilderConstraintGatherer extends TypeConstraintGatherer with StandardBounds { final ClassHierarchyBuilder hierarchy; TypeBuilderConstraintGatherer( this.hierarchy, Iterable<TypeParameter> typeParameters) : super.subclassing(typeParameters); @override Class get objectClass => hierarchy.objectClass; @override Class get functionClass => hierarchy.functionClass; @override Class get futureClass => hierarchy.futureClass; @override Class get futureOrClass => hierarchy.futureOrClass; @override Class get nullClass => hierarchy.nullClass; @override InterfaceType get nullType => hierarchy.coreTypes.nullType; @override InterfaceType get objectLegacyRawType => hierarchy.coreTypes.objectLegacyRawType; @override InterfaceType get functionLegacyRawType => hierarchy.coreTypes.functionLegacyRawType; @override void addLowerBound(TypeConstraint constraint, DartType lower) { constraint.lower = getStandardUpperBound(constraint.lower, lower); } @override void addUpperBound(TypeConstraint constraint, DartType upper) { constraint.upper = getStandardLowerBound(constraint.upper, upper); } @override Member getInterfaceMember(Class class_, Name name, {bool setter: false}) { return null; } @override InterfaceType getTypeAsInstanceOf(InterfaceType type, Class superclass) { return hierarchy.getKernelTypeAsInstanceOf(type, superclass); } @override InterfaceType futureType(DartType type) { return new InterfaceType(hierarchy.futureClass, <DartType>[type]); } @override bool isSubtypeOf( DartType subtype, DartType supertype, SubtypeCheckMode mode) { return hierarchy.types.isSubtypeOfKernel(subtype, supertype, mode); } @override InterfaceType getLegacyLeastUpperBound( InterfaceType type1, InterfaceType type2) { return hierarchy.getKernelLegacyLeastUpperBound(type1, type2); } } class DelayedOverrideCheck { final ClassBuilder classBuilder; final ClassMember a; final ClassMember b; const DelayedOverrideCheck(this.classBuilder, this.a, this.b); void check(ClassHierarchyBuilder hierarchy) { void callback( Member declaredMember, Member interfaceMember, bool isSetter) { classBuilder.checkOverride( hierarchy.types, declaredMember, interfaceMember, isSetter, callback, isInterfaceCheck: !classBuilder.isMixinApplication); } ClassMember a = this.a; debug?.log("Delayed override check of ${fullName(a)} " "${fullName(b)} wrt. ${classBuilder.fullNameForErrors}"); if (classBuilder == a.classBuilder) { if (a is ProcedureBuilder) { if (a.isGetter && !hasExplicitReturnType(a)) { DartType type; if (b.isGetter) { Procedure bTarget = b.member; type = bTarget.function.returnType; } else if (b.isSetter) { Procedure bTarget = b.member; type = bTarget.function.positionalParameters.single.type; } else if (b.isField) { Field bTarget = b.member; type = bTarget.type; } if (type != null) { type = Substitution.fromInterfaceType( hierarchy.getKernelTypeAsInstanceOf( classBuilder.cls.thisType, b.member.enclosingClass)) .substituteType(type); if (!a.hadTypesInferred || !b.isSetter) { inferReturnType( classBuilder, a, type, a.hadTypesInferred, hierarchy); } } } else if (a.isSetter && !hasExplicitlyTypedFormalParameter(a, 0)) { DartType type; if (b.isGetter) { Procedure bTarget = b.member; type = bTarget.function.returnType; } else if (b.isSetter) { Procedure bTarget = b.member; type = bTarget.function.positionalParameters.single.type; } else if (b.isField) { Field bTarget = b.member; type = bTarget.type; } if (type != null) { type = Substitution.fromInterfaceType( hierarchy.getKernelTypeAsInstanceOf( classBuilder.cls.thisType, b.member.enclosingClass)) .substituteType(type); if (!a.hadTypesInferred || !b.isGetter) { inferParameterType(classBuilder, a, a.formals.single, type, a.hadTypesInferred, hierarchy); } } } a.hadTypesInferred = true; } else if (a is FieldBuilder && a.type == null) { DartType type; if (b.isGetter) { Procedure bTarget = b.member; type = bTarget.function.returnType; } else if (b.isSetter) { Procedure bTarget = b.member; type = bTarget.function.positionalParameters.single.type; } else if (b.isField) { Field bTarget = b.member; type = bTarget.type; } if (type != null) { type = Substitution.fromInterfaceType( hierarchy.getKernelTypeAsInstanceOf( classBuilder.cls.thisType, b.member.enclosingClass)) .substituteType(type); if (type != a.field.type) { if (a.hadTypesInferred) { if (b.isSetter && (!impliesSetter(a) || hierarchy.types.isSubtypeOfKernel(type, a.field.type, SubtypeCheckMode.ignoringNullabilities))) { type = a.field.type; } else { reportCantInferFieldType(classBuilder, a); type = const InvalidType(); } } debug?.log("Inferred type ${type} for ${fullName(a)}"); a.field.type = type; } } a.hadTypesInferred = true; } } callback(a.member, b.member, a.isSetter); } } abstract class DelayedMember implements ClassMember { /// The class which has inherited [declarations]. @override final ClassBuilder classBuilder; /// Conflicting declarations. final List<ClassMember> declarations; final bool isSetter; final bool modifyKernel; DelayedMember( this.classBuilder, this.declarations, this.isSetter, this.modifyKernel); bool get isStatic => false; bool get isField => false; bool get isGetter => false; bool get isFinal => false; bool get isConst => false; bool get isDuplicate => false; void addAllDeclarationsTo(List<ClassMember> declarations) { for (int i = 0; i < this.declarations.length; i++) { addDeclarationIfDifferent(this.declarations[i], declarations); } assert(declarations.toSet().length == declarations.length); } Member check(ClassHierarchyBuilder hierarchy); DelayedMember withParent(ClassBuilder parent); @override Uri get fileUri => classBuilder.fileUri; @override int get charOffset => classBuilder.charOffset; @override String get fullNameForErrors => declarations.map(fullName).join("%"); bool get isInheritableConflict => true; @override Member get member => declarations.first.member; } /// This represents a concrete implementation inherited from a superclass that /// has conflicts with methods inherited from an interface. The concrete /// implementation is the first element of [declarations]. class InheritedImplementationInterfaceConflict extends DelayedMember { Member combinedMemberSignatureResult; @override final bool isInheritableConflict; InheritedImplementationInterfaceConflict(ClassBuilder parent, List<ClassMember> declarations, bool isSetter, bool modifyKernel, {this.isInheritableConflict = true}) : super(parent, declarations, isSetter, modifyKernel); @override String toString() { return "InheritedImplementationInterfaceConflict(" "${classBuilder.fullNameForErrors}, " "[${declarations.map(fullName).join(', ')}])"; } @override Member check(ClassHierarchyBuilder hierarchy) { if (combinedMemberSignatureResult != null) { return combinedMemberSignatureResult; } if (!classBuilder.isAbstract) { ClassMember concreteImplementation = declarations.first; for (int i = 1; i < declarations.length; i++) { new DelayedOverrideCheck( classBuilder, concreteImplementation, declarations[i]) .check(hierarchy); } } return combinedMemberSignatureResult = new InterfaceConflict( classBuilder, declarations, isSetter, modifyKernel) .check(hierarchy); } @override DelayedMember withParent(ClassBuilder parent) { return parent == this.classBuilder ? this : new InheritedImplementationInterfaceConflict( parent, declarations, isSetter, modifyKernel); } static ClassMember combined( ClassBuilder parent, ClassMember concreteImplementation, ClassMember other, bool isSetter, bool createForwarders, {bool isInheritableConflict = true}) { List<ClassMember> declarations = <ClassMember>[]; if (concreteImplementation is DelayedMember) { concreteImplementation.addAllDeclarationsTo(declarations); } else { declarations.add(concreteImplementation); } if (other is DelayedMember) { other.addAllDeclarationsTo(declarations); } else { addDeclarationIfDifferent(other, declarations); } if (declarations.length == 1) { return declarations.single; } else { return new InheritedImplementationInterfaceConflict( parent, declarations, isSetter, createForwarders, isInheritableConflict: isInheritableConflict); } } } class InterfaceConflict extends DelayedMember { InterfaceConflict(ClassBuilder parent, List<ClassMember> declarations, bool isSetter, bool modifyKernel) : super(parent, declarations, isSetter, modifyKernel); Member combinedMemberSignatureResult; @override String toString() { return "InterfaceConflict(${classBuilder.fullNameForErrors}, " "[${declarations.map(fullName).join(', ')}])"; } DartType computeMemberType( ClassHierarchyBuilder hierarchy, DartType thisType, Member member) { DartType type; if (member is Procedure) { if (member.isGetter) { type = member.getterType; } else if (member.isSetter) { type = member.setterType; } else { type = member.function.functionType; } } else if (member is Field) { type = member.type; } else { unhandled("${member.runtimeType}", "$member", classBuilder.charOffset, classBuilder.fileUri); } return Substitution.fromInterfaceType(hierarchy.getKernelTypeAsInstanceOf( thisType, member.enclosingClass)) .substituteType(type); } bool isMoreSpecific(ClassHierarchyBuilder hierarchy, DartType a, DartType b) { if (isSetter) { return hierarchy.types .isSubtypeOfKernel(b, a, SubtypeCheckMode.ignoringNullabilities); } else { return hierarchy.types .isSubtypeOfKernel(a, b, SubtypeCheckMode.ignoringNullabilities); } } @override Member check(ClassHierarchyBuilder hierarchy) { if (combinedMemberSignatureResult != null) { return combinedMemberSignatureResult; } if (classBuilder.library is! SourceLibraryBuilder) { return combinedMemberSignatureResult = declarations.first.member; } DartType thisType = classBuilder.cls.thisType; ClassMember bestSoFar; DartType bestTypeSoFar; for (int i = declarations.length - 1; i >= 0; i--) { ClassMember candidate = declarations[i]; Member target = candidate.member; DartType candidateType = computeMemberType(hierarchy, thisType, target); if (bestSoFar == null) { bestSoFar = candidate; bestTypeSoFar = candidateType; } else { if (isMoreSpecific(hierarchy, candidateType, bestTypeSoFar)) { debug?.log("Combined Member Signature: ${fullName(candidate)} " "${candidateType} <: ${fullName(bestSoFar)} ${bestTypeSoFar}"); bestSoFar = candidate; bestTypeSoFar = candidateType; } else { debug?.log("Combined Member Signature: " "${fullName(candidate)} !<: ${fullName(bestSoFar)}"); } } } if (bestSoFar != null) { debug?.log("Combined Member Signature bestSoFar: ${fullName(bestSoFar)}"); for (int i = 0; i < declarations.length; i++) { ClassMember candidate = declarations[i]; Member target = candidate.member; DartType candidateType = computeMemberType(hierarchy, thisType, target); if (!isMoreSpecific(hierarchy, bestTypeSoFar, candidateType)) { debug?.log("Combined Member Signature: " "${fullName(bestSoFar)} !<: ${fullName(candidate)}"); String uri = '${classBuilder.library.uri}'; if (uri == 'dart:js' && classBuilder.fileUri.pathSegments.last == 'js_dart2js.dart' || uri == 'dart:_interceptors' && classBuilder.fileUri.pathSegments.last == 'js_number.dart') { // TODO(johnniwinther): Fix the dart2js libraries and remove the // above URIs. } else { bestSoFar = null; bestTypeSoFar = null; } break; } } } if (bestSoFar == null) { String name = classBuilder.fullNameForErrors; int length = classBuilder.isAnonymousMixinApplication ? 1 : name.length; List<LocatedMessage> context = declarations.map((ClassMember d) { return messageDeclaredMemberConflictsWithInheritedMemberCause .withLocation(d.fileUri, d.charOffset, d.fullNameForErrors.length); }).toList(); classBuilder.addProblem( templateCombinedMemberSignatureFailed.withArguments( classBuilder.fullNameForErrors, declarations.first.fullNameForErrors), classBuilder.charOffset, length, context: context); return null; } debug?.log("Combined Member Signature of ${fullNameForErrors}: " "${fullName(bestSoFar)}"); ProcedureKind kind = ProcedureKind.Method; Member bestMemberSoFar = bestSoFar.member; if (bestSoFar.isField || bestSoFar.isSetter || bestSoFar.isGetter) { kind = isSetter ? ProcedureKind.Setter : ProcedureKind.Getter; } else if (bestMemberSoFar is Procedure && bestMemberSoFar.kind == ProcedureKind.Operator) { kind = ProcedureKind.Operator; } if (modifyKernel) { debug?.log("Combined Member Signature of ${fullNameForErrors}: new " "ForwardingNode($classBuilder, $bestSoFar, $declarations, $kind)"); Member stub = new ForwardingNode( hierarchy, classBuilder, bestSoFar, declarations, kind) .finalize(); if (classBuilder.cls == stub.enclosingClass) { classBuilder.cls.addMember(stub); SourceLibraryBuilder library = classBuilder.library; if (bestSoFar.member is Procedure) { library.forwardersOrigins..add(stub)..add(bestSoFar.member); } debug?.log("Combined Member Signature of ${fullNameForErrors}: " "added stub $stub"); if (classBuilder.isMixinApplication) { return combinedMemberSignatureResult = bestSoFar.member; } else { return combinedMemberSignatureResult = stub; } } } debug?.log( "Combined Member Signature of ${fullNameForErrors}: picked bestSoFar"); return combinedMemberSignatureResult = bestSoFar.member; } @override DelayedMember withParent(ClassBuilder parent) { return parent == this.classBuilder ? this : new InterfaceConflict(parent, declarations, isSetter, modifyKernel); } static ClassMember combined(ClassBuilder parent, ClassMember a, ClassMember b, bool isSetter, bool createForwarders) { List<ClassMember> declarations = <ClassMember>[]; if (a is DelayedMember) { a.addAllDeclarationsTo(declarations); } else { declarations.add(a); } if (b is DelayedMember) { b.addAllDeclarationsTo(declarations); } else { addDeclarationIfDifferent(b, declarations); } if (declarations.length == 1) { return declarations.single; } else { return new InterfaceConflict( parent, declarations, isSetter, createForwarders); } } } class AbstractMemberOverridingImplementation extends DelayedMember { AbstractMemberOverridingImplementation( ClassBuilder parent, ClassMember abstractMember, ClassMember concreteImplementation, bool isSetter, bool modifyKernel) : super(parent, <ClassMember>[concreteImplementation, abstractMember], isSetter, modifyKernel); ClassMember get concreteImplementation => declarations[0]; ClassMember get abstractMember => declarations[1]; Member check(ClassHierarchyBuilder hierarchy) { if (!classBuilder.isAbstract && !hierarchy.nodes[classBuilder.cls].hasNoSuchMethod) { new DelayedOverrideCheck( classBuilder, concreteImplementation, abstractMember) .check(hierarchy); } ProcedureKind kind = ProcedureKind.Method; if (abstractMember.isSetter || abstractMember.isGetter) { kind = isSetter ? ProcedureKind.Setter : ProcedureKind.Getter; } if (modifyKernel) { // This call will add a body to the abstract method if needed for // isGenericCovariantImpl checks. new ForwardingNode( hierarchy, classBuilder, abstractMember, declarations, kind) .finalize(); } return abstractMember.member; } @override DelayedMember withParent(ClassBuilder parent) { return parent == this.classBuilder ? this : new AbstractMemberOverridingImplementation(parent, abstractMember, concreteImplementation, isSetter, modifyKernel); } static ClassMember selectAbstract(ClassMember declaration) { if (declaration is AbstractMemberOverridingImplementation) { return declaration.abstractMember; } else { return declaration; } } static ClassMember selectConcrete(ClassMember declaration) { if (declaration is AbstractMemberOverridingImplementation) { return declaration.concreteImplementation; } else { return declaration; } } } void addDeclarationIfDifferent( ClassMember declaration, List<ClassMember> declarations) { Member target = declaration.member; if (target is Procedure) { FunctionNode function = target.function; for (int i = 0; i < declarations.length; i++) { Member other = declarations[i].member; if (other is Procedure) { if (hasSameSignature(function, other.function)) return; } } } else { for (int i = 0; i < declarations.length; i++) { if (declaration == declarations[i]) return; } } declarations.add(declaration); } String fullName(ClassMember declaration) { String suffix = declaration.isSetter ? "=" : ""; if (declaration is DelayedMember) { return "${declaration.fullNameForErrors}$suffix"; } String className = declaration.classBuilder?.fullNameForErrors; return className == null ? "${declaration.fullNameForErrors}$suffix" : "${className}.${declaration.fullNameForErrors}$suffix"; } int compareNamedParameters(VariableDeclaration a, VariableDeclaration b) { return a.name.compareTo(b.name); } bool isAbstract(ClassMember declaration) { return declaration.member.isAbstract || declaration is InterfaceConflict; } bool inferParameterType( ClassBuilder classBuilder, ProcedureBuilder memberBuilder, FormalParameterBuilder parameterBuilder, DartType type, bool hadTypesInferred, ClassHierarchyBuilder hierarchy) { debug?.log("Inferred type ${type} for ${parameterBuilder}"); if (type == parameterBuilder.variable.type) return true; bool result = true; if (hadTypesInferred) { reportCantInferParameterType( classBuilder, memberBuilder, parameterBuilder, hierarchy); type = const InvalidType(); result = false; } parameterBuilder.variable.type = type; memberBuilder.hadTypesInferred = true; return result; } void reportCantInferParameterType(ClassBuilder cls, MemberBuilder member, FormalParameterBuilder parameter, ClassHierarchyBuilder hierarchy) { String name = parameter.name; cls.addProblem( templateCantInferTypeDueToInconsistentOverrides.withArguments(name), parameter.charOffset, name.length, wasHandled: true); } bool inferReturnType(ClassBuilder cls, ProcedureBuilder procedureBuilder, DartType type, bool hadTypesInferred, ClassHierarchyBuilder hierarchy) { if (type == procedureBuilder.procedure.function.returnType) return true; bool result = true; if (hadTypesInferred) { reportCantInferReturnType(cls, procedureBuilder, hierarchy); type = const InvalidType(); result = false; } else { procedureBuilder.hadTypesInferred = true; } procedureBuilder.procedure.function.returnType = type; return result; } void reportCantInferReturnType( ClassBuilder cls, MemberBuilder member, ClassHierarchyBuilder hierarchy) { String name = member.fullNameForErrors; List<LocatedMessage> context; // // TODO(ahe): The following is for debugging, but could be cleaned up and // // used to improve this error message in general. // // context = <LocatedMessage>[]; // ClassHierarchyNode supernode = hierarchy.getNodeFromType(cls.supertype); // // TODO(ahe): Wrong template. // Template<Message Function(String)> template = // templateMissingImplementationCause; // if (supernode != null) { // Declaration superMember = // supernode.getInterfaceMember(new Name(name), false); // if (superMember != null) { // context.add(template // .withArguments(name) // .withLocation( // superMember.fileUri, superMember.charOffset, name.length)); // } // superMember = supernode.getInterfaceMember(new Name(name), true); // if (superMember != null) { // context.add(template // .withArguments(name) // .withLocation( // superMember.fileUri, superMember.charOffset, name.length)); // } // } // List<TypeBuilder> directInterfaces = cls.interfaces; // for (int i = 0; i < directInterfaces.length; i++) { // ClassHierarchyNode supernode = // hierarchy.getNodeFromType(directInterfaces[i]); // if (supernode != null) { // Declaration superMember = // supernode.getInterfaceMember(new Name(name), false); // if (superMember != null) { // context.add(template // .withArguments(name) // .withLocation( // superMember.fileUri, superMember.charOffset, name.length)); // } // superMember = supernode.getInterfaceMember(new Name(name), true); // if (superMember != null) { // context.add(template // .withArguments(name) // .withLocation( // superMember.fileUri, superMember.charOffset, name.length)); // } // } // } cls.addProblem( templateCantInferReturnTypeDueToInconsistentOverrides.withArguments(name), member.charOffset, name.length, wasHandled: true, context: context); } void reportCantInferFieldType(ClassBuilder cls, FieldBuilder member) { String name = member.fullNameForErrors; cls.addProblem( templateCantInferTypeDueToInconsistentOverrides.withArguments(name), member.charOffset, name.length, wasHandled: true); } ClassBuilder getClass(TypeBuilder type) { Builder declaration = type.declaration; return declaration is ClassBuilder ? declaration : null; } bool hasExplicitReturnType(ClassMember declaration) { assert(declaration is ProcedureBuilder || declaration is DillMemberBuilder, "${declaration.runtimeType}"); return declaration is ProcedureBuilder ? declaration.returnType != null : true; } bool hasExplicitlyTypedFormalParameter(ClassMember declaration, int index) { assert(declaration is ProcedureBuilder || declaration is DillMemberBuilder, "${declaration.runtimeType}"); return declaration is ProcedureBuilder ? declaration.formals[index].type != null : true; }
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/kernel/type_labeler.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert' show json; import 'package:kernel/ast.dart' show BoolConstant, BottomType, Class, Constant, ConstantMapEntry, DartType, DoubleConstant, DynamicType, Field, FunctionType, InvalidType, InstanceConstant, IntConstant, InterfaceType, Library, ListConstant, MapConstant, NullConstant, PartialInstantiationConstant, Procedure, SetConstant, StringConstant, SymbolConstant, TearOffConstant, TreeNode, TypedefType, TypeLiteralConstant, TypeParameter, TypeParameterType, UnevaluatedConstant, VoidType; import 'package:kernel/visitor.dart' show ConstantVisitor, DartTypeVisitor; import '../blacklisted_classes.dart' show blacklistedCoreClasses; import '../fasta_codes.dart' show Message, templateTypeOrigin, templateTypeOriginWithFileUri; import '../problems.dart' show unsupported; /// A pretty-printer for Kernel types and constants with the ability to label /// raw types with numeric markers in Dart comments (e.g. `/*1*/`) to /// distinguish different types with the same name. This is used in diagnostic /// messages to indicate the origins of types occurring in the message. class TypeLabeler implements DartTypeVisitor<void>, ConstantVisitor<void> { List<LabeledNode> names = <LabeledNode>[]; Map<String, List<LabeledNode>> nameMap = <String, List<LabeledNode>>{}; List<Object> result; /// Pretty-print a type. /// When all types and constants appearing in the same message have been /// pretty-printed, the returned list can be converted to its string /// representation (with labels on duplicated names) by the `join()` method. List<Object> labelType(DartType type) { // TODO(askesc): Remove null check when we are completely null clean here. if (type == null) return ["null-type"]; result = []; type.accept(this); return result; } /// Pretty-print a constant. /// When all types and constants appearing in the same message have been /// pretty-printed, the returned list can be converted to its string /// representation (with labels on duplicated names) by the `join()` method. List<Object> labelConstant(Constant constant) { // TODO(askesc): Remove null check when we are completely null clean here. if (constant == null) return ["null-constant"]; result = []; constant.accept(this); return result; } /// Get a textual description of the origins of the raw types appearing in /// types and constants that have been pretty-printed using this labeler. String get originMessages { StringBuffer messages = new StringBuffer(); for (LabeledNode name in names) { messages.write(name.originMessage); } return messages.toString(); } // We don't have access to coreTypes here, so we have our own Object check. static bool isObject(DartType type) { if (type is InterfaceType && type.classNode.name == 'Object') { Uri importUri = type.classNode.enclosingLibrary.importUri; return importUri.scheme == 'dart' && importUri.path == 'core'; } return false; } LabeledNode nameForEntity( TreeNode node, String nodeName, Uri importUri, Uri fileUri) { List<LabeledNode> labelsForName = nameMap[nodeName]; if (labelsForName == null) { // First encountered entity with this name LabeledNode name = new LabeledNode(node, nodeName, importUri, fileUri, this); names.add(name); nameMap[nodeName] = [name]; return name; } else { for (LabeledNode entityForName in labelsForName) { if (entityForName.node == node) { // Previously encountered entity return entityForName; } } // New entity with name that was previously encountered LabeledNode name = new LabeledNode(node, nodeName, importUri, fileUri, this); names.add(name); labelsForName.add(name); return name; } } void defaultDartType(DartType type) {} void visitTypedefType(TypedefType node) {} void visitInvalidType(InvalidType node) { // TODO(askesc): Throw internal error if InvalidType appears in diagnostics. result.add("invalid-type"); } void visitBottomType(BottomType node) { // TODO(askesc): Throw internal error if BottomType appears in diagnostics. result.add("bottom-type"); } void visitDynamicType(DynamicType node) { result.add("dynamic"); } void visitVoidType(VoidType node) { result.add("void"); } void visitTypeParameterType(TypeParameterType node) { TreeNode parent = node.parameter; while (parent is! Library && parent != null) { parent = parent.parent; } // Note that this can be null if, for instance, the erroneous code is not // actually in the tree - then we don't know where it comes from! Library enclosingLibrary = parent; result.add(nameForEntity( node.parameter, node.parameter.name, enclosingLibrary == null ? unknownUri : enclosingLibrary.importUri, enclosingLibrary == null ? unknownUri : enclosingLibrary.fileUri)); } void visitFunctionType(FunctionType node) { node.returnType.accept(this); result.add(" Function"); if (node.typeParameters.isNotEmpty) { result.add("<"); bool first = true; for (TypeParameter param in node.typeParameters) { if (!first) result.add(", "); result.add(param.name); if (isObject(param.bound) && param.defaultType is DynamicType) { // Bound was not specified, and therefore should not be printed. } else { result.add(" extends "); param.bound.accept(this); } first = false; } result.add(">"); } result.add("("); bool first = true; for (int i = 0; i < node.requiredParameterCount; i++) { if (!first) result.add(", "); node.positionalParameters[i].accept(this); first = false; } if (node.positionalParameters.length > node.requiredParameterCount) { if (node.requiredParameterCount > 0) result.add(", "); result.add("["); first = true; for (int i = node.requiredParameterCount; i < node.positionalParameters.length; i++) { if (!first) result.add(", "); node.positionalParameters[i].accept(this); first = false; } result.add("]"); } if (node.namedParameters.isNotEmpty) { if (node.positionalParameters.isNotEmpty) result.add(", "); result.add("{"); first = true; for (int i = 0; i < node.namedParameters.length; i++) { if (!first) result.add(", "); node.namedParameters[i].type.accept(this); result.add(" ${node.namedParameters[i].name}"); first = false; } result.add("}"); } result.add(")"); } void visitInterfaceType(InterfaceType node) { Class classNode = node.classNode; result.add(nameForEntity( classNode, classNode.name, classNode.enclosingLibrary.importUri, classNode.enclosingLibrary.fileUri)); if (node.typeArguments.isNotEmpty) { result.add("<"); bool first = true; for (DartType typeArg in node.typeArguments) { if (!first) result.add(", "); typeArg.accept(this); first = false; } result.add(">"); } } void defaultConstant(Constant node) {} void visitNullConstant(NullConstant node) { result.add(node); } void visitBoolConstant(BoolConstant node) { result.add(node); } void visitIntConstant(IntConstant node) { result.add(node); } void visitDoubleConstant(DoubleConstant node) { result.add(node); } void visitSymbolConstant(SymbolConstant node) { result.add(node); } void visitStringConstant(StringConstant node) { result.add(json.encode(node.value)); } void visitInstanceConstant(InstanceConstant node) { new InterfaceType(node.classNode, node.typeArguments).accept(this); result.add(" {"); bool first = true; for (Field field in node.classNode.fields) { if (field.isStatic) continue; if (!first) result.add(", "); result.add("${field.name}: "); node.fieldValues[field.reference].accept(this); first = false; } result.add("}"); } void visitListConstant(ListConstant node) { result.add("<"); node.typeArgument.accept(this); result.add(">["); bool first = true; for (Constant constant in node.entries) { if (!first) result.add(", "); constant.accept(this); first = false; } result.add("]"); } void visitSetConstant(SetConstant node) { result.add("<"); node.typeArgument.accept(this); result.add(">{"); bool first = true; for (Constant constant in node.entries) { if (!first) result.add(", "); constant.accept(this); first = false; } result.add("}"); } void visitMapConstant(MapConstant node) { result.add("<"); node.keyType.accept(this); result.add(", "); node.valueType.accept(this); result.add(">{"); bool first = true; for (ConstantMapEntry entry in node.entries) { if (!first) result.add(", "); entry.key.accept(this); result.add(": "); entry.value.accept(this); first = false; } result.add("}"); } void visitTearOffConstant(TearOffConstant node) { Procedure procedure = node.procedure; Class classNode = procedure.enclosingClass; if (classNode != null) { result.add(nameForEntity( classNode, classNode.name, classNode.enclosingLibrary.importUri, classNode.enclosingLibrary.fileUri)); result.add("."); } result.add(procedure.name.name); } void visitPartialInstantiationConstant(PartialInstantiationConstant node) { node.tearOffConstant.accept(this); if (node.types.isNotEmpty) { result.add("<"); bool first = true; for (DartType typeArg in node.types) { if (!first) result.add(", "); typeArg.accept(this); first = false; } result.add(">"); } } void visitTypeLiteralConstant(TypeLiteralConstant node) { node.type.accept(this); } void visitUnevaluatedConstant(UnevaluatedConstant node) { unsupported('printing unevaluated constants', -1, null); } } final Uri unknownUri = Uri.parse("unknown"); class LabeledNode { final TreeNode node; final TypeLabeler typeLabeler; final String name; final Uri importUri; final Uri fileUri; LabeledNode( this.node, this.name, this.importUri, this.fileUri, this.typeLabeler); String toString() { List<LabeledNode> entityForName = typeLabeler.nameMap[name]; if (entityForName.length == 1) { return name; } return "$name/*${entityForName.indexOf(this) + 1}*/"; } String get originMessage { if (importUri.scheme == 'dart' && importUri.path == 'core') { if (node is Class && blacklistedCoreClasses.contains(name)) { // Blacklisted core class. Only print if ambiguous. List<LabeledNode> entityForName = typeLabeler.nameMap[name]; if (entityForName.length == 1) { return ""; } } } if (importUri == unknownUri || node is! Class) { // We don't know where it comes from and/or it's not a class. // Only print if ambiguous. List<LabeledNode> entityForName = typeLabeler.nameMap[name]; if (entityForName.length == 1) { return ""; } } Message message = (importUri == fileUri || importUri.scheme == 'dart') ? templateTypeOrigin.withArguments(toString(), importUri) : templateTypeOriginWithFileUri.withArguments( toString(), importUri, fileUri); return "\n - " + message.message; } }
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/kernel/constness.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.constness; enum Constness { explicitConst, explicitNew, implicit, }
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/kernel/redirecting_factory_body.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.redirecting_factory_body; import 'package:kernel/ast.dart' show DartType, Expression, ExpressionStatement, FunctionNode, InvalidExpression, Let, Member, NullLiteral, Procedure, StaticGet, StringLiteral, TypeParameterType, VariableDeclaration; import 'package:kernel/type_algebra.dart' show Substitution; import 'body_builder.dart' show EnsureLoaded; const String letName = "#redirecting_factory"; class RedirectingFactoryBody extends ExpressionStatement { RedirectingFactoryBody.internal(Expression value, [List<DartType> typeArguments]) : super(new Let(new VariableDeclaration(letName, initializer: value), encodeTypeArguments(typeArguments))); RedirectingFactoryBody(Member target, [List<DartType> typeArguments]) : this.internal(new StaticGet(target), typeArguments); RedirectingFactoryBody.unresolved(String name) : this.internal(new StringLiteral(name)); Member get target { dynamic value = getValue(expression); return value is StaticGet ? value.target : null; } String get unresolvedName { dynamic value = getValue(expression); return value is StringLiteral ? value.value : null; } bool get isUnresolved => unresolvedName != null; List<DartType> get typeArguments { if (expression is Let) { Let bodyExpression = expression; if (bodyExpression.variable.name == letName) { return decodeTypeArguments(bodyExpression.body); } } return null; } static getValue(Expression expression) { if (expression is Let) { VariableDeclaration variable = expression.variable; if (variable.name == letName) { return variable.initializer; } } return null; } static void restoreFromDill(Procedure factory) { // This is a hack / work around for storing redirecting constructors in // dill files. See `ClassBuilder.addRedirectingConstructor` in // [kernel_class_builder.dart](kernel_class_builder.dart). FunctionNode function = factory.function; ExpressionStatement statement = function.body; List<DartType> typeArguments; if (statement.expression is Let) { Let expression = statement.expression; typeArguments = decodeTypeArguments(expression.body); } function.body = new RedirectingFactoryBody.internal( getValue(statement.expression), typeArguments) ..parent = function; } static Expression encodeTypeArguments(List<DartType> typeArguments) { String varNamePrefix = "#typeArg"; Expression result = new InvalidExpression(null); if (typeArguments == null) { return result; } for (int i = typeArguments.length - 1; i >= 0; i--) { result = new Let( new VariableDeclaration("$varNamePrefix$i", type: typeArguments[i], initializer: new NullLiteral()), result); } return result; } static List<DartType> decodeTypeArguments(Expression encoded) { if (encoded is InvalidExpression) { return null; } List<DartType> result = <DartType>[]; while (encoded is Let) { Let head = encoded; result.add(head.variable.type); encoded = head.body; } return result; } } bool isRedirectingFactory(Member member, {EnsureLoaded helper}) { assert(helper == null || helper.isLoaded(member)); return member is Procedure && member.function.body is RedirectingFactoryBody; } RedirectingFactoryBody getRedirectingFactoryBody(Member member) { return isRedirectingFactory(member) ? member.function.body : null; } class RedirectionTarget { final Member target; final List<DartType> typeArguments; RedirectionTarget(this.target, this.typeArguments); } RedirectionTarget getRedirectionTarget(Procedure member, EnsureLoaded helper) { List<DartType> typeArguments = <DartType>[]..length = member.function.typeParameters.length; for (int i = 0; i < typeArguments.length; i++) { typeArguments[i] = new TypeParameterType(member.function.typeParameters[i]); } // We use the [tortoise and hare algorithm] // (https://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare) to // handle cycles. Member tortoise = member; RedirectingFactoryBody tortoiseBody = getRedirectingFactoryBody(tortoise); Member hare = tortoiseBody?.target; helper.ensureLoaded(hare); RedirectingFactoryBody hareBody = getRedirectingFactoryBody(hare); while (tortoise != hare) { if (tortoiseBody?.isUnresolved ?? true) { return new RedirectionTarget(tortoise, typeArguments); } Member nextTortoise = tortoiseBody.target; helper.ensureLoaded(nextTortoise); List<DartType> nextTypeArguments = tortoiseBody.typeArguments; if (nextTypeArguments == null) { nextTypeArguments = <DartType>[]; } Substitution sub = Substitution.fromPairs(tortoise.function.typeParameters, typeArguments); typeArguments = <DartType>[]..length = nextTypeArguments.length; for (int i = 0; i < typeArguments.length; i++) { typeArguments[i] = sub.substituteType(nextTypeArguments[i]); } tortoise = nextTortoise; tortoiseBody = getRedirectingFactoryBody(tortoise); helper.ensureLoaded(hareBody?.target); hare = getRedirectingFactoryBody(hareBody?.target)?.target; helper.ensureLoaded(hare); hareBody = getRedirectingFactoryBody(hare); } 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/util/link.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.util.link; import 'link_implementation.dart' show LinkBuilderImplementation, LinkEntry, LinkIterator, MappedLinkIterable; class Link<T> implements Iterable<T> { T get head => throw new StateError("no elements"); Link<T> get tail => null; const Link(); Link<T> prepend(T element) { return new LinkEntry<T>(element, this); } Iterator<T> get iterator => new LinkIterator<T>(this); void printOn(StringBuffer buffer, [separatedBy]) {} List<T> toList({bool growable: true}) { List<T> result; if (!growable) { result = new List<T>(slowLength()); } else { result = new List<T>(); result.length = slowLength(); } int i = 0; for (Link<T> link = this; !link.isEmpty; link = link.tail) { result[i++] = link.head; } return result; } /// Lazily maps over this linked list, returning an [Iterable]. Iterable<K> map<K>(K fn(T item)) { return new MappedLinkIterable<T, K>(this, fn); } /// Invokes `fn` for every item in the linked list and returns the results /// in a [List]. List<E> mapToList<E>(E fn(T item), {bool growable: true}) { List<E> result; if (!growable) { result = new List<E>(slowLength()); } else { result = new List<E>(); result.length = slowLength(); } int i = 0; for (Link<T> link = this; !link.isEmpty; link = link.tail) { result[i++] = fn(link.head); } return result; } bool get isEmpty => true; bool get isNotEmpty => false; Link<T> reverse(Link<T> tail) => this; Link<T> reversePrependAll(Link<T> from) { if (from.isEmpty) return this; return this.prepend(from.head).reversePrependAll(from.tail); } Link<T> skip(int n) { if (n == 0) return this; throw new RangeError('Index $n out of range'); } void forEach(void f(T element)) {} bool operator ==(other) { if (other is! Link<T>) return false; return other.isEmpty; } int get hashCode => throw new UnsupportedError('Link.hashCode'); String toString() => "[]"; get length { throw new UnsupportedError('get:length'); } int slowLength() => 0; // TODO(ahe): Remove this method? bool contains(Object element) { for (Link<T> link = this; !link.isEmpty; link = link.tail) { if (link.head == element) return true; } return false; } // TODO(ahe): Remove this method? T get single { if (isEmpty) throw new StateError('No elements'); if (!tail.isEmpty) throw new StateError('More than one element'); return head; } // TODO(ahe): Remove this method? T get first { if (isEmpty) throw new StateError('No elements'); return head; } /// Returns true if f returns true for all elements of this list. /// /// Returns true for the empty list. bool every(bool f(T e)) { for (Link<T> link = this; !link.isEmpty; link = link.tail) { if (!f(link.head)) return false; } return true; } // // Unsupported Iterable<T> methods. // bool any(bool f(T e)) => _unsupported('any'); Iterable<T> cast<T>() => _unsupported('cast'); T elementAt(int i) => _unsupported('elementAt'); Iterable<K> expand<K>(Iterable<K> f(T e)) => _unsupported('expand'); T firstWhere(bool f(T e), {T orElse()}) => _unsupported('firstWhere'); K fold<K>(K initialValue, K combine(K value, T element)) { return _unsupported('fold'); } Iterable<T> followedBy(Iterable<T> other) => _unsupported('followedBy'); T get last => _unsupported('get:last'); T lastWhere(bool f(T e), {T orElse()}) => _unsupported('lastWhere'); String join([separator = '']) => _unsupported('join'); T reduce(T combine(T a, T b)) => _unsupported('reduce'); Iterable<T> retype<T>() => _unsupported('retype'); T singleWhere(bool f(T e), {T orElse()}) => _unsupported('singleWhere'); Iterable<T> skipWhile(bool f(T e)) => _unsupported('skipWhile'); Iterable<T> take(int n) => _unsupported('take'); Iterable<T> takeWhile(bool f(T e)) => _unsupported('takeWhile'); Set<T> toSet() => _unsupported('toSet'); Iterable<T> whereType<T>() => _unsupported('whereType'); Iterable<T> where(bool f(T e)) => _unsupported('where'); _unsupported(String method) => throw new UnsupportedError(method); } /// Builder object for creating linked lists using [Link] or fixed-length [List] /// objects. abstract class LinkBuilder<T> { factory LinkBuilder() = LinkBuilderImplementation<T>; /// Prepends all elements added to the builder to [tail]. The resulting list /// is returned and the builder is cleared. Link<T> toLink(Link<T> tail); /// Creates a new fixed length containing all added elements. The /// resulting list is returned and the builder is cleared. List<T> toList(); /// Adds the element [t] to the end of the list being built. Link<T> addLast(T t); /// Returns the first element in the list being built. T get first; /// Returns the number of elements in the list being built. final int length; /// Returns `true` if the list being built is empty. final bool isEmpty; /// Removes all added elements and resets the builder. void clear(); }
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/util/link_implementation.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.util.link_implementation; import 'dart:collection' show IterableBase; import 'link.dart' show Link, LinkBuilder; class LinkIterator<T> implements Iterator<T> { T _current; Link<T> _link; LinkIterator(this._link); T get current => _current; bool moveNext() { if (_link.isEmpty) { _current = null; return false; } _current = _link.head; _link = _link.tail; return true; } } typedef T Transformation<S, T>(S input); class MappedLinkIterator<S, T> extends Iterator<T> { Transformation<S, T> _transformation; Link<S> _link; T _current; MappedLinkIterator(this._link, this._transformation); T get current => _current; bool moveNext() { if (_link.isEmpty) { _current = null; return false; } _current = _transformation(_link.head); _link = _link.tail; return true; } } class MappedLinkIterable<S, T> extends IterableBase<T> { Transformation<S, T> _transformation; Link<S> _link; MappedLinkIterable(this._link, this._transformation); Iterator<T> get iterator { return new MappedLinkIterator<S, T>(_link, _transformation); } } class LinkEntry<T> extends Link<T> { final T head; Link<T> tail; LinkEntry(this.head, [Link<T> tail]) : tail = tail ?? const Link<Null>(); Link<T> prepend(T element) { // TODO(ahe): Use new Link<T>, but this cost 8% performance on VM. return new LinkEntry<T>(element, this); } void printOn(StringBuffer buffer, [separatedBy]) { buffer.write(head); if (separatedBy == null) separatedBy = ''; for (Link<T> link = tail; link.isNotEmpty; link = link.tail) { buffer.write(separatedBy); buffer.write(link.head); } } String toString() { StringBuffer buffer = new StringBuffer(); buffer.write('[ '); printOn(buffer, ', '); buffer.write(' ]'); return buffer.toString(); } @override Link<T> reverse(Link<T> tail) { Link<T> result = tail; for (Link<T> link = this; link.isNotEmpty; link = link.tail) { result = result.prepend(link.head); } return result; } Link<T> reversePrependAll(Link<T> from) { Link<T> result; for (result = this; from.isNotEmpty; from = from.tail) { result = result.prepend(from.head); } return result; } Link<T> skip(int n) { Link<T> link = this; for (int i = 0; i < n; i++) { if (link.isEmpty) { throw new RangeError('Index $n out of range'); } link = link.tail; } return link; } bool get isEmpty => false; bool get isNotEmpty => true; void forEach(void f(T element)) { for (Link<T> link = this; link.isNotEmpty; link = link.tail) { f(link.head); } } bool operator ==(other) { if (other is! Link<T>) return false; Link<T> myElements = this; while (myElements.isNotEmpty && other.isNotEmpty) { if (myElements.head != other.head) { return false; } myElements = myElements.tail; other = other.tail; } return myElements.isEmpty && other.isEmpty; } int get hashCode => throw new UnsupportedError('LinkEntry.hashCode'); int slowLength() { int length = 0; for (Link<T> current = this; current.isNotEmpty; current = current.tail) { ++length; } return length; } } class LinkBuilderImplementation<T> implements LinkBuilder<T> { LinkEntry<T> head = null; LinkEntry<T> lastLink = null; int length = 0; LinkBuilderImplementation(); @override Link<T> toLink(Link<T> tail) { if (head == null) return tail; lastLink.tail = tail; Link<T> link = head; lastLink = null; head = null; length = 0; return link; } List<T> toList() { if (length == 0) return new List<T>(0); List<T> list = new List<T>(length); int index = 0; Link<T> link = head; while (link.isNotEmpty) { list[index] = link.head; link = link.tail; index++; } lastLink = null; head = null; length = 0; return list; } Link<T> addLast(T t) { length++; LinkEntry<T> entry = new LinkEntry<T>(t, null); if (head == null) { head = entry; } else { lastLink.tail = entry; } lastLink = entry; return entry; } bool get isEmpty => length == 0; T get first { if (head != null) { return head.head; } throw new StateError("no elements"); } void clear() { head = null; lastLink = null; length = 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/util/error_reporter_file_copier.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:io' show Directory, File, GZipCodec; Uri saveAsGzip(List<int> data, String filename) { // TODO(jensj): This should be done via the FileSystem instead, but it // currently doesn't support writing. GZipCodec gZipCodec = new GZipCodec(); List<int> gzippedInitializedFromData = gZipCodec.encode(data); Directory tempDir = Directory.systemTemp.createTempSync("$filename"); File file = new File("${tempDir.path}/${filename}.gz"); file.writeAsBytesSync(gzippedInitializedFromData); return file.uri; }
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/util/relativize.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.util.relativize; import 'dart:math'; String relativizeUri(Uri base, Uri uri, bool isWindows) { bool equalsNCS(String a, String b) { return a.toLowerCase() == b.toLowerCase(); } if (!equalsNCS(base.scheme, uri.scheme) || equalsNCS(base.scheme, 'dart') || equalsNCS(base.scheme, 'package')) { return uri.toString(); } if (!equalsNCS(base.scheme, 'file')) { isWindows = false; } String normalize(String path) { if (isWindows) { return path.toLowerCase(); } else { return path; } } if (base.userInfo == uri.userInfo && equalsNCS(base.host, uri.host) && base.port == uri.port && uri.query == "" && uri.fragment == "") { if (normalize(uri.path).startsWith(normalize(base.path))) { return uri.path.substring(base.path.lastIndexOf('/') + 1); } if (!base.path.startsWith('/') || !uri.path.startsWith('/')) { return uri.toString(); } List<String> uriParts = uri.path.split('/'); List<String> baseParts = base.path.split('/'); int common = 0; int length = min(uriParts.length, baseParts.length); while (common < length && normalize(uriParts[common]) == normalize(baseParts[common])) { common++; } if (common == 1 || (isWindows && common == 2)) { // The first part will always be an empty string because the // paths are absolute. On Windows, we must also consider drive // letters or hostnames. if (baseParts.length > common + 1) { // Avoid using '..' to go to the root, unless we are already there. return uri.path; } } StringBuffer sb = new StringBuffer(); for (int i = common + 1; i < baseParts.length; i++) { sb.write('../'); } for (int i = common; i < uriParts.length - 1; i++) { sb.write('${uriParts[i]}/'); } sb.write('${uriParts.last}'); return sb.toString(); } return uri.toString(); }
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/util/bytes_sink.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 BytesBuilder; // TODO(ahe): https://github.com/dart-lang/sdk/issues/28316 class BytesSink implements Sink<List<int>> { final BytesBuilder builder = new BytesBuilder(); void add(List<int> data) { builder.add(data); } void close() { // Nothing to do. } }
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/type_inference/type_inference_engine.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'package:kernel/ast.dart' show Constructor, DartType, DartTypeVisitor, DynamicType, Field, FunctionType, InterfaceType, Member, NamedType, TypeParameter, TypeParameterType, TypedefType, VariableDeclaration; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy; import 'package:kernel/core_types.dart' show CoreTypes; import '../../base/instrumentation.dart' show Instrumentation; import '../kernel/kernel_builder.dart' show ClassHierarchyBuilder, ImplicitFieldType, LibraryBuilder; import '../source/source_library_builder.dart' show SourceLibraryBuilder; import 'type_inferrer.dart' show TypeInferrer; import 'type_schema_environment.dart' show TypeSchemaEnvironment; enum Variance { covariant, contravariant, invariant, } Variance invertVariance(Variance variance) { switch (variance) { case Variance.covariant: return Variance.contravariant; case Variance.contravariant: return Variance.covariant; case Variance.invariant: } return variance; } /// Visitor to check whether a given type mentions any of a class's type /// parameters in a non-covariant fashion. class IncludesTypeParametersNonCovariantly extends DartTypeVisitor<bool> { Variance _variance; final List<TypeParameter> _typeParametersToSearchFor; IncludesTypeParametersNonCovariantly(this._typeParametersToSearchFor, {Variance initialVariance}) : _variance = initialVariance; @override bool defaultDartType(DartType node) => false; @override bool visitFunctionType(FunctionType node) { if (node.returnType.accept(this)) return true; Variance oldVariance = _variance; _variance = Variance.invariant; for (TypeParameter parameter in node.typeParameters) { if (parameter.bound.accept(this)) return true; } _variance = invertVariance(oldVariance); for (DartType parameter in node.positionalParameters) { if (parameter.accept(this)) return true; } for (NamedType parameter in node.namedParameters) { if (parameter.type.accept(this)) return true; } _variance = oldVariance; return false; } @override bool visitInterfaceType(InterfaceType node) { for (DartType argument in node.typeArguments) { if (argument.accept(this)) return true; } return false; } @override bool visitTypedefType(TypedefType node) { return node.unalias.accept(this); } @override bool visitTypeParameterType(TypeParameterType node) { return _variance != Variance.covariant && _typeParametersToSearchFor.contains(node.parameter); } } /// Keeps track of the global state for the type inference that occurs outside /// of method bodies and initializers. /// /// This class describes the interface for use by clients of type inference /// (e.g. DietListener). Derived classes should derive from /// [TypeInferenceEngineImpl]. abstract class TypeInferenceEngine { ClassHierarchy classHierarchy; ClassHierarchyBuilder hierarchyBuilder; CoreTypes coreTypes; /// Indicates whether the "prepare" phase of type inference is complete. bool isTypeInferencePrepared = false; TypeSchemaEnvironment typeSchemaEnvironment; /// A map containing constructors with initializing formals whose types /// need to be inferred. /// /// This is represented as a map from a constructor to its library /// builder because the builder is used to report errors due to cyclic /// inference dependencies. final Map<Constructor, LibraryBuilder> toBeInferred = {}; /// A map containing constructors in the process of being inferred. /// /// This is used to detect cyclic inference dependencies. It is represented /// as a map from a constructor to its library builder because the builder /// is used to report errors. final Map<Constructor, LibraryBuilder> beingInferred = {}; final Instrumentation instrumentation; TypeInferenceEngine(this.instrumentation); /// Creates a type inferrer for use inside of a method body declared in a file /// with the given [uri]. TypeInferrer createLocalTypeInferrer( Uri uri, InterfaceType thisType, SourceLibraryBuilder library); /// Creates a [TypeInferrer] object which is ready to perform type inference /// on the given [field]. TypeInferrer createTopLevelTypeInferrer( Uri uri, InterfaceType thisType, SourceLibraryBuilder library); /// Performs the third phase of top level inference, which is to visit all /// constructors still needing inference and infer the types of their /// initializing formals from the corresponding fields. void finishTopLevelInitializingFormals() { // Field types have all been inferred so there cannot be a cyclic // dependency. for (Constructor constructor in toBeInferred.keys) { for (VariableDeclaration declaration in constructor.function.positionalParameters) { inferInitializingFormal(declaration, constructor); } for (VariableDeclaration declaration in constructor.function.namedParameters) { inferInitializingFormal(declaration, constructor); } } toBeInferred.clear(); } void inferInitializingFormal(VariableDeclaration formal, Constructor parent) { if (formal.type == null) { for (Field field in parent.enclosingClass.fields) { if (field.name.name == formal.name) { TypeInferenceEngine.resolveInferenceNode(field); formal.type = field.type; return; } } // We did not find the corresponding field, so the program is erroneous. // The error should have been reported elsewhere and type inference // should continue by inferring dynamic. formal.type = const DynamicType(); } } /// Gets ready to do top level type inference for the component having the /// given [hierarchy], using the given [coreTypes]. void prepareTopLevel(CoreTypes coreTypes, ClassHierarchy hierarchy) { this.coreTypes = coreTypes; this.classHierarchy = hierarchy; this.typeSchemaEnvironment = new TypeSchemaEnvironment(coreTypes, hierarchy); } static Member resolveInferenceNode(Member member) { if (member is Field) { DartType type = member.type; if (type is ImplicitFieldType) { if (type.member.target != member) { type.member.inferCopiedType(member); } else { type.member.inferType(); } } } return 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/type_inference/inference_helper.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:core' hide MapEntry; import 'package:kernel/ast.dart'; import 'package:kernel/core_types.dart' show CoreTypes; import '../fasta_codes.dart' show LocatedMessage, Message; import '../kernel/forest.dart'; abstract class InferenceHelper { CoreTypes get coreTypes; Uri get uri; Forest get forest; set transformSetLiterals(bool value); Expression buildProblem(Message message, int charOffset, int length, {List<LocatedMessage> context, bool suppressMessage}); LocatedMessage checkArgumentsForType( FunctionType function, Arguments arguments, int offset); void addProblem(Message message, int charOffset, int length, {List<LocatedMessage> context, bool wasHandled}); Expression wrapInProblem(Expression expression, Message message, int length, {List<LocatedMessage> context}); String constructorNameForDiagnostics(String name, {String className, bool isSuper}); }
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/type_inference/type_constraint_gatherer.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'package:kernel/ast.dart' show Class, DartType, DynamicType, FunctionType, InterfaceType, Member, Name, NamedType, Procedure, TypeParameter, TypeParameterType, VoidType; import 'package:kernel/type_algebra.dart' show substitute, Substitution; import 'type_schema.dart' show UnknownType; import 'type_schema_environment.dart' show TypeConstraint, TypeSchemaEnvironment, substituteTypeParams; import '../names.dart' show callName; import 'type_schema.dart'; import 'type_schema_environment.dart'; /// Creates a collection of [TypeConstraint]s corresponding to type parameters, /// based on an attempt to make one type schema a subtype of another. abstract class TypeConstraintGatherer { final _protoConstraints = <_ProtoConstraint>[]; final List<TypeParameter> _parametersToConstrain; /// Creates a [TypeConstraintGatherer] which is prepared to gather type /// constraints for the given [typeParameters]. TypeConstraintGatherer.subclassing(Iterable<TypeParameter> typeParameters) : _parametersToConstrain = typeParameters.toList(); factory TypeConstraintGatherer(TypeSchemaEnvironment environment, Iterable<TypeParameter> typeParameters) { return new TypeSchemaConstraintGatherer(environment, typeParameters); } Class get objectClass; Class get functionClass; Class get futureOrClass; Class get nullClass; void addUpperBound(TypeConstraint constraint, DartType upper); void addLowerBound(TypeConstraint constraint, DartType lower); Member getInterfaceMember(Class class_, Name name, {bool setter: false}); InterfaceType getTypeAsInstanceOf(InterfaceType type, Class superclass); InterfaceType futureType(DartType type); /// Returns the set of type constraints that was gathered. Map<TypeParameter, TypeConstraint> computeConstraints() { Map<TypeParameter, TypeConstraint> result = <TypeParameter, TypeConstraint>{}; for (TypeParameter parameter in _parametersToConstrain) { result[parameter] = new TypeConstraint(); } for (_ProtoConstraint protoConstraint in _protoConstraints) { if (protoConstraint.isUpper) { addUpperBound(result[protoConstraint.parameter], protoConstraint.bound); } else { addLowerBound(result[protoConstraint.parameter], protoConstraint.bound); } } return result; } /// Tries to match [subtype] against [supertype]. /// /// If the match succeeds, the resulting type constraints are recorded for /// later use by [computeConstraints]. If the match fails, the set of type /// constraints is unchanged. bool trySubtypeMatch(DartType subtype, DartType supertype) { int oldProtoConstraintsLength = _protoConstraints.length; bool isMatch = _isSubtypeMatch(subtype, supertype); if (!isMatch) { _protoConstraints.length = oldProtoConstraintsLength; } return isMatch; } void _constrainLower(TypeParameter parameter, DartType lower) { _protoConstraints.add(new _ProtoConstraint.lower(parameter, lower)); } void _constrainUpper(TypeParameter parameter, DartType upper) { _protoConstraints.add(new _ProtoConstraint.upper(parameter, upper)); } bool _isFunctionSubtypeMatch(FunctionType subtype, FunctionType supertype) { // A function type `(M0,..., Mn, [M{n+1}, ..., Mm]) -> R0` is a subtype // match for a function type `(N0,..., Nk, [N{k+1}, ..., Nr]) -> R1` with // respect to `L` under constraints `C0 + ... + Cr + C` // - If `R0` is a subtype match for a type `R1` with respect to `L` under // constraints `C`: // - If `n <= k` and `r <= m`. // - And for `i` in `0...r`, `Ni` is a subtype match for `Mi` with respect // to `L` under constraints `Ci`. // Function types with named parameters are treated analogously to the // positional parameter case above. // A generic function type `<T0 extends B0, ..., Tn extends Bn>F0` is a // subtype match for a generic function type `<S0 extends B0, ..., Sn // extends Bn>F1` with respect to `L` under constraints `Cl`: // - If `F0[Z0/T0, ..., Zn/Tn]` is a subtype match for `F0[Z0/S0, ..., // Zn/Sn]` with respect to `L` under constraints `C`, where each `Zi` is a // fresh type variable with bound `Bi`. // - And `Cl` is `C` with each constraint replaced with its closure with // respect to `[Z0, ..., Zn]`. if (subtype.requiredParameterCount > supertype.requiredParameterCount) { return false; } if (subtype.positionalParameters.length < supertype.positionalParameters.length) { return false; } if (subtype.typeParameters.length != supertype.typeParameters.length) { return false; } if (subtype.typeParameters.isNotEmpty) { Map<TypeParameter, DartType> subtypeSubstitution = <TypeParameter, DartType>{}; Map<TypeParameter, DartType> supertypeSubstitution = <TypeParameter, DartType>{}; List<TypeParameter> freshTypeVariables = <TypeParameter>[]; if (!_matchTypeFormals(subtype.typeParameters, supertype.typeParameters, subtypeSubstitution, supertypeSubstitution, freshTypeVariables)) { return false; } subtype = substituteTypeParams( subtype, subtypeSubstitution, freshTypeVariables); supertype = substituteTypeParams( supertype, supertypeSubstitution, freshTypeVariables); } // Test the return types. if (supertype.returnType is! VoidType && !_isSubtypeMatch(subtype.returnType, supertype.returnType)) { return false; } // Test the parameter types. for (int i = 0; i < supertype.positionalParameters.length; ++i) { DartType supertypeParameter = supertype.positionalParameters[i]; DartType subtypeParameter = subtype.positionalParameters[i]; // Termination: Both types shrink in size. if (!_isSubtypeMatch(supertypeParameter, subtypeParameter)) { return false; } } int subtypeNameIndex = 0; for (NamedType supertypeParameter in supertype.namedParameters) { while (subtypeNameIndex < subtype.namedParameters.length && subtype.namedParameters[subtypeNameIndex].name != supertypeParameter.name) { ++subtypeNameIndex; } if (subtypeNameIndex == subtype.namedParameters.length) return false; NamedType subtypeParameter = subtype.namedParameters[subtypeNameIndex]; // Termination: Both types shrink in size. if (!_isSubtypeMatch(supertypeParameter.type, subtypeParameter.type)) { return false; } } return true; } bool _isInterfaceSubtypeMatch( InterfaceType subtype, InterfaceType supertype) { // A type `P<M0, ..., Mk>` is a subtype match for `P<N0, ..., Nk>` with // respect to `L` under constraints `C0 + ... + Ck`: // - If `Mi` is a subtype match for `Ni` with respect to `L` under // constraints `Ci`. // A type `P<M0, ..., Mk>` is a subtype match for `Q<N0, ..., Nj>` with // respect to `L` under constraints `C`: // - If `R<B0, ..., Bj>` is the superclass of `P<M0, ..., Mk>` and `R<B0, // ..., Bj>` is a subtype match for `Q<N0, ..., Nj>` with respect to `L` // under constraints `C`. // - Or `R<B0, ..., Bj>` is one of the interfaces implemented by `P<M0, ..., // Mk>` (considered in lexical order) and `R<B0, ..., Bj>` is a subtype // match for `Q<N0, ..., Nj>` with respect to `L` under constraints `C`. // - Or `R<B0, ..., Bj>` is a mixin into `P<M0, ..., Mk>` (considered in // lexical order) and `R<B0, ..., Bj>` is a subtype match for `Q<N0, ..., // Nj>` with respect to `L` under constraints `C`. // Note that since kernel requires that no class may only appear in the set // of supertypes of a given type more than once, the order of the checks // above is irrelevant; we just need to find the matched superclass, // substitute, and then iterate through type variables. InterfaceType matchingSupertypeOfSubtype = getTypeAsInstanceOf(subtype, supertype.classNode); if (matchingSupertypeOfSubtype == null) return false; for (int i = 0; i < supertype.classNode.typeParameters.length; i++) { if (!_isSubtypeMatch(matchingSupertypeOfSubtype.typeArguments[i], supertype.typeArguments[i])) { return false; } } return true; } bool _isNull(DartType type) { // TODO(paulberry): would it be better to call this "_isBottom", and to have // it return `true` for both Null and bottom types? Revisit this once // enough functionality is implemented that we can compare the behavior with // the old analyzer-based implementation. return type is InterfaceType && identical(type.classNode, nullClass); } /// Attempts to match [subtype] as a subtype of [supertype], gathering any /// constraints discovered in the process. /// /// If a set of constraints was found, `true` is returned and the caller /// may proceed to call [computeConstraints]. Otherwise, `false` is returned. /// /// In the case where `false` is returned, some bogus constraints may have /// been added to [_protoConstraints]. It is the caller's responsibility to /// discard them if necessary. bool _isSubtypeMatch(DartType subtype, DartType supertype) { // The unknown type `?` is a subtype match for any type `Q` with no // constraints. if (subtype is UnknownType) return true; // Any type `P` is a subtype match for the unknown type `?` with no // constraints. if (supertype is UnknownType) return true; // A type variable `T` in `L` is a subtype match for any type schema `Q`: // - Under constraint `T <: Q`. if (subtype is TypeParameterType && _parametersToConstrain.contains(subtype.parameter)) { _constrainUpper(subtype.parameter, supertype); return true; } // A type schema `Q` is a subtype match for a type variable `T` in `L`: // - Under constraint `Q <: T`. if (supertype is TypeParameterType && _parametersToConstrain.contains(supertype.parameter)) { _constrainLower(supertype.parameter, subtype); return true; } // Any two equal types `P` and `Q` are subtype matches under no constraints. // Note: to avoid making the algorithm quadratic, we just check for // identical(). If P and Q are equal but not identical, recursing through // the types will give the proper result. if (identical(subtype, supertype)) return true; // Handle FutureOr<T> union type. if (subtype is InterfaceType && identical(subtype.classNode, futureOrClass)) { DartType subtypeArg = subtype.typeArguments[0]; if (supertype is InterfaceType && identical(supertype.classNode, futureOrClass)) { // `FutureOr<P>` is a subtype match for `FutureOr<Q>` with respect to // `L` under constraints `C`: // - If `P` is a subtype match for `Q` with respect to `L` under // constraints `C`. DartType supertypeArg = supertype.typeArguments[0]; return _isSubtypeMatch(subtypeArg, supertypeArg); } // `FutureOr<P>` is a subtype match for `Q` with respect to `L` under // constraints `C0 + C1`: // - If `Future<P>` is a subtype match for `Q` with respect to `L` under // constraints `C0`. // - And `P` is a subtype match for `Q` with respect to `L` under // constraints `C1`. InterfaceType subtypeFuture = futureType(subtypeArg); return _isSubtypeMatch(subtypeFuture, supertype) && _isSubtypeMatch(subtypeArg, supertype); } if (supertype is InterfaceType && identical(supertype.classNode, futureOrClass)) { // `P` is a subtype match for `FutureOr<Q>` with respect to `L` under // constraints `C`: // - If `P` is a subtype match for `Future<Q>` with respect to `L` under // constraints `C`. // - Or `P` is not a subtype match for `Future<Q>` with respect to `L` // under constraints `C` // - And `P` is a subtype match for `Q` with respect to `L` under // constraints `C` DartType supertypeArg = supertype.typeArguments[0]; DartType supertypeFuture = futureType(supertypeArg); // The match against FutureOr<X> succeeds if the match against either // Future<X> or X succeeds. If they both succeed, the one adding new // constraints should be preferred. If both matches against Future<X> and // X add new constraints, the former should be preferred over the latter. int oldProtoConstraintsLength = _protoConstraints.length; bool matchesFuture = trySubtypeMatch(subtype, supertypeFuture); bool matchesArg = oldProtoConstraintsLength != _protoConstraints.length ? false : _isSubtypeMatch(subtype, supertypeArg); return matchesFuture || matchesArg; } // Any type `P` is a subtype match for `dynamic`, `Object`, or `void` under // no constraints. if (_isTop(supertype)) return true; // `Null` is a subtype match for any type `Q` under no constraints. // Note that nullable types will change this. if (_isNull(subtype)) return true; // A type variable `T` not in `L` with bound `P` is a subtype match for the // same type variable `T` with bound `Q` with respect to `L` under // constraints `C`: // - If `P` is a subtype match for `Q` with respect to `L` under constraints // `C`. if (subtype is TypeParameterType) { if (supertype is TypeParameterType && identical(subtype.parameter, supertype.parameter)) { // Kernel doesn't yet allow a type variable to have different bounds // under different circumstances (see dartbug.com/29529) so for now if // we get here, the bounds must be the same. // TODO(paulberry): update this code once dartbug.com/29529 is // addressed. return true; } // A type variable `T` not in `L` with bound `P` is a subtype match for a // type `Q` with respect to `L` under constraints `C`: // - If `P` is a subtype match for `Q` with respect to `L` under // constraints `C`. return _isSubtypeMatch(subtype.parameter.bound, supertype); } if (subtype is InterfaceType && supertype is InterfaceType) { return _isInterfaceSubtypeMatch(subtype, supertype); } if (subtype is FunctionType) { if (supertype is InterfaceType) { return identical(supertype.classNode, functionClass) || identical(supertype.classNode, objectClass); } else if (supertype is FunctionType) { return _isFunctionSubtypeMatch(subtype, supertype); } } // A type `P` is a subtype match for a type `Q` with respect to `L` under // constraints `C`: // - If `P` is an interface type which implements a call method of type `F`, // and `F` is a subtype match for a type `Q` with respect to `L` under // constraints `C`. if (subtype is InterfaceType) { Member callMember = getInterfaceMember(subtype.classNode, callName); if (callMember is Procedure && !callMember.isGetter) { DartType callType = callMember.getterType; if (callType != null) { callType = Substitution.fromInterfaceType(subtype).substituteType(callType); // TODO(kmillikin): The subtype check will fail if the type of a // generic call method is a subtype of a non-generic function type. // For example, if `T call<T>(T arg)` is a subtype of `S->S` for some // S. However, explicitly tearing off that call method will work and // insert an explicit instantiation, so the implicit tear off should // work as well. Figure out how to support this case. return _isSubtypeMatch(callType, supertype); } } } return false; } bool _isTop(DartType type) => type is DynamicType || type is VoidType || (type is InterfaceType && identical(type.classNode, objectClass)); /// Given two lists of function type formal parameters, checks that their /// bounds are compatible. /// /// The return value indicates whether a match was found. If it was, entries /// are added to [substitution1] and [substitution2] which substitute a fresh /// set of type variables for the type parameters [params1] and [params2], /// respectively, allowing further comparison. bool _matchTypeFormals( List<TypeParameter> params1, List<TypeParameter> params2, Map<TypeParameter, DartType> substitution1, Map<TypeParameter, DartType> substitution2, List<TypeParameter> freshTypeVariables) { assert(params1.length == params2.length); // TODO(paulberry): in imitation of analyzer, we're checking the bounds as // we build up the substitutions. But I don't think that's correct--I think // we should build up both substitutions completely before checking any // bounds. See dartbug.com/29629. for (int i = 0; i < params1.length; ++i) { TypeParameter pFresh = new TypeParameter(params2[i].name); freshTypeVariables.add(pFresh); DartType variableFresh = new TypeParameterType(pFresh); substitution1[params1[i]] = variableFresh; substitution2[params2[i]] = variableFresh; DartType bound1 = substitute(params1[i].bound, substitution1); DartType bound2 = substitute(params2[i].bound, substitution2); pFresh.bound = bound2; if (!_isSubtypeMatch(bound2, bound1)) return false; } return true; } } class TypeSchemaConstraintGatherer extends TypeConstraintGatherer { final TypeSchemaEnvironment environment; TypeSchemaConstraintGatherer( this.environment, Iterable<TypeParameter> typeParameters) : super.subclassing(typeParameters); @override Class get objectClass => environment.coreTypes.objectClass; @override Class get functionClass => environment.coreTypes.functionClass; @override Class get futureOrClass => environment.coreTypes.futureOrClass; @override Class get nullClass => environment.coreTypes.nullClass; @override void addUpperBound(TypeConstraint constraint, DartType upper) { environment.addUpperBound(constraint, upper); } @override void addLowerBound(TypeConstraint constraint, DartType lower) { environment.addLowerBound(constraint, lower); } @override Member getInterfaceMember(Class class_, Name name, {bool setter: false}) { return environment.hierarchy .getInterfaceMember(class_, name, setter: setter); } @override InterfaceType getTypeAsInstanceOf(InterfaceType type, Class superclass) { return environment.getTypeAsInstanceOf(type, superclass); } @override InterfaceType futureType(DartType type) { return environment.futureType(type); } } /// Tracks a single constraint on a single type variable. /// /// This is called "_ProtoConstraint" to distinguish from [TypeConstraint], /// which tracks the upper and lower bounds that are together implied by a set /// of [_ProtoConstraint]s. class _ProtoConstraint { final TypeParameter parameter; final DartType bound; final bool isUpper; _ProtoConstraint.lower(this.parameter, this.bound) : isUpper = false; _ProtoConstraint.upper(this.parameter, this.bound) : isUpper = true; String toString() { return isUpper ? "${parameter.name} <: $bound" : "$bound <: ${parameter.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/type_inference/type_inferrer.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'dart:core' hide MapEntry; import 'package:front_end/src/fasta/kernel/kernel_shadow_ast.dart'; import 'package:kernel/ast.dart' hide Variance; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy; import 'package:kernel/core_types.dart' show CoreTypes; import 'package:kernel/type_algebra.dart'; import 'package:kernel/type_environment.dart'; import 'package:kernel/src/bounds_checks.dart' show calculateBounds; import '../../base/instrumentation.dart' show Instrumentation, InstrumentationValueForMember, InstrumentationValueForType, InstrumentationValueForTypeArgs; import '../builder/extension_builder.dart'; import '../builder/member_builder.dart'; import '../fasta_codes.dart' show LocatedMessage, Message, Template, messageReturnFromVoidFunction, messageReturnWithoutExpression, messageVoidExpression, noLength, templateArgumentTypeNotAssignable, templateDuplicatedNamedArgument, templateImplicitCallOfNonMethod, templateInvalidAssignment, templateInvalidCastFunctionExpr, templateInvalidCastLiteralList, templateInvalidCastLiteralMap, templateInvalidCastLiteralSet, templateInvalidCastLocalFunction, templateInvalidCastNewExpr, templateInvalidCastStaticMethod, templateInvalidCastTopLevelFunction, templateInvokeNonFunction, templateMixinInferenceNoMatchingClass, templateUndefinedGetter, templateUndefinedMethod, templateUndefinedSetter; import '../kernel/expression_generator.dart' show buildIsNull; import '../kernel/kernel_shadow_ast.dart' show ShadowTypeInferenceEngine, ShadowTypeInferrer, VariableDeclarationImpl, getExplicitTypeArguments, getExtensionTypeParameterCount; import '../kernel/type_algorithms.dart' show hasAnyTypeVariables; import '../names.dart'; import '../problems.dart' show unexpected, unhandled; import '../source/source_library_builder.dart' show SourceLibraryBuilder; import 'inference_helper.dart' show InferenceHelper; import 'type_constraint_gatherer.dart' show TypeConstraintGatherer; import 'type_inference_engine.dart' show IncludesTypeParametersNonCovariantly, TypeInferenceEngine, Variance; import 'type_promotion.dart' show TypePromoter; import 'type_schema.dart' show isKnown, UnknownType; import 'type_schema_elimination.dart' show greatestClosure; import 'type_schema_environment.dart' show getNamedParameterType, getPositionalParameterType, TypeConstraint, TypeVariableEliminator, TypeSchemaEnvironment; /// Given a [FunctionNode], gets the named parameter identified by [name], or /// `null` if there is no parameter with the given name. VariableDeclaration getNamedFormal(FunctionNode function, String name) { for (VariableDeclaration formal in function.namedParameters) { if (formal.name == name) return formal; } return null; } /// Given a [FunctionNode], gets the [i]th positional formal parameter, or /// `null` if there is no parameter with that index. VariableDeclaration getPositionalFormal(FunctionNode function, int i) { if (i < function.positionalParameters.length) { return function.positionalParameters[i]; } else { return null; } } bool isOverloadableArithmeticOperator(String name) { return identical(name, '+') || identical(name, '-') || identical(name, '*') || identical(name, '%'); } /// Keeps track of information about the innermost function or closure being /// inferred. class ClosureContext { final bool isAsync; final bool isGenerator; /// The typing expectation for the subexpression of a `return` or `yield` /// statement inside the function. /// /// For non-generator async functions, this will be a "FutureOr" type (since /// it is permissible for such a function to return either a direct value or /// a future). /// /// For generator functions containing a `yield*` statement, the expected type /// for the subexpression of the `yield*` statement is the result of wrapping /// this typing expectation in `Stream` or `Iterator`, as appropriate. final DartType returnOrYieldContext; final DartType declaredReturnType; final bool _needToInferReturnType; /// The type that actually appeared as the subexpression of `return` or /// `yield` statements inside the function. /// /// For non-generator async functions, this is the "unwrapped" type (e.g. if /// the function is expected to return `Future<int>`, this is `int`). /// /// For generator functions containing a `yield*` statement, the type that /// appeared as the subexpression of the `yield*` statement was the result of /// wrapping this type in `Stream` or `Iterator`, as appropriate. DartType _inferredUnwrappedReturnOrYieldType; /// Whether the function is an arrow function. bool isArrow; /// A list of return statements in functions whose return type is being /// inferred. /// /// The returns are checked for validity after the return type is inferred. List<ReturnStatement> returnStatements; /// A list of return expression types in functions whose return type is /// being inferred. List<DartType> returnExpressionTypes; factory ClosureContext(TypeInferrerImpl inferrer, AsyncMarker asyncMarker, DartType returnContext, bool needToInferReturnType) { assert(returnContext != null); DartType declaredReturnType = greatestClosure(inferrer.coreTypes, returnContext); bool isAsync = asyncMarker == AsyncMarker.Async || asyncMarker == AsyncMarker.AsyncStar; bool isGenerator = asyncMarker == AsyncMarker.SyncStar || asyncMarker == AsyncMarker.AsyncStar; if (isGenerator) { if (isAsync) { returnContext = inferrer.getTypeArgumentOf( returnContext, inferrer.coreTypes.streamClass); } else { returnContext = inferrer.getTypeArgumentOf( returnContext, inferrer.coreTypes.iterableClass); } } else if (isAsync) { returnContext = inferrer.wrapFutureOrType( inferrer.typeSchemaEnvironment.unfutureType(returnContext)); } return new ClosureContext._(isAsync, isGenerator, returnContext, declaredReturnType, needToInferReturnType); } ClosureContext._(this.isAsync, this.isGenerator, this.returnOrYieldContext, this.declaredReturnType, this._needToInferReturnType) { if (_needToInferReturnType) { returnStatements = []; returnExpressionTypes = []; } } bool checkValidReturn(TypeInferrerImpl inferrer, DartType returnType, ReturnStatement statement, DartType expressionType) { // The rules for valid returns for functions with return type T and possibly // a return expression with static type S. DartType flattenedReturnType = isAsync ? inferrer.typeSchemaEnvironment.unfutureType(returnType) : returnType; if (statement.expression == null) { // Sync: return; is a valid return if T is void, dynamic, or Null. // Async: return; is a valid return if flatten(T) is void, dynamic, or // Null. if (flattenedReturnType is VoidType || flattenedReturnType is DynamicType || flattenedReturnType == inferrer.coreTypes.nullType) { return true; } statement.expression = inferrer.helper.wrapInProblem( new NullLiteral()..fileOffset = statement.fileOffset, messageReturnWithoutExpression, noLength) ..parent = statement; return false; } // Arrow functions are valid if: // Sync: T is void or return exp; is a valid for a block-bodied function. // Async: flatten(T) is void or return exp; is valid for a block-bodied // function. if (isArrow && flattenedReturnType is VoidType) return true; // Sync: invalid if T is void and S is not void, dynamic, or Null // Async: invalid if T is void and flatten(S) is not void, dynamic, or Null. DartType flattenedExpressionType = isAsync ? inferrer.typeSchemaEnvironment.unfutureType(expressionType) : expressionType; if (returnType is VoidType && flattenedExpressionType is! VoidType && flattenedExpressionType is! DynamicType && flattenedExpressionType != inferrer.coreTypes.nullType) { statement.expression = inferrer.helper.wrapInProblem( statement.expression, messageReturnFromVoidFunction, noLength) ..parent = statement; return false; } // Sync: invalid if S is void and T is not void, dynamic, or Null. // Async: invalid if flatten(S) is void and flatten(T) is not void, dynamic, // or Null. if (flattenedExpressionType is VoidType && flattenedReturnType is! VoidType && flattenedReturnType is! DynamicType && flattenedReturnType != inferrer.coreTypes.nullType) { statement.expression = inferrer.helper .wrapInProblem(statement.expression, messageVoidExpression, noLength) ..parent = statement; return false; } // The caller will check that the return expression is assignable to the // return type. return true; } /// Updates the inferred return type based on the presence of a return /// statement returning the given [type]. void handleReturn(TypeInferrerImpl inferrer, ReturnStatement statement, DartType type, bool isArrow) { if (isGenerator) return; // The first return we see tells us if we have an arrow function. if (this.isArrow == null) { this.isArrow = isArrow; } else { assert(this.isArrow == isArrow); } if (_needToInferReturnType) { // Add the return to a list to be checked for validity after we've // inferred the return type. returnStatements.add(statement); returnExpressionTypes.add(type); // The return expression has to be assignable to the return type // expectation from the downwards inference context. if (statement.expression != null && inferrer.ensureAssignable(returnOrYieldContext, type, statement.expression, statement.fileOffset, isReturnFromAsync: isAsync, isVoidAllowed: true) != null) { // Not assignable, use the expectation. type = greatestClosure(inferrer.coreTypes, returnOrYieldContext); } DartType unwrappedType = type; if (isAsync) { unwrappedType = inferrer.typeSchemaEnvironment.unfutureType(type); } if (_inferredUnwrappedReturnOrYieldType == null) { _inferredUnwrappedReturnOrYieldType = unwrappedType; } else { _inferredUnwrappedReturnOrYieldType = inferrer.typeSchemaEnvironment .getStandardUpperBound( _inferredUnwrappedReturnOrYieldType, unwrappedType); } return; } // If we are not inferring a type we can immediately check that the return // is valid. if (checkValidReturn(inferrer, declaredReturnType, statement, type) && statement.expression != null) { inferrer.ensureAssignable(returnOrYieldContext, type, statement.expression, statement.fileOffset, isReturnFromAsync: isAsync, isVoidAllowed: true); } } void handleYield(TypeInferrerImpl inferrer, bool isYieldStar, DartType type, Expression expression, int fileOffset) { if (!isGenerator) return; DartType expectedType = isYieldStar ? _wrapAsyncOrGenerator(inferrer, returnOrYieldContext) : returnOrYieldContext; if (inferrer.ensureAssignable(expectedType, type, expression, fileOffset, isReturnFromAsync: isAsync) != null) { type = greatestClosure(inferrer.coreTypes, expectedType); } if (_needToInferReturnType) { DartType unwrappedType = type; if (isYieldStar) { unwrappedType = inferrer.getDerivedTypeArgumentOf( type, isAsync ? inferrer.coreTypes.streamClass : inferrer.coreTypes.iterableClass) ?? type; } if (_inferredUnwrappedReturnOrYieldType == null) { _inferredUnwrappedReturnOrYieldType = unwrappedType; } else { _inferredUnwrappedReturnOrYieldType = inferrer.typeSchemaEnvironment .getStandardUpperBound( _inferredUnwrappedReturnOrYieldType, unwrappedType); } } } DartType inferReturnType(TypeInferrerImpl inferrer) { assert(_needToInferReturnType); DartType inferredType = inferrer.inferReturnType(_inferredUnwrappedReturnOrYieldType); if (!inferrer.typeSchemaEnvironment.isSubtypeOf(inferredType, returnOrYieldContext, SubtypeCheckMode.ignoringNullabilities)) { // If the inferred return type isn't a subtype of the context, we use the // context. inferredType = greatestClosure(inferrer.coreTypes, returnOrYieldContext); } inferredType = _wrapAsyncOrGenerator(inferrer, inferredType); for (int i = 0; i < returnStatements.length; ++i) { checkValidReturn(inferrer, inferredType, returnStatements[i], returnExpressionTypes[i]); } return inferredType; } DartType _wrapAsyncOrGenerator(TypeInferrerImpl inferrer, DartType type) { if (isGenerator) { if (isAsync) { return inferrer.wrapType(type, inferrer.coreTypes.streamClass); } else { return inferrer.wrapType(type, inferrer.coreTypes.iterableClass); } } else if (isAsync) { return inferrer.wrapFutureType(type); } else { return type; } } } /// Enum denoting the kinds of contravariance check that might need to be /// inserted for a method call. enum MethodContravarianceCheckKind { /// No contravariance check is needed. none, /// The return value from the method call needs to be checked. checkMethodReturn, /// The method call needs to be desugared into a getter call, followed by an /// "as" check, followed by an invocation of the resulting function object. checkGetterReturn, } /// Keeps track of the local state for the type inference that occurs during /// compilation of a single method body or top level initializer. /// /// This class describes the interface for use by clients of type inference /// (e.g. BodyBuilder). Derived classes should derive from [TypeInferrerImpl]. abstract class TypeInferrer { final CoreTypes coreTypes; TypeInferrer.private(this.coreTypes); factory TypeInferrer( ShadowTypeInferenceEngine engine, Uri uri, bool topLevel, InterfaceType thisType, SourceLibraryBuilder library) = ShadowTypeInferrer.private; SourceLibraryBuilder get library; /// Gets the [TypePromoter] that can be used to perform type promotion within /// this method body or initializer. TypePromoter get typePromoter; /// Gets the [TypeSchemaEnvironment] being used for type inference. TypeSchemaEnvironment get typeSchemaEnvironment; /// The URI of the code for which type inference is currently being /// performed--this is used for testing. Uri get uri; /// Performs full type inference on the given field initializer. void inferFieldInitializer( InferenceHelper helper, DartType declaredType, Expression initializer); /// Performs type inference on the given function body. void inferFunctionBody(InferenceHelper helper, DartType returnType, AsyncMarker asyncMarker, Statement body); /// Performs type inference on the given constructor initializer. void inferInitializer(InferenceHelper helper, Initializer initializer); /// Performs type inference on the given metadata annotations. void inferMetadata(InferenceHelper helper, List<Expression> annotations); /// Performs type inference on the given metadata annotations keeping the /// existing helper if possible. void inferMetadataKeepingHelper(List<Expression> annotations); /// Performs type inference on the given function parameter initializer /// expression. void inferParameterInitializer( InferenceHelper helper, Expression initializer, DartType declaredType); } /// Derived class containing generic implementations of [TypeInferrer]. /// /// This class contains as much of the implementation of type inference as /// possible without knowing the identity of the type parameters. It defers to /// abstract methods for everything else. abstract class TypeInferrerImpl extends TypeInferrer { /// Marker object to indicate that a function takes an unknown number /// of arguments. static final FunctionType unknownFunction = new FunctionType(const [], const DynamicType()); final TypeInferenceEngine engine; @override final Uri uri; /// Indicates whether the construct we are currently performing inference for /// is outside of a method body, and hence top level type inference rules /// should apply. final bool isTopLevel; final ClassHierarchy classHierarchy; final Instrumentation instrumentation; final TypeSchemaEnvironment typeSchemaEnvironment; final InterfaceType thisType; @override final SourceLibraryBuilder library; InferenceHelper helper; /// Context information for the current closure, or `null` if we are not /// inside a closure. ClosureContext closureContext; /// The [Substitution] inferred by the last [inferInvocation], or `null` if /// the last invocation didn't require any inference. Substitution lastInferredSubstitution; /// The [FunctionType] of the callee in the last [inferInvocation], or `null` /// if the last invocation didn't require any inference. FunctionType lastCalleeType; TypeInferrerImpl.private( this.engine, this.uri, bool topLevel, this.thisType, this.library) : assert(library != null), classHierarchy = engine.classHierarchy, instrumentation = topLevel ? null : engine.instrumentation, typeSchemaEnvironment = engine.typeSchemaEnvironment, isTopLevel = topLevel, super.private(engine.coreTypes); /// Gets the type promoter that should be used to promote types during /// inference. TypePromoter get typePromoter; bool isDoubleContext(DartType typeContext) { // A context is a double context if double is assignable to it but int is // not. That is the type context is a double context if it is: // * double // * FutureOr<T> where T is a double context // // We check directly, rather than using isAssignable because it's simpler. while (typeContext is InterfaceType && typeContext.classNode == coreTypes.futureOrClass && typeContext.typeArguments.isNotEmpty) { InterfaceType type = typeContext; typeContext = type.typeArguments.first; } return typeContext is InterfaceType && typeContext.classNode == coreTypes.doubleClass; } bool isAssignable(DartType expectedType, DartType actualType) { return typeSchemaEnvironment.isSubtypeOf( expectedType, actualType, SubtypeCheckMode.ignoringNullabilities) || typeSchemaEnvironment.isSubtypeOf( actualType, expectedType, SubtypeCheckMode.ignoringNullabilities); } /// Checks whether [actualType] can be assigned to the greatest closure of /// [expectedType], and inserts an implicit downcast if appropriate. Expression ensureAssignable(DartType expectedType, DartType actualType, Expression expression, int fileOffset, {bool isReturnFromAsync: false, bool isVoidAllowed: false, Template<Message Function(DartType, DartType)> template}) { assert(expectedType != null); expectedType = greatestClosure(coreTypes, expectedType); DartType initialExpectedType = expectedType; if (isReturnFromAsync && !isAssignable(expectedType, actualType)) { // If the body of the function is async, the expected return type has the // shape FutureOr<T>. We check both branches for FutureOr here: both T // and Future<T>. DartType unfuturedExpectedType = typeSchemaEnvironment.unfutureType(expectedType); DartType futuredExpectedType = wrapFutureType(unfuturedExpectedType); if (isAssignable(unfuturedExpectedType, actualType)) { expectedType = unfuturedExpectedType; } else if (isAssignable(futuredExpectedType, actualType)) { expectedType = futuredExpectedType; } } // We don't need to insert assignability checks when doing top level type // inference since top level type inference only cares about the type that // is inferred (the kernel code is discarded). if (isTopLevel) return null; // If an interface type is being assigned to a function type, see if we // should tear off `.call`. // TODO(paulberry): use resolveTypeParameter. See findInterfaceMember. if (actualType is InterfaceType) { Class classNode = (actualType as InterfaceType).classNode; Member callMember = classHierarchy.getInterfaceMember(classNode, callName); if (callMember is Procedure && callMember.kind == ProcedureKind.Method) { if (_shouldTearOffCall(expectedType, actualType)) { // Replace expression with: // `let t = expression in t == null ? null : t.call` TreeNode parent = expression.parent; VariableDeclaration t = new VariableDeclaration.forValue(expression, type: actualType) ..fileOffset = fileOffset; Expression nullCheck = buildIsNull(new VariableGet(t), fileOffset, helper); PropertyGet tearOff = new PropertyGet(new VariableGet(t), callName, callMember) ..fileOffset = fileOffset; actualType = getGetterTypeForMemberTarget(callMember, actualType); ConditionalExpression conditional = new ConditionalExpression( nullCheck, new NullLiteral()..fileOffset = fileOffset, tearOff, actualType); Let let = new Let(t, conditional)..fileOffset = fileOffset; parent?.replaceChild(expression, let); expression = let; } } } if (actualType is VoidType && !isVoidAllowed) { // Error: not assignable. Perform error recovery. TreeNode parent = expression.parent; Expression errorNode = helper.wrapInProblem(expression, messageVoidExpression, noLength); parent?.replaceChild(expression, errorNode); return errorNode; } if (expectedType == null || typeSchemaEnvironment.isSubtypeOf( actualType, expectedType, SubtypeCheckMode.ignoringNullabilities)) { // Types are compatible. return null; } if (!typeSchemaEnvironment.isSubtypeOf( expectedType, actualType, SubtypeCheckMode.ignoringNullabilities)) { // Error: not assignable. Perform error recovery. TreeNode parent = expression.parent; Expression errorNode = new AsExpression( expression, // TODO(ahe): The outline phase doesn't correctly remove invalid // uses of type variables, for example, on static members. Once // that has been fixed, we should always be able to use // [expectedType] directly here. hasAnyTypeVariables(expectedType) ? const BottomType() : expectedType) ..isTypeError = true ..fileOffset = expression.fileOffset; if (expectedType is! InvalidType && actualType is! InvalidType) { errorNode = helper.wrapInProblem( errorNode, (template ?? templateInvalidAssignment) .withArguments(actualType, expectedType), noLength); } parent?.replaceChild(expression, errorNode); return errorNode; } else { Template<Message Function(DartType, DartType)> template = _getPreciseTypeErrorTemplate(expression); if (template != null) { // The type of the expression is known precisely, so an implicit // downcast is guaranteed to fail. Insert a compile-time error. TreeNode parent = expression.parent; Expression errorNode = helper.wrapInProblem(expression, template.withArguments(actualType, expectedType), noLength); parent?.replaceChild(expression, errorNode); return errorNode; } else { // Insert an implicit downcast. TreeNode parent = expression.parent; AsExpression typeCheck = new AsExpression(expression, initialExpectedType) ..isTypeError = true ..fileOffset = fileOffset; parent?.replaceChild(expression, typeCheck); return typeCheck; } } } bool isNull(DartType type) { return type is InterfaceType && type.classNode == coreTypes.nullClass; } /// Computes the type arguments for an access to an extension instance member /// on [extension] with the static [receiverType]. If [explicitTypeArguments] /// are provided, these are returned, otherwise type arguments are inferred /// using [receiverType]. List<DartType> computeExtensionTypeArgument(Extension extension, List<DartType> explicitTypeArguments, DartType receiverType) { if (explicitTypeArguments != null) { assert(explicitTypeArguments.length == extension.typeParameters.length); return explicitTypeArguments; } else if (extension.typeParameters.isEmpty) { assert(explicitTypeArguments == null); return const <DartType>[]; } else { return inferExtensionTypeArguments(extension, receiverType); } } /// Infers the type arguments for an access to an extension instance member /// on [extension] with the static [receiverType]. List<DartType> inferExtensionTypeArguments( Extension extension, DartType receiverType) { List<TypeParameter> typeParameters = extension.typeParameters; DartType onType = extension.onType; List<DartType> inferredTypes = new List<DartType>.filled(typeParameters.length, const UnknownType()); typeSchemaEnvironment.inferGenericFunctionOrType( null, typeParameters, [onType], [receiverType], null, inferredTypes); return inferredTypes; } /// Finds a member of [receiverType] called [name], and if it is found, /// reports it through instrumentation using [fileOffset]. /// /// For the case where [receiverType] is a [FunctionType], and the name /// is `call`, the string 'call' is returned as a sentinel object. /// /// For the case where [receiverType] is `dynamic`, and the name is declared /// in Object, the member from Object is returned though the call may not end /// up targeting it if the arguments do not match (the basic principle is that /// the Object member is used for inferring types only if noSuchMethod cannot /// be targeted due to, e.g., an incorrect argument count). ObjectAccessTarget findInterfaceMember( DartType receiverType, Name name, int fileOffset, {bool setter: false, bool instrumented: true, bool includeExtensionMethods: false}) { assert(receiverType != null && isKnown(receiverType)); receiverType = resolveTypeParameter(receiverType); if (receiverType is FunctionType && name.name == 'call') { return const ObjectAccessTarget.callFunction(); } Class classNode = receiverType is InterfaceType ? receiverType.classNode : coreTypes.objectClass; Member interfaceMember = _getInterfaceMember(classNode, name, setter, fileOffset); ObjectAccessTarget target; if (interfaceMember != null) { target = new ObjectAccessTarget.interfaceMember(interfaceMember); } else if (receiverType is DynamicType) { target = const ObjectAccessTarget.dynamic(); } else if (receiverType is InvalidType) { target = const ObjectAccessTarget.invalid(); } else if (receiverType == coreTypes.functionLegacyRawType && name.name == 'call') { target = const ObjectAccessTarget.callFunction(); } else { target = const ObjectAccessTarget.missing(); } if (instrumented && receiverType != const DynamicType() && target.isInstanceMember) { instrumentation?.record(uri, fileOffset, 'target', new InstrumentationValueForMember(target.member)); } if (target.isUnresolved && receiverType is! DynamicType && includeExtensionMethods) { Name otherName = name; bool otherIsSetter; if (name == indexGetName) { // [] must be checked against []=. otherName = indexSetName; otherIsSetter = false; } else if (name == indexSetName) { // []= must be checked against []. otherName = indexGetName; otherIsSetter = false; } else { otherName = name; otherIsSetter = !setter; } Member otherMember = _getInterfaceMember(classNode, otherName, otherIsSetter, fileOffset); if (otherMember != null) { // If we're looking for `foo` and `foo=` can be found or vice-versa then // extension methods should not be found. return target; } ExtensionAccessCandidate bestSoFar; List<ExtensionAccessCandidate> noneMoreSpecific = []; library.scope.forEachExtension((ExtensionBuilder extensionBuilder) { MemberBuilder thisBuilder = extensionBuilder.lookupLocalMember(name.name, setter: setter); MemberBuilder otherBuilder = extensionBuilder .lookupLocalMember(otherName.name, setter: otherIsSetter); if ((thisBuilder != null && !thisBuilder.isStatic) || (otherBuilder != null && !otherBuilder.isStatic)) { DartType onType; DartType onTypeInstantiateToBounds; List<DartType> inferredTypeArguments; if (extensionBuilder.extension.typeParameters.isEmpty) { onTypeInstantiateToBounds = onType = extensionBuilder.extension.onType; inferredTypeArguments = const <DartType>[]; } else { List<TypeParameter> typeParameters = extensionBuilder.extension.typeParameters; inferredTypeArguments = inferExtensionTypeArguments( extensionBuilder.extension, receiverType); Substitution inferredSubstitution = Substitution.fromPairs(typeParameters, inferredTypeArguments); for (int index = 0; index < typeParameters.length; index++) { TypeParameter typeParameter = typeParameters[index]; DartType typeArgument = inferredTypeArguments[index]; DartType bound = inferredSubstitution.substituteType(typeParameter.bound); if (!typeSchemaEnvironment.isSubtypeOf(typeArgument, bound, SubtypeCheckMode.ignoringNullabilities)) { return; } } onType = inferredSubstitution .substituteType(extensionBuilder.extension.onType); List<DartType> instantiateToBoundTypeArguments = calculateBounds(typeParameters, coreTypes.objectClass); Substitution instantiateToBoundsSubstitution = Substitution.fromPairs( typeParameters, instantiateToBoundTypeArguments); onTypeInstantiateToBounds = instantiateToBoundsSubstitution .substituteType(extensionBuilder.extension.onType); } if (typeSchemaEnvironment.isSubtypeOf( receiverType, onType, SubtypeCheckMode.ignoringNullabilities)) { ExtensionAccessCandidate candidate = new ExtensionAccessCandidate( onType, onTypeInstantiateToBounds, thisBuilder != null ? new ObjectAccessTarget.extensionMember( thisBuilder.procedure, thisBuilder.extensionTearOff, thisBuilder.kind, inferredTypeArguments) : const ObjectAccessTarget.missing(), isPlatform: extensionBuilder.library.uri.scheme == 'dart'); if (noneMoreSpecific.isNotEmpty) { bool isMostSpecific = true; for (ExtensionAccessCandidate other in noneMoreSpecific) { bool isMoreSpecific = candidate.isMoreSpecificThan(typeSchemaEnvironment, other); if (isMoreSpecific != true) { isMostSpecific = false; break; } } if (isMostSpecific) { bestSoFar = candidate; noneMoreSpecific.clear(); } else { noneMoreSpecific.add(candidate); } } else if (bestSoFar == null) { bestSoFar = candidate; } else { bool isMoreSpecific = candidate.isMoreSpecificThan( typeSchemaEnvironment, bestSoFar); if (isMoreSpecific == true) { bestSoFar = candidate; } else if (isMoreSpecific == null) { noneMoreSpecific.add(bestSoFar); noneMoreSpecific.add(candidate); bestSoFar = null; } } } } }); if (bestSoFar != null) { target = bestSoFar.target; } else { // TODO(johnniwinther): Report a better error message when more than // one potential targets were found. } } return target; } /// Finds a member of [receiverType] called [name], and if it is found, /// reports it through instrumentation using [fileOffset]. /// /// For the case where [receiverType] is a [FunctionType], and the name /// is `call`, the string 'call' is returned as a sentinel object. /// /// For the case where [receiverType] is `dynamic`, and the name is declared /// in Object, the member from Object is returned though the call may not end /// up targeting it if the arguments do not match (the basic principle is that /// the Object member is used for inferring types only if noSuchMethod cannot /// be targeted due to, e.g., an incorrect argument count). /// /// If no target is found on a non-dynamic receiver an error is reported /// using [errorTemplate] and [expression] is replaced by an invalid /// expression. ObjectAccessTarget findInterfaceMemberOrReport( DartType receiverType, Name name, int fileOffset, Template<Message Function(String, DartType)> errorTemplate, Expression expression, {bool setter: false, bool instrumented: true, bool includeExtensionMethods: false}) { ObjectAccessTarget target = findInterfaceMember( receiverType, name, fileOffset, setter: setter, instrumented: instrumented, includeExtensionMethods: includeExtensionMethods); assert(receiverType != null && isKnown(receiverType)); if (!isTopLevel && target.isMissing && errorTemplate != null) { int length = name.name.length; if (identical(name.name, callName.name) || identical(name.name, unaryMinusName.name)) { length = 1; } expression.parent.replaceChild( expression, helper.buildProblem( errorTemplate.withArguments( name.name, resolveTypeParameter(receiverType)), fileOffset, length)); } return target; } /// Finds a member of [receiverType] called [name] and records it in /// [methodInvocation]. ObjectAccessTarget findMethodInvocationMember( DartType receiverType, InvocationExpression methodInvocation, {bool instrumented: true}) { // TODO(paulberry): could we add getters to InvocationExpression to make // these is-checks unnecessary? if (methodInvocation is MethodInvocation) { ObjectAccessTarget interfaceTarget = findInterfaceMemberOrReport( receiverType, methodInvocation.name, methodInvocation.fileOffset, templateUndefinedMethod, methodInvocation, instrumented: instrumented, includeExtensionMethods: true); if (interfaceTarget.isInstanceMember) { Member interfaceMember = interfaceTarget.member; if (receiverType == const DynamicType() && interfaceMember is Procedure) { Arguments arguments = methodInvocation.arguments; FunctionNode signature = interfaceMember.function; if (arguments.positional.length < signature.requiredParameterCount || arguments.positional.length > signature.positionalParameters.length) { return const ObjectAccessTarget.unresolved(); } for (NamedExpression argument in arguments.named) { if (!signature.namedParameters .any((declaration) => declaration.name == argument.name)) { return const ObjectAccessTarget.unresolved(); } } if (instrumented && instrumentation != null) { instrumentation.record(uri, methodInvocation.fileOffset, 'target', new InstrumentationValueForMember(interfaceMember)); } } methodInvocation.interfaceTarget = interfaceMember; } return interfaceTarget; } else if (methodInvocation is SuperMethodInvocation) { assert(receiverType != const DynamicType()); ObjectAccessTarget interfaceTarget = findInterfaceMember( receiverType, methodInvocation.name, methodInvocation.fileOffset, instrumented: instrumented); if (interfaceTarget.isInstanceMember) { methodInvocation.interfaceTarget = interfaceTarget.member; } return interfaceTarget; } else { throw unhandled("${methodInvocation.runtimeType}", "findMethodInvocationMember", methodInvocation.fileOffset, uri); } } /// Finds a member of [receiverType] called [name], and if it is found, /// reports it through instrumentation and records it in [propertyGet]. ObjectAccessTarget findPropertyGetMember( DartType receiverType, Expression propertyGet, {bool instrumented: true}) { // TODO(paulberry): could we add a common base class to PropertyGet and // SuperPropertyGet to make these is-checks unnecessary? if (propertyGet is PropertyGet) { ObjectAccessTarget readTarget = findInterfaceMemberOrReport( receiverType, propertyGet.name, propertyGet.fileOffset, templateUndefinedGetter, propertyGet, instrumented: instrumented); if (readTarget.isInstanceMember) { if (instrumented && instrumentation != null && receiverType == const DynamicType()) { instrumentation.record(uri, propertyGet.fileOffset, 'target', new InstrumentationValueForMember(readTarget.member)); } propertyGet.interfaceTarget = readTarget.member; } return readTarget; } else if (propertyGet is SuperPropertyGet) { assert(receiverType != const DynamicType()); ObjectAccessTarget interfaceMember = findInterfaceMember( receiverType, propertyGet.name, propertyGet.fileOffset, instrumented: instrumented); if (interfaceMember.isInstanceMember) { propertyGet.interfaceTarget = interfaceMember.member; } return interfaceMember; } else { return unhandled("${propertyGet.runtimeType}", "findPropertyGetMember", propertyGet.fileOffset, uri); } } /// Finds a member of [receiverType] called [name], and if it is found, /// reports it through instrumentation and records it in [propertySet]. ObjectAccessTarget findPropertySetMember( DartType receiverType, Expression propertySet, {bool instrumented: true}) { if (propertySet is PropertySet) { ObjectAccessTarget writeTarget = findInterfaceMemberOrReport( receiverType, propertySet.name, propertySet.fileOffset, templateUndefinedSetter, propertySet, setter: true, instrumented: instrumented, includeExtensionMethods: true); if (writeTarget.isInstanceMember) { if (instrumented && instrumentation != null && receiverType == const DynamicType()) { instrumentation.record(uri, propertySet.fileOffset, 'target', new InstrumentationValueForMember(writeTarget.member)); } propertySet.interfaceTarget = writeTarget.member; } return writeTarget; } else if (propertySet is SuperPropertySet) { assert(receiverType != const DynamicType()); ObjectAccessTarget interfaceMember = findInterfaceMember( receiverType, propertySet.name, propertySet.fileOffset, setter: true, instrumented: instrumented); if (interfaceMember.isInstanceMember) { propertySet.interfaceTarget = interfaceMember.member; } return interfaceMember; } else { throw unhandled("${propertySet.runtimeType}", "findPropertySetMember", propertySet.fileOffset, uri); } } /// Returns the type of [target] when accessed as a getter on [receiverType]. /// /// For instance /// /// class Class<T> { /// T method() {} /// T getter => null; /// } /// /// Class<int> c = ... /// c.method; // The getter type is `int Function()`. /// c.getter; // The getter type is `int`. /// DartType getGetterType(ObjectAccessTarget target, DartType receiverType) { switch (target.kind) { case ObjectAccessTargetKind.callFunction: return receiverType; case ObjectAccessTargetKind.unresolved: case ObjectAccessTargetKind.dynamic: case ObjectAccessTargetKind.invalid: case ObjectAccessTargetKind.missing: return const DynamicType(); case ObjectAccessTargetKind.instanceMember: return getGetterTypeForMemberTarget(target.member, receiverType); case ObjectAccessTargetKind.extensionMember: switch (target.extensionMethodKind) { case ProcedureKind.Method: case ProcedureKind.Operator: FunctionType functionType = target.member.function.functionType; List<TypeParameter> extensionTypeParameters = functionType .typeParameters .take(target.inferredExtensionTypeArguments.length) .toList(); Substitution substitution = Substitution.fromPairs( extensionTypeParameters, target.inferredExtensionTypeArguments); return substitution.substituteType(new FunctionType( functionType.positionalParameters.skip(1).toList(), functionType.returnType, namedParameters: functionType.namedParameters, typeParameters: functionType.typeParameters .skip(target.inferredExtensionTypeArguments.length) .toList(), requiredParameterCount: functionType.requiredParameterCount - 1)); case ProcedureKind.Getter: FunctionType functionType = target.member.function.functionType; List<TypeParameter> extensionTypeParameters = functionType .typeParameters .take(target.inferredExtensionTypeArguments.length) .toList(); Substitution substitution = Substitution.fromPairs( extensionTypeParameters, target.inferredExtensionTypeArguments); return substitution.substituteType(functionType.returnType); case ProcedureKind.Setter: case ProcedureKind.Factory: break; } } throw unhandled('$target', 'getGetterType', null, null); } /// Returns the getter type of [member] on a receiver of type [receiverType]. /// /// For instance /// /// class Class<T> { /// T method() {} /// T getter => null; /// } /// /// Class<int> c = ... /// c.method; // The getter type is `int Function()`. /// c.getter; // The getter type is `int`. /// DartType getGetterTypeForMemberTarget( Member interfaceMember, DartType receiverType) { Class memberClass = interfaceMember.enclosingClass; assert(interfaceMember is Field || interfaceMember is Procedure, "Unexpected interface member $interfaceMember."); DartType calleeType = interfaceMember.getterType; if (memberClass.typeParameters.isNotEmpty) { receiverType = resolveTypeParameter(receiverType); if (receiverType is InterfaceType) { InterfaceType castedType = classHierarchy.getTypeAsInstanceOf(receiverType, memberClass); calleeType = Substitution.fromInterfaceType(castedType) .substituteType(calleeType); } } return calleeType; } /// Returns the type of [target] when accessed as an invocation on /// [receiverType]. /// /// If the target is known not to be invokable [unknownFunction] is returned. /// /// For instance /// /// class Class<T> { /// T method() {} /// T Function() getter1 => null; /// T getter2 => null; /// } /// /// Class<int> c = ... /// c.method; // The getter type is `int Function()`. /// c.getter1; // The getter type is `int Function()`. /// c.getter2; // The getter type is [unknownFunction]. /// FunctionType getFunctionType( ObjectAccessTarget target, DartType receiverType, bool followCall) { switch (target.kind) { case ObjectAccessTargetKind.callFunction: return _getFunctionType(receiverType, followCall); case ObjectAccessTargetKind.unresolved: case ObjectAccessTargetKind.dynamic: case ObjectAccessTargetKind.invalid: case ObjectAccessTargetKind.missing: return unknownFunction; case ObjectAccessTargetKind.instanceMember: return _getFunctionType( getGetterTypeForMemberTarget(target.member, receiverType), followCall); case ObjectAccessTargetKind.extensionMember: switch (target.extensionMethodKind) { case ProcedureKind.Method: case ProcedureKind.Operator: return target.member.function.functionType; case ProcedureKind.Getter: // TODO(johnniwinther): Handle implicit .call on extension getter. return _getFunctionType(target.member.function.returnType, false); case ProcedureKind.Setter: case ProcedureKind.Factory: break; } } throw unhandled('$target', 'getFunctionType', null, null); } /// Returns the type of the receiver argument in an access to an extension /// member on [extension] with the given extension [typeArguments]. DartType getExtensionReceiverType( Extension extension, List<DartType> typeArguments) { DartType receiverType = extension.onType; if (extension.typeParameters.isNotEmpty) { Substitution substitution = Substitution.fromPairs(extension.typeParameters, typeArguments); return substitution.substituteType(receiverType); } return receiverType; } /// Returns the return type of the invocation of [target] on [receiverType]. // TODO(johnniwinther): Cleanup [getFunctionType], [getReturnType], // [getIndexKeyType] and [getIndexSetValueType]. We shouldn't need that many. DartType getReturnType(ObjectAccessTarget target, DartType receiverType) { switch (target.kind) { case ObjectAccessTargetKind.instanceMember: FunctionType functionType = _getFunctionType( getGetterTypeForMemberTarget(target.member, receiverType), false); return functionType.returnType; break; case ObjectAccessTargetKind.extensionMember: switch (target.extensionMethodKind) { case ProcedureKind.Operator: FunctionType functionType = target.member.function.functionType; DartType returnType = functionType.returnType; if (functionType.typeParameters.isNotEmpty) { Substitution substitution = Substitution.fromPairs( functionType.typeParameters, target.inferredExtensionTypeArguments); return substitution.substituteType(returnType); } return returnType; default: throw unhandled('$target', 'getFunctionType', null, null); } break; case ObjectAccessTargetKind.callFunction: case ObjectAccessTargetKind.unresolved: case ObjectAccessTargetKind.dynamic: case ObjectAccessTargetKind.invalid: case ObjectAccessTargetKind.missing: break; } return const DynamicType(); } DartType getPositionalParameterTypeForTarget( ObjectAccessTarget target, DartType receiverType, int index) { switch (target.kind) { case ObjectAccessTargetKind.instanceMember: FunctionType functionType = _getFunctionType( getGetterTypeForMemberTarget(target.member, receiverType), false); if (functionType.positionalParameters.length > index) { return functionType.positionalParameters[index]; } break; case ObjectAccessTargetKind.extensionMember: FunctionType functionType = target.member.function.functionType; if (functionType.positionalParameters.length > index + 1) { DartType keyType = functionType.positionalParameters[index + 1]; if (functionType.typeParameters.isNotEmpty) { Substitution substitution = Substitution.fromPairs( functionType.typeParameters, target.inferredExtensionTypeArguments); return substitution.substituteType(keyType); } return keyType; } break; case ObjectAccessTargetKind.callFunction: case ObjectAccessTargetKind.unresolved: case ObjectAccessTargetKind.dynamic: case ObjectAccessTargetKind.invalid: case ObjectAccessTargetKind.missing: break; } return const DynamicType(); } /// Returns the type of the 'key' parameter in an [] or []= implementation. /// /// For instance /// /// class Class<K, V> { /// V operator [](K key) => null; /// void operator []=(K key, V value) {} /// } /// /// extension Extension<K, V> on Class<K, V> { /// V operator [](K key) => null; /// void operator []=(K key, V value) {} /// } /// /// new Class<int, String>()[0]; // The key type is `int`. /// new Class<int, String>()[0] = 'foo'; // The key type is `int`. /// Extension<int, String>(null)[0]; // The key type is `int`. /// Extension<int, String>(null)[0] = 'foo'; // The key type is `int`. /// DartType getIndexKeyType(ObjectAccessTarget target, DartType receiverType) { switch (target.kind) { case ObjectAccessTargetKind.instanceMember: FunctionType functionType = _getFunctionType( getGetterTypeForMemberTarget(target.member, receiverType), false); if (functionType.positionalParameters.length >= 1) { return functionType.positionalParameters[0]; } break; case ObjectAccessTargetKind.extensionMember: switch (target.extensionMethodKind) { case ProcedureKind.Operator: FunctionType functionType = target.member.function.functionType; if (functionType.positionalParameters.length >= 2) { DartType keyType = functionType.positionalParameters[1]; if (functionType.typeParameters.isNotEmpty) { Substitution substitution = Substitution.fromPairs( functionType.typeParameters, target.inferredExtensionTypeArguments); return substitution.substituteType(keyType); } return keyType; } break; default: throw unhandled('$target', 'getFunctionType', null, null); } break; case ObjectAccessTargetKind.callFunction: case ObjectAccessTargetKind.unresolved: case ObjectAccessTargetKind.dynamic: case ObjectAccessTargetKind.invalid: case ObjectAccessTargetKind.missing: break; } return const DynamicType(); } /// Returns the type of the 'value' parameter in an []= implementation. /// /// For instance /// /// class Class<K, V> { /// void operator []=(K key, V value) {} /// } /// /// extension Extension<K, V> on Class<K, V> { /// void operator []=(K key, V value) {} /// } /// /// new Class<int, String>()[0] = 'foo'; // The value type is `String`. /// Extension<int, String>(null)[0] = 'foo'; // The value type is `String`. /// DartType getIndexSetValueType( ObjectAccessTarget target, DartType receiverType) { switch (target.kind) { case ObjectAccessTargetKind.instanceMember: FunctionType functionType = _getFunctionType( getGetterTypeForMemberTarget(target.member, receiverType), false); if (functionType.positionalParameters.length >= 2) { return functionType.positionalParameters[1]; } break; case ObjectAccessTargetKind.extensionMember: switch (target.extensionMethodKind) { case ProcedureKind.Operator: FunctionType functionType = target.member.function.functionType; if (functionType.positionalParameters.length >= 3) { DartType indexType = functionType.positionalParameters[2]; if (functionType.typeParameters.isNotEmpty) { Substitution substitution = Substitution.fromPairs( functionType.typeParameters, target.inferredExtensionTypeArguments); return substitution.substituteType(indexType); } return indexType; } break; default: throw unhandled('$target', 'getFunctionType', null, null); } break; case ObjectAccessTargetKind.callFunction: case ObjectAccessTargetKind.unresolved: case ObjectAccessTargetKind.dynamic: case ObjectAccessTargetKind.invalid: case ObjectAccessTargetKind.missing: break; } return const DynamicType(); } FunctionType _getFunctionType(DartType calleeType, bool followCall) { if (calleeType is FunctionType) { return calleeType; } else if (followCall && calleeType is InterfaceType) { Member member = _getInterfaceMember(calleeType.classNode, callName, false, -1); if (member != null) { DartType callType = getGetterTypeForMemberTarget(member, calleeType); if (callType is FunctionType) { return callType; } } } return unknownFunction; } DartType getDerivedTypeArgumentOf(DartType type, Class class_) { if (type is InterfaceType) { InterfaceType typeAsInstanceOfClass = classHierarchy.getTypeAsInstanceOf(type, class_); if (typeAsInstanceOfClass != null) { return typeAsInstanceOfClass.typeArguments[0]; } } return null; } /// Gets the initializer for the given [field], or `null` if there is no /// initializer. Expression getFieldInitializer(Field field); /// If the [member] is a forwarding stub, return the target it forwards to. /// Otherwise return the given [member]. Member getRealTarget(Member member) { if (member is Procedure && member.isForwardingStub) { return member.forwardingStubInterfaceTarget; } return member; } DartType getSetterType(ObjectAccessTarget target, DartType receiverType) { switch (target.kind) { case ObjectAccessTargetKind.unresolved: case ObjectAccessTargetKind.dynamic: case ObjectAccessTargetKind.invalid: case ObjectAccessTargetKind.missing: return const DynamicType(); case ObjectAccessTargetKind.instanceMember: Member interfaceMember = target.member; Class memberClass = interfaceMember.enclosingClass; DartType setterType; if (interfaceMember is Procedure) { assert(interfaceMember.kind == ProcedureKind.Setter); List<VariableDeclaration> setterParameters = interfaceMember.function.positionalParameters; setterType = setterParameters.length > 0 ? setterParameters[0].type : const DynamicType(); } else if (interfaceMember is Field) { setterType = interfaceMember.type; } else { throw unhandled(interfaceMember.runtimeType.toString(), 'getSetterType', null, null); } if (memberClass.typeParameters.isNotEmpty) { receiverType = resolveTypeParameter(receiverType); if (receiverType is InterfaceType) { InterfaceType castedType = classHierarchy.getTypeAsInstanceOf(receiverType, memberClass); setterType = Substitution.fromInterfaceType(castedType) .substituteType(setterType); } } return setterType; case ObjectAccessTargetKind.extensionMember: switch (target.extensionMethodKind) { case ProcedureKind.Setter: FunctionType functionType = target.member.function.functionType; List<TypeParameter> extensionTypeParameters = functionType .typeParameters .take(target.inferredExtensionTypeArguments.length) .toList(); Substitution substitution = Substitution.fromPairs( extensionTypeParameters, target.inferredExtensionTypeArguments); return substitution .substituteType(functionType.positionalParameters[1]); case ProcedureKind.Method: case ProcedureKind.Getter: case ProcedureKind.Factory: case ProcedureKind.Operator: break; } // TODO(johnniwinther): Compute the right setter type. return const DynamicType(); case ObjectAccessTargetKind.callFunction: break; } throw unhandled(target.runtimeType.toString(), 'getSetterType', null, null); } DartType getTypeArgumentOf(DartType type, Class class_) { if (type is InterfaceType && identical(type.classNode, class_)) { return type.typeArguments[0]; } else { return const UnknownType(); } } /// Adds an "as" check to a [MethodInvocation] if necessary due to /// contravariance. /// /// The returned expression is the [AsExpression], if one was added; otherwise /// it is the [MethodInvocation]. Expression handleInvocationContravariance( MethodContravarianceCheckKind checkKind, MethodInvocation desugaredInvocation, Arguments arguments, Expression expression, DartType inferredType, FunctionType functionType, int fileOffset) { Expression expressionToReplace = desugaredInvocation ?? expression; switch (checkKind) { case MethodContravarianceCheckKind.checkMethodReturn: TreeNode parent = expressionToReplace.parent; AsExpression replacement = new AsExpression(expressionToReplace, inferredType) ..isTypeError = true ..fileOffset = fileOffset; parent.replaceChild(expressionToReplace, replacement); if (instrumentation != null) { int offset = arguments.fileOffset == -1 ? expression.fileOffset : arguments.fileOffset; instrumentation.record(uri, offset, 'checkReturn', new InstrumentationValueForType(inferredType)); } return replacement; case MethodContravarianceCheckKind.checkGetterReturn: TreeNode parent = expressionToReplace.parent; PropertyGet propertyGet = new PropertyGet(desugaredInvocation.receiver, desugaredInvocation.name, desugaredInvocation.interfaceTarget); AsExpression asExpression = new AsExpression(propertyGet, functionType) ..isTypeError = true ..fileOffset = fileOffset; MethodInvocation replacement = new MethodInvocation( asExpression, callName, desugaredInvocation.arguments); parent.replaceChild(expressionToReplace, replacement); if (instrumentation != null) { int offset = arguments.fileOffset == -1 ? expression.fileOffset : arguments.fileOffset; instrumentation.record(uri, offset, 'checkGetterReturn', new InstrumentationValueForType(functionType)); } return replacement; case MethodContravarianceCheckKind.none: break; } return expressionToReplace; } /// Add an "as" check if necessary due to contravariance. /// /// Returns the "as" check if it was added; otherwise returns the original /// expression. Expression handlePropertyGetContravariance( Expression receiver, ObjectAccessTarget readTarget, PropertyGet desugaredGet, Expression expression, DartType inferredType, int fileOffset) { bool checkReturn = false; if (receiver != null && readTarget.isInstanceMember && receiver is! ThisExpression) { Member interfaceMember = readTarget.member; if (interfaceMember is Procedure) { checkReturn = returnedTypeParametersOccurNonCovariantly( interfaceMember.enclosingClass, interfaceMember.function.returnType); } else if (interfaceMember is Field) { checkReturn = returnedTypeParametersOccurNonCovariantly( interfaceMember.enclosingClass, interfaceMember.type); } } Expression replacedExpression = desugaredGet ?? expression; if (checkReturn) { Expression expressionToReplace = replacedExpression; TreeNode parent = expressionToReplace.parent; replacedExpression = new AsExpression(expressionToReplace, inferredType) ..isTypeError = true ..fileOffset = fileOffset; parent.replaceChild(expressionToReplace, replacedExpression); } if (instrumentation != null && checkReturn) { instrumentation.record(uri, expression.fileOffset, 'checkReturn', new InstrumentationValueForType(inferredType)); } return replacedExpression; } /// Modifies a type as appropriate when inferring a declared variable's type. DartType inferDeclarationType(DartType initializerType) { if (initializerType is BottomType || (initializerType is InterfaceType && initializerType.classNode == coreTypes.nullClass)) { // If the initializer type is Null or bottom, the inferred type is // dynamic. // TODO(paulberry): this rule is inherited from analyzer behavior but is // not spec'ed anywhere. return const DynamicType(); } return initializerType; } /// Performs type inference on the given [expression]. /// /// [typeContext] is the expected type of the expression, based on surrounding /// code. [typeNeeded] indicates whether it is necessary to compute the /// actual type of the expression. If [typeNeeded] is `true`, /// [ExpressionInferenceResult.inferredType] is the actual type of the /// expression; otherwise `null`. /// /// Derived classes should override this method with logic that dispatches on /// the expression type and calls the appropriate specialized "infer" method. ExpressionInferenceResult inferExpression( Expression expression, DartType typeContext, bool typeNeeded, {bool isVoidAllowed}); @override void inferFieldInitializer( InferenceHelper helper, DartType context, Expression initializer, ) { assert(closureContext == null); assert(!isTopLevel); this.helper = helper; ExpressionInferenceResult result = inferExpression(initializer, context, true, isVoidAllowed: true); if (result.replacement != null) { initializer = result.replacement; } ensureAssignable( context, result.inferredType, initializer, initializer.fileOffset, isVoidAllowed: context is VoidType); this.helper = null; } @override void inferFunctionBody(InferenceHelper helper, DartType returnType, AsyncMarker asyncMarker, Statement body) { assert(closureContext == null); this.helper = helper; closureContext = new ClosureContext(this, asyncMarker, returnType, false); inferStatement(body); closureContext = null; this.helper = null; } DartType inferInvocation(DartType typeContext, int offset, FunctionType calleeType, Arguments arguments, {bool isOverloadedArithmeticOperator: false, DartType returnType, DartType receiverType, bool skipTypeArgumentInference: false, bool isConst: false, bool isImplicitExtensionMember: false}) { assert( returnType == null || !containsFreeFunctionTypeVariables(returnType), "Return type $returnType contains free variables." "Provided function type: $calleeType."); int extensionTypeParameterCount = getExtensionTypeParameterCount(arguments); if (extensionTypeParameterCount != 0) { assert(returnType == null, "Unexpected explicit return type for extension method invocation."); return _inferGenericExtensionMethodInvocation(extensionTypeParameterCount, typeContext, offset, calleeType, arguments, isOverloadedArithmeticOperator: isOverloadedArithmeticOperator, receiverType: receiverType, skipTypeArgumentInference: skipTypeArgumentInference, isConst: isConst, isImplicitExtensionMember: isImplicitExtensionMember); } return _inferInvocation(typeContext, offset, calleeType, arguments, isOverloadedArithmeticOperator: isOverloadedArithmeticOperator, receiverType: receiverType, returnType: returnType, skipTypeArgumentInference: skipTypeArgumentInference, isConst: isConst, isImplicitExtensionMember: isImplicitExtensionMember); } DartType _inferGenericExtensionMethodInvocation( int extensionTypeParameterCount, DartType typeContext, int offset, FunctionType calleeType, Arguments arguments, {bool isOverloadedArithmeticOperator: false, DartType receiverType, bool skipTypeArgumentInference: false, bool isConst: false, bool isImplicitExtensionMember: false}) { FunctionType extensionFunctionType = new FunctionType( [calleeType.positionalParameters.first], const DynamicType(), requiredParameterCount: 1, typeParameters: calleeType.typeParameters .take(extensionTypeParameterCount) .toList()); Arguments extensionArguments = helper.forest.createArguments( arguments.fileOffset, [arguments.positional.first], types: getExplicitExtensionTypeArguments(arguments)); _inferInvocation( const UnknownType(), offset, extensionFunctionType, extensionArguments, skipTypeArgumentInference: skipTypeArgumentInference, receiverType: receiverType, isImplicitExtensionMember: isImplicitExtensionMember); Substitution extensionSubstitution = Substitution.fromPairs( extensionFunctionType.typeParameters, extensionArguments.types); List<TypeParameter> targetTypeParameters = const <TypeParameter>[]; if (calleeType.typeParameters.length > extensionTypeParameterCount) { targetTypeParameters = calleeType.typeParameters.skip(extensionTypeParameterCount).toList(); } FunctionType targetFunctionType = new FunctionType( calleeType.positionalParameters.skip(1).toList(), calleeType.returnType, requiredParameterCount: calleeType.requiredParameterCount - 1, namedParameters: calleeType.namedParameters, typeParameters: targetTypeParameters); targetFunctionType = extensionSubstitution.substituteType(targetFunctionType); Arguments targetArguments = helper.forest.createArguments( arguments.fileOffset, arguments.positional.skip(1).toList(), named: arguments.named, types: getExplicitTypeArguments(arguments)); DartType inferredType = _inferInvocation( typeContext, offset, targetFunctionType, targetArguments, isOverloadedArithmeticOperator: isOverloadedArithmeticOperator, skipTypeArgumentInference: skipTypeArgumentInference, isConst: isConst); arguments.positional.clear(); arguments.positional.addAll(extensionArguments.positional); arguments.positional.addAll(targetArguments.positional); setParents(arguments.positional, arguments); // The `targetArguments.named` is the same list as `arguments.named` so // we just need to ensure that parent relations are realigned. setParents(arguments.named, arguments); arguments.types.clear(); arguments.types.addAll(extensionArguments.types); arguments.types.addAll(targetArguments.types); return inferredType; } /// Performs the type inference steps that are shared by all kinds of /// invocations (constructors, instance methods, and static methods). DartType _inferInvocation(DartType typeContext, int offset, FunctionType calleeType, Arguments arguments, {bool isOverloadedArithmeticOperator: false, bool isBinaryOperator: false, DartType receiverType, DartType returnType, bool skipTypeArgumentInference: false, bool isConst: false, bool isImplicitExtensionMember: false}) { assert( returnType == null || !containsFreeFunctionTypeVariables(returnType), "Return type $returnType contains free variables." "Provided function type: $calleeType."); lastInferredSubstitution = null; lastCalleeType = null; List<TypeParameter> calleeTypeParameters = calleeType.typeParameters; if (calleeTypeParameters.isNotEmpty) { // It's possible that one of the callee type parameters might match a type // that already exists as part of inference (e.g. the type of an // argument). This might happen, for instance, in the case where a // function or method makes a recursive call to itself. To avoid the // callee type parameters accidentally matching a type that already // exists, and creating invalid inference results, we need to create fresh // type parameters for the callee (see dartbug.com/31759). // TODO(paulberry): is it possible to find a narrower set of circumstances // in which me must do this, to avoid a performance regression? FreshTypeParameters fresh = getFreshTypeParameters(calleeTypeParameters); calleeType = fresh.applyToFunctionType(calleeType); if (returnType != null) { returnType = fresh.substitute(returnType); } calleeTypeParameters = fresh.freshTypeParameters; } List<DartType> explicitTypeArguments = getExplicitTypeArguments(arguments); bool inferenceNeeded = !skipTypeArgumentInference && explicitTypeArguments == null && calleeTypeParameters.isNotEmpty; bool typeChecksNeeded = !isTopLevel; List<DartType> inferredTypes; Substitution substitution; List<DartType> formalTypes; List<DartType> actualTypes; if (inferenceNeeded || typeChecksNeeded) { formalTypes = []; actualTypes = []; } if (inferenceNeeded) { if (isConst && typeContext != null) { typeContext = new TypeVariableEliminator(coreTypes).substituteType(typeContext); } inferredTypes = new List<DartType>.filled( calleeTypeParameters.length, const UnknownType()); typeSchemaEnvironment.inferGenericFunctionOrType( returnType ?? calleeType.returnType, calleeTypeParameters, null, null, typeContext, inferredTypes); substitution = Substitution.fromPairs(calleeTypeParameters, inferredTypes); } else if (explicitTypeArguments != null && calleeTypeParameters.length == explicitTypeArguments.length) { substitution = Substitution.fromPairs(calleeTypeParameters, explicitTypeArguments); } else if (calleeTypeParameters.length != 0) { substitution = Substitution.fromPairs( calleeTypeParameters, new List<DartType>.filled( calleeTypeParameters.length, const DynamicType())); } // TODO(paulberry): if we are doing top level inference and type arguments // were omitted, report an error. int i = 0; _forEachArgument(arguments, (name, expression) { DartType formalType = name != null ? getNamedParameterType(calleeType, name) : getPositionalParameterType(calleeType, i++); DartType inferredFormalType = substitution != null ? substitution.substituteType(formalType) : formalType; DartType inferredType; if (isImplicitExtensionMember && i == 1) { assert( receiverType != null, "No receiver type provided for implicit extension member " "invocation."); inferredType = receiverType; } else { ExpressionInferenceResult result = inferExpression( expression, inferredFormalType, inferenceNeeded || isOverloadedArithmeticOperator || typeChecksNeeded); inferredType = result.inferredType; } if (inferenceNeeded || typeChecksNeeded) { formalTypes.add(formalType); actualTypes.add(inferredType); } if (isOverloadedArithmeticOperator) { returnType = typeSchemaEnvironment.getTypeOfOverloadedArithmetic( receiverType, inferredType); } }); // Check for and remove duplicated named arguments. List<NamedExpression> named = arguments.named; if (named.length == 2) { if (named[0].name == named[1].name) { String name = named[1].name; Expression error = helper.buildProblem( templateDuplicatedNamedArgument.withArguments(name), named[1].fileOffset, name.length); arguments.named = [new NamedExpression(named[1].name, error)]; formalTypes.removeLast(); actualTypes.removeLast(); } } else if (named.length > 2) { Map<String, NamedExpression> seenNames = <String, NamedExpression>{}; bool hasProblem = false; int namedTypeIndex = arguments.positional.length; List<NamedExpression> uniqueNamed = <NamedExpression>[]; for (NamedExpression expression in named) { String name = expression.name; if (seenNames.containsKey(name)) { hasProblem = true; NamedExpression prevNamedExpression = seenNames[name]; prevNamedExpression.value = helper.buildProblem( templateDuplicatedNamedArgument.withArguments(name), expression.fileOffset, name.length) ..parent = prevNamedExpression; formalTypes.removeAt(namedTypeIndex); actualTypes.removeAt(namedTypeIndex); } else { seenNames[name] = expression; uniqueNamed.add(expression); namedTypeIndex++; } } if (hasProblem) { arguments.named = uniqueNamed; } } if (inferenceNeeded) { typeSchemaEnvironment.inferGenericFunctionOrType( returnType ?? calleeType.returnType, calleeTypeParameters, formalTypes, actualTypes, typeContext, inferredTypes); substitution = Substitution.fromPairs(calleeTypeParameters, inferredTypes); instrumentation?.record(uri, offset, 'typeArgs', new InstrumentationValueForTypeArgs(inferredTypes)); arguments.types.clear(); arguments.types.addAll(inferredTypes); } if (typeChecksNeeded && !identical(calleeType, unknownFunction)) { LocatedMessage argMessage = helper.checkArgumentsForType(calleeType, arguments, offset); if (argMessage != null) { helper.addProblem( argMessage.messageObject, argMessage.charOffset, argMessage.length); } else { // Argument counts and names match. Compare types. int numPositionalArgs = arguments.positional.length; for (int i = 0; i < formalTypes.length; i++) { DartType formalType = formalTypes[i]; DartType expectedType = substitution != null ? substitution.substituteType(formalType) : formalType; DartType actualType = actualTypes[i]; Expression expression = i < numPositionalArgs ? arguments.positional[i] : arguments.named[i - numPositionalArgs].value; ensureAssignable( expectedType, actualType, expression, expression.fileOffset, isVoidAllowed: expectedType is VoidType, // TODO(johnniwinther): Specialize message for operator // invocations. template: templateArgumentTypeNotAssignable); } } } DartType inferredType; lastInferredSubstitution = substitution; lastCalleeType = calleeType; if (returnType != null) { inferredType = substitution == null ? returnType : substitution.substituteType(returnType); } else { if (substitution != null) { calleeType = substitution.substituteType(calleeType.withoutTypeParameters); } inferredType = calleeType.returnType; } assert( !containsFreeFunctionTypeVariables(inferredType), "Inferred return type $inferredType contains free variables." "Inferred function type: $calleeType."); return inferredType; } DartType inferLocalFunction(FunctionNode function, DartType typeContext, int fileOffset, DartType returnContext) { bool hasImplicitReturnType = false; if (returnContext == null) { hasImplicitReturnType = true; returnContext = const DynamicType(); } if (!isTopLevel) { List<VariableDeclaration> positionalParameters = function.positionalParameters; for (int i = 0; i < positionalParameters.length; i++) { VariableDeclaration parameter = positionalParameters[i]; inferMetadataKeepingHelper(parameter.annotations); if (parameter.initializer != null) { inferExpression(parameter.initializer, parameter.type, !isTopLevel); } } for (VariableDeclaration parameter in function.namedParameters) { inferMetadataKeepingHelper(parameter.annotations); inferExpression(parameter.initializer, parameter.type, !isTopLevel); } } // Let `<T0, ..., Tn>` be the set of type parameters of the closure (with // `n`=0 if there are no type parameters). List<TypeParameter> typeParameters = function.typeParameters; // Let `(P0 x0, ..., Pm xm)` be the set of formal parameters of the closure // (including required, positional optional, and named optional parameters). // If any type `Pi` is missing, denote it as `_`. List<VariableDeclaration> formals = function.positionalParameters.toList() ..addAll(function.namedParameters); // Let `B` denote the closure body. If `B` is an expression function body // (`=> e`), treat it as equivalent to a block function body containing a // single `return` statement (`{ return e; }`). // Attempt to match `K` as a function type compatible with the closure (that // is, one having n type parameters and a compatible set of formal // parameters). If there is a successful match, let `<S0, ..., Sn>` be the // set of matched type parameters and `(Q0, ..., Qm)` be the set of matched // formal parameter types, and let `N` be the return type. Substitution substitution; List<DartType> formalTypesFromContext = new List<DartType>.filled(formals.length, null); if (typeContext is FunctionType) { for (int i = 0; i < formals.length; i++) { if (i < function.positionalParameters.length) { formalTypesFromContext[i] = getPositionalParameterType(typeContext, i); } else { formalTypesFromContext[i] = getNamedParameterType(typeContext, formals[i].name); } } returnContext = typeContext.returnType; // Let `[T/S]` denote the type substitution where each `Si` is replaced // with the corresponding `Ti`. Map<TypeParameter, DartType> substitutionMap = <TypeParameter, DartType>{}; for (int i = 0; i < typeContext.typeParameters.length; i++) { substitutionMap[typeContext.typeParameters[i]] = i < typeParameters.length ? new TypeParameterType(typeParameters[i]) : const DynamicType(); } substitution = Substitution.fromMap(substitutionMap); } else { // If the match is not successful because `K` is `_`, let all `Si`, all // `Qi`, and `N` all be `_`. // If the match is not successful for any other reason, this will result // in a type error, so the implementation is free to choose the best // error recovery path. substitution = Substitution.empty; } // Define `Ri` as follows: if `Pi` is not `_`, let `Ri` be `Pi`. // Otherwise, if `Qi` is not `_`, let `Ri` be the greatest closure of // `Qi[T/S]` with respect to `?`. Otherwise, let `Ri` be `dynamic`. for (int i = 0; i < formals.length; i++) { VariableDeclarationImpl formal = formals[i]; if (VariableDeclarationImpl.isImplicitlyTyped(formal)) { DartType inferredType; if (formalTypesFromContext[i] == coreTypes.nullType) { inferredType = coreTypes.objectRawType(library.nullable); } else if (formalTypesFromContext[i] != null) { inferredType = greatestClosure(coreTypes, substitution.substituteType(formalTypesFromContext[i])); } else { inferredType = const DynamicType(); } instrumentation?.record(uri, formal.fileOffset, 'type', new InstrumentationValueForType(inferredType)); formal.type = inferredType; } } // Let `N'` be `N[T/S]`. The [ClosureContext] constructor will adjust // accordingly if the closure is declared with `async`, `async*`, or // `sync*`. if (returnContext is! UnknownType) { returnContext = substitution.substituteType(returnContext); } // Apply type inference to `B` in return context `N’`, with any references // to `xi` in `B` having type `Pi`. This produces `B’`. bool needToSetReturnType = hasImplicitReturnType; ClosureContext oldClosureContext = this.closureContext; ClosureContext closureContext = new ClosureContext( this, function.asyncMarker, returnContext, needToSetReturnType); this.closureContext = closureContext; inferStatement(function.body); // If the closure is declared with `async*` or `sync*`, let `M` be the // least upper bound of the types of the `yield` expressions in `B’`, or // `void` if `B’` contains no `yield` expressions. Otherwise, let `M` be // the least upper bound of the types of the `return` expressions in `B’`, // or `void` if `B’` contains no `return` expressions. DartType inferredReturnType; if (needToSetReturnType) { inferredReturnType = closureContext.inferReturnType(this); } // Then the result of inference is `<T0, ..., Tn>(R0 x0, ..., Rn xn) B` with // type `<T0, ..., Tn>(R0, ..., Rn) -> M’` (with some of the `Ri` and `xi` // denoted as optional or named parameters, if appropriate). if (needToSetReturnType) { instrumentation?.record(uri, fileOffset, 'returnType', new InstrumentationValueForType(inferredReturnType)); function.returnType = inferredReturnType; } this.closureContext = oldClosureContext; return function.functionType; } @override void inferMetadata(InferenceHelper helper, List<Expression> annotations) { if (annotations != null) { this.helper = helper; inferMetadataKeepingHelper(annotations); this.helper = null; } } @override void inferMetadataKeepingHelper(List<Expression> annotations) { if (annotations != null) { // Place annotations in a temporary list literal so that they will have a // parent. This is necessary in case any of the annotations need to get // replaced during type inference. List<TreeNode> parents = annotations.map((e) => e.parent).toList(); new ListLiteral(annotations); for (Expression annotation in annotations) { inferExpression(annotation, const UnknownType(), !isTopLevel); } for (int i = 0; i < annotations.length; ++i) { annotations[i].parent = parents[i]; } } } StaticInvocation transformExtensionMethodInvocation(ObjectAccessTarget target, Expression expression, Expression receiver, Arguments arguments) { assert(target.isExtensionMember); Procedure procedure = target.member; Expression replacement; expression.parent.replaceChild( expression, replacement = helper.forest.createStaticInvocation( expression.fileOffset, target.member, arguments = helper.forest.createArgumentsForExtensionMethod( arguments.fileOffset, target.inferredExtensionTypeArguments.length, procedure.function.typeParameters.length - target.inferredExtensionTypeArguments.length, receiver, extensionTypeArguments: target.inferredExtensionTypeArguments, positionalArguments: arguments.positional, namedArguments: arguments.named, typeArguments: arguments.types))); return replacement; } /// Performs the core type inference algorithm for method invocations (this /// handles both null-aware and non-null-aware method invocations). ExpressionInferenceResult inferMethodInvocation( MethodInvocationImpl node, DartType typeContext) { // First infer the receiver so we can look up the method that was invoked. ExpressionInferenceResult result = inferExpression(node.receiver, const UnknownType(), true); DartType receiverType = result.inferredType; ObjectAccessTarget target = findMethodInvocationMember(receiverType, node); Name methodName = node.name; Arguments arguments = node.arguments; assert(target != null, "No target for ${node}."); bool isOverloadedArithmeticOperator = isOverloadedArithmeticOperatorAndType(target, receiverType); DartType calleeType = getGetterType(target, receiverType); FunctionType functionType = getFunctionType(target, receiverType, !node.isImplicitCall); if (!target.isUnresolved && calleeType is! DynamicType && !(calleeType is InterfaceType && calleeType.classNode == coreTypes.functionClass) && identical(functionType, unknownFunction)) { TreeNode parent = node.parent; Expression error = helper.wrapInProblem(node, templateInvokeNonFunction.withArguments(methodName.name), noLength); parent?.replaceChild(node, error); return const ExpressionInferenceResult(const DynamicType()); } MethodContravarianceCheckKind checkKind = preCheckInvocationContravariance( receiverType, target, isThisReceiver: node.receiver is ThisExpression); StaticInvocation replacement; if (target.isExtensionMember) { replacement = transformExtensionMethodInvocation( target, node, node.receiver, arguments); arguments = replacement.arguments; } DartType inferredType = inferInvocation( typeContext, node.fileOffset, functionType, arguments, isOverloadedArithmeticOperator: isOverloadedArithmeticOperator, receiverType: receiverType, isImplicitExtensionMember: target.isExtensionMember); if (methodName.name == '==') { inferredType = coreTypes.boolRawType(library.nonNullable); } handleInvocationContravariance(checkKind, node, arguments, node, inferredType, functionType, node.fileOffset); if (node.isImplicitCall && target.isInstanceMember) { Member member = target.member; if (!(member is Procedure && member.kind == ProcedureKind.Method)) { TreeNode parent = node.parent; Expression errorNode = helper.wrapInProblem( node, templateImplicitCallOfNonMethod.withArguments(receiverType), noLength); parent?.replaceChild(node, errorNode); } } if (target.isExtensionMember) { library.checkBoundsInStaticInvocation( replacement, typeSchemaEnvironment, helper.uri); } else { _checkBoundsInMethodInvocation(target, receiverType, calleeType, methodName, arguments, node.fileOffset); } return new ExpressionInferenceResult(inferredType, replacement); } void _checkBoundsInMethodInvocation( ObjectAccessTarget target, DartType receiverType, DartType calleeType, Name methodName, Arguments arguments, int fileOffset) { // If [arguments] were inferred, check them. // TODO(dmitryas): Figure out why [library] is sometimes null? Answer: // because top level inference never got a library. This has changed so // we always have a library. Should we still skip this for top level // inference? if (!isTopLevel) { // [actualReceiverType], [interfaceTarget], and [actualMethodName] below // are for a workaround for the cases like the following: // // class C1 { var f = new C2(); } // class C2 { int call<X extends num>(X x) => 42; } // main() { C1 c = new C1(); c.f("foobar"); } DartType actualReceiverType; Member interfaceTarget; Name actualMethodName; if (calleeType is InterfaceType) { actualReceiverType = calleeType; interfaceTarget = null; actualMethodName = callName; } else { actualReceiverType = receiverType; interfaceTarget = target.isInstanceMember ? target.member : null; actualMethodName = methodName; } library.checkBoundsInMethodInvocation( actualReceiverType, typeSchemaEnvironment, classHierarchy, this, actualMethodName, interfaceTarget, arguments, helper.uri, fileOffset, inferred: getExplicitTypeArguments(arguments) == null); } } bool isOverloadedArithmeticOperatorAndType( ObjectAccessTarget target, DartType receiverType) { return target.isInstanceMember && target.member is Procedure && typeSchemaEnvironment.isOverloadedArithmeticOperatorAndType( target.member, receiverType); } /// Performs the core type inference algorithm for super method invocations. ExpressionInferenceResult inferSuperMethodInvocation( SuperMethodInvocation expression, DartType typeContext, ObjectAccessTarget target) { int fileOffset = expression.fileOffset; Name methodName = expression.name; Arguments arguments = expression.arguments; DartType receiverType = thisType; bool isOverloadedArithmeticOperator = isOverloadedArithmeticOperatorAndType(target, receiverType); DartType calleeType = getGetterType(target, receiverType); FunctionType functionType = getFunctionType(target, receiverType, true); if (!target.isUnresolved && calleeType is! DynamicType && !(calleeType is InterfaceType && calleeType.classNode == coreTypes.functionClass) && identical(functionType, unknownFunction)) { TreeNode parent = expression.parent; Expression error = helper.wrapInProblem(expression, templateInvokeNonFunction.withArguments(methodName.name), noLength); parent?.replaceChild(expression, error); return const ExpressionInferenceResult(const DynamicType()); } DartType inferredType = inferInvocation( typeContext, fileOffset, functionType, arguments, isOverloadedArithmeticOperator: isOverloadedArithmeticOperator, receiverType: receiverType, isImplicitExtensionMember: target.isExtensionMember); if (methodName.name == '==') { inferredType = coreTypes.boolRawType(library.nonNullable); } _checkBoundsInMethodInvocation( target, receiverType, calleeType, methodName, arguments, fileOffset); return new ExpressionInferenceResult(inferredType); } @override void inferParameterInitializer( InferenceHelper helper, Expression initializer, DartType declaredType) { assert(closureContext == null); this.helper = helper; assert(declaredType != null); ExpressionInferenceResult result = inferExpression(initializer, declaredType, true); if (result.replacement != null) { initializer = result.replacement; } ensureAssignable( declaredType, result.inferredType, initializer, initializer.fileOffset); this.helper = null; } /// Performs the core type inference algorithm for property gets (this handles /// both null-aware and non-null-aware property gets). ExpressionInferenceResult inferPropertyGet( Expression expression, Expression receiver, int fileOffset, DartType typeContext, PropertyGet propertyGet, {VariableDeclaration nullAwareReceiverVariable}) { // First infer the receiver so we can look up the getter that was invoked. DartType receiverType; if (receiver == null) { receiverType = thisType; } else { ExpressionInferenceResult result = inferExpression(receiver, const UnknownType(), true); if (result.replacement != null) { receiver = result.replacement; } receiverType = result.inferredType; } nullAwareReceiverVariable?.type = receiverType; Name propertyName = propertyGet.name; ObjectAccessTarget readTarget = findInterfaceMemberOrReport(receiverType, propertyName, fileOffset, templateUndefinedGetter, expression, includeExtensionMethods: true); if (readTarget.isInstanceMember) { if (instrumentation != null && receiverType == const DynamicType()) { instrumentation.record(uri, propertyGet.fileOffset, 'target', new InstrumentationValueForMember(readTarget.member)); } propertyGet.interfaceTarget = readTarget.member; } DartType inferredType = getGetterType(readTarget, receiverType); Expression replacedExpression = handlePropertyGetContravariance(receiver, readTarget, propertyGet, expression, inferredType, fileOffset); Expression replacement; if (readTarget.isInstanceMember) { Member member = readTarget.member; if (member is Procedure && member.kind == ProcedureKind.Method) { inferredType = instantiateTearOff(inferredType, typeContext, replacedExpression); } } else if (readTarget.isExtensionMember) { int fileOffset = expression.fileOffset; switch (readTarget.extensionMethodKind) { case ProcedureKind.Getter: expression.parent.replaceChild( expression, replacement = expression = helper.forest.createStaticInvocation( fileOffset, readTarget.member, helper.forest.createArgumentsForExtensionMethod( fileOffset, readTarget.inferredExtensionTypeArguments.length, 0, receiver, extensionTypeArguments: readTarget.inferredExtensionTypeArguments))); break; case ProcedureKind.Method: expression.parent.replaceChild( expression, replacement = expression = helper.forest.createStaticInvocation( fileOffset, readTarget.tearoffTarget, helper.forest.createArgumentsForExtensionMethod( fileOffset, readTarget.inferredExtensionTypeArguments.length, 0, receiver, extensionTypeArguments: readTarget.inferredExtensionTypeArguments))); inferredType = instantiateTearOff(inferredType, typeContext, expression); break; case ProcedureKind.Setter: case ProcedureKind.Factory: case ProcedureKind.Operator: unhandled('$readTarget', "inferPropertyGet", fileOffset, uri); break; } } return new ExpressionInferenceResult(inferredType, replacement); } /// Performs the core type inference algorithm for super property get. ExpressionInferenceResult inferSuperPropertyGet(SuperPropertyGet expression, DartType typeContext, ObjectAccessTarget readTarget) { DartType receiverType = thisType; DartType inferredType = getGetterType(readTarget, receiverType); Expression replacement; if (readTarget.isInstanceMember) { Member member = readTarget.member; if (member is Procedure && member.kind == ProcedureKind.Method) { inferredType = instantiateTearOff(inferredType, typeContext, expression); } } return new ExpressionInferenceResult(inferredType, replacement); } /// Modifies a type as appropriate when inferring a closure return type. DartType inferReturnType(DartType returnType) { return returnType ?? typeSchemaEnvironment.nullType; } /// Performs type inference on the given [statement]. /// /// Derived classes should override this method with logic that dispatches on /// the statement type and calls the appropriate specialized "infer" method. void inferStatement(Statement statement); /// Performs the type inference steps necessary to instantiate a tear-off /// (if necessary). DartType instantiateTearOff( DartType tearoffType, DartType context, Expression expression) { if (tearoffType is FunctionType && context is FunctionType && context.typeParameters.isEmpty) { List<TypeParameter> typeParameters = tearoffType.typeParameters; if (typeParameters.isNotEmpty) { List<DartType> inferredTypes = new List<DartType>.filled( typeParameters.length, const UnknownType()); FunctionType instantiatedType = tearoffType.withoutTypeParameters; typeSchemaEnvironment.inferGenericFunctionOrType( instantiatedType, typeParameters, [], [], context, inferredTypes); if (!isTopLevel) { TreeNode parent = expression.parent; parent.replaceChild( expression, new Instantiation(expression, inferredTypes) ..fileOffset = expression.fileOffset); } Substitution substitution = Substitution.fromPairs(typeParameters, inferredTypes); return substitution.substituteType(instantiatedType); } } return tearoffType; } /// True if the returned [type] has non-covariant occurrences of any of /// [class_]'s type parameters. /// /// A non-covariant occurrence of a type parameter is either a contravariant /// or an invariant position. /// /// A contravariant position is to the left of an odd number of arrows. For /// example, T occurs contravariantly in T -> T0, T0 -> (T -> T1), /// (T0 -> T) -> T1 but not in (T -> T0) -> T1. /// /// An invariant position is without a bound of a type parameter. For example, /// T occurs invariantly in `S Function<S extends T>()` and /// `void Function<S extends C<T>>(S)`. static bool returnedTypeParametersOccurNonCovariantly( Class class_, DartType type) { if (class_.typeParameters.isEmpty) return false; IncludesTypeParametersNonCovariantly checker = new IncludesTypeParametersNonCovariantly(class_.typeParameters, // We are checking the returned type (field/getter type or return // type of a method) and this is a covariant position. initialVariance: Variance.covariant); return type.accept(checker); } /// Determines the dispatch category of a [MethodInvocation] and returns a /// boolean indicating whether an "as" check will need to be added due to /// contravariance. MethodContravarianceCheckKind preCheckInvocationContravariance( DartType receiverType, ObjectAccessTarget target, {bool isThisReceiver}) { assert(isThisReceiver != null); if (target.isInstanceMember) { Member interfaceMember = target.member; if (interfaceMember is Field || interfaceMember is Procedure && interfaceMember.kind == ProcedureKind.Getter) { DartType getType = getGetterType(target, receiverType); if (getType is DynamicType) { return MethodContravarianceCheckKind.none; } if (!isThisReceiver) { if ((interfaceMember is Field && returnedTypeParametersOccurNonCovariantly( interfaceMember.enclosingClass, interfaceMember.type)) || (interfaceMember is Procedure && returnedTypeParametersOccurNonCovariantly( interfaceMember.enclosingClass, interfaceMember.function.returnType))) { return MethodContravarianceCheckKind.checkGetterReturn; } } } else if (!isThisReceiver && interfaceMember is Procedure && returnedTypeParametersOccurNonCovariantly( interfaceMember.enclosingClass, interfaceMember.function.returnType)) { return MethodContravarianceCheckKind.checkMethodReturn; } } return MethodContravarianceCheckKind.none; } /// If the given [type] is a [TypeParameterType], resolve it to its bound. DartType resolveTypeParameter(DartType type) { DartType resolveOneStep(DartType type) { if (type is TypeParameterType) { return type.bound; } else { return null; } } DartType resolved = resolveOneStep(type); if (resolved == null) return type; // Detect circularities using the tortoise-and-hare algorithm. type = resolved; DartType hare = resolveOneStep(type); if (hare == null) return type; while (true) { if (identical(type, hare)) { // We found a circularity. Give up and return `dynamic`. return const DynamicType(); } // Hare takes two steps DartType step1 = resolveOneStep(hare); if (step1 == null) return hare; DartType step2 = resolveOneStep(step1); if (step2 == null) return hare; hare = step2; // Tortoise takes one step type = resolveOneStep(type); } } DartType wrapFutureOrType(DartType type) { if (type is InterfaceType && identical(type.classNode, coreTypes.futureOrClass)) { return type; } // TODO(paulberry): If [type] is a subtype of `Future`, should we just // return it unmodified? return new InterfaceType( coreTypes.futureOrClass, <DartType>[type ?? const DynamicType()]); } DartType wrapFutureType(DartType type) { DartType typeWithoutFutureOr = type ?? const DynamicType(); return new InterfaceType( coreTypes.futureClass, <DartType>[typeWithoutFutureOr]); } DartType wrapType(DartType type, Class class_) { return new InterfaceType(class_, <DartType>[type ?? const DynamicType()]); } void _forEachArgument( Arguments arguments, void callback(String name, Expression expression)) { for (Expression expression in arguments.positional) { callback(null, expression); } for (NamedExpression namedExpression in arguments.named) { callback(namedExpression.name, namedExpression.value); } } Member _getInterfaceMember( Class class_, Name name, bool setter, int charOffset) { Member member = engine.hierarchyBuilder.getCombinedMemberSignatureKernel( class_, name, setter, charOffset, library); if (member == null && library.isPatch) { // TODO(dmitryas): Hack for parts. member ??= classHierarchy.getInterfaceMember(class_, name, setter: setter); } return TypeInferenceEngine.resolveInferenceNode(member); } /// Determines if the given [expression]'s type is precisely known at compile /// time. /// /// If it is, an error message template is returned, which can be used by the /// caller to report an invalid cast. Otherwise, `null` is returned. Template<Message Function(DartType, DartType)> _getPreciseTypeErrorTemplate( Expression expression) { if (expression is ListLiteral) { return templateInvalidCastLiteralList; } if (expression is MapLiteral) { return templateInvalidCastLiteralMap; } if (expression is SetLiteral) { return templateInvalidCastLiteralSet; } if (expression is FunctionExpression) { return templateInvalidCastFunctionExpr; } if (expression is ConstructorInvocation) { return templateInvalidCastNewExpr; } if (expression is StaticGet) { Member target = expression.target; if (target is Procedure && target.kind == ProcedureKind.Method) { if (target.enclosingClass != null) { return templateInvalidCastStaticMethod; } else { return templateInvalidCastTopLevelFunction; } } return null; } if (expression is VariableGet) { VariableDeclaration variable = expression.variable; if (variable is VariableDeclarationImpl && VariableDeclarationImpl.isLocalFunction(variable)) { return templateInvalidCastLocalFunction; } } return null; } bool _shouldTearOffCall(DartType expectedType, DartType actualType) { if (expectedType is InterfaceType && expectedType.classNode == typeSchemaEnvironment.futureOrClass) { expectedType = (expectedType as InterfaceType).typeArguments[0]; } if (expectedType is FunctionType) return true; if (expectedType == typeSchemaEnvironment.functionLegacyRawType) { if (!typeSchemaEnvironment.isSubtypeOf( actualType, expectedType, SubtypeCheckMode.ignoringNullabilities)) { return true; } } return false; } } abstract class MixinInferrer { final CoreTypes coreTypes; final TypeConstraintGatherer gatherer; MixinInferrer(this.coreTypes, this.gatherer); Supertype asInstantiationOf(Supertype type, Class superclass); void reportProblem(Message message, Class cls); void generateConstraints( Class mixinClass, Supertype baseType, Supertype mixinSupertype) { if (mixinSupertype.typeArguments.isEmpty) { // The supertype constraint isn't generic; it doesn't constrain anything. } else if (mixinSupertype.classNode.isAnonymousMixin) { // We have either a mixin declaration `mixin M<X0, ..., Xn> on S0, S1` or // a VM-style super mixin `abstract class M<X0, ..., Xn> extends S0 with // S1` where S0 and S1 are superclass constraints that possibly have type // arguments. // // It has been compiled by naming the superclass to either: // // abstract class S0&S1<...> extends Object implements S0, S1 {} // abstract class M<X0, ..., Xn> extends S0&S1<...> ... // // for a mixin declaration, or else: // // abstract class S0&S1<...> = S0 with S1; // abstract class M<X0, ..., Xn> extends S0&S1<...> // // for a VM-style super mixin. The type parameters of S0&S1 are the X0, // ..., Xn that occurred free in S0 and S1. Treat S0 and S1 as separate // supertype constraints by recursively calling this algorithm. // // In the Dart VM the mixin application classes themselves are all // eliminated by translating them to normal classes. In that case, the // mixin appears as the only interface in the introduced class. We // support three forms for the superclass constraints: // // abstract class S0&S1<...> extends Object implements S0, S1 {} // abstract class S0&S1<...> = S0 with S1; // abstract class S0&S1<...> extends S0 implements S1 {} Class mixinSuperclass = mixinSupertype.classNode; if (mixinSuperclass.mixedInType == null && mixinSuperclass.implementedTypes.length != 1 && (mixinSuperclass.superclass != coreTypes.objectClass || mixinSuperclass.implementedTypes.length != 2)) { unexpected( 'Compiler-generated mixin applications have a mixin or else ' 'implement exactly one type', '$mixinSuperclass implements ' '${mixinSuperclass.implementedTypes.length} types', mixinSuperclass.fileOffset, mixinSuperclass.fileUri); } Substitution substitution = Substitution.fromSupertype(mixinSupertype); Supertype s0, s1; if (mixinSuperclass.implementedTypes.length == 2) { s0 = mixinSuperclass.implementedTypes[0]; s1 = mixinSuperclass.implementedTypes[1]; } else if (mixinSuperclass.implementedTypes.length == 1) { s0 = mixinSuperclass.supertype; s1 = mixinSuperclass.implementedTypes.first; } else { s0 = mixinSuperclass.supertype; s1 = mixinSuperclass.mixedInType; } s0 = substitution.substituteSupertype(s0); s1 = substitution.substituteSupertype(s1); generateConstraints(mixinClass, baseType, s0); generateConstraints(mixinClass, baseType, s1); } else { // Find the type U0 which is baseType as an instance of mixinSupertype's // class. Supertype supertype = asInstantiationOf(baseType, mixinSupertype.classNode); if (supertype == null) { reportProblem( templateMixinInferenceNoMatchingClass.withArguments(mixinClass.name, baseType.classNode.name, mixinSupertype.asInterfaceType), mixinClass); return; } InterfaceType u0 = Substitution.fromSupertype(baseType) .substituteSupertype(supertype) .asInterfaceType; // We want to solve U0 = S0 where S0 is mixinSupertype, but we only have // a subtype constraints. Solve for equality by solving // both U0 <: S0 and S0 <: U0. InterfaceType s0 = mixinSupertype.asInterfaceType; gatherer.trySubtypeMatch(u0, s0); gatherer.trySubtypeMatch(s0, u0); } } void infer(Class classNode) { Supertype mixedInType = classNode.mixedInType; assert(mixedInType.typeArguments.every((t) => t == const UnknownType())); // Note that we have no anonymous mixin applications, they have all // been named. Note also that mixin composition has been translated // so that we only have mixin applications of the form `S with M`. Supertype baseType = classNode.supertype; Class mixinClass = mixedInType.classNode; Supertype mixinSupertype = mixinClass.supertype; // Generate constraints based on the mixin's supertype. generateConstraints(mixinClass, baseType, mixinSupertype); // Solve them to get a map from type parameters to upper and lower // bounds. Map<TypeParameter, TypeConstraint> result = gatherer.computeConstraints(); // Generate new type parameters with the solution as bounds. List<TypeParameter> parameters = mixinClass.typeParameters.map((p) { TypeConstraint constraint = result[p]; // Because we solved for equality, a valid solution has a parameter // either unconstrained or else with identical upper and lower bounds. if (constraint != null && constraint.upper != constraint.lower) { reportProblem( templateMixinInferenceNoMatchingClass.withArguments(mixinClass.name, baseType.classNode.name, mixinSupertype.asInterfaceType), mixinClass); return p; } assert(constraint == null || constraint.upper == constraint.lower); bool exact = constraint != null && constraint.upper != const UnknownType(); return new TypeParameter( p.name, exact ? constraint.upper : p.bound, p.defaultType); }).toList(); // Bounds might mention the mixin class's type parameters so we have to // substitute them before calling instantiate to bounds. Substitution substitution = Substitution.fromPairs( mixinClass.typeParameters, parameters.map((p) => new TypeParameterType(p)).toList()); for (TypeParameter p in parameters) { p.bound = substitution.substituteType(p.bound); } // Use instantiate to bounds. List<DartType> bounds = calculateBounds(parameters, coreTypes.objectClass); for (int i = 0; i < mixedInType.typeArguments.length; ++i) { mixedInType.typeArguments[i] = bounds[i]; } } } /// The result of an expression inference. class ExpressionInferenceResult { /// The inferred type of the expression. final DartType inferredType; /// If not-null, the [replacement] that replaced the inferred expression. final Expression replacement; const ExpressionInferenceResult(this.inferredType, [this.replacement]); } enum ObjectAccessTargetKind { instanceMember, callFunction, extensionMember, dynamic, invalid, missing, // TODO(johnniwinther): Remove this. unresolved, } /// Result for performing an access on an object, like `o.foo`, `o.foo()` and /// `o.foo = ...`. class ObjectAccessTarget { final ObjectAccessTargetKind kind; final Member member; const ObjectAccessTarget.internal(this.kind, this.member); /// Creates an access to the instance [member]. factory ObjectAccessTarget.interfaceMember(Member member) { assert(member != null); return new ObjectAccessTarget.internal( ObjectAccessTargetKind.instanceMember, member); } /// Creates an access to the extension [member]. factory ObjectAccessTarget.extensionMember( Member member, Member tearoffTarget, ProcedureKind kind, List<DartType> inferredTypeArguments) = ExtensionAccessTarget; /// Creates an access to a 'call' method on a function, i.e. a function /// invocation. const ObjectAccessTarget.callFunction() : this.internal(ObjectAccessTargetKind.callFunction, null); /// Creates an access with no known target. const ObjectAccessTarget.unresolved() : this.internal(ObjectAccessTargetKind.unresolved, null); /// Creates an access on a dynamic receiver type with no known target. const ObjectAccessTarget.dynamic() : this.internal(ObjectAccessTargetKind.dynamic, null); /// Creates an access with no target due to an invalid receiver type. /// /// This is not in itself an error but a consequence of another error. const ObjectAccessTarget.invalid() : this.internal(ObjectAccessTargetKind.invalid, null); /// Creates an access with no target. /// /// This is an error case. const ObjectAccessTarget.missing() : this.internal(ObjectAccessTargetKind.missing, null); /// Returns `true` if this is an access to an instance member. bool get isInstanceMember => kind == ObjectAccessTargetKind.instanceMember; /// Returns `true` if this is an access to an extension member. bool get isExtensionMember => kind == ObjectAccessTargetKind.extensionMember; /// Returns `true` if this is an access to the 'call' method on a function. bool get isCallFunction => kind == ObjectAccessTargetKind.callFunction; /// Returns `true` if this is an access without a known target. bool get isUnresolved => kind == ObjectAccessTargetKind.unresolved || isDynamic || isInvalid || isMissing; /// Returns `true` if this is an access on a dynamic receiver type. bool get isDynamic => kind == ObjectAccessTargetKind.dynamic; /// Returns `true` if this is an access on an invalid receiver type. bool get isInvalid => kind == ObjectAccessTargetKind.invalid; /// Returns `true` if this is an access with no target. bool get isMissing => kind == ObjectAccessTargetKind.missing; /// Returns the original procedure kind, if this is an extension method /// target. /// /// This is need because getters, setters, and methods are converted into /// top level methods, but access and invocation should still be treated as /// if they are the original procedure kind. ProcedureKind get extensionMethodKind => throw new UnsupportedError('ObjectAccessTarget.extensionMethodKind'); /// Returns inferred type arguments for the type parameters of an extension /// method that comes from the extension declaration. List<DartType> get inferredExtensionTypeArguments => throw new UnsupportedError( 'ObjectAccessTarget.inferredExtensionTypeArguments'); /// Returns the member to use for a tearoff. /// /// This is currently used for extension methods. // TODO(johnniwinther): Normalize use by having `readTarget` and // `invokeTarget`? Member get tearoffTarget => throw new UnsupportedError('ObjectAccessTarget.tearoffTarget'); @override String toString() => 'ObjectAccessTarget($kind,$member)'; } class ExtensionAccessTarget extends ObjectAccessTarget { final Member tearoffTarget; final ProcedureKind extensionMethodKind; final List<DartType> inferredExtensionTypeArguments; ExtensionAccessTarget(Member member, this.tearoffTarget, this.extensionMethodKind, this.inferredExtensionTypeArguments) : super.internal(ObjectAccessTargetKind.extensionMember, member); @override String toString() => 'ExtensionAccessTarget($kind,$member,$extensionMethodKind,' '$inferredExtensionTypeArguments)'; } class ExtensionAccessCandidate { final bool isPlatform; final DartType onType; final DartType onTypeInstantiateToBounds; final ObjectAccessTarget target; ExtensionAccessCandidate( this.onType, this.onTypeInstantiateToBounds, this.target, {this.isPlatform}); bool isMoreSpecificThan(TypeSchemaEnvironment typeSchemaEnvironment, ExtensionAccessCandidate other) { if (this.isPlatform == other.isPlatform) { // Both are platform or not platform. bool thisIsSubtype = typeSchemaEnvironment.isSubtypeOf( this.onType, other.onType, SubtypeCheckMode.ignoringNullabilities); bool thisIsSupertype = typeSchemaEnvironment.isSubtypeOf( other.onType, this.onType, SubtypeCheckMode.ignoringNullabilities); if (thisIsSubtype && !thisIsSupertype) { // This is subtype of other and not vice-versa. return true; } else if (thisIsSupertype && !thisIsSubtype) { // [other] is subtype of this and not vice-versa. return false; } else if (thisIsSubtype || thisIsSupertype) { thisIsSubtype = typeSchemaEnvironment.isSubtypeOf( this.onTypeInstantiateToBounds, other.onTypeInstantiateToBounds, SubtypeCheckMode.ignoringNullabilities); thisIsSupertype = typeSchemaEnvironment.isSubtypeOf( other.onTypeInstantiateToBounds, this.onTypeInstantiateToBounds, SubtypeCheckMode.ignoringNullabilities); if (thisIsSubtype && !thisIsSupertype) { // This is subtype of other and not vice-versa. return true; } else if (thisIsSupertype && !thisIsSubtype) { // [other] is subtype of this and not vice-versa. return false; } } } else if (other.isPlatform) { // This is not platform, [other] is: this is more specific. return true; } else { // This is platform, [other] is not: other is more specific. return false; } // Neither is more specific than the other. 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/type_inference/type_schema_elimination.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'package:kernel/ast.dart' show DartType, DartTypeVisitor, DynamicType, FunctionType, InterfaceType, NamedType; import 'package:kernel/core_types.dart' show CoreTypes; import 'type_schema.dart' show UnknownType; /// Returns the greatest closure of the given type [schema] with respect to `?`. /// /// The greatest closure of a type schema `P` with respect to `?` is defined as /// `P` with every covariant occurrence of `?` replaced with `Null`, and every /// contravariant occurrence of `?` replaced with `Object`. /// /// If the schema contains no instances of `?`, the original schema object is /// returned to avoid unnecessary allocation. /// /// Note that the closure of a type schema is a proper type. /// /// Note that the greatest closure of a type schema is always a supertype of any /// type which matches the schema. DartType greatestClosure(CoreTypes coreTypes, DartType schema) => _TypeSchemaEliminationVisitor.run(coreTypes, false, schema); /// Returns the least closure of the given type [schema] with respect to `?`. /// /// The least closure of a type schema `P` with respect to `?` is defined as /// `P` with every covariant occurrence of `?` replaced with `Object`, and every /// contravariant occurrence of `?` replaced with `Null`. /// /// If the schema contains no instances of `?`, the original schema object is /// returned to avoid unnecessary allocation. /// /// Note that the closure of a type schema is a proper type. /// /// Note that the least closure of a type schema is always a subtype of any type /// which matches the schema. DartType leastClosure(CoreTypes coreTypes, DartType schema) => _TypeSchemaEliminationVisitor.run(coreTypes, true, schema); /// Visitor that computes least and greatest closures of a type schema. /// /// Each visitor method returns `null` if there are no `?`s contained in the /// type, otherwise it returns the result of substituting `?` with `Null` or /// `Object`, as appropriate. class _TypeSchemaEliminationVisitor extends DartTypeVisitor<DartType> { final DartType nullType; bool isLeastClosure; _TypeSchemaEliminationVisitor(CoreTypes coreTypes, this.isLeastClosure) : nullType = coreTypes.nullType; @override DartType visitFunctionType(FunctionType node) { DartType newReturnType = node.returnType.accept(this); isLeastClosure = !isLeastClosure; List<DartType> newPositionalParameters = null; for (int i = 0; i < node.positionalParameters.length; i++) { DartType substitution = node.positionalParameters[i].accept(this); if (substitution != null) { newPositionalParameters ??= node.positionalParameters.toList(growable: false); newPositionalParameters[i] = substitution; } } List<NamedType> newNamedParameters = null; for (int i = 0; i < node.namedParameters.length; i++) { DartType substitution = node.namedParameters[i].type.accept(this); if (substitution != null) { newNamedParameters ??= node.namedParameters.toList(growable: false); newNamedParameters[i] = new NamedType( node.namedParameters[i].name, substitution, isRequired: node.namedParameters[i].isRequired); } } isLeastClosure = !isLeastClosure; DartType typedefType = node.typedefType?.accept(this); if (newReturnType == null && newPositionalParameters == null && newNamedParameters == null && typedefType == null) { // No types had to be substituted. return null; } else { return new FunctionType( newPositionalParameters ?? node.positionalParameters, newReturnType ?? node.returnType, namedParameters: newNamedParameters ?? node.namedParameters, typeParameters: node.typeParameters, requiredParameterCount: node.requiredParameterCount, typedefType: typedefType); } } @override DartType visitInterfaceType(InterfaceType node) { List<DartType> newTypeArguments = null; for (int i = 0; i < node.typeArguments.length; i++) { DartType substitution = node.typeArguments[i].accept(this); if (substitution != null) { newTypeArguments ??= node.typeArguments.toList(growable: false); newTypeArguments[i] = substitution; } } if (newTypeArguments == null) { // No type arguments needed to be substituted. return null; } else { return new InterfaceType(node.classNode, newTypeArguments); } } @override DartType defaultDartType(DartType node) { if (node is UnknownType) { return isLeastClosure ? nullType : const DynamicType(); } return null; } /// Runs an instance of the visitor on the given [schema] and returns the /// resulting type. If the schema contains no instances of `?`, the original /// schema object is returned to avoid unnecessary allocation. static DartType run( CoreTypes coreTypes, bool isLeastClosure, DartType schema) { _TypeSchemaEliminationVisitor visitor = new _TypeSchemaEliminationVisitor(coreTypes, isLeastClosure); DartType result = schema.accept(visitor); assert(visitor.isLeastClosure == isLeastClosure); return result ?? schema; } }
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/type_inference/type_promotion.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'package:kernel/ast.dart' show DartType, Expression, TypeParameterType, VariableDeclaration; import 'package:kernel/type_environment.dart' show SubtypeCheckMode; import '../fasta_codes.dart' show templateInternalProblemStackNotEmpty; import '../problems.dart' show internalProblem; import '../kernel/kernel_shadow_ast.dart' show ShadowTypePromoter; import 'type_schema_environment.dart' show TypeSchemaEnvironment; /// Keeps track of the state necessary to perform type promotion. /// /// Theory of operation: during parsing, the BodyBuilder calls methods in this /// class to inform it of syntactic constructs that are encountered. Those /// methods maintain a linked list of [TypePromotionFact] objects tracking what /// is known about the state of each variable at the current point in the code, /// as well as a linked list of [TypePromotionScope] objects tracking the /// component's nesting structure. Whenever a variable is read, the current /// [TypePromotionFact] and [TypePromotionScope] are recorded for later use. /// /// During type inference, the [TypeInferrer] calls back into this class to ask /// whether each variable read is a promoted read. This is determined by /// examining the [TypePromotionScope] and [TypePromotionFact] objects that were /// recorded at the time the variable read was parsed, as well as other state /// that may have been updated later during the parsing process. /// /// This class abstracts away the representation of the underlying AST using /// generic parameters. Derived classes should set E and V to the class they /// use to represent expressions and variable declarations, respectively. abstract class TypePromoter { TypePromoter.private(); factory TypePromoter(TypeSchemaEnvironment typeSchemaEnvironment) = ShadowTypePromoter.private; factory TypePromoter.disabled() = TypePromoterDisabled.private; /// Returns the current type promotion scope. TypePromotionScope get currentScope; /// Computes the promoted type of a variable read having the given [fact] and /// [scope]. Returns `null` if there is no promotion. /// /// [mutatedInClosure] indicates whether the variable was mutated in a closure /// somewhere in the method. DartType computePromotedType( TypePromotionFact fact, TypePromotionScope scope, bool mutatedInClosure); /// Updates the state to reflect the fact that we are entering an "else" /// branch. void enterElse(); /// Updates the state to reflect the fact that the LHS of an "&&" or "||" /// expression has just been parsed, and we are entering the RHS. void enterLogicalExpression(Expression lhs, String operator); /// Updates the state to reflect the fact that the "condition" part of an "if" /// statement or conditional expression has just been parsed, and we are /// entering the "then" branch. void enterThen(Expression condition); /// Updates the state to reflect the fact that we have exited the "else" /// branch of an "if" statement or conditional expression. void exitConditional(); /// Updates the state to reflect the fact that we have exited the RHS of an /// "&&" or "||" expression. void exitLogicalExpression(Expression rhs, Expression logicalExpression); /// Verifies that enter/exit calls were properly nested. void finished(); /// Records that the given [variable] was accessed for reading, and returns a /// [TypePromotionFact] describing the variable's current type promotion /// state. /// /// [functionNestingLevel] should be the current nesting level of closures. /// This is used to determine if the variable was accessed in a closure. TypePromotionFact getFactForAccess( VariableDeclaration variable, int functionNestingLevel); /// Updates the state to reflect the fact that an "is" check of a local /// variable was just parsed. void handleIsCheck(Expression isExpression, bool isInverted, VariableDeclaration variable, DartType type, int functionNestingLevel); /// Updates the state to reflect the fact that the given [variable] was /// mutated. void mutateVariable(VariableDeclaration variable, int functionNestingLevel); } /// Implementation of [TypePromoter] which doesn't do any type promotion. /// /// This is intended for profiling, to ensure that type inference and type /// promotion do not slow down compilation too much. class TypePromoterDisabled extends TypePromoter { TypePromoterDisabled.private() : super.private(); @override TypePromotionScope get currentScope => null; @override DartType computePromotedType(TypePromotionFact fact, TypePromotionScope scope, bool mutatedInClosure) => null; @override void enterElse() {} @override void enterLogicalExpression(Expression lhs, String operator) {} @override void enterThen(Expression condition) {} @override void exitConditional() {} @override void exitLogicalExpression(Expression rhs, Expression logicalExpression) {} @override void finished() {} @override TypePromotionFact getFactForAccess( VariableDeclaration variable, int functionNestingLevel) => null; @override void handleIsCheck(Expression isExpression, bool isInverted, VariableDeclaration variable, DartType type, int functionNestingLevel) {} @override void mutateVariable(VariableDeclaration variable, int functionNestingLevel) {} } /// Derived class containing generic implementations of [TypePromoter]. /// /// This class contains as much of the implementation of type promotion as /// possible without needing access to private members of shadow objects. It /// defers to abstract methods for everything else. abstract class TypePromoterImpl extends TypePromoter { final TypeSchemaEnvironment typeSchemaEnvironment; /// [TypePromotionFact] representing the initial state (no facts have been /// determined yet). /// /// All linked lists of facts terminate in this object. final _NullFact _nullFacts; /// Map from variable declaration to the most recent [TypePromotionFact] /// associated with the variable. /// /// [TypePromotionFact]s that are not associated with any variable show up in /// this map under the key `null`. final _factCache = <VariableDeclaration, TypePromotionFact>{}; /// Linked list of [TypePromotionFact]s that was current at the time the /// [_factCache] was last updated. TypePromotionFact _factCacheState; /// Linked list of [TypePromotionFact]s describing what is known to be true /// after execution of the expression or statement that was most recently /// parsed. TypePromotionFact _currentFacts; /// The most recently parsed expression whose outcome potentially affects what /// is known to be true (e.g. an "is" check or a logical expression). May be /// `null` if no such expression has been encountered yet. Expression _promotionExpression; /// Linked list of [TypePromotionFact]s describing what is known to be true /// after execution of [_promotionExpression], assuming that /// [_promotionExpression] evaluates to `true`. TypePromotionFact _trueFactsForPromotionExpression; /// Linked list of [TypePromotionScope]s describing the nesting structure that /// contains the expression or statement that was most recently parsed. TypePromotionScope _currentScope = const _TopLevelScope(); /// The sequence number of the [TypePromotionFact] that was most recently /// created. int _lastFactSequenceNumber = 0; TypePromoterImpl.private(TypeSchemaEnvironment typeSchemaEnvironment) : this._(typeSchemaEnvironment, new _NullFact()); TypePromoterImpl._(this.typeSchemaEnvironment, _NullFact this._nullFacts) : _factCacheState = _nullFacts, _currentFacts = _nullFacts, super.private() { _factCache[null] = _nullFacts; } @override TypePromotionScope get currentScope => _currentScope; @override DartType computePromotedType( TypePromotionFact fact, TypePromotionScope scope, bool mutatedInClosure) { if (mutatedInClosure) return null; return fact?._computePromotedType(this, scope); } /// For internal debugging use, optionally prints the current state followed /// by the event name. Uncomment the call to [_printEvent] to see the /// sequence of calls into the type promoter and the corresponding states. void debugEvent(String name) { // _printEvent(name); } @override void enterElse() { debugEvent('enterElse'); _ConditionalScope scope = _currentScope; // Record the current fact state so that once we exit the "else" branch, we // can merge facts from the two branches. scope.afterTrue = _currentFacts; // While processing the "else" block, assume the condition was false. _currentFacts = scope.beforeElse; } @override void enterLogicalExpression(Expression lhs, String operator) { debugEvent('enterLogicalExpression'); // Figure out what the facts are based on possible LHS outcomes. TypePromotionFact trueFacts = _factsWhenTrue(lhs); TypePromotionFact falseFacts = _factsWhenFalse(lhs); // Record the fact that we are entering a new scope, and save the // appropriate facts for the case where the expression gets short-cut. bool isAnd = identical(operator, '&&'); _currentScope = new _LogicalScope(_currentScope, isAnd, isAnd ? falseFacts : trueFacts); // While processing the RHS, assume the condition was false or true, // depending on the type of logical expression. _currentFacts = isAnd ? trueFacts : falseFacts; } @override void enterThen(Expression condition) { debugEvent('enterThen'); // Figure out what the facts are based on possible condition outcomes. TypePromotionFact trueFacts = _factsWhenTrue(condition); TypePromotionFact falseFacts = _factsWhenFalse(condition); // Record the fact that we are entering a new scope, and save the "false" // facts for when we enter the "else" branch. _currentScope = new _ConditionalScope(_currentScope, falseFacts); // While processing the "then" block, assume the condition was true. _currentFacts = trueFacts; } @override void exitConditional() { debugEvent('exitConditional'); _ConditionalScope scope = _currentScope; _currentScope = _currentScope._enclosing; _currentFacts = _mergeFacts(scope.afterTrue, _currentFacts); } @override void exitLogicalExpression(Expression rhs, Expression logicalExpression) { debugEvent('exitLogicalExpression'); _LogicalScope scope = _currentScope; _currentScope = _currentScope._enclosing; if (scope.isAnd) { _recordPromotionExpression(logicalExpression, _factsWhenTrue(rhs), _mergeFacts(scope.shortcutFacts, _currentFacts)); } else { _recordPromotionExpression( logicalExpression, _mergeFacts(scope.shortcutFacts, _currentFacts), _factsWhenFalse(rhs)); } } @override void finished() { debugEvent('finished'); if (_currentScope is! _TopLevelScope) { internalProblem( templateInternalProblemStackNotEmpty.withArguments( "$runtimeType", "$_currentScope"), -1, null); } } @override TypePromotionFact getFactForAccess( VariableDeclaration variable, int functionNestingLevel) { debugEvent('getFactForAccess'); TypePromotionFact fact = _computeCurrentFactMap()[variable]; TypePromotionFact._recordAccessedInScope( fact, _currentScope, functionNestingLevel); return fact; } /// Returns the nesting level that was in effect when [variable] was declared. int getVariableFunctionNestingLevel(VariableDeclaration variable); @override void handleIsCheck(Expression isExpression, bool isInverted, VariableDeclaration variable, DartType type, int functionNestingLevel) { debugEvent('handleIsCheck'); if (!isPromotionCandidate(variable)) return; _IsCheck isCheck = new _IsCheck( ++_lastFactSequenceNumber, variable, _currentFacts, _computeCurrentFactMap()[variable], functionNestingLevel, type); if (!isInverted) { _recordPromotionExpression(isExpression, isCheck, _currentFacts); } } /// Determines whether the given variable should be considered for promotion /// at all. /// /// This is needed because in kernel, [VariableDeclaration] objects are /// sometimes used to represent local functions, which are not subject to /// promotion. bool isPromotionCandidate(VariableDeclaration variable); /// Updates the state to reflect the fact that the given [variable] was /// mutated. void mutateVariable(VariableDeclaration variable, int functionNestingLevel) { debugEvent('mutateVariable'); TypePromotionFact fact = _computeCurrentFactMap()[variable]; TypePromotionFact._recordMutatedInScope(fact, _currentScope); if (getVariableFunctionNestingLevel(variable) < functionNestingLevel) { setVariableMutatedInClosure(variable); } setVariableMutatedAnywhere(variable); } /// Determines whether [a] and [b] represent the same expression, after /// dropping redundant enclosing parentheses. bool sameExpressions(Expression a, Expression b); /// Records that the given variable was mutated somewhere inside the method. void setVariableMutatedAnywhere(VariableDeclaration variable); /// Records that the given variable was mutated inside a closure. void setVariableMutatedInClosure(VariableDeclaration variable); /// Indicates whether [setVariableMutatedAnywhere] has been called for the /// given [variable]. bool wasVariableMutatedAnywhere(VariableDeclaration variable); /// Returns a map from variable declaration to the most recent /// [TypePromotionFact] associated with the variable. Map<VariableDeclaration, TypePromotionFact> _computeCurrentFactMap() { // Roll back any map entries associated with facts that are no longer in // effect, and set [commonAncestor] to the fact that is an ancestor of // the current state and the previously cached state. To do this, we set a // variable pointing to [_currentFacts], and then walk both it and // [_factCacheState] back to their common ancestor, updating [_factCache] as // we go. TypePromotionFact commonAncestor = _currentFacts; while (commonAncestor.sequenceNumber != _factCacheState.sequenceNumber) { if (commonAncestor.sequenceNumber > _factCacheState.sequenceNumber) { // The currently cached state is older than the common ancestor guess, // so the common ancestor guess needs to be walked back. commonAncestor = commonAncestor.previous; } else { // The common ancestor guess is older than the currently cached state, // so we need to roll back the map entry associated with the currently // cached state. _factCache[_factCacheState.variable] = _factCacheState.previousForVariable; _factCacheState = _factCacheState.previous; } } assert(identical(commonAncestor, _factCacheState)); // Roll forward any map entries associated with facts that are newly in // effect. Since newer facts link to older ones, it is easiest to do roll // forward the most recent facts first. for (TypePromotionFact newState = _currentFacts; !identical(newState, commonAncestor); newState = newState.previous) { TypePromotionFact currentlyCached = _factCache[newState.variable]; // Note: Since we roll forward the most recent facts first, we need to be // careful not write an older fact over a newer one. if (currentlyCached == null || newState.sequenceNumber > currentlyCached.sequenceNumber) { _factCache[newState.variable] = newState; } } _factCacheState = _currentFacts; return _factCache; } /// Returns the set of facts known to be true after the execution of [e] /// assuming it evaluates to `false`. /// /// [e] must be the most recently parsed expression or statement. TypePromotionFact _factsWhenFalse(Expression e) { // Type promotion currently only occurs when an "is" or logical expression // evaluates to `true`, so no special logic is required; we just use // [_currentFacts]. // // TODO(paulberry): experiment with supporting promotion in cases like // `if (x is! T) { ... } else { ...access x... }` return _currentFacts; } /// Returns the set of facts known to be true after the execution of [e] /// assuming it evaluates to `true`. /// /// [e] must be the most recently parsed expression or statement. TypePromotionFact _factsWhenTrue(Expression e) => sameExpressions(_promotionExpression, e) ? _trueFactsForPromotionExpression : _currentFacts; /// Returns the set of facts known to be true after two branches of execution /// rejoin. TypePromotionFact _mergeFacts(TypePromotionFact a, TypePromotionFact b) { // Type promotion currently doesn't support any mechanism for facts to // accumulate along a straight-line execution path (they can only accumulate // when entering a scope), so we can simply find the common ancestor fact. // // TODO(paulberry): experiment with supporting promotion in cases like: // if (...) { // if (x is! T) return; // } else { // if (x is! T) return; // } // ...access x... while (a.sequenceNumber != b.sequenceNumber) { if (a.sequenceNumber > b.sequenceNumber) { a = a.previous; } else { b = b.previous; } } assert(identical(a, b)); return a; } /// For internal debugging use, prints the current state followed by the event /// name. void _printEvent(String name) { Iterable<TypePromotionFact> factChain(TypePromotionFact fact) sync* { while (fact != null) { yield fact; fact = fact.previousForVariable; } } _computeCurrentFactMap().forEach((variable, fact) { if (fact == null) return; print(' ${variable ?? '(null)'}: ${factChain(fact).join(' -> ')}'); }); if (_promotionExpression != null) { print(' _promotionExpression: $_promotionExpression'); if (!identical(_trueFactsForPromotionExpression, _currentFacts)) { print(' if true: $_trueFactsForPromotionExpression'); } } print(name); } /// Records that after the evaluation of [expression], the facts will be /// [ifTrue] on a branch where the expression evaluated to `true`, and /// [ifFalse] on a branch where the expression evaluated to `false` (or where /// the truth value of the expression doesn't matter). /// /// TODO(paulberry): when we start handling promotion in "else" clauses, we'll /// need to split [ifFalse] into two cases, one for when the expression /// evaluated to `false`, and one where the truth value of the expression /// doesn't matter. void _recordPromotionExpression(Expression expression, TypePromotionFact ifTrue, TypePromotionFact ifFalse) { _promotionExpression = expression; _trueFactsForPromotionExpression = ifTrue; _currentFacts = ifFalse; } } /// A single fact which is known to the type promotion engine about the state of /// a variable (or about the flow control of the component). /// /// The type argument V represents is the class which represents local variable /// declarations. /// /// Facts are linked together into linked lists via the [previous] pointer into /// a data structure called a "fact chain" (or sometimes a "fact state"), which /// represents all facts that are known to hold at a certain point in the /// component. /// /// The fact is said to "apply" to a given point in the execution of the /// component if the fact is part of the current fact state at the point the /// parser reaches that point in the component. /// /// Note: just because a fact "applies" to a given point in the execution of /// the component doesn't mean a type will be promoted--it simply means that /// the fact was deduced at a previous point in the straight line execution of /// the code. It's possible that the fact will be overshadowed by a later /// fact, or its effect will be cancelled by a later assignment. The final /// determination of whether promotion occurs is left to [_computePromotedType]. abstract class TypePromotionFact { /// The variable this fact records information about, or `null` if this fact /// records information about general flow control. final VariableDeclaration variable; /// The fact chain that was in effect prior to execution of the statement or /// expression that caused this fact to be true. final TypePromotionFact previous; /// Integer associated with this fact. Each time a fact is created it is /// given a sequence number one greater than the previously generated fact. /// This simplifies the algorithm for finding the common ancestor of two /// facts; we repeatedly walk backward the fact with the larger sequence /// number until the sequence numbers are the same. final int sequenceNumber; /// The most recent fact appearing in the fact chain [previous] whose /// [variable] matches this one, or `null` if there is no such fact. final TypePromotionFact previousForVariable; /// The function nesting level of the expression that led to this fact. final int functionNestingLevel; /// If this fact's variable was mutated within any scopes the /// fact applies to, a set of the corresponding scopes. Otherwise `null`. /// /// TODO(paulberry): the size of this set is probably very small most of the /// time. Would it be better to use a list? Set<TypePromotionScope> _mutatedInScopes; /// If this fact's variable was accessed inside a closure within any scopes /// the fact applies to, a set of the corresponding scopes. Otherwise `null`. /// /// TODO(paulberry): the size of this set is probably very small most of the /// time. Would it be better to use a list? Set<TypePromotionScope> _accessedInClosureInScopes; TypePromotionFact(this.sequenceNumber, this.variable, this.previous, this.previousForVariable, this.functionNestingLevel); /// Computes the promoted type for [variable] at a location in the code where /// this fact applies. /// /// Should not be called until after parsing of the entire method is complete. DartType _computePromotedType( TypePromoterImpl promoter, TypePromotionScope scope); /// Records the fact that the variable referenced by [fact] was accessed /// within the given scope, at the given function nesting level. /// /// If `null` is passed in for [fact], there is no effect. static void _recordAccessedInScope(TypePromotionFact fact, TypePromotionScope scope, int functionNestingLevel) { // TODO(paulberry): make some integration test cases that exercise the // behaviors of this function. In particular verify that it's correct to // test functionNestingLevel against fact.functionNestingLevel (as opposed // to testing it against getVariableFunctionNestingLevel(variable)). while (fact != null) { if (functionNestingLevel > fact.functionNestingLevel) { fact._accessedInClosureInScopes ??= new Set<TypePromotionScope>.identity(); if (!fact._accessedInClosureInScopes.add(scope)) return; } fact = fact.previousForVariable; } } /// Records the fact that the variable referenced by [fact] was mutated /// within the given scope. /// /// If `null` is passed in for [fact], there is no effect. static void _recordMutatedInScope( TypePromotionFact fact, TypePromotionScope scope) { while (fact != null) { fact._mutatedInScopes ??= new Set<TypePromotionScope>.identity(); if (!fact._mutatedInScopes.add(scope)) return; fact = fact.previousForVariable; } } } /// Represents a contiguous block of program text in which variables may or may /// not be promoted. Also used as a stack to keep track of state while the /// method is being parsed. class TypePromotionScope { /// The nesting depth of this scope. The outermost scope (representing the /// whole method body) has a depth of 0. final int _depth; /// The [TypePromotionScope] representing the scope enclosing this one. final TypePromotionScope _enclosing; TypePromotionScope(this._enclosing) : _depth = _enclosing._depth + 1; const TypePromotionScope._topLevel() : _enclosing = null, _depth = 0; /// Determines whether this scope completely encloses (or is the same as) /// [other]. bool containsScope(TypePromotionScope other) { if (this._depth > other._depth) { // We can't possibly contain a scope if we are at greater nesting depth // than it is. return false; } while (this._depth < other._depth) { other = other._enclosing; } return identical(this, other); } } /// [TypePromotionScope] representing the "then" and "else" bodies of an "if" /// statement or conditional expression. class _ConditionalScope extends TypePromotionScope { /// The fact state in effect at the top of the "else" block. final TypePromotionFact beforeElse; /// The fact state which was in effect at the bottom of the "then" block. TypePromotionFact afterTrue; _ConditionalScope(TypePromotionScope enclosing, this.beforeElse) : super(enclosing); } /// [TypePromotionFact] representing an "is" check which succeeded. class _IsCheck extends TypePromotionFact { /// The type appearing on the right hand side of "is". final DartType checkedType; _IsCheck( int sequenceNumber, VariableDeclaration variable, TypePromotionFact previous, TypePromotionFact previousForVariable, int functionNestingLevel, this.checkedType) : super(sequenceNumber, variable, previous, previousForVariable, functionNestingLevel); @override String toString() => 'isCheck($checkedType)'; @override DartType _computePromotedType( TypePromoterImpl promoter, TypePromotionScope scope) { DartType previousPromotedType = previousForVariable?._computePromotedType(promoter, scope); // If the variable was mutated somewhere in the scope of the potential // promotion, promotion does not occur. if (_mutatedInScopes != null) { for (TypePromotionScope assignmentScope in _mutatedInScopes) { if (assignmentScope.containsScope(scope)) { return previousPromotedType; } } } // If the variable was mutated anywhere, and it was accessed inside a // closure somewhere in the scope of the potential promotion, promotion does // not occur. if (promoter.wasVariableMutatedAnywhere(variable) && _accessedInClosureInScopes != null) { for (TypePromotionScope accessScope in _accessedInClosureInScopes) { if (accessScope.containsScope(scope)) { return previousPromotedType; } } } // What we do now depends on the relationship between the previous type of // the variable and the type we are checking against. DartType previousType = previousPromotedType ?? variable.type; if (promoter.typeSchemaEnvironment.isSubtypeOf( checkedType, previousType, SubtypeCheckMode.ignoringNullabilities)) { // The type we are checking against is a subtype of the previous type of // the variable, so this is a refinement; we can promote. return checkedType; } else if (previousType is TypeParameterType && promoter.typeSchemaEnvironment.isSubtypeOf(checkedType, previousType.bound, SubtypeCheckMode.ignoringNullabilities)) { // The type we are checking against is a subtype of the bound of the // previous type of the variable; we can promote the bound. return new TypeParameterType( previousType.parameter, checkedType, previousType.nullability); } else { // The types aren't sufficiently related; we can't promote. return previousPromotedType; } } } /// [TypePromotionScope] representing the RHS of a logical expression. class _LogicalScope extends TypePromotionScope { /// Indicates whether the logical operation is an `&&` or an `||`. final bool isAnd; /// The fact state in effect if the logical expression gets short-cut. final TypePromotionFact shortcutFacts; _LogicalScope(TypePromotionScope enclosing, this.isAnd, this.shortcutFacts) : super(enclosing); } /// Instance of [TypePromotionFact] representing the facts which are known on /// entry to the method (i.e. nothing). class _NullFact extends TypePromotionFact { _NullFact() : super(0, null, null, null, 0); @override String toString() => 'null'; @override DartType _computePromotedType( TypePromoter promoter, TypePromotionScope scope) { throw new StateError('Tried to create promoted type for no variable'); } } /// Instance of [TypePromotionScope] representing the entire method body. class _TopLevelScope extends TypePromotionScope { const _TopLevelScope() : super._topLevel(); }
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/type_inference/standard_bounds.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.md file. import 'dart:math' as math; import 'package:kernel/ast.dart' show BottomType, Class, DartType, DynamicType, FunctionType, InterfaceType, InvalidType, NamedType, Nullability, TypeParameterType, VoidType; import 'package:kernel/type_algebra.dart' show Substitution; import 'package:kernel/type_environment.dart' show SubtypeCheckMode; import 'type_schema.dart' show UnknownType; abstract class StandardBounds { Class get functionClass; Class get futureClass; Class get futureOrClass; InterfaceType get nullType; InterfaceType get objectLegacyRawType; InterfaceType get functionLegacyRawType; bool isSubtypeOf(DartType subtype, DartType supertype, SubtypeCheckMode mode); InterfaceType getLegacyLeastUpperBound( InterfaceType type1, InterfaceType type2); /// Computes the standard lower bound of [type1] and [type2]. /// /// Standard lower bound is a lower bound function that imposes an /// ordering on the top types `void`, `dynamic`, and `object`. This function /// additionally handles the unknown type that appears during type inference. DartType getStandardLowerBound(DartType type1, DartType type2) { // For all types T, SLB(T,T) = T. Note that we don't test for equality // because we don't want to make the algorithm quadratic. This is ok // because the check is not needed for correctness; it's just a speed // optimization. if (identical(type1, type2)) { return type1; } // For any type T, SLB(?, T) = SLB(T, ?) = T. if (type1 is UnknownType) { return type2; } if (type2 is UnknownType) { return type1; } // SLB(void, T) = SLB(T, void) = T. if (type1 is VoidType) { return type2; } if (type2 is VoidType) { return type1; } // SLB(dynamic, T) = SLB(T, dynamic) = T if T is not void. if (type1 is DynamicType) { return type2; } if (type2 is DynamicType) { return type1; } // SLB(Object, T) = SLB(T, Object) = T if T is not void or dynamic. if (type1 == objectLegacyRawType) { return type2; } if (type2 == objectLegacyRawType) { return type1; } // SLB(bottom, T) = SLB(T, bottom) = bottom. if (type1 is BottomType) return type1; if (type2 is BottomType) return type2; if (type1 == nullType) return type1; if (type2 == nullType) return type2; // Function types have structural lower bounds. if (type1 is FunctionType && type2 is FunctionType) { return _functionStandardLowerBound(type1, type2); } // Otherwise, the lower bounds of two types is one of them it if it is a // subtype of the other. if (isSubtypeOf(type1, type2, SubtypeCheckMode.ignoringNullabilities)) { return type1; } if (isSubtypeOf(type2, type1, SubtypeCheckMode.ignoringNullabilities)) { return type2; } // See https://github.com/dart-lang/sdk/issues/37439#issuecomment-519654959. if (type1 is InterfaceType && type1.classNode == futureOrClass) { if (type2 is InterfaceType) { if (type2.classNode == futureOrClass) { // GLB(FutureOr<A>, FutureOr<B>) == FutureOr<GLB(A, B)> return new InterfaceType(futureOrClass, <DartType>[ getStandardLowerBound( type1.typeArguments[0], type2.typeArguments[0]) ]); } if (type2.classNode == futureClass) { // GLB(FutureOr<A>, Future<B>) == Future<GLB(A, B)> return new InterfaceType(futureClass, <DartType>[ getStandardLowerBound( type1.typeArguments[0], type2.typeArguments[0]) ]); } } // GLB(FutureOr<A>, B) == GLB(A, B) return getStandardLowerBound(type1.typeArguments[0], type2); } // The if-statement below handles the following rule: // GLB(A, FutureOr<B>) == GLB(FutureOr<B>, A) // It's broken down into sub-cases instead of making a recursive call to // avoid making the checks that were already made above. Note that at this // point it's not possible for type1 to be a FutureOr. if (type2 is InterfaceType && type2.classNode == futureOrClass) { if (type1 is InterfaceType && type1.classNode == futureClass) { // GLB(Future<A>, FutureOr<B>) == Future<GLB(B, A)> return new InterfaceType(futureClass, <DartType>[ getStandardLowerBound(type2.typeArguments[0], type1.typeArguments[0]) ]); } // GLB(A, FutureOr<B>) == GLB(B, A) return getStandardLowerBound(type2.typeArguments[0], type1); } // No subtype relation, so the lower bound is bottom. return const BottomType(); } /// Computes the standard upper bound of two types. /// /// Standard upper bound is an upper bound function that imposes an ordering /// on the top types 'void', 'dynamic', and `object`. This function /// additionally handles the unknown type that appears during type inference. DartType getStandardUpperBound(DartType type1, DartType type2) { // For all types T, SUB(T,T) = T. Note that we don't test for equality // because we don't want to make the algorithm quadratic. This is ok // because the check is not needed for correctness; it's just a speed // optimization. if (identical(type1, type2)) { return type1; } // For any type T, SUB(?, T) = SUB(T, ?) = T. if (type1 is UnknownType) { return type2; } if (type2 is UnknownType) { return type1; } // SUB(void, T) = SUB(T, void) = void. if (type1 is VoidType) { return type1; } if (type2 is VoidType) { return type2; } // SUB(dynamic, T) = SUB(T, dynamic) = dynamic if T is not void. if (type1 is DynamicType) { return type1; } if (type2 is DynamicType) { return type2; } // SUB(Object, T) = SUB(T, Object) = Object if T is not void or dynamic. if (type1 == objectLegacyRawType) { return type1; } if (type2 == objectLegacyRawType) { return type2; } // SUB(bottom, T) = SUB(T, bottom) = T. if (type1 is BottomType) return type2; if (type2 is BottomType) return type1; if (type1 == nullType) return type2; if (type2 == nullType) return type1; if (type1 is TypeParameterType || type2 is TypeParameterType) { return _typeParameterStandardUpperBound(type1, type2); } // The standard upper bound of a function type and an interface type T is // the standard upper bound of Function and T. if (type1 is FunctionType && type2 is InterfaceType) { type1 = functionLegacyRawType; } if (type2 is FunctionType && type1 is InterfaceType) { type2 = functionLegacyRawType; } // At this point type1 and type2 should both either be interface types or // function types. if (type1 is InterfaceType && type2 is InterfaceType) { return _interfaceStandardUpperBound(type1, type2); } if (type1 is FunctionType && type2 is FunctionType) { return _functionStandardUpperBound(type1, type2); } if (type1 is InvalidType || type2 is InvalidType) { return const InvalidType(); } // Should never happen. As a defensive measure, return the dynamic type. assert(false, "type1 = $type1; type2 = $type2"); return const DynamicType(); } /// Compute the standard lower bound of function types [f] and [g]. /// /// The spec rules for SLB on function types, informally, are pretty simple: /// /// - If a parameter is required in both, it stays required. /// /// - If a positional parameter is optional or missing in one, it becomes /// optional. (This is because we're trying to build a function type which /// is a subtype of both [f] and [g], meaning it accepts all possible inputs /// that [f] and [g] accept.) /// /// - Named parameters are unioned together. /// /// - For any parameter that exists in both functions, use the SUB of them as /// the resulting parameter type. /// /// - Use the SLB of their return types. DartType _functionStandardLowerBound(FunctionType f, FunctionType g) { // TODO(rnystrom,paulberry): Right now, this assumes f and g do not have any // type parameters. Revisit that in the presence of generic methods. // Calculate the SUB of each corresponding pair of parameters. int totalPositional = math.max(f.positionalParameters.length, g.positionalParameters.length); List<DartType> positionalParameters = new List<DartType>(totalPositional); for (int i = 0; i < totalPositional; i++) { if (i < f.positionalParameters.length) { DartType fType = f.positionalParameters[i]; if (i < g.positionalParameters.length) { DartType gType = g.positionalParameters[i]; positionalParameters[i] = getStandardUpperBound(fType, gType); } else { positionalParameters[i] = fType; } } else { positionalParameters[i] = g.positionalParameters[i]; } } // Parameters that are required in both functions are required in the // result. Parameters that are optional or missing in either end up // optional. int requiredParameterCount = math.min(f.requiredParameterCount, g.requiredParameterCount); bool hasPositional = requiredParameterCount < totalPositional; // Union the named parameters together. List<NamedType> namedParameters = []; { int i = 0; int j = 0; while (true) { if (i < f.namedParameters.length) { if (j < g.namedParameters.length) { String fName = f.namedParameters[i].name; String gName = g.namedParameters[j].name; int order = fName.compareTo(gName); if (order < 0) { namedParameters.add(f.namedParameters[i++]); } else if (order > 0) { namedParameters.add(g.namedParameters[j++]); } else { namedParameters.add(new NamedType( fName, getStandardUpperBound(f.namedParameters[i++].type, g.namedParameters[j++].type))); } } else { namedParameters.addAll(f.namedParameters.skip(i)); break; } } else { namedParameters.addAll(g.namedParameters.skip(j)); break; } } } bool hasNamed = namedParameters.isNotEmpty; // Edge case. Dart does not support functions with both optional positional // and named parameters. If we would synthesize that, give up. if (hasPositional && hasNamed) return const BottomType(); // Calculate the SLB of the return type. DartType returnType = getStandardLowerBound(f.returnType, g.returnType); return new FunctionType(positionalParameters, returnType, namedParameters: namedParameters, requiredParameterCount: requiredParameterCount); } /// Compute the standard upper bound of function types [f] and [g]. /// /// The rules for SUB on function types, informally, are pretty simple: /// /// - If the functions don't have the same number of required parameters, /// always return `Function`. /// /// - Discard any optional named or positional parameters the two types do not /// have in common. /// /// - Compute the SLB of each corresponding pair of parameter types, and the /// SUB of the return types. Return a function type with those types. DartType _functionStandardUpperBound(FunctionType f, FunctionType g) { // TODO(rnystrom): Right now, this assumes f and g do not have any type // parameters. Revisit that in the presence of generic methods. // If F and G differ in their number of required parameters, then the // standard upper bound of F and G is Function. // TODO(paulberry): We could do better here, e.g.: // SUB(([int]) -> void, (int) -> void) = (int) -> void if (f.requiredParameterCount != g.requiredParameterCount) { return new InterfaceType( functionClass, const <DynamicType>[], Nullability.legacy); } int requiredParameterCount = f.requiredParameterCount; // Calculate the SLB of each corresponding pair of parameters. // Ignore any extra optional positional parameters if one has more than the // other. int totalPositional = math.min(f.positionalParameters.length, g.positionalParameters.length); List<DartType> positionalParameters = new List<DartType>(totalPositional); for (int i = 0; i < totalPositional; i++) { positionalParameters[i] = getStandardLowerBound( f.positionalParameters[i], g.positionalParameters[i]); } // Intersect the named parameters. List<NamedType> namedParameters = []; { int i = 0; int j = 0; while (true) { if (i < f.namedParameters.length) { if (j < g.namedParameters.length) { String fName = f.namedParameters[i].name; String gName = g.namedParameters[j].name; int order = fName.compareTo(gName); if (order < 0) { i++; } else if (order > 0) { j++; } else { namedParameters.add(new NamedType( fName, getStandardLowerBound(f.namedParameters[i++].type, g.namedParameters[j++].type))); } } else { break; } } else { break; } } } // Calculate the SUB of the return type. DartType returnType = getStandardUpperBound(f.returnType, g.returnType); return new FunctionType(positionalParameters, returnType, namedParameters: namedParameters, requiredParameterCount: requiredParameterCount); } DartType _interfaceStandardUpperBound( InterfaceType type1, InterfaceType type2) { // This currently does not implement a very complete standard upper bound // algorithm, but handles a couple of the very common cases that are // causing pain in real code. The current algorithm is: // 1. If either of the types is a supertype of the other, return it. // This is in fact the best result in this case. // 2. If the two types have the same class element, then take the // pointwise standard upper bound of the type arguments. This is again // the best result, except that the recursive calls may not return // the true standard upper bounds. The result is guaranteed to be a // well-formed type under the assumption that the input types were // well-formed (and assuming that the recursive calls return // well-formed types). // 3. Otherwise return the spec-defined standard upper bound. This will // be an upper bound, might (or might not) be least, and might // (or might not) be a well-formed type. if (isSubtypeOf(type1, type2, SubtypeCheckMode.ignoringNullabilities)) { return type2; } if (isSubtypeOf(type2, type1, SubtypeCheckMode.ignoringNullabilities)) { return type1; } if (type1 is InterfaceType && type2 is InterfaceType && identical(type1.classNode, type2.classNode)) { List<DartType> tArgs1 = type1.typeArguments; List<DartType> tArgs2 = type2.typeArguments; assert(tArgs1.length == tArgs2.length); List<DartType> tArgs = new List(tArgs1.length); for (int i = 0; i < tArgs1.length; i++) { tArgs[i] = getStandardUpperBound(tArgs1[i], tArgs2[i]); } return new InterfaceType(type1.classNode, tArgs); } return getLegacyLeastUpperBound(type1, type2); } DartType _typeParameterStandardUpperBound(DartType type1, DartType type2) { // This currently just implements a simple standard upper bound to // handle some common cases. It also avoids some termination issues // with the naive spec algorithm. The standard upper bound of two types // (at least one of which is a type parameter) is computed here as: // 1. If either type is a supertype of the other, return it. // 2. If the first type is a type parameter, replace it with its bound, // with recursive occurrences of itself replaced with Object. // The second part of this should ensure termination. Informally, // each type variable instantiation in one of the arguments to the // standard upper bound algorithm now strictly reduces the number // of bound variables in scope in that argument position. // 3. If the second type is a type parameter, do the symmetric operation // to #2. // // It's not immediately obvious why this is symmetric in the case that both // of them are type parameters. For #1, symmetry holds since subtype // is antisymmetric. For #2, it's clearly not symmetric if upper bounds of // bottom are allowed. Ignoring this (for various reasons, not least // of which that there's no way to write it), there's an informal // argument (that might even be right) that you will always either // end up expanding both of them or else returning the same result no matter // which order you expand them in. A key observation is that // identical(expand(type1), type2) => subtype(type1, type2) // and hence the contra-positive. // // TODO(leafp): Think this through and figure out what's the right // definition. Be careful about termination. // // I suspect in general a reasonable algorithm is to expand the innermost // type variable first. Alternatively, you could probably choose to treat // it as just an instance of the interface type upper bound problem, with // the "inheritance" chain extended by the bounds placed on the variables. if (isSubtypeOf(type1, type2, SubtypeCheckMode.ignoringNullabilities)) { return type2; } if (isSubtypeOf(type2, type1, SubtypeCheckMode.ignoringNullabilities)) { return type1; } if (type1 is TypeParameterType) { // TODO(paulberry): Analyzer collapses simple bounds in one step, i.e. for // C<T extends U, U extends List>, T gets resolved directly to List. Do // we need to replicate that behavior? return getStandardUpperBound( Substitution.fromMap({type1.parameter: objectLegacyRawType}) .substituteType(type1.parameter.bound), type2); } else if (type2 is TypeParameterType) { return getStandardUpperBound( type1, Substitution.fromMap({type2.parameter: objectLegacyRawType}) .substituteType(type2.parameter.bound)); } else { // We should only be called when at least one of the types is a // TypeParameterType assert(false); return const DynamicType(); } } }
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/type_inference/type_schema_environment.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'package:kernel/ast.dart' show Class, DartType, DynamicType, FunctionType, InterfaceType, NamedType, Procedure, TypeParameter; import 'package:kernel/class_hierarchy.dart' show ClassHierarchy; import 'package:kernel/core_types.dart' show CoreTypes; import 'package:kernel/type_algebra.dart' show Substitution; import 'package:kernel/type_environment.dart' show SubtypeCheckMode; import 'package:kernel/src/hierarchy_based_type_environment.dart' show HierarchyBasedTypeEnvironment; import 'standard_bounds.dart' show StandardBounds; import 'type_constraint_gatherer.dart' show TypeConstraintGatherer; import 'type_schema.dart' show UnknownType, typeSchemaToString, isKnown; import 'type_schema_elimination.dart' show greatestClosure, leastClosure; // TODO(paulberry): try to push this functionality into kernel. FunctionType substituteTypeParams( FunctionType type, Map<TypeParameter, DartType> substitutionMap, List<TypeParameter> newTypeParameters) { Substitution substitution = Substitution.fromMap(substitutionMap); return new FunctionType( type.positionalParameters.map(substitution.substituteType).toList(), substitution.substituteType(type.returnType), namedParameters: type.namedParameters .map((named) => new NamedType( named.name, substitution.substituteType(named.type), isRequired: named.isRequired)) .toList(), typeParameters: newTypeParameters, requiredParameterCount: type.requiredParameterCount, typedefType: type.typedefType == null ? null : substitution.substituteType(type.typedefType)); } /// Given a [FunctionType], gets the type of the named parameter with the given /// [name], or `dynamic` if there is no parameter with the given name. DartType getNamedParameterType(FunctionType functionType, String name) { return functionType.getNamedParameter(name) ?? const DynamicType(); } /// Given a [FunctionType], gets the type of the [i]th positional parameter, or /// `dynamic` if there is no parameter with that index. DartType getPositionalParameterType(FunctionType functionType, int i) { if (i < functionType.positionalParameters.length) { return functionType.positionalParameters[i]; } else { return const DynamicType(); } } /// A constraint on a type parameter that we're inferring. class TypeConstraint { /// The lower bound of the type being constrained. This bound must be a /// subtype of the type being constrained. DartType lower; /// The upper bound of the type being constrained. The type being constrained /// must be a subtype of this bound. DartType upper; TypeConstraint() : lower = const UnknownType(), upper = const UnknownType(); TypeConstraint._(this.lower, this.upper); TypeConstraint clone() => new TypeConstraint._(lower, upper); String toString() => '${typeSchemaToString(lower)} <: <type> <: ${typeSchemaToString(upper)}'; } class TypeSchemaEnvironment extends HierarchyBasedTypeEnvironment with StandardBounds { TypeSchemaEnvironment(CoreTypes coreTypes, ClassHierarchy hierarchy) : super(coreTypes, hierarchy); Class get functionClass => coreTypes.functionClass; Class get futureClass => coreTypes.futureClass; Class get futureOrClass => coreTypes.futureOrClass; InterfaceType getLegacyLeastUpperBound( InterfaceType type1, InterfaceType type2) { return hierarchy.getLegacyLeastUpperBound(type1, type2, this.coreTypes); } /// Modify the given [constraint]'s lower bound to include [lower]. void addLowerBound(TypeConstraint constraint, DartType lower) { constraint.lower = getStandardUpperBound(constraint.lower, lower); } /// Modify the given [constraint]'s upper bound to include [upper]. void addUpperBound(TypeConstraint constraint, DartType upper) { constraint.upper = getStandardLowerBound(constraint.upper, upper); } @override DartType getTypeOfOverloadedArithmetic(DartType type1, DartType type2) { // TODO(paulberry): this matches what is defined in the spec. It would be // nice if we could change kernel to match the spec and not have to // override. if (type1 == coreTypes.intLegacyRawType) { if (type2 == coreTypes.intLegacyRawType) return type2; if (type2 == coreTypes.doubleLegacyRawType) return type2; } return coreTypes.numLegacyRawType; } /// Infers a generic type, function, method, or list/map literal /// instantiation, using the downward context type as well as the argument /// types if available. /// /// For example, given a function type with generic type parameters, this /// infers the type parameters from the actual argument types. /// /// Concretely, given a function type with parameter types P0, P1, ... Pn, /// result type R, and generic type parameters T0, T1, ... Tm, use the /// argument types A0, A1, ... An to solve for the type parameters. /// /// For each parameter Pi, we want to ensure that Ai <: Pi. We can do this by /// running the subtype algorithm, and when we reach a type parameter Tj, /// recording the lower or upper bound it must satisfy. At the end, all /// constraints can be combined to determine the type. /// /// All constraints on each type parameter Tj are tracked, as well as where /// they originated, so we can issue an error message tracing back to the /// argument values, type parameter "extends" clause, or the return type /// context. /// /// If non-null values for [formalTypes] and [actualTypes] are provided, this /// is upwards inference. Otherwise it is downward inference. void inferGenericFunctionOrType( DartType declaredReturnType, List<TypeParameter> typeParametersToInfer, List<DartType> formalTypes, List<DartType> actualTypes, DartType returnContextType, List<DartType> inferredTypes, {bool isConst: false}) { if (typeParametersToInfer.isEmpty) { return; } // Create a TypeConstraintGatherer that will allow certain type parameters // to be inferred. It will optimistically assume these type parameters can // be subtypes (or supertypes) as necessary, and track the constraints that // are implied by this. TypeConstraintGatherer gatherer = new TypeConstraintGatherer(this, typeParametersToInfer); if (!isEmptyContext(returnContextType)) { if (isConst) { returnContextType = new TypeVariableEliminator(coreTypes) .substituteType(returnContextType); } gatherer.trySubtypeMatch(declaredReturnType, returnContextType); } if (formalTypes != null) { for (int i = 0; i < formalTypes.length; i++) { // Try to pass each argument to each parameter, recording any type // parameter bounds that were implied by this assignment. gatherer.trySubtypeMatch(actualTypes[i], formalTypes[i]); } } inferTypeFromConstraints( gatherer.computeConstraints(), typeParametersToInfer, inferredTypes, downwardsInferPhase: formalTypes == null); } bool hasOmittedBound(TypeParameter parameter) { // If the bound was omitted by the programmer, the Kernel representation for // the parameter will look similar to the following: // // T extends Object = dynamic // // Note that it's not possible to receive [Object] as [TypeParameter.bound] // and `dynamic` as [TypeParameter.defaultType] from the front end in any // other way. DartType bound = parameter.bound; return bound is InterfaceType && identical(bound.classNode, coreTypes.objectClass) && parameter.defaultType is DynamicType; } /// Use the given [constraints] to substitute for type variables. /// /// [typeParametersToInfer] is the set of type parameters that should be /// substituted for. [inferredTypes] should be a list of the same length. /// /// If [downwardsInferPhase] is `true`, then we are in the first pass of /// inference, pushing context types down. This means we are allowed to push /// down `?` to precisely represent an unknown type. [inferredTypes] should /// be initially populated with `?`. These `?`s will be replaced, if /// appropriate, with the types that were inferred by downwards inference. /// /// If [downwardsInferPhase] is `false`, then we are in the second pass of /// inference, and must not conclude `?` for any type formal. In this pass, /// [inferredTypes] should contain the values from the first pass. They will /// be replaced with the final inferred types. void inferTypeFromConstraints(Map<TypeParameter, TypeConstraint> constraints, List<TypeParameter> typeParametersToInfer, List<DartType> inferredTypes, {bool downwardsInferPhase: false}) { List<DartType> typesFromDownwardsInference = downwardsInferPhase ? null : inferredTypes.toList(growable: false); for (int i = 0; i < typeParametersToInfer.length; i++) { TypeParameter typeParam = typeParametersToInfer[i]; DartType typeParamBound = typeParam.bound; DartType extendsConstraint; if (!hasOmittedBound(typeParam)) { extendsConstraint = Substitution.fromPairs(typeParametersToInfer, inferredTypes) .substituteType(typeParamBound); } TypeConstraint constraint = constraints[typeParam]; if (downwardsInferPhase) { inferredTypes[i] = _inferTypeParameterFromContext(constraint, extendsConstraint); } else { inferredTypes[i] = _inferTypeParameterFromAll( typesFromDownwardsInference[i], constraint, extendsConstraint); } } // If the downwards infer phase has failed, we'll catch this in the upwards // phase later on. if (downwardsInferPhase) { return; } // Check the inferred types against all of the constraints. Map<TypeParameter, DartType> knownTypes = <TypeParameter, DartType>{}; for (int i = 0; i < typeParametersToInfer.length; i++) { TypeParameter typeParam = typeParametersToInfer[i]; TypeConstraint constraint = constraints[typeParam]; DartType typeParamBound = Substitution.fromPairs(typeParametersToInfer, inferredTypes) .substituteType(typeParam.bound); DartType inferred = inferredTypes[i]; bool success = typeSatisfiesConstraint(inferred, constraint); if (success && !hasOmittedBound(typeParam)) { // If everything else succeeded, check the `extends` constraint. DartType extendsConstraint = typeParamBound; success = isSubtypeOf(inferred, extendsConstraint, SubtypeCheckMode.ignoringNullabilities); } if (!success) { // TODO(paulberry): report error. // Heuristic: even if we failed, keep the erroneous type. // It should satisfy at least some of the constraints (e.g. the return // context). If we fall back to instantiateToBounds, we'll typically get // more errors (e.g. because `dynamic` is the most common bound). } if (isKnown(inferred)) { knownTypes[typeParam] = inferred; } } // TODO(paulberry): report any errors from instantiateToBounds. } @override bool isSubtypeOf( DartType subtype, DartType supertype, SubtypeCheckMode mode) { if (subtype is UnknownType) return true; if (subtype == Null && supertype is UnknownType) return true; return super.isSubtypeOf(subtype, supertype, mode); } bool isEmptyContext(DartType context) { if (context is DynamicType) { // Analyzer treats a type context of `dynamic` as equivalent to an empty // context. TODO(paulberry): this is not spec'ed anywhere; do we still // want to do this? return true; } return context == null; } /// True if [member] is a binary operator that returns an `int` if both /// operands are `int`, and otherwise returns `double`. /// /// Note that this behavior depends on the receiver type, so we can only make /// this determination if we know the type of the receiver. /// /// This is a case of type-based overloading, which in Dart is only supported /// by giving special treatment to certain arithmetic operators. bool isOverloadedArithmeticOperatorAndType( Procedure member, DartType receiverType) { // TODO(paulberry): this matches what is defined in the spec. It would be // nice if we could change kernel to match the spec and not have to // override. if (member.name.name == 'remainder') return false; if (!(receiverType is InterfaceType && identical(receiverType.classNode, coreTypes.intClass))) { return false; } return isOverloadedArithmeticOperator(member); } @override bool isTop(DartType t) { if (t is UnknownType) { return true; } else { return super.isTop(t); } } /// Computes the constraint solution for a type variable based on a given set /// of constraints. /// /// If [grounded] is `true`, then the returned type is guaranteed to be a /// known type (i.e. it will not contain any instances of `?`). DartType solveTypeConstraint(TypeConstraint constraint, {bool grounded: false}) { // Prefer the known bound, if any. if (isKnown(constraint.lower)) return constraint.lower; if (isKnown(constraint.upper)) return constraint.upper; // Otherwise take whatever bound has partial information, e.g. `Iterable<?>` if (constraint.lower is! UnknownType) { return grounded ? leastClosure(coreTypes, constraint.lower) : constraint.lower; } else { return grounded ? greatestClosure(coreTypes, constraint.upper) : constraint.upper; } } /// Determine if the given [type] satisfies the given type [constraint]. bool typeSatisfiesConstraint(DartType type, TypeConstraint constraint) { return isSubtypeOf( constraint.lower, type, SubtypeCheckMode.ignoringNullabilities) && isSubtypeOf( type, constraint.upper, SubtypeCheckMode.ignoringNullabilities); } DartType _inferTypeParameterFromAll(DartType typeFromContextInference, TypeConstraint constraint, DartType extendsConstraint) { // See if we already fixed this type from downwards inference. // If so, then we aren't allowed to change it based on argument types. if (isKnown(typeFromContextInference)) { return typeFromContextInference; } if (extendsConstraint != null) { constraint = constraint.clone(); addUpperBound(constraint, extendsConstraint); } return solveTypeConstraint(constraint, grounded: true); } DartType _inferTypeParameterFromContext( TypeConstraint constraint, DartType extendsConstraint) { DartType t = solveTypeConstraint(constraint); if (!isKnown(t)) { return t; } // If we're about to make our final choice, apply the extends clause. // This gives us a chance to refine the choice, in case it would violate // the `extends` clause. For example: // // Object obj = math.min/*<infer Object, error>*/(1, 2); // // If we consider the `T extends num` we conclude `<num>`, which works. if (extendsConstraint != null) { constraint = constraint.clone(); addUpperBound(constraint, extendsConstraint); return solveTypeConstraint(constraint); } return t; } } class TypeVariableEliminator extends Substitution { final CoreTypes _coreTypes; // TODO(dmitryas): Instead of a CoreTypes object pass null and an Object type // explicitly, with the suitable nullability on the latter. TypeVariableEliminator(this._coreTypes); @override DartType getSubstitute(TypeParameter parameter, bool upperBound) { return upperBound ? _coreTypes.nullType : _coreTypes.objectLegacyRawType; } }
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/type_inference/type_schema.dart
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. import 'package:kernel/ast.dart' show DartType, DartTypeVisitor, DartTypeVisitor1, FunctionType, InterfaceType, NamedType, Nullability, TypedefType, Visitor; import 'package:kernel/import_table.dart' show ImportTable; import 'package:kernel/text/ast_to_text.dart' show Annotator, NameSystem, Printer, globalDebuggingNames; /// Determines whether a type schema contains `?` somewhere inside it. bool isKnown(DartType schema) => schema.accept(new _IsKnownVisitor()); /// Converts a [DartType] to a string, representing the unknown type as `?`. String typeSchemaToString(DartType schema) { StringBuffer buffer = new StringBuffer(); new TypeSchemaPrinter(buffer, syntheticNames: globalDebuggingNames) .writeNode(schema); return '$buffer'; } /// Extension of [Printer] that represents the unknown type as `?`. class TypeSchemaPrinter extends Printer { TypeSchemaPrinter(StringSink sink, {NameSystem syntheticNames, bool showExternal, bool showOffsets: false, ImportTable importTable, Annotator annotator}) : super(sink, syntheticNames: syntheticNames, showExternal: showExternal, showOffsets: showOffsets, importTable: importTable, annotator: annotator); @override defaultDartType(covariant UnknownType node) { writeWord('?'); } } /// The unknown type (denoted `?`) is an object which can appear anywhere that /// a type is expected. It represents a component of a type which has not yet /// been fixed by inference. /// /// The unknown type cannot appear in programs or in final inferred types: it is /// purely part of the local inference process. class UnknownType extends DartType { @override Nullability get nullability => null; const UnknownType(); bool operator ==(Object other) { // This class doesn't have any fields so all instances of `UnknownType` are // equal. return other is UnknownType; } @override R accept<R>(DartTypeVisitor<R> v) { return v.defaultDartType(this); } @override R accept1<R, A>(DartTypeVisitor1<R, A> v, arg) => v.defaultDartType(this, arg); @override visitChildren(Visitor<dynamic> v) {} @override UnknownType withNullability(Nullability nullability) => this; } /// Visitor that computes [isKnown]. class _IsKnownVisitor extends DartTypeVisitor<bool> { @override bool defaultDartType(DartType node) => node is! UnknownType; @override bool visitFunctionType(FunctionType node) { if (!node.returnType.accept(this)) return false; for (DartType parameterType in node.positionalParameters) { if (!parameterType.accept(this)) return false; } for (NamedType namedParameterType in node.namedParameters) { if (!namedParameterType.type.accept(this)) return false; } return true; } @override bool visitInterfaceType(InterfaceType node) { for (DartType typeArgument in node.typeArguments) { if (!typeArgument.accept(this)) return false; } return true; } @override bool visitTypedefType(TypedefType node) { for (DartType typeArgument in node.typeArguments) { if (!typeArgument.accept(this)) return false; } return true; } }
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/error_delegation_listener.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../../scanner/token.dart' show Token; import '../fasta_codes.dart' show Message; import 'listener.dart' show Listener; /// A listener which forwards error reports to another listener but ignores /// all other events. class ErrorDelegationListener extends Listener { Listener delegate; ErrorDelegationListener(this.delegate); void handleRecoverableError( Message message, Token startToken, Token endToken) { return delegate.handleRecoverableError(message, startToken, endToken); } }
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/declaration_kind.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. enum DeclarationKind { /// A top level declaration. TopLevel, /// A class declaration. Not including a named mixin declaration. Class, /// A mixin declaration. Not including a named mixin declaration. Mixin, /// An extension declaration. Extension, }
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/identifier_context_impl.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../../scanner/token.dart' show Token; import '../fasta_codes.dart' as fasta; import '../scanner/token_constants.dart' show IDENTIFIER_TOKEN, STRING_TOKEN; import 'identifier_context.dart'; import 'parser.dart' show Parser; import 'type_info.dart' show isValidTypeReference; import 'util.dart' show isOneOfOrEof, optional; /// See [IdentifierContext.catchParameter]. class CatchParameterIdentifierContext extends IdentifierContext { const CatchParameterIdentifierContext() : super('catchParameter'); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery parser.reportRecoverableError(identifier, fasta.messageCatchSyntax); if (looksLikeStatementStart(identifier) || isOneOfOrEof(identifier, const [',', ')'])) { return parser.rewriter.insertSyntheticIdentifier(token); } else if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. return parser.rewriter.insertSyntheticIdentifier(identifier); } return identifier; } } /// See [IdentifierContext.classOrMixinOrExtensionDeclaration]. class ClassOrMixinOrExtensionIdentifierContext extends IdentifierContext { const ClassOrMixinOrExtensionIdentifierContext() : super('classOrMixinDeclaration', inDeclaration: true, isBuiltInIdentifierAllowed: false); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.type.isPseudo) { return identifier; } // Recovery if (looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier, const ['<', '{', 'extends', 'with', 'implements', 'on'])) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else if (identifier.type.isBuiltIn) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateBuiltInIdentifierInDeclaration); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.combinator]. class CombinatorIdentifierContext extends IdentifierContext { const CombinatorIdentifierContext() : super('combinator'); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); const List<String> followingValues = const [ ';', ',', 'if', 'as', 'show', 'hide' ]; if (identifier.isIdentifier) { if (!looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier.next, followingValues)) { return identifier; } // Although this is a valid identifier name, the import declaration // is invalid and this looks like the start of the next declaration. // In this situation, fall through to insert a synthetic identifier. } // Recovery if (isOneOfOrEof(identifier, followingValues) || looksLikeStartOfNextTopLevelDeclaration(identifier)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.constructorReference] /// and [IdentifierContext.constructorReferenceContinuation] /// and [IdentifierContext.constructorReferenceContinuationAfterTypeArguments]. class ConstructorReferenceIdentifierContext extends IdentifierContext { const ConstructorReferenceIdentifierContext() : super('constructorReference', isScopeReference: true); const ConstructorReferenceIdentifierContext.continuation() : super('constructorReferenceContinuation', isContinuation: true); const ConstructorReferenceIdentifierContext.continuationAfterTypeArguments() : super('constructorReferenceContinuationAfterTypeArguments', isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery if (!identifier.isKeywordOrIdentifier) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); } return identifier; } } /// See [IdentifierContext.dottedName]. class DottedNameIdentifierContext extends IdentifierContext { const DottedNameIdentifierContext() : super('dottedName'); const DottedNameIdentifierContext.continuation() : super('dottedNameContinuation', isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); const List<String> followingValues = const ['.', '==', ')']; if (identifier.isIdentifier) { // DottedNameIdentifierContext are only used in conditional import // expressions. Although some top level keywords such as `import` can be // used as identifiers, they are more likely the start of the next // directive or declaration. if (!identifier.isTopLevelKeyword || isOneOfOrEof(identifier.next, followingValues)) { return identifier; } } // Recovery if (looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier, followingValues)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.enumDeclaration]. class EnumDeclarationIdentifierContext extends IdentifierContext { const EnumDeclarationIdentifierContext() : super('enumDeclaration', inDeclaration: true, isBuiltInIdentifierAllowed: false); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.type.isPseudo) { return identifier; } // Recovery if (looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier, const ['{'])) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else if (identifier.type.isBuiltIn) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateBuiltInIdentifierInDeclaration); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.enumValueDeclaration]. class EnumValueDeclarationIdentifierContext extends IdentifierContext { const EnumValueDeclarationIdentifierContext() : super('enumValueDeclaration', inDeclaration: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { return identifier; } // Recovery parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier, const [',', '}'])) { return parser.rewriter.insertSyntheticIdentifier(token); } else if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. return parser.rewriter.insertSyntheticIdentifier(identifier); } return identifier; } } /// See [IdentifierContext.expression]. class ExpressionIdentifierContext extends IdentifierContext { const ExpressionIdentifierContext() : super('expression', isScopeReference: true); const ExpressionIdentifierContext.continuation() : super('expressionContinuation', isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { if (optional('await', identifier) && identifier.next.isIdentifier) { // Although the `await` can be used in an expression, // it is followed by another identifier which does not form // a valid expression. Report an error on the `await` token // rather than the token following it. parser.reportRecoverableErrorWithToken( identifier, fasta.templateUnexpectedToken); // TODO(danrubel) Consider a new listener event so that analyzer // can represent this as an await expression in a context that does // not allow await. return identifier.next; } else { checkAsyncAwaitYieldAsIdentifier(identifier, parser); } return identifier; } // Recovery parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (optional(r'$', token) && identifier.isKeyword && identifier.next.kind == STRING_TOKEN) { // Keyword used as identifier in string interpolation return identifier; } else if (!looksLikeStatementStart(identifier)) { if (identifier.isKeywordOrIdentifier) { if (isContinuation || !isOneOfOrEof(identifier, const ['as', 'is'])) { return identifier; } } else if (!identifier.isOperator && !isOneOfOrEof(identifier, const ['.', ',', '(', ')', '[', ']', '{', '}', '?', ':', ';'])) { // When in doubt, consume the token to ensure we make progress token = identifier; identifier = token.next; } } // Insert a synthetic identifier to satisfy listeners. return parser.rewriter.insertSyntheticIdentifier(token); } } /// See [IdentifierContext.fieldDeclaration]. class FieldDeclarationIdentifierContext extends IdentifierContext { const FieldDeclarationIdentifierContext() : super('fieldDeclaration', inDeclaration: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { return identifier; } // Recovery if (isOneOfOrEof(identifier, const [';', '=', ',', '}']) || looksLikeStartOfNextClassMember(identifier)) { return parser.insertSyntheticIdentifier(token, this); } else if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. return parser.insertSyntheticIdentifier(identifier, this, message: fasta.templateExpectedIdentifier.withArguments(identifier), messageOnToken: identifier); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); return identifier; } } } /// See [IdentifierContext.fieldInitializer]. class FieldInitializerIdentifierContext extends IdentifierContext { const FieldInitializerIdentifierContext() : super('fieldInitializer', isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { assert(optional('.', token)); Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { return identifier; } // Recovery parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); // Insert a synthetic identifier to satisfy listeners. return parser.rewriter.insertSyntheticIdentifier(token); } } /// See [IdentifierContext.formalParameterDeclaration]. class FormalParameterDeclarationIdentifierContext extends IdentifierContext { const FormalParameterDeclarationIdentifierContext() : super('formalParameterDeclaration', inDeclaration: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery const List<String> followingValues = const [ ':', '=', ',', '(', ')', '[', ']', '{', '}' ]; if (looksLikeStartOfNextClassMember(identifier) || looksLikeStatementStart(identifier) || isOneOfOrEof(identifier, followingValues)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.importPrefixDeclaration]. class ImportPrefixIdentifierContext extends IdentifierContext { const ImportPrefixIdentifierContext() : super('importPrefixDeclaration', inDeclaration: true, isBuiltInIdentifierAllowed: false); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.type.isPseudo) { return identifier; } // Recovery const List<String> followingValues = const [ ';', 'if', 'show', 'hide', 'deferred', 'as' ]; if (identifier.type.isBuiltIn && isOneOfOrEof(identifier.next, followingValues)) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateBuiltInIdentifierInDeclaration); } else if (looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier, followingValues)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } class LiteralSymbolIdentifierContext extends IdentifierContext { const LiteralSymbolIdentifierContext() : super('literalSymbol', inSymbol: true); const LiteralSymbolIdentifierContext.continuation() : super('literalSymbolContinuation', inSymbol: true, isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { return identifier; } // Recovery return parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } } /// See [IdentifierContext.localFunctionDeclaration] /// and [IdentifierContext.localFunctionDeclarationContinuation]. class LocalFunctionDeclarationIdentifierContext extends IdentifierContext { const LocalFunctionDeclarationIdentifierContext() : super('localFunctionDeclaration', inDeclaration: true); const LocalFunctionDeclarationIdentifierContext.continuation() : super('localFunctionDeclarationContinuation', inDeclaration: true, isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery if (isOneOfOrEof(identifier, const ['.', '(', '{', '=>']) || looksLikeStatementStart(identifier)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.labelDeclaration]. class LabelDeclarationIdentifierContext extends IdentifierContext { const LabelDeclarationIdentifierContext() : super('labelDeclaration', inDeclaration: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery if (isOneOfOrEof(identifier, const [':']) || looksLikeStatementStart(identifier)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.labelReference]. class LabelReferenceIdentifierContext extends IdentifierContext { const LabelReferenceIdentifierContext() : super('labelReference'); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery if (isOneOfOrEof(identifier, const [';'])) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.libraryName], /// and [IdentifierContext.libraryNameContinuation] /// and [IdentifierContext.partName], /// and [IdentifierContext.partNameContinuation]. class LibraryIdentifierContext extends IdentifierContext { const LibraryIdentifierContext() : super('libraryName', inLibraryOrPartOfDeclaration: true); const LibraryIdentifierContext.continuation() : super('libraryNameContinuation', inLibraryOrPartOfDeclaration: true, isContinuation: true); const LibraryIdentifierContext.partName() : super('partName', inLibraryOrPartOfDeclaration: true); const LibraryIdentifierContext.partNameContinuation() : super('partNameContinuation', inLibraryOrPartOfDeclaration: true, isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); const List<String> followingValues = const ['.', ';']; if (identifier.isIdentifier) { Token next = identifier.next; if (!looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(next, followingValues)) { return identifier; } // Although this is a valid library name, the library declaration // is invalid and this looks like the start of the next declaration. // In this situation, fall through to insert a synthetic library name. } // Recovery if (isOneOfOrEof(identifier, followingValues) || looksLikeStartOfNextTopLevelDeclaration(identifier)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.localVariableDeclaration]. class LocalVariableDeclarationIdentifierContext extends IdentifierContext { const LocalVariableDeclarationIdentifierContext() : super('localVariableDeclaration', inDeclaration: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery if (isOneOfOrEof(identifier, const [';', '=', ',', '{', '}']) || looksLikeStatementStart(identifier) || identifier.kind == STRING_TOKEN) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.metadataReference] /// and [IdentifierContext.metadataContinuation] /// and [IdentifierContext.metadataContinuationAfterTypeArguments]. class MetadataReferenceIdentifierContext extends IdentifierContext { const MetadataReferenceIdentifierContext() : super('metadataReference', isScopeReference: true); const MetadataReferenceIdentifierContext.continuation() : super('metadataContinuation', isContinuation: true); const MetadataReferenceIdentifierContext.continuationAfterTypeArguments() : super('metadataContinuationAfterTypeArguments', isContinuation: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery if (isOneOfOrEof(identifier, const ['{', '}', '(', ')', ']']) || looksLikeStartOfNextTopLevelDeclaration(identifier) || looksLikeStartOfNextClassMember(identifier) || looksLikeStatementStart(identifier)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.methodDeclaration], /// and [IdentifierContext.methodDeclarationContinuation], /// and [IdentifierContext.operatorName]. class MethodDeclarationIdentifierContext extends IdentifierContext { const MethodDeclarationIdentifierContext() : super('methodDeclaration', inDeclaration: true); const MethodDeclarationIdentifierContext.continuation() : super('methodDeclarationContinuation', inDeclaration: true, isContinuation: true); const MethodDeclarationIdentifierContext.operatorName() : super('operatorName', inDeclaration: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { return identifier; } // Recovery if (identifier.isUserDefinableOperator && !isContinuation) { return parser.insertSyntheticIdentifier(identifier, this, message: fasta.messageMissingOperatorKeyword, messageOnToken: identifier); } else if (isOneOfOrEof(identifier, const ['.', '(', '{', '=>', '}']) || looksLikeStartOfNextClassMember(identifier)) { return parser.insertSyntheticIdentifier(token, this); } else if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. return parser.insertSyntheticIdentifier(identifier, this, message: fasta.templateExpectedIdentifier.withArguments(identifier), messageOnToken: identifier); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); return identifier; } } } /// See [IdentifierContext.namedArgumentReference]. class NamedArgumentReferenceIdentifierContext extends IdentifierContext { const NamedArgumentReferenceIdentifierContext() : super('namedArgumentReference', allowedInConstantExpression: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { checkAsyncAwaitYieldAsIdentifier(identifier, parser); return identifier; } // Recovery if (isOneOfOrEof(identifier, const [':'])) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.topLevelFunctionDeclaration] /// and [IdentifierContext.topLevelVariableDeclaration]. class TopLevelDeclarationIdentifierContext extends IdentifierContext { final List<String> followingValues; const TopLevelDeclarationIdentifierContext(String name, this.followingValues) : super(name, inDeclaration: true); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.isIdentifier) { Token next = identifier.next; if (!looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(next, followingValues)) { return identifier; } // Although this is a valid top level name, the declaration // is invalid and this looks like the start of the next declaration. // In this situation, fall through to insert a synthetic name. } // Recovery if (looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier, followingValues)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else if (identifier.type.isBuiltIn) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateBuiltInIdentifierInDeclaration); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.typedefDeclaration]. class TypedefDeclarationIdentifierContext extends IdentifierContext { const TypedefDeclarationIdentifierContext() : super('typedefDeclaration', inDeclaration: true, isBuiltInIdentifierAllowed: false); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.type.isPseudo) { if (optional('Function', identifier)) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); } return identifier; } // Recovery const List<String> followingValues = const ['(', '<', '=', ';']; if (identifier.type.isBuiltIn && isOneOfOrEof(identifier.next, followingValues)) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateBuiltInIdentifierInDeclaration); } else if (looksLikeStartOfNextTopLevelDeclaration(identifier) || isOneOfOrEof(identifier, followingValues)) { identifier = parser.insertSyntheticIdentifier(token, this, message: fasta.templateExpectedIdentifier.withArguments(identifier)); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } /// See [IdentifierContext.typeReference]. class TypeReferenceIdentifierContext extends IdentifierContext { const TypeReferenceIdentifierContext() : super('typeReference', isScopeReference: true, isBuiltInIdentifierAllowed: false, recoveryTemplate: fasta.templateExpectedType); const TypeReferenceIdentifierContext.continuation() : super('typeReferenceContinuation', isContinuation: true, isBuiltInIdentifierAllowed: false); const TypeReferenceIdentifierContext.prefixed() : super('prefixedTypeReference', isScopeReference: true, isBuiltInIdentifierAllowed: true, recoveryTemplate: fasta.templateExpectedType); @override Token ensureIdentifier(Token token, Parser parser) { Token next = token.next; assert(next.kind != IDENTIFIER_TOKEN); if (isValidTypeReference(next)) { return next; } else if (next.isKeywordOrIdentifier) { if (optional("void", next)) { parser.reportRecoverableError(next, fasta.messageInvalidVoid); } else if (next.type.isBuiltIn) { if (!isBuiltInIdentifierAllowed) { parser.reportRecoverableErrorWithToken( next, fasta.templateBuiltInIdentifierAsType); } } else if (optional('var', next)) { parser.reportRecoverableError(next, fasta.messageVarAsTypeName); } else { parser.reportRecoverableErrorWithToken( next, fasta.templateExpectedType); } return next; } parser.reportRecoverableErrorWithToken(next, fasta.templateExpectedType); if (!isOneOfOrEof( next, const ['<', '>', ')', '[', ']', '[]', '{', '}', ',', ';'])) { // When in doubt, consume the token to ensure we make progress token = next; next = token.next; } // Insert a synthetic identifier to satisfy listeners. return parser.rewriter.insertSyntheticIdentifier(token); } } // See [IdentifierContext.typeVariableDeclaration]. class TypeVariableDeclarationIdentifierContext extends IdentifierContext { const TypeVariableDeclarationIdentifierContext() : super('typeVariableDeclaration', inDeclaration: true, isBuiltInIdentifierAllowed: false); @override Token ensureIdentifier(Token token, Parser parser) { Token identifier = token.next; assert(identifier.kind != IDENTIFIER_TOKEN); if (identifier.type.isPseudo) { return identifier; } // Recovery const List<String> followingValues = const [ '<', '>', ';', '}', 'extends', 'super' ]; if (looksLikeStartOfNextTopLevelDeclaration(identifier) || looksLikeStartOfNextClassMember(identifier) || looksLikeStatementStart(identifier) || isOneOfOrEof(identifier, followingValues)) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); identifier = parser.rewriter.insertSyntheticIdentifier(token); } else if (identifier.type.isBuiltIn) { parser.reportRecoverableErrorWithToken( identifier, fasta.templateBuiltInIdentifierInDeclaration); } else { parser.reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); if (!identifier.isKeywordOrIdentifier) { // When in doubt, consume the token to ensure we make progress // but insert a synthetic identifier to satisfy listeners. identifier = parser.rewriter.insertSyntheticIdentifier(identifier); } } return identifier; } } void checkAsyncAwaitYieldAsIdentifier(Token identifier, Parser parser) { if (!parser.inPlainSync && identifier.type.isPseudo) { if (optional('await', identifier)) { parser.reportRecoverableError(identifier, fasta.messageAwaitAsIdentifier); } else if (optional('yield', identifier)) { parser.reportRecoverableError(identifier, fasta.messageYieldAsIdentifier); } } } bool looksLikeStartOfNextClassMember(Token token) => token.isModifier || isOneOfOrEof(token, const ['@', 'get', 'set', 'void']); bool looksLikeStartOfNextTopLevelDeclaration(Token token) => token.isTopLevelKeyword || isOneOfOrEof(token, const ['const', 'get', 'final', 'set', 'var', 'void']);
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/top_level_parser.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.parser.top_level_parser; import '../../scanner/token.dart' show Token; import 'declaration_kind.dart' show DeclarationKind; import 'class_member_parser.dart' show ClassMemberParser; import 'listener.dart' show Listener; /// Parser which only parses top-level elements, but ignores their bodies. /// Use [Parser] to parse everything. class TopLevelParser extends ClassMemberParser { TopLevelParser(Listener listener) : super(listener); @override Token parseClassOrMixinOrExtensionBody( Token token, DeclarationKind kind, String enclosingDeclarationName) => skipClassOrMixinOrExtensionBody(token); }
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/literal_entry_info_impl.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 '../../scanner/token.dart'; import 'literal_entry_info.dart'; import 'parser.dart'; import 'util.dart'; /// [ifCondition] is the first step for parsing a literal entry /// starting with `if` control flow. const LiteralEntryInfo ifCondition = const IfCondition(); /// [spreadOperator] is the first step for parsing a literal entry /// preceded by a '...' spread operator. const LiteralEntryInfo spreadOperator = const SpreadOperator(); /// The first step when processing a `for` control flow collection entry. class ForCondition extends LiteralEntryInfo { bool inStyle; ForCondition() : super(false, 0); @override Token parse(Token token, Parser parser) { Token next = token.next; Token awaitToken; if (optional('await', next)) { awaitToken = token = next; next = token.next; } final Token forToken = next; assert(optional('for', forToken)); parser.listener.beginForControlFlow(awaitToken, forToken); token = parser.parseForLoopPartsStart(awaitToken, forToken); Token identifier = token.next; token = parser.parseForLoopPartsMid(token, awaitToken, forToken); if (optional('in', token.next) || optional(':', token.next)) { // Process `for ( ... in ... )` inStyle = true; token = parser.parseForInLoopPartsRest( token, awaitToken, forToken, identifier); } else { // Process `for ( ... ; ... ; ... )` inStyle = false; token = parser.parseForLoopPartsRest(token, forToken, awaitToken); } return token; } @override LiteralEntryInfo computeNext(Token token) { Token next = token.next; if (optional('for', next) || (optional('await', next) && optional('for', next.next))) { return new Nested( new ForCondition(), inStyle ? const ForInComplete() : const ForComplete(), ); } else if (optional('if', next)) { return new Nested( ifCondition, inStyle ? const ForInComplete() : const ForComplete(), ); } else if (optional('...', next) || optional('...?', next)) { return inStyle ? const ForInSpread() : const ForSpread(); } return inStyle ? const ForInEntry() : const ForEntry(); } } /// A step for parsing a spread collection /// as the "for" control flow's expression. class ForSpread extends SpreadOperator { const ForSpread(); @override LiteralEntryInfo computeNext(Token token) { return const ForComplete(); } } /// A step for parsing a spread collection /// as the "for-in" control flow's expression. class ForInSpread extends SpreadOperator { const ForInSpread(); @override LiteralEntryInfo computeNext(Token token) { return const ForInComplete(); } } /// A step for parsing a literal list, set, or map entry /// as the "for" control flow's expression. class ForEntry extends LiteralEntryInfo { const ForEntry() : super(true, 0); @override LiteralEntryInfo computeNext(Token token) { return const ForComplete(); } } /// A step for parsing a literal list, set, or map entry /// as the "for-in" control flow's expression. class ForInEntry extends LiteralEntryInfo { const ForInEntry() : super(true, 0); @override LiteralEntryInfo computeNext(Token token) { return const ForInComplete(); } } class ForComplete extends LiteralEntryInfo { const ForComplete() : super(false, 0); @override Token parse(Token token, Parser parser) { parser.listener.endForControlFlow(token); return token; } } class ForInComplete extends LiteralEntryInfo { const ForInComplete() : super(false, 0); @override Token parse(Token token, Parser parser) { parser.listener.endForInControlFlow(token); return token; } } /// The first step when processing an `if` control flow collection entry. class IfCondition extends LiteralEntryInfo { const IfCondition() : super(false, 1); @override Token parse(Token token, Parser parser) { final Token ifToken = token.next; assert(optional('if', ifToken)); parser.listener.beginIfControlFlow(ifToken); Token result = parser.ensureParenthesizedCondition(ifToken); parser.listener.beginThenControlFlow(result); return result; } @override LiteralEntryInfo computeNext(Token token) { Token next = token.next; if (optional('for', next) || (optional('await', next) && optional('for', next.next))) { return new Nested(new ForCondition(), const IfComplete()); } else if (optional('if', next)) { return new Nested(ifCondition, const IfComplete()); } else if (optional('...', next) || optional('...?', next)) { return const IfSpread(); } return const IfEntry(); } } /// A step for parsing a spread collection /// as the `if` control flow's then-expression. class IfSpread extends SpreadOperator { const IfSpread(); @override LiteralEntryInfo computeNext(Token token) => const IfComplete(); } /// A step for parsing a literal list, set, or map entry /// as the `if` control flow's then-expression. class IfEntry extends LiteralEntryInfo { const IfEntry() : super(true, 0); @override LiteralEntryInfo computeNext(Token token) => const IfComplete(); } class IfComplete extends LiteralEntryInfo { const IfComplete() : super(false, 0); @override Token parse(Token token, Parser parser) { if (!optional('else', token.next)) { parser.listener.endIfControlFlow(token); } return token; } @override LiteralEntryInfo computeNext(Token token) { return optional('else', token.next) ? const IfElse() : null; } } /// A step for parsing the `else` portion of an `if` control flow. class IfElse extends LiteralEntryInfo { const IfElse() : super(false, -1); @override Token parse(Token token, Parser parser) { Token elseToken = token.next; assert(optional('else', elseToken)); parser.listener.handleElseControlFlow(elseToken); return elseToken; } @override LiteralEntryInfo computeNext(Token token) { assert(optional('else', token)); Token next = token.next; if (optional('for', next) || (optional('await', next) && optional('for', next.next))) { return new Nested(new ForCondition(), const IfElseComplete()); } else if (optional('if', next)) { return new Nested(ifCondition, const IfElseComplete()); } else if (optional('...', next) || optional('...?', next)) { return const ElseSpread(); } return const ElseEntry(); } } class ElseSpread extends SpreadOperator { const ElseSpread(); @override LiteralEntryInfo computeNext(Token token) { return const IfElseComplete(); } } class ElseEntry extends LiteralEntryInfo { const ElseEntry() : super(true, 0); @override LiteralEntryInfo computeNext(Token token) { return const IfElseComplete(); } } class IfElseComplete extends LiteralEntryInfo { const IfElseComplete() : super(false, 0); @override Token parse(Token token, Parser parser) { parser.listener.endIfElseControlFlow(token); return token; } } /// The first step when processing a spread entry. class SpreadOperator extends LiteralEntryInfo { const SpreadOperator() : super(false, 0); @override Token parse(Token token, Parser parser) { final Token operator = token.next; assert(optional('...', operator) || optional('...?', operator)); token = parser.parseExpression(operator); parser.listener.handleSpreadExpression(operator); return token; } } class Nested extends LiteralEntryInfo { LiteralEntryInfo nestedStep; final LiteralEntryInfo lastStep; Nested(this.nestedStep, this.lastStep) : super(false, 0); @override bool get hasEntry => nestedStep.hasEntry; @override Token parse(Token token, Parser parser) => nestedStep.parse(token, parser); @override LiteralEntryInfo computeNext(Token token) { nestedStep = nestedStep.computeNext(token); return nestedStep != null ? this : lastStep; } }
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/identifier_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 '../../scanner/token.dart' show Token, TokenType; import '../fasta_codes.dart' show Message, Template, templateExpectedIdentifier; import '../scanner/token_constants.dart' show IDENTIFIER_TOKEN; import 'identifier_context_impl.dart'; import 'parser.dart' show Parser; import 'util.dart' show isOneOfOrEof, optional; /// Information about the parser state that is passed to the listener at the /// time an identifier is encountered. It is also used by the parser for error /// recovery when a recovery template is defined. /// /// This can be used by the listener to determine the context in which the /// identifier appears; that in turn can help the listener decide how to resolve /// the identifier (if the listener is doing resolution). class IdentifierContext { /// Identifier is being declared as the name of an import prefix (i.e. `Foo` /// in `import "..." as Foo;`) static const ImportPrefixIdentifierContext importPrefixDeclaration = const ImportPrefixIdentifierContext(); /// Identifier is the start of a dotted name in a conditional import or /// export. static const DottedNameIdentifierContext dottedName = const DottedNameIdentifierContext(); /// Identifier is part of a dotted name in a conditional import or export, but /// it's not the first identifier of the dotted name. static const DottedNameIdentifierContext dottedNameContinuation = const DottedNameIdentifierContext.continuation(); /// Identifier is one of the shown/hidden names in an import/export /// combinator. static const CombinatorIdentifierContext combinator = const CombinatorIdentifierContext(); /// Identifier is the start of a name in an annotation that precedes a /// declaration (i.e. it appears directly after an `@`). static const MetadataReferenceIdentifierContext metadataReference = const MetadataReferenceIdentifierContext(); /// Identifier is part of a name in an annotation that precedes a declaration, /// but it's not the first identifier in the name. static const MetadataReferenceIdentifierContext metadataContinuation = const MetadataReferenceIdentifierContext.continuation(); /// Identifier is part of a name in an annotation that precedes a declaration, /// but it appears after type parameters (e.g. `foo` in `@X<Y>.foo()`). static const MetadataReferenceIdentifierContext metadataContinuationAfterTypeArguments = const MetadataReferenceIdentifierContext.continuationAfterTypeArguments(); /// Identifier is the name being declared by a typedef declaration. static const TypedefDeclarationIdentifierContext typedefDeclaration = const TypedefDeclarationIdentifierContext(); /// Identifier is a field initializer in a formal parameter list (i.e. it /// appears directly after `this.`). static const FieldInitializerIdentifierContext fieldInitializer = const FieldInitializerIdentifierContext(); /// Identifier is a formal parameter being declared as part of a function, /// method, or typedef declaration. static const FormalParameterDeclarationIdentifierContext formalParameterDeclaration = const FormalParameterDeclarationIdentifierContext(); /// Identifier is a formal parameter being declared as part of a catch block /// in a try/catch/finally statement. static const CatchParameterIdentifierContext catchParameter = const CatchParameterIdentifierContext(); /// Identifier is the start of a library name (e.g. `foo` in the directive /// 'library foo;`). static const LibraryIdentifierContext libraryName = const LibraryIdentifierContext(); /// Identifier is part of a library name, but it's not the first identifier in /// the name. static const LibraryIdentifierContext libraryNameContinuation = const LibraryIdentifierContext.continuation(); /// Identifier is the start of a library name referenced by a `part of` /// directive (e.g. `foo` in the directive `part of foo;`). static const LibraryIdentifierContext partName = const LibraryIdentifierContext.partName(); /// Identifier is part of a library name referenced by a `part of` directive, /// but it's not the first identifier in the name. static const LibraryIdentifierContext partNameContinuation = const LibraryIdentifierContext.partNameContinuation(); /// Identifier is the type name being declared by an enum declaration. static const EnumDeclarationIdentifierContext enumDeclaration = const EnumDeclarationIdentifierContext(); /// Identifier is an enumerated value name being declared by an enum /// declaration. static const EnumValueDeclarationIdentifierContext enumValueDeclaration = const EnumValueDeclarationIdentifierContext(); /// Identifier is the name being declared by a class declaration, a mixin /// declaration, or a named mixin application, for example, /// `Foo` in `class Foo = X with Y;`. static const ClassOrMixinOrExtensionIdentifierContext classOrMixinOrExtensionDeclaration = const ClassOrMixinOrExtensionIdentifierContext(); /// Identifier is the name of a type variable being declared (e.g. `Foo` in /// `class C<Foo extends num> {}`). static const TypeVariableDeclarationIdentifierContext typeVariableDeclaration = const TypeVariableDeclarationIdentifierContext(); /// Identifier is the start of a reference to a type that starts with prefix. static const TypeReferenceIdentifierContext prefixedTypeReference = const TypeReferenceIdentifierContext.prefixed(); /// Identifier is the start of a reference to a type declared elsewhere. static const TypeReferenceIdentifierContext typeReference = const TypeReferenceIdentifierContext(); /// Identifier is part of a reference to a type declared elsewhere, but it's /// not the first identifier of the reference. static const TypeReferenceIdentifierContext typeReferenceContinuation = const TypeReferenceIdentifierContext.continuation(); /// Identifier is a name being declared by a top level variable declaration. static const TopLevelDeclarationIdentifierContext topLevelVariableDeclaration = const TopLevelDeclarationIdentifierContext( 'topLevelVariableDeclaration', const [';', '=', ',']); /// Identifier is a name being declared by a field declaration. static const FieldDeclarationIdentifierContext fieldDeclaration = const FieldDeclarationIdentifierContext(); /// Identifier is the name being declared by a top level function declaration. static const TopLevelDeclarationIdentifierContext topLevelFunctionDeclaration = const TopLevelDeclarationIdentifierContext( 'topLevelFunctionDeclaration', const ['<', '(', '{', '=>']); /// Identifier is the start of the name being declared by a method /// declaration. static const MethodDeclarationIdentifierContext methodDeclaration = const MethodDeclarationIdentifierContext(); /// Identifier is part of the name being declared by a method declaration, /// but it's not the first identifier of the name. /// /// In valid Dart, this can only happen if the identifier is the name of a /// named constructor which is being declared, e.g. `foo` in /// `class C { C.foo(); }`. static const MethodDeclarationIdentifierContext methodDeclarationContinuation = const MethodDeclarationIdentifierContext.continuation(); /// Identifier appears after the word `operator` in a method declaration. /// /// TODO(paulberry,ahe): Does this ever occur in valid Dart, or does it only /// occur as part of error recovery? If it's only as part of error recovery, /// perhaps we should just re-use methodDeclaration. static const MethodDeclarationIdentifierContext operatorName = const MethodDeclarationIdentifierContext.continuation(); /// Identifier is the start of the name being declared by a local function /// declaration. static const LocalFunctionDeclarationIdentifierContext localFunctionDeclaration = const LocalFunctionDeclarationIdentifierContext(); /// Identifier is part of the name being declared by a local function /// declaration, but it's not the first identifier of the name. /// /// TODO(paulberry,ahe): Does this ever occur in valid Dart, or does it only /// occur as part of error recovery? static const LocalFunctionDeclarationIdentifierContext localFunctionDeclarationContinuation = const LocalFunctionDeclarationIdentifierContext.continuation(); /// Identifier is the start of a reference to a constructor declared /// elsewhere. static const ConstructorReferenceIdentifierContext constructorReference = const ConstructorReferenceIdentifierContext(); /// Identifier is part of a reference to a constructor declared elsewhere, but /// it's not the first identifier of the reference. static const ConstructorReferenceIdentifierContext constructorReferenceContinuation = const ConstructorReferenceIdentifierContext.continuation(); /// Identifier is part of a reference to a constructor declared elsewhere, but /// it appears after type parameters (e.g. `foo` in `X<Y>.foo`). static const ConstructorReferenceIdentifierContext constructorReferenceContinuationAfterTypeArguments = const ConstructorReferenceIdentifierContext .continuationAfterTypeArguments(); /// Identifier is the declaration of a label (i.e. it is followed by `:` and /// then a statement). static const LabelDeclarationIdentifierContext labelDeclaration = const LabelDeclarationIdentifierContext(); /// Identifier is the start of a reference occurring in a literal symbol (e.g. /// `foo` in `#foo`). static const LiteralSymbolIdentifierContext literalSymbol = const LiteralSymbolIdentifierContext(); /// Identifier is part of a reference occurring in a literal symbol, but it's /// not the first identifier of the reference (e.g. `foo` in `#prefix.foo`). static const LiteralSymbolIdentifierContext literalSymbolContinuation = const LiteralSymbolIdentifierContext.continuation(); /// Identifier appears in an expression, and it does not immediately follow a /// `.`. static const ExpressionIdentifierContext expression = const ExpressionIdentifierContext(); /// Identifier appears in an expression, and it immediately follows a `.`. static const ExpressionIdentifierContext expressionContinuation = const ExpressionIdentifierContext.continuation(); /// Identifier is a reference to a named argument of a function or method /// invocation (e.g. `foo` in `f(foo: 0);`. static const NamedArgumentReferenceIdentifierContext namedArgumentReference = const NamedArgumentReferenceIdentifierContext(); /// Identifier is a name being declared by a local variable declaration. static const LocalVariableDeclarationIdentifierContext localVariableDeclaration = const LocalVariableDeclarationIdentifierContext(); /// Identifier is a reference to a label (e.g. `foo` in `break foo;`). /// Labels have their own scope. static const LabelReferenceIdentifierContext labelReference = const LabelReferenceIdentifierContext(); final String _name; /// Indicates whether the identifier represents a name which is being /// declared. final bool inDeclaration; /// Indicates whether the identifier is within a `library` or `part of` /// declaration. final bool inLibraryOrPartOfDeclaration; /// Indicates whether the identifier is within a symbol literal. final bool inSymbol; /// Indicates whether the identifier follows a `.`. final bool isContinuation; /// Indicates whether the identifier should be looked up in the current scope. final bool isScopeReference; /// Indicates whether built-in identifiers are allowed in this context. final bool isBuiltInIdentifierAllowed; /// Indicated whether the identifier is allowed in a context where constant /// expressions are required. final bool allowedInConstantExpression; final Template<_MessageWithArgument<Token>> recoveryTemplate; const IdentifierContext(this._name, {this.inDeclaration: false, this.inLibraryOrPartOfDeclaration: false, this.inSymbol: false, this.isContinuation: false, this.isScopeReference: false, this.isBuiltInIdentifierAllowed: true, bool allowedInConstantExpression, this.recoveryTemplate: templateExpectedIdentifier}) : this.allowedInConstantExpression = // Generally, declarations are legal in constant expressions. A // continuation doesn't affect constant expressions: if what it's // continuing is a problem, it has already been reported. allowedInConstantExpression ?? (inDeclaration || isContinuation || inSymbol); String toString() => _name; /// Ensure that the next token is an identifier (or keyword which should be /// treated as an identifier) and return that identifier. /// Report errors as necessary via [parser]. Token ensureIdentifier(Token token, Parser parser) { assert(token.next.kind != IDENTIFIER_TOKEN); // TODO(danrubel): Implement this method for each identifier context // such that they return a non-null value. return null; } } /// Return `true` if the given [token] should be treated like the start of /// an expression for the purposes of recovery. bool looksLikeExpressionStart(Token next) => next.isIdentifier || next.isKeyword && !looksLikeStatementStart(next) || next.type == TokenType.DOUBLE || next.type == TokenType.HASH || next.type == TokenType.HEXADECIMAL || next.type == TokenType.IDENTIFIER || next.type == TokenType.INT || next.type == TokenType.STRING || optional('{', next) || optional('(', next) || optional('[', next) || optional('[]', next) || optional('<', next) || optional('!', next) || optional('-', next) || optional('~', next) || optional('++', next) || optional('--', next); /// Return `true` if the given [token] should be treated like the start of /// a new statement for the purposes of recovery. bool looksLikeStatementStart(Token token) => isOneOfOrEof(token, const [ '@', 'assert', 'break', 'continue', 'do', 'else', 'final', 'for', // 'if', 'return', 'switch', 'try', 'var', 'void', 'while', // ]); // TODO(ahe): Remove when analyzer supports generalized function syntax. typedef _MessageWithArgument<T> = Message Function(T);
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/member_kind.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.member_kind; enum MemberKind { /// A catch block, not a real member. Catch, /// A factory Factory, /// Old-style typedef. FunctionTypeAlias, /// Old-style function-typed parameter, not a real member. FunctionTypedParameter, /// A generalized function type, not a real member. GeneralizedFunctionType, /// A local function. Local, /// A non-static method in a class (including constructors). NonStaticMethod, /// A static method in a class. StaticMethod, /// A top-level method. TopLevelMethod, /// An instance field in a class. NonStaticField, /// A static field in a class. StaticField, /// A top-level field. TopLevelField, }
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/recovery_listeners.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/token.dart' show Token; import 'forwarding_listener.dart' show ForwardingListener; class ClassHeaderRecoveryListener extends ForwardingListener { Token extendsKeyword; Token implementsKeyword; Token withKeyword; void clear() { extendsKeyword = null; implementsKeyword = null; withKeyword = null; } @override void handleClassExtends(Token extendsKeyword) { this.extendsKeyword = extendsKeyword; super.handleClassExtends(extendsKeyword); } @override void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { this.implementsKeyword = implementsKeyword; super.handleClassOrMixinImplements(implementsKeyword, interfacesCount); } @override void handleClassWithClause(Token withKeyword) { this.withKeyword = withKeyword; super.handleClassWithClause(withKeyword); } } class ImportRecoveryListener extends ForwardingListener { Token asKeyword; Token deferredKeyword; Token ifKeyword; bool hasCombinator = false; void clear() { asKeyword = null; deferredKeyword = null; ifKeyword = null; hasCombinator = false; } void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) { this.ifKeyword = ifKeyword; super.endConditionalUri(ifKeyword, leftParen, equalSign); } void endHide(Token hideKeyword) { this.hasCombinator = true; super.endHide(hideKeyword); } void endShow(Token showKeyword) { this.hasCombinator = true; super.endShow(showKeyword); } void handleImportPrefix(Token deferredKeyword, Token asKeyword) { this.deferredKeyword = deferredKeyword; this.asKeyword = asKeyword; super.handleImportPrefix(deferredKeyword, asKeyword); } } class MixinHeaderRecoveryListener extends ForwardingListener { Token onKeyword; Token implementsKeyword; void clear() { onKeyword = null; implementsKeyword = null; } @override void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { this.implementsKeyword = implementsKeyword; super.handleClassOrMixinImplements(implementsKeyword, interfacesCount); } @override void handleMixinOn(Token onKeyword, int typeCount) { this.onKeyword = onKeyword; super.handleMixinOn(onKeyword, typeCount); } }
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/util.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.util; import 'package:kernel/ast.dart' show TreeNode; import '../fasta_codes.dart' show noLength; import '../scanner.dart' show Token; import '../../scanner/token.dart' show BeginToken, SimpleToken, SyntheticToken, TokenType; /// Returns true if [token] is the symbol or keyword [value]. bool optional(String value, Token token) { return identical(value, token.stringValue); } /// Returns the token before the close brace, bracket, or parenthesis /// associated with [left]. For '<', it may return `null`. Token beforeCloseBraceTokenFor(BeginToken left) { Token endToken = left.endToken; if (endToken == null) { return null; } Token token = left; Token next = token.next; while (next != endToken && next != next.next) { token = next; next = token.next; } return token; } /// Return [token] or a token before [token] which is either /// not synthetic or synthetic with non-zero length. Token findPreviousNonZeroLengthToken(Token token) { while (token.isSynthetic && token.length == 0) { Token previous = token.beforeSynthetic; if (previous == null) { break; } token = previous; } return token; } /// Return [token] or a token after [token] which is either /// not synthetic or synthetic with non-zero length. /// This may return EOF if there are no more non-synthetic tokens in the stream. Token findNonZeroLengthToken(Token token) { while (token.isSynthetic && token.length == 0 && !token.isEof) { token = token.next; } return token; } /// A null-aware alternative to `token.offset`. If [token] is `null`, returns /// `TreeNode.noOffset`. int offsetForToken(Token token) { return token == null ? TreeNode.noOffset : token.offset; } bool isDigit(int c) => c >= 0x30 && c <= 0x39; bool isLetter(int c) => c >= 0x41 && c <= 0x5A || c >= 0x61 && c <= 0x7A; bool isLetterOrDigit(int c) => isLetter(c) || isDigit(c); bool isWhitespace(int c) => c == 0x20 || c == 0xA || c == 0xD || c == 0x9; /// Return true if the given token matches one of the given values. bool isOneOf(Token token, Iterable<String> values) { for (String tokenValue in values) { if (optional(tokenValue, token)) { return true; } } return false; } /// Return true if the given token matches one of the given values or is EOF. bool isOneOfOrEof(Token token, Iterable<String> values) { for (String tokenValue in values) { if (optional(tokenValue, token)) { return true; } } return token.isEof; } /// A null-aware alternative to `token.length`. If [token] is `null`, returns /// [noLength]. int lengthForToken(Token token) { return token == null ? noLength : token.length; } /// Returns the length of the span from [begin] to [end] (inclusive). If both /// tokens are null, return [noLength]. If one of the tokens are null, return /// the length of the other token. int lengthOfSpan(Token begin, Token end) { if (begin == null) return lengthForToken(end); if (end == null) return lengthForToken(begin); return end.offset + end.length - begin.offset; } Token skipMetadata(Token token) { token = token.next; assert(optional('@', token)); Token next = token.next; if (next.isIdentifier) { token = next; next = token.next; while (optional('.', next)) { token = next; next = token.next; if (next.isIdentifier) { token = next; next = token.next; } } if (optional('(', next) && !next.endGroup.isSynthetic) { token = next.endGroup; next = token.next; } } return token; } /// Split `>=` into two separate tokens. /// Call [Token.setNext] to add the token to the stream. Token splitGtEq(Token token) { assert(optional('>=', token)); return new SimpleToken( TokenType.GT, token.charOffset, token.precedingComments) ..setNext(new SimpleToken(TokenType.EQ, token.charOffset + 1) // Set next rather than calling Token.setNext // so that the previous token is not set. ..next = token.next); } /// Split `>>` into two separate tokens. /// Call [Token.setNext] to add the token to the stream. SimpleToken splitGtGt(Token token) { assert(optional('>>', token)); return new SimpleToken( TokenType.GT, token.charOffset, token.precedingComments) ..setNext(new SimpleToken(TokenType.GT, token.charOffset + 1) // Set next rather than calling Token.setNext // so that the previous token is not set. ..next = token.next); } /// Split `>>=` into three separate tokens. /// Call [Token.setNext] to add the token to the stream. Token splitGtGtEq(Token token) { assert(optional('>>=', token)); return new SimpleToken( TokenType.GT, token.charOffset, token.precedingComments) ..setNext(new SimpleToken(TokenType.GT, token.charOffset + 1) ..setNext(new SimpleToken(TokenType.EQ, token.charOffset + 2) // Set next rather than calling Token.setNext // so that the previous token is not set. ..next = token.next)); } /// Split `>>=` into two separate tokens... `>` followed by `>=`. /// Call [Token.setNext] to add the token to the stream. Token splitGtFromGtGtEq(Token token) { assert(optional('>>=', token)); return new SimpleToken( TokenType.GT, token.charOffset, token.precedingComments) ..setNext(new SimpleToken(TokenType.GT_EQ, token.charOffset + 1) // Set next rather than calling Token.setNext // so that the previous token is not set. ..next = token.next); } /// Split `>>>` into two separate tokens... `>` followed by `>>`. /// Call [Token.setNext] to add the token to the stream. Token splitGtFromGtGtGt(Token token) { assert(optional('>>>', token)); return new SimpleToken( TokenType.GT, token.charOffset, token.precedingComments) ..setNext(new SimpleToken(TokenType.GT_GT, token.charOffset + 1) // Set next rather than calling Token.setNext // so that the previous token is not set. ..next = token.next); } /// Split `>>>=` into two separate tokens... `>` followed by `>>=`. /// Call [Token.setNext] to add the token to the stream. Token splitGtFromGtGtGtEq(Token token) { assert(optional('>>>=', token)); return new SimpleToken( TokenType.GT, token.charOffset, token.precedingComments) ..setNext(new SimpleToken(TokenType.GT_GT_EQ, token.charOffset + 1) // Set next rather than calling Token.setNext // so that the previous token is not set. ..next = token.next); } /// Return a synthetic `<` followed by [next]. /// Call [Token.setNext] to add the token to the stream. Token syntheticGt(Token next) { return new SyntheticToken(TokenType.GT, next.charOffset) // Set next rather than calling Token.setNext // so that the previous token is not set. ..next = next; }
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/parser.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.parser.parser; import '../fasta_codes.dart' show Message, Template; import '../fasta_codes.dart' as fasta; import '../scanner.dart' show ErrorToken, Token; import '../../scanner/token.dart' show ASSIGNMENT_PRECEDENCE, BeginToken, CASCADE_PRECEDENCE, EQUALITY_PRECEDENCE, Keyword, POSTFIX_PRECEDENCE, RELATIONAL_PRECEDENCE, SELECTOR_PRECEDENCE, SyntheticBeginToken, SyntheticKeywordToken, SyntheticStringToken, SyntheticToken, TokenType; import '../scanner/token_constants.dart' show BANG_EQ_EQ_TOKEN, COMMA_TOKEN, DOUBLE_TOKEN, EOF_TOKEN, EQ_EQ_EQ_TOKEN, EQ_TOKEN, FUNCTION_TOKEN, HASH_TOKEN, HEXADECIMAL_TOKEN, IDENTIFIER_TOKEN, INT_TOKEN, KEYWORD_TOKEN, LT_TOKEN, OPEN_CURLY_BRACKET_TOKEN, OPEN_PAREN_TOKEN, OPEN_SQUARE_BRACKET_TOKEN, SEMICOLON_TOKEN, STRING_INTERPOLATION_IDENTIFIER_TOKEN, STRING_INTERPOLATION_TOKEN, STRING_TOKEN; import 'assert.dart' show Assert; import 'async_modifier.dart' show AsyncModifier; import 'declaration_kind.dart' show DeclarationKind; import 'directive_context.dart'; import 'formal_parameter_kind.dart' show FormalParameterKind, isMandatoryFormalParameterKind, isOptionalPositionalFormalParameterKind; import 'forwarding_listener.dart' show ForwardingListener; import 'identifier_context.dart' show IdentifierContext, looksLikeExpressionStart; import 'listener.dart' show Listener; import 'literal_entry_info.dart' show LiteralEntryInfo, computeLiteralEntry, looksLikeLiteralEntry, simpleEntry; import 'loop_state.dart' show LoopState; import 'member_kind.dart' show MemberKind; import 'modifier_context.dart' show ModifierRecoveryContext, isModifier; import 'recovery_listeners.dart' show ClassHeaderRecoveryListener, ImportRecoveryListener, MixinHeaderRecoveryListener; import 'token_stream_rewriter.dart' show TokenStreamRewriter; import 'type_info.dart' show TypeInfo, TypeParamOrArgInfo, computeMethodTypeArguments, computeType, computeTypeParamOrArg, isValidTypeReference, noType, noTypeParamOrArg; import 'util.dart' show findNonZeroLengthToken, findPreviousNonZeroLengthToken, isLetter, isLetterOrDigit, isOneOf, isOneOfOrEof, isWhitespace, optional; /// An event generating parser of Dart programs. This parser expects all tokens /// in a linked list (aka a token stream). /// /// The class [Scanner] is used to generate a token stream. See the file /// [scanner.dart](../scanner.dart). /// /// Subclasses of the class [Listener] are used to listen to events. /// /// Most methods of this class belong in one of four major categories: parse /// methods, peek methods, ensure methods, and skip methods. /// /// Parse methods all have the prefix `parse`, generate events /// (by calling methods on [listener]), and return the next token to parse. /// Some exceptions to this last point are methods such as [parseFunctionBody] /// and [parseClassOrMixinOrExtensionBody] which return the last token parsed /// rather than the next token to be parsed. /// Parse methods are generally named `parseGrammarProductionSuffix`. /// The suffix can be one of `opt`, or `star`. /// `opt` means zero or one matches, `star` means zero or more matches. /// For example, [parseMetadataStar] corresponds to this grammar snippet: /// `metadata*`, and [parseArgumentsOpt] corresponds to: `arguments?`. /// /// Peek methods all have the prefix `peek`, do not generate events /// (except for errors) and may return null. /// /// Ensure methods all have the prefix `ensure` and may generate events. /// They return the current token, or insert and return a synthetic token /// if the current token does not match. For example, /// [ensureSemicolon] returns the current token if the current token is a /// semicolon, otherwise inserts a synthetic semicolon in the token stream /// before the current token and then returns that new synthetic token. /// /// Skip methods are like parse methods, but all have the prefix `skip` /// and skip over some parts of the file being parsed. /// Typically, skip methods generate an event for the structure being skipped, /// but not for its substructures. /// /// ## Current Token /// /// The current token is always to be found in a formal parameter named /// `token`. This parameter should be the first as this increases the chance /// that a compiler will place it in a register. /// /// ## Implementation Notes /// /// The parser assumes that keywords, built-in identifiers, and other special /// words (pseudo-keywords) are all canonicalized. To extend the parser to /// recognize a new identifier, one should modify /// [keyword.dart](../scanner/keyword.dart) and ensure the identifier is added /// to the keyword table. /// /// As a consequence of this, one should not use `==` to compare strings in the /// parser. One should favor the methods [optional] and [expect] to recognize /// keywords or identifiers. In some cases, it's possible to compare a token's /// `stringValue` using [identical], but normally [optional] will suffice. /// /// Historically, we over-used identical, and when identical is used on objects /// other than strings, it can often be replaced by `==`. /// /// ## Flexibility, Extensibility, and Specification /// /// The parser is designed to be flexible and extensible. Its methods are /// designed to be overridden in subclasses, so it can be extended to handle /// unspecified language extension or experiments while everything in this file /// attempts to follow the specification (unless when it interferes with error /// recovery). /// /// We achieve flexibility, extensible, and specification compliance by /// following a few rules-of-thumb: /// /// 1. All methods in the parser should be public. /// /// 2. The methods follow the specified grammar, and do not implement custom /// extensions, for example, `native`. /// /// 3. The parser doesn't rewrite the token stream (when dealing with `>>`). /// /// ### Implementing Extensions /// /// For various reasons, some Dart language implementations have used /// custom/unspecified extensions to the Dart grammar. Examples of this /// includes diet parsing, patch files, `native` keyword, and generic /// comments. This class isn't supposed to implement any of these /// features. Instead it provides hooks for those extensions to be implemented /// in subclasses or listeners. Let's examine how diet parsing and `native` /// keyword is currently supported by Fasta. /// /// #### Legacy Implementation of `native` Keyword /// /// TODO(ahe,danrubel): Remove this section. /// /// Both dart2js and the Dart VM have used the `native` keyword to mark methods /// that couldn't be implemented in the Dart language and needed to be /// implemented in JavaScript or C++, respectively. An example of the syntax /// extension used by the Dart VM is: /// /// nativeFunction() native "NativeFunction"; /// /// When attempting to parse this function, the parser eventually calls /// [parseFunctionBody]. This method will report an unrecoverable error to the /// listener with the code [fasta.messageExpectedFunctionBody]. The listener can /// then look at the error code and the token and use the methods in /// [native_support.dart](native_support.dart) to parse the native syntax. /// /// #### Implementation of Diet Parsing /// /// We call it _diet_ _parsing_ when the parser skips parts of a file. Both /// dart2js and the Dart VM have been relying on this from early on as it allows /// them to more quickly compile small programs that use small parts of big /// libraries. It's also become an integrated part of how Fasta builds up /// outlines before starting to parse method bodies. /// /// When looking through this parser, you'll find a number of unused methods /// starting with `skip`. These methods are only used by subclasses, such as /// [ClassMemberParser](class_member_parser.dart) and /// [TopLevelParser](top_level_parser.dart). These methods violate the /// principle above about following the specified grammar, and originally lived /// in subclasses. However, we realized that these methods were so widely used /// and hard to maintain in subclasses, that it made sense to move them here. /// /// ### Specification and Error Recovery /// /// To improve error recovery, the parser will inform the listener of /// recoverable errors and continue to parse. An example of a recoverable /// error is: /// /// Error: Asynchronous for-loop can only be used in 'async' or 'async*'... /// main() { await for (var x in []) {} } /// ^^^^^ /// /// ### Legacy Error Recovery /// /// What's described below will be phased out in preference of the parser /// reporting and recovering from syntax errors. The motivation for this is /// that we have multiple listeners that use the parser, and this will ensure /// consistency. /// /// For unrecoverable errors, the parser will ask the listener for help to /// recover from the error. We haven't made much progress on these kinds of /// errors, so in most cases, the parser aborts by skipping to the end of file. /// /// Historically, this parser has been rather lax in what it allows, and /// deferred the enforcement of some syntactical rules to subsequent phases. It /// doesn't matter how we got there, only that we've identified that it's /// easier if the parser reports as many errors it can, but informs the /// listener if the error is recoverable or not. class Parser { Listener listener; Uri get uri => listener.uri; bool mayParseFunctionExpressions = true; /// Represents parser state: what asynchronous syntax is allowed in the /// function being currently parsed. In rare situations, this can be set by /// external clients, for example, to parse an expression outside a function. AsyncModifier asyncState = AsyncModifier.Sync; // TODO(danrubel): The [loopState] and associated functionality in the // [Parser] duplicates work that the resolver needs to do when resolving // break/continue targets. Long term, this state and functionality will be // removed from the [Parser] class and the resolver will be responsible // for generating all break/continue error messages. /// Represents parser state: whether parsing outside a loop, /// inside a loop, or inside a switch. This is used to determine whether /// break and continue statements are allowed. LoopState loopState = LoopState.OutsideLoop; /// A rewriter for inserting synthetic tokens. /// Access using [rewriter] for lazy initialization. TokenStreamRewriter cachedRewriter; TokenStreamRewriter get rewriter { cachedRewriter ??= new TokenStreamRewriter(); return cachedRewriter; } Parser(this.listener); bool get inGenerator { return asyncState == AsyncModifier.AsyncStar || asyncState == AsyncModifier.SyncStar; } bool get inAsync { return asyncState == AsyncModifier.Async || asyncState == AsyncModifier.AsyncStar; } bool get inPlainSync => asyncState == AsyncModifier.Sync; bool get isBreakAllowed => loopState != LoopState.OutsideLoop; bool get isContinueAllowed => loopState == LoopState.InsideLoop; bool get isContinueWithLabelAllowed => loopState != LoopState.OutsideLoop; /// Parse a compilation unit. /// /// This method is only invoked from outside the parser. As a result, this /// method takes the next token to be consumed rather than the last consumed /// token and returns the token after the last consumed token rather than the /// last consumed token. /// /// ``` /// libraryDefinition: /// scriptTag? /// libraryName? /// importOrExport* /// partDirective* /// topLevelDefinition* /// ; /// /// partDeclaration: /// partHeader topLevelDefinition* /// ; /// ``` Token parseUnit(Token token) { // Skip over error tokens and report them at the end // so that the parser has the chance to adjust the error location. Token errorToken = token; token = skipErrorTokens(errorToken); listener.beginCompilationUnit(token); int count = 0; DirectiveContext directiveState = new DirectiveContext(); token = syntheticPreviousToken(token); if (identical(token.next.type, TokenType.SCRIPT_TAG)) { directiveState?.checkScriptTag(this, token.next); token = parseScript(token); } while (!token.next.isEof) { final Token start = token.next; token = parseTopLevelDeclarationImpl(token, directiveState); listener.endTopLevelDeclaration(token.next); count++; if (start == token.next) { // Recovery: // If progress has not been made reaching the end of the token stream, // then report an error and skip the current token. token = token.next; listener.beginMetadataStar(token); listener.endMetadataStar(0); reportRecoverableErrorWithToken( token, fasta.templateExpectedDeclaration); listener.handleInvalidTopLevelDeclaration(token); listener.endTopLevelDeclaration(token.next); count++; } } token = token.next; reportAllErrorTokens(errorToken); listener.endCompilationUnit(count, token); // Clear fields that could lead to memory leak. cachedRewriter = null; return token; } /// This method exists for analyzer compatibility only /// and will be removed once analyzer/fasta integration is complete. /// /// Similar to [parseUnit], this method parses a compilation unit, /// but stops when it reaches the first declaration or EOF. /// /// This method is only invoked from outside the parser. As a result, this /// method takes the next token to be consumed rather than the last consumed /// token and returns the token after the last consumed token rather than the /// last consumed token. Token parseDirectives(Token token) { listener.beginCompilationUnit(token); int count = 0; DirectiveContext directiveState = new DirectiveContext(); token = syntheticPreviousToken(token); while (!token.next.isEof) { final Token start = token.next; final String nextValue = start.next.stringValue; // If a built-in keyword is being used as function name, then stop. if (identical(nextValue, '.') || identical(nextValue, '<') || identical(nextValue, '(')) { break; } if (identical(token.next.type, TokenType.SCRIPT_TAG)) { directiveState?.checkScriptTag(this, token.next); token = parseScript(token); } else { token = parseMetadataStar(token); Token keyword = token.next; final String value = keyword.stringValue; if (identical(value, 'import')) { directiveState?.checkImport(this, keyword); token = parseImport(keyword); } else if (identical(value, 'export')) { directiveState?.checkExport(this, keyword); token = parseExport(keyword); } else if (identical(value, 'library')) { directiveState?.checkLibrary(this, keyword); token = parseLibraryName(keyword); } else if (identical(value, 'part')) { token = parsePartOrPartOf(keyword, directiveState); } else if (identical(value, ';')) { token = start; } else { listener.handleDirectivesOnly(); break; } } listener.endTopLevelDeclaration(token.next); } token = token.next; listener.endCompilationUnit(count, token); // Clear fields that could lead to memory leak. cachedRewriter = null; return token; } /// Parse a top-level declaration. /// /// This method is only invoked from outside the parser. As a result, this /// method takes the next token to be consumed rather than the last consumed /// token and returns the token after the last consumed token rather than the /// last consumed token. Token parseTopLevelDeclaration(Token token) { token = parseTopLevelDeclarationImpl(syntheticPreviousToken(token), null).next; listener.endTopLevelDeclaration(token); return token; } /// ``` /// topLevelDefinition: /// classDefinition | /// enumType | /// typeAlias | /// 'external'? functionSignature ';' | /// 'external'? getterSignature ';' | /// 'external''? setterSignature ';' | /// functionSignature functionBody | /// returnType? 'get' identifier functionBody | /// returnType? 'set' identifier formalParameterList functionBody | /// ('final' | 'const') type? staticFinalDeclarationList ';' | /// variableDeclaration ';' /// ; /// ``` Token parseTopLevelDeclarationImpl( Token token, DirectiveContext directiveState) { token = parseMetadataStar(token); Token next = token.next; if (next.isTopLevelKeyword) { return parseTopLevelKeywordDeclaration(token, next, directiveState); } Token start = token; // Skip modifiers to find a top level keyword or identifier if (next.isModifier) { if (optional('var', next) || optional('late', next) || ((optional('const', next) || optional('final', next)) && // Ignore `const class` and `final class` so that it is reported // below as an invalid modifier on a class. !optional('class', next.next))) { directiveState?.checkDeclaration(); return parseTopLevelMemberImpl(token); } while (token.next.isModifier) { token = token.next; } } next = token.next; if (next.isTopLevelKeyword) { return parseTopLevelKeywordDeclaration(start, next, directiveState); } else if (next.isKeywordOrIdentifier) { // TODO(danrubel): improve parseTopLevelMember // so that we don't parse modifiers twice. directiveState?.checkDeclaration(); return parseTopLevelMemberImpl(start); } else if (start.next != next) { directiveState?.checkDeclaration(); // Handle the edge case where a modifier is being used as an identifier return parseTopLevelMemberImpl(start); } // Recovery if (next.isOperator && optional('(', next.next)) { // This appears to be a top level operator declaration, which is invalid. reportRecoverableError(next, fasta.messageTopLevelOperator); // Insert a synthetic identifier // and continue parsing as a top level function. rewriter.insertSyntheticIdentifier( next, '#synthetic_function_${next.charOffset}'); return parseTopLevelMemberImpl(next); } // Ignore any preceding modifiers and just report the unexpected token listener.beginTopLevelMember(next); return parseInvalidTopLevelDeclaration(token); } /// Parse the modifiers before the `class` keyword. /// Return the first `abstract` modifier or `null` if not found. Token parseClassDeclarationModifiers(Token start, Token keyword) { Token modifier = start.next; while (modifier != keyword) { if (optional('abstract', modifier)) { parseTopLevelKeywordModifiers(modifier, keyword); return modifier; } else { // Recovery reportTopLevelModifierError(modifier, keyword); } modifier = modifier.next; } return null; } /// Report errors on any modifiers before the specified keyword. void parseTopLevelKeywordModifiers(Token start, Token keyword) { Token modifier = start.next; while (modifier != keyword) { // Recovery reportTopLevelModifierError(modifier, keyword); modifier = modifier.next; } } // Report an error for the given modifier preceding a top level keyword // such as `import` or `class`. void reportTopLevelModifierError(Token modifier, Token afterModifiers) { if (optional('const', modifier) && optional('class', afterModifiers)) { reportRecoverableError(modifier, fasta.messageConstClass); } else if (optional('external', modifier)) { if (optional('class', afterModifiers)) { reportRecoverableError(modifier, fasta.messageExternalClass); } else if (optional('enum', afterModifiers)) { reportRecoverableError(modifier, fasta.messageExternalEnum); } else if (optional('typedef', afterModifiers)) { reportRecoverableError(modifier, fasta.messageExternalTypedef); } else { reportRecoverableErrorWithToken( modifier, fasta.templateExtraneousModifier); } } else { reportRecoverableErrorWithToken( modifier, fasta.templateExtraneousModifier); } } /// Parse any top-level declaration that begins with a keyword. /// [start] is the token before any modifiers preceding [keyword]. Token parseTopLevelKeywordDeclaration( Token start, Token keyword, DirectiveContext directiveState) { assert(keyword.isTopLevelKeyword); final String value = keyword.stringValue; if (identical(value, 'class')) { directiveState?.checkDeclaration(); Token abstractToken = parseClassDeclarationModifiers(start, keyword); return parseClassOrNamedMixinApplication(abstractToken, keyword); } else if (identical(value, 'enum')) { directiveState?.checkDeclaration(); parseTopLevelKeywordModifiers(start, keyword); return parseEnum(keyword); } else { // The remaining top level keywords are built-in keywords // and can be used in a top level declaration // as an identifier such as "abstract<T>() => 0;" // or as a prefix such as "abstract.A b() => 0;". String nextValue = keyword.next.stringValue; if (identical(nextValue, '(') || identical(nextValue, '.')) { directiveState?.checkDeclaration(); return parseTopLevelMemberImpl(start); } else if (identical(nextValue, '<')) { if (identical(value, 'extension')) { // The name in an extension declaration is optional: // `extension<T> on ...` Token endGroup = keyword.next.endGroup; if (endGroup != null && optional('on', endGroup.next)) { directiveState?.checkDeclaration(); return parseExtension(keyword); } } directiveState?.checkDeclaration(); return parseTopLevelMemberImpl(start); } else { parseTopLevelKeywordModifiers(start, keyword); if (identical(value, 'import')) { directiveState?.checkImport(this, keyword); return parseImport(keyword); } else if (identical(value, 'export')) { directiveState?.checkExport(this, keyword); return parseExport(keyword); } else if (identical(value, 'typedef')) { directiveState?.checkDeclaration(); return parseTypedef(keyword); } else if (identical(value, 'mixin')) { directiveState?.checkDeclaration(); return parseMixin(keyword); } else if (identical(value, 'extension')) { directiveState?.checkDeclaration(); return parseExtension(keyword); } else if (identical(value, 'part')) { return parsePartOrPartOf(keyword, directiveState); } else if (identical(value, 'library')) { directiveState?.checkLibrary(this, keyword); return parseLibraryName(keyword); } } } throw "Internal error: Unhandled top level keyword '$value'."; } /// ``` /// libraryDirective: /// 'library' qualified ';' /// ; /// ``` Token parseLibraryName(Token libraryKeyword) { assert(optional('library', libraryKeyword)); listener.beginLibraryName(libraryKeyword); Token token = parseQualified(libraryKeyword, IdentifierContext.libraryName, IdentifierContext.libraryNameContinuation); token = ensureSemicolon(token); listener.endLibraryName(libraryKeyword, token); return token; } /// ``` /// importPrefix: /// 'deferred'? 'as' identifier /// ; /// ``` Token parseImportPrefixOpt(Token token) { Token next = token.next; if (optional('deferred', next) && optional('as', next.next)) { Token deferredToken = next; Token asKeyword = next.next; token = ensureIdentifier( asKeyword, IdentifierContext.importPrefixDeclaration); listener.handleImportPrefix(deferredToken, asKeyword); } else if (optional('as', next)) { Token asKeyword = next; token = ensureIdentifier(next, IdentifierContext.importPrefixDeclaration); listener.handleImportPrefix(null, asKeyword); } else { listener.handleImportPrefix(null, null); } return token; } /// ``` /// importDirective: /// 'import' uri ('if' '(' test ')' uri)* importPrefix? combinator* ';' /// ; /// ``` Token parseImport(Token importKeyword) { assert(optional('import', importKeyword)); listener.beginImport(importKeyword); Token token = ensureLiteralString(importKeyword); Token uri = token; token = parseConditionalUriStar(token); token = parseImportPrefixOpt(token); token = parseCombinatorStar(token).next; if (optional(';', token)) { listener.endImport(importKeyword, token); return token; } else { // Recovery listener.endImport(importKeyword, null); return parseImportRecovery(uri); } } /// Recover given out-of-order clauses in an import directive where [token] is /// the import keyword. Token parseImportRecovery(Token token) { final Listener primaryListener = listener; final ImportRecoveryListener recoveryListener = new ImportRecoveryListener(); // Reparse to determine which clauses have already been parsed // but intercept the events so they are not sent to the primary listener listener = recoveryListener; token = parseConditionalUriStar(token); token = parseImportPrefixOpt(token); token = parseCombinatorStar(token); Token firstDeferredKeyword = recoveryListener.deferredKeyword; bool hasPrefix = recoveryListener.asKeyword != null; bool hasCombinator = recoveryListener.hasCombinator; // Update the recovery listener to forward subsequent events // to the primary listener recoveryListener.listener = primaryListener; // Parse additional out-of-order clauses. Token semicolon; do { Token start = token.next; // Check for extraneous token in the middle of an import statement. token = skipUnexpectedTokenOpt( token, const <String>['if', 'deferred', 'as', 'hide', 'show', ';']); // During recovery, clauses are parsed in the same order // and generate the same events as in the parseImport method above. recoveryListener.clear(); token = parseConditionalUriStar(token); if (recoveryListener.ifKeyword != null) { if (firstDeferredKeyword != null) { // TODO(danrubel): report error indicating conditional should // be moved before deferred keyword } else if (hasPrefix) { // TODO(danrubel): report error indicating conditional should // be moved before prefix clause } else if (hasCombinator) { // TODO(danrubel): report error indicating conditional should // be moved before combinators } } if (optional('deferred', token.next) && !optional('as', token.next.next)) { listener.handleImportPrefix(token.next, null); token = token.next; } else { token = parseImportPrefixOpt(token); } if (recoveryListener.deferredKeyword != null) { if (firstDeferredKeyword != null) { reportRecoverableError( recoveryListener.deferredKeyword, fasta.messageDuplicateDeferred); } else { if (hasPrefix) { reportRecoverableError(recoveryListener.deferredKeyword, fasta.messageDeferredAfterPrefix); } firstDeferredKeyword = recoveryListener.deferredKeyword; } } if (recoveryListener.asKeyword != null) { if (hasPrefix) { reportRecoverableError( recoveryListener.asKeyword, fasta.messageDuplicatePrefix); } else { if (hasCombinator) { reportRecoverableError( recoveryListener.asKeyword, fasta.messagePrefixAfterCombinator); } hasPrefix = true; } } token = parseCombinatorStar(token); hasCombinator = hasCombinator || recoveryListener.hasCombinator; if (optional(';', token.next)) { semicolon = token.next; } else if (identical(start, token.next)) { // If no forward progress was made, insert ';' so that we exit loop. semicolon = ensureSemicolon(token); } listener.handleRecoverImport(semicolon); } while (semicolon == null); if (firstDeferredKeyword != null && !hasPrefix) { reportRecoverableError( firstDeferredKeyword, fasta.messageMissingPrefixInDeferredImport); } return semicolon; } /// ``` /// conditionalUris: /// conditionalUri* /// ; /// ``` Token parseConditionalUriStar(Token token) { listener.beginConditionalUris(token.next); int count = 0; while (optional('if', token.next)) { count++; token = parseConditionalUri(token); } listener.endConditionalUris(count); return token; } /// ``` /// conditionalUri: /// 'if' '(' dottedName ('==' literalString)? ')' uri /// ; /// ``` Token parseConditionalUri(Token token) { Token ifKeyword = token = token.next; assert(optional('if', token)); listener.beginConditionalUri(token); Token leftParen = token.next; if (!optional('(', leftParen)) { reportRecoverableError( leftParen, fasta.templateExpectedButGot.withArguments('(')); leftParen = rewriter.insertParens(token, true); } token = parseDottedName(leftParen); Token next = token.next; Token equalitySign; if (optional('==', next)) { equalitySign = next; token = ensureLiteralString(next); next = token.next; } if (next != leftParen.endGroup) { Token endGroup = leftParen.endGroup; if (endGroup.isSynthetic) { // The scanner did not place the synthetic ')' correctly, so move it. next = rewriter.moveSynthetic(token, endGroup); } else { reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); next = endGroup; } } token = next; assert(optional(')', token)); token = ensureLiteralString(token); listener.endConditionalUri(ifKeyword, leftParen, equalitySign); return token; } /// ``` /// dottedName: /// identifier ('.' identifier)* /// ; /// ``` Token parseDottedName(Token token) { token = ensureIdentifier(token, IdentifierContext.dottedName); Token firstIdentifier = token; int count = 1; while (optional('.', token.next)) { token = ensureIdentifier( token.next, IdentifierContext.dottedNameContinuation); count++; } listener.handleDottedName(count, firstIdentifier); return token; } /// ``` /// exportDirective: /// 'export' uri conditional-uris* combinator* ';' /// ; /// ``` Token parseExport(Token exportKeyword) { assert(optional('export', exportKeyword)); listener.beginExport(exportKeyword); Token token = ensureLiteralString(exportKeyword); token = parseConditionalUriStar(token); token = parseCombinatorStar(token); token = ensureSemicolon(token); listener.endExport(exportKeyword, token); return token; } /// ``` /// combinators: /// (hideCombinator | showCombinator)* /// ; /// ``` Token parseCombinatorStar(Token token) { Token next = token.next; listener.beginCombinators(next); int count = 0; while (true) { String value = next.stringValue; if (identical('hide', value)) { token = parseHide(token); } else if (identical('show', value)) { token = parseShow(token); } else { listener.endCombinators(count); break; } next = token.next; count++; } return token; } /// ``` /// hideCombinator: /// 'hide' identifierList /// ; /// ``` Token parseHide(Token token) { Token hideKeyword = token.next; assert(optional('hide', hideKeyword)); listener.beginHide(hideKeyword); token = parseIdentifierList(hideKeyword); listener.endHide(hideKeyword); return token; } /// ``` /// showCombinator: /// 'show' identifierList /// ; /// ``` Token parseShow(Token token) { Token showKeyword = token.next; assert(optional('show', showKeyword)); listener.beginShow(showKeyword); token = parseIdentifierList(showKeyword); listener.endShow(showKeyword); return token; } /// ``` /// identifierList: /// identifier (',' identifier)* /// ; /// ``` Token parseIdentifierList(Token token) { token = ensureIdentifier(token, IdentifierContext.combinator); int count = 1; while (optional(',', token.next)) { token = ensureIdentifier(token.next, IdentifierContext.combinator); count++; } listener.handleIdentifierList(count); return token; } /// ``` /// typeList: /// type (',' type)* /// ; /// ``` Token parseTypeList(Token token) { listener.beginTypeList(token.next); token = computeType(token, true).ensureTypeOrVoid(token, this); int count = 1; while (optional(',', token.next)) { token = computeType(token.next, true).ensureTypeOrVoid(token.next, this); count++; } listener.endTypeList(count); return token; } Token parsePartOrPartOf(Token partKeyword, DirectiveContext directiveState) { assert(optional('part', partKeyword)); if (optional('of', partKeyword.next)) { directiveState?.checkPartOf(this, partKeyword); return parsePartOf(partKeyword); } else { directiveState?.checkPart(this, partKeyword); return parsePart(partKeyword); } } /// ``` /// partDirective: /// 'part' uri ';' /// ; /// ``` Token parsePart(Token partKeyword) { assert(optional('part', partKeyword)); listener.beginPart(partKeyword); Token token = ensureLiteralString(partKeyword); token = ensureSemicolon(token); listener.endPart(partKeyword, token); return token; } /// ``` /// partOfDirective: /// 'part' 'of' (qualified | uri) ';' /// ; /// ``` Token parsePartOf(Token partKeyword) { Token ofKeyword = partKeyword.next; assert(optional('part', partKeyword)); assert(optional('of', ofKeyword)); listener.beginPartOf(partKeyword); bool hasName = ofKeyword.next.isIdentifier; Token token; if (hasName) { token = parseQualified(ofKeyword, IdentifierContext.partName, IdentifierContext.partNameContinuation); } else { token = ensureLiteralString(ofKeyword); } token = ensureSemicolon(token); listener.endPartOf(partKeyword, ofKeyword, token, hasName); return token; } /// ``` /// metadata: /// annotation* /// ; /// ``` Token parseMetadataStar(Token token) { listener.beginMetadataStar(token.next); int count = 0; while (optional('@', token.next)) { token = parseMetadata(token); count++; } listener.endMetadataStar(count); return token; } /// ``` /// annotation: /// '@' qualified ('.' identifier)? arguments? /// ; /// ``` Token parseMetadata(Token token) { Token atToken = token.next; assert(optional('@', atToken)); listener.beginMetadata(atToken); token = ensureIdentifier(atToken, IdentifierContext.metadataReference); token = parseQualifiedRestOpt(token, IdentifierContext.metadataContinuation); if (optional("<", token.next)) { reportRecoverableError(token.next, fasta.messageMetadataTypeArguments); } token = computeTypeParamOrArg(token).parseArguments(token, this); Token period = null; if (optional('.', token.next)) { period = token.next; token = ensureIdentifier( period, IdentifierContext.metadataContinuationAfterTypeArguments); } token = parseArgumentsOpt(token); listener.endMetadata(atToken, period, token.next); return token; } /// ``` /// scriptTag: /// '#!' (˜NEWLINE)* NEWLINE /// ; /// ``` Token parseScript(Token token) { token = token.next; assert(identical(token.type, TokenType.SCRIPT_TAG)); listener.handleScript(token); return token; } /// ``` /// typeAlias: /// metadata 'typedef' typeAliasBody | /// metadata 'typedef' identifier typeParameters? '=' functionType ';' /// ; /// /// functionType: /// returnType? 'Function' typeParameters? parameterTypeList /// /// typeAliasBody: /// functionTypeAlias /// ; /// /// functionTypeAlias: /// functionPrefix typeParameters? formalParameterList ‘;’ /// ; /// /// functionPrefix: /// returnType? identifier /// ; /// ``` Token parseTypedef(Token typedefKeyword) { assert(optional('typedef', typedefKeyword)); listener.beginFunctionTypeAlias(typedefKeyword); TypeInfo typeInfo = computeType(typedefKeyword, false); Token token = typeInfo.skipType(typedefKeyword).next; Token equals; TypeParamOrArgInfo typeParam = computeTypeParamOrArg(token, true); if (typeInfo == noType && (token.kind == IDENTIFIER_TOKEN || token.type.isPseudo) && optional('=', typeParam.skip(token).next)) { listener.handleIdentifier(token, IdentifierContext.typedefDeclaration); equals = typeParam.parseVariables(token, this).next; assert(optional('=', equals)); token = computeType(equals, true).ensureTypeOrVoid(equals, this); } else { token = typeInfo.parseType(typedefKeyword, this); token = ensureIdentifier(token, IdentifierContext.typedefDeclaration); token = typeParam.parseVariables(token, this); token = parseFormalParametersRequiredOpt(token, MemberKind.FunctionTypeAlias); } token = ensureSemicolon(token); listener.endFunctionTypeAlias(typedefKeyword, equals, token); return token; } /// Parse a mixin application starting from `with`. Assumes that the first /// type has already been parsed. Token parseMixinApplicationRest(Token token) { Token withKeyword = token.next; if (!optional('with', withKeyword)) { // Recovery: Report an error and insert synthetic `with` clause. reportRecoverableError( withKeyword, fasta.templateExpectedButGot.withArguments('with')); withKeyword = rewriter.insertSyntheticKeyword(token, Keyword.WITH); if (!isValidTypeReference(withKeyword.next)) { rewriter.insertSyntheticIdentifier(withKeyword); } } token = parseTypeList(withKeyword); listener.handleNamedMixinApplicationWithClause(withKeyword); return token; } Token parseWithClauseOpt(Token token) { Token withKeyword = token.next; if (optional('with', withKeyword)) { token = parseTypeList(withKeyword); listener.handleClassWithClause(withKeyword); } else { listener.handleClassNoWithClause(); } return token; } /// Parse the formal parameters of a getter (which shouldn't have parameters) /// or function or method. Token parseGetterOrFormalParameters( Token token, Token name, bool isGetter, MemberKind kind) { Token next = token.next; if (optional("(", next)) { if (isGetter) { reportRecoverableError(next, fasta.messageGetterWithFormals); } token = parseFormalParameters(token, kind); } else if (isGetter) { listener.handleNoFormalParameters(next, kind); } else { // Recovery if (optional('operator', name)) { Token next = name.next; if (next.isOperator) { name = next; } else if (isUnaryMinus(next)) { name = next.next; } } reportRecoverableError(name, missingParameterMessage(kind)); token = rewriter.insertParens(token, false); token = parseFormalParametersRest(token, kind); } return token; } Token parseFormalParametersOpt(Token token, MemberKind kind) { Token next = token.next; if (optional('(', next)) { token = parseFormalParameters(token, kind); } else { listener.handleNoFormalParameters(next, kind); } return token; } Token skipFormalParameters(Token token, MemberKind kind) { return skipFormalParametersRest(token.next, kind); } Token skipFormalParametersRest(Token token, MemberKind kind) { assert(optional('(', token)); // TODO(ahe): Shouldn't this be `beginFormalParameters`? listener.beginOptionalFormalParameters(token); Token closeBrace = token.endGroup; assert(optional(')', closeBrace)); listener.endFormalParameters(0, token, closeBrace, kind); return closeBrace; } /// Parses the formal parameter list of a function. /// /// If `kind == MemberKind.GeneralizedFunctionType`, then names may be /// omitted (except for named arguments). Otherwise, types may be omitted. Token parseFormalParametersRequiredOpt(Token token, MemberKind kind) { Token next = token.next; if (!optional('(', next)) { reportRecoverableError(next, missingParameterMessage(kind)); next = rewriter.insertParens(token, false); } return parseFormalParametersRest(next, kind); } /// Parses the formal parameter list of a function given that the left /// parenthesis is known to exist. /// /// If `kind == MemberKind.GeneralizedFunctionType`, then names may be /// omitted (except for named arguments). Otherwise, types may be omitted. Token parseFormalParameters(Token token, MemberKind kind) { return parseFormalParametersRest(token.next, kind); } /// Parses the formal parameter list of a function given that the left /// parenthesis passed in as [token]. /// /// If `kind == MemberKind.GeneralizedFunctionType`, then names may be /// omitted (except for named arguments). Otherwise, types may be omitted. Token parseFormalParametersRest(Token token, MemberKind kind) { Token begin = token; assert(optional('(', token)); listener.beginFormalParameters(begin, kind); int parameterCount = 0; while (true) { Token next = token.next; if (optional(')', next)) { token = next; break; } ++parameterCount; String value = next.stringValue; if (identical(value, '[')) { token = parseOptionalPositionalParameters(token, kind); token = ensureCloseParen(token, begin); break; } else if (identical(value, '{')) { token = parseOptionalNamedParameters(token, kind); token = ensureCloseParen(token, begin); break; } else if (identical(value, '[]')) { // Recovery token = rewriteSquareBrackets(token); token = parseOptionalPositionalParameters(token, kind); token = ensureCloseParen(token, begin); break; } token = parseFormalParameter(token, FormalParameterKind.mandatory, kind); next = token.next; if (!optional(',', next)) { Token next = token.next; if (optional(')', next)) { token = next; } else { // Recovery if (begin.endGroup.isSynthetic) { // Scanner has already reported a missing `)` error, // but placed the `)` in the wrong location, so move it. token = rewriter.moveSynthetic(token, begin.endGroup); } else if (next.kind == IDENTIFIER_TOKEN && next.next.kind == IDENTIFIER_TOKEN) { // Looks like a missing comma token = rewriteAndRecover( token, fasta.templateExpectedButGot.withArguments(','), new SyntheticToken(TokenType.COMMA, next.charOffset)); continue; } else { token = ensureCloseParen(token, begin); } } break; } token = next; } assert(optional(')', token)); listener.endFormalParameters(parameterCount, begin, token, kind); return token; } /// Return the message that should be produced when the formal parameters are /// missing. Message missingParameterMessage(MemberKind kind) { if (kind == MemberKind.FunctionTypeAlias) { return fasta.messageMissingTypedefParameters; } else if (kind == MemberKind.NonStaticMethod || kind == MemberKind.StaticMethod) { return fasta.messageMissingMethodParameters; } return fasta.messageMissingFunctionParameters; } /// ``` /// normalFormalParameter: /// functionFormalParameter | /// fieldFormalParameter | /// simpleFormalParameter /// ; /// /// functionFormalParameter: /// metadata 'covariant'? returnType? identifier formalParameterList /// ; /// /// simpleFormalParameter: /// metadata 'covariant'? finalConstVarOrType? identifier | /// ; /// /// fieldFormalParameter: /// metadata finalConstVarOrType? 'this' '.' identifier formalParameterList? /// ; /// ``` Token parseFormalParameter( Token token, FormalParameterKind parameterKind, MemberKind memberKind) { assert(parameterKind != null); token = parseMetadataStar(token); Token next = token.next; Token start = next; final bool inFunctionType = memberKind == MemberKind.GeneralizedFunctionType; Token requiredToken; Token covariantToken; Token varFinalOrConst; if (isModifier(next)) { if (optional('required', next)) { if (parameterKind == FormalParameterKind.optionalNamed) { requiredToken = token = next; next = token.next; } } if (isModifier(next)) { if (optional('covariant', next)) { if (memberKind != MemberKind.StaticMethod && memberKind != MemberKind.TopLevelMethod) { covariantToken = token = next; next = token.next; } } if (isModifier(next)) { if (!inFunctionType) { if (optional('var', next)) { varFinalOrConst = token = next; next = token.next; } else if (optional('final', next)) { varFinalOrConst = token = next; next = token.next; } } if (isModifier(next)) { // Recovery ModifierRecoveryContext context = new ModifierRecoveryContext(this) ..covariantToken = covariantToken ..requiredToken = requiredToken ..varFinalOrConst = varFinalOrConst; token = context.parseFormalParameterModifiers( token, parameterKind, memberKind); next = token.next; covariantToken = context.covariantToken; requiredToken = context.requiredToken; varFinalOrConst = context.varFinalOrConst; context = null; } } } } listener.beginFormalParameter( start, memberKind, requiredToken, covariantToken, varFinalOrConst); // Type is required in a generalized function type, but optional otherwise. final Token beforeType = token; TypeInfo typeInfo = computeType(token, inFunctionType); token = typeInfo.skipType(token); next = token.next; if (typeInfo == noType && (optional('.', next) || (next.isIdentifier && optional('.', next.next)))) { // Recovery: Malformed type reference. typeInfo = computeType(beforeType, true); token = typeInfo.skipType(beforeType); next = token.next; } final bool isNamedParameter = parameterKind == FormalParameterKind.optionalNamed; Token thisKeyword; Token periodAfterThis; IdentifierContext nameContext = IdentifierContext.formalParameterDeclaration; if (!inFunctionType && optional('this', next)) { thisKeyword = token = next; next = token.next; if (!optional('.', next)) { // Recover from a missing period by inserting one. next = rewriteAndRecover( token, fasta.templateExpectedButGot.withArguments('.'), new SyntheticToken(TokenType.PERIOD, next.charOffset)); } periodAfterThis = token = next; next = token.next; nameContext = IdentifierContext.fieldInitializer; } if (next.isIdentifier) { token = next; next = token.next; } Token beforeInlineFunctionType; TypeParamOrArgInfo typeParam = noTypeParamOrArg; if (optional("<", next)) { typeParam = computeTypeParamOrArg(token); if (typeParam != noTypeParamOrArg) { Token closer = typeParam.skip(token); if (optional("(", closer.next)) { if (varFinalOrConst != null) { reportRecoverableError( varFinalOrConst, fasta.messageFunctionTypedParameterVar); } beforeInlineFunctionType = token; token = closer.next.endGroup; next = token.next; } } } else if (optional("(", next)) { if (varFinalOrConst != null) { reportRecoverableError( varFinalOrConst, fasta.messageFunctionTypedParameterVar); } beforeInlineFunctionType = token; token = next.endGroup; next = token.next; } if (typeInfo != noType && varFinalOrConst != null && optional('var', varFinalOrConst)) { reportRecoverableError(varFinalOrConst, fasta.messageTypeAfterVar); } Token endInlineFunctionType; if (beforeInlineFunctionType != null) { endInlineFunctionType = typeParam.parseVariables(beforeInlineFunctionType, this); listener.beginFunctionTypedFormalParameter(beforeInlineFunctionType.next); token = typeInfo.parseType(beforeType, this); endInlineFunctionType = parseFormalParametersRequiredOpt( endInlineFunctionType, MemberKind.FunctionTypedParameter); Token question; if (optional('?', endInlineFunctionType.next)) { question = endInlineFunctionType = endInlineFunctionType.next; } listener.endFunctionTypedFormalParameter( beforeInlineFunctionType, question); // Generalized function types don't allow inline function types. // The following isn't allowed: // int Function(int bar(String x)). if (inFunctionType) { reportRecoverableError(beforeInlineFunctionType.next, fasta.messageInvalidInlineFunctionType); } } else if (inFunctionType) { token = typeInfo.ensureTypeOrVoid(beforeType, this); } else { token = typeInfo.parseType(beforeType, this); } Token nameToken; if (periodAfterThis != null) { token = periodAfterThis; } next = token.next; if (inFunctionType && !isNamedParameter && !next.isKeywordOrIdentifier && beforeInlineFunctionType == null) { nameToken = token.next; listener.handleNoName(nameToken); } else { nameToken = token = ensureIdentifier(token, nameContext); if (isNamedParameter && nameToken.lexeme.startsWith("_")) { reportRecoverableError(nameToken, fasta.messagePrivateNamedParameter); } } if (endInlineFunctionType != null) { token = endInlineFunctionType; } next = token.next; String value = next.stringValue; Token initializerStart, initializerEnd; if ((identical('=', value)) || (identical(':', value))) { Token equal = next; initializerStart = equal.next; listener.beginFormalParameterDefaultValueExpression(); token = initializerEnd = parseExpression(equal); next = token.next; listener.endFormalParameterDefaultValueExpression(); // TODO(danrubel): Consider removing the last parameter from the // handleValuedFormalParameter event... it appears to be unused. listener.handleValuedFormalParameter(equal, next); if (isMandatoryFormalParameterKind(parameterKind)) { reportRecoverableError( equal, fasta.messageRequiredParameterWithDefault); } else if (isOptionalPositionalFormalParameterKind(parameterKind) && identical(':', value)) { reportRecoverableError( equal, fasta.messagePositionalParameterWithEquals); } else if (inFunctionType || memberKind == MemberKind.FunctionTypeAlias || memberKind == MemberKind.FunctionTypedParameter) { reportRecoverableError(equal, fasta.messageFunctionTypeDefaultValue); } } else { listener.handleFormalParameterWithoutValue(next); } listener.endFormalParameter(thisKeyword, periodAfterThis, nameToken, initializerStart, initializerEnd, parameterKind, memberKind); return token; } /// ``` /// defaultFormalParameter: /// normalFormalParameter ('=' expression)? /// ; /// ``` Token parseOptionalPositionalParameters(Token token, MemberKind kind) { Token begin = token = token.next; assert(optional('[', token)); listener.beginOptionalFormalParameters(begin); int parameterCount = 0; while (true) { Token next = token.next; if (optional(']', next)) { break; } token = parseFormalParameter( token, FormalParameterKind.optionalPositional, kind); next = token.next; ++parameterCount; if (!optional(',', next)) { if (!optional(']', next)) { // Recovery reportRecoverableError( next, fasta.templateExpectedButGot.withArguments(']')); // Scanner guarantees a closing bracket. next = begin.endGroup; while (token.next != next) { token = token.next; } } break; } token = next; } if (parameterCount == 0) { rewriteAndRecover( token, fasta.messageEmptyOptionalParameterList, new SyntheticStringToken( TokenType.IDENTIFIER, '', token.next.charOffset, 0)); token = parseFormalParameter( token, FormalParameterKind.optionalPositional, kind); ++parameterCount; } token = token.next; assert(optional(']', token)); listener.endOptionalFormalParameters(parameterCount, begin, token); return token; } /// ``` /// defaultNamedParameter: /// normalFormalParameter ('=' expression)? | /// normalFormalParameter (':' expression)? /// ; /// ``` Token parseOptionalNamedParameters(Token token, MemberKind kind) { Token begin = token = token.next; assert(optional('{', token)); listener.beginOptionalFormalParameters(begin); int parameterCount = 0; while (true) { Token next = token.next; if (optional('}', next)) { break; } token = parseFormalParameter(token, FormalParameterKind.optionalNamed, kind); next = token.next; ++parameterCount; if (!optional(',', next)) { if (!optional('}', next)) { // Recovery reportRecoverableError( next, fasta.templateExpectedButGot.withArguments('}')); // Scanner guarantees a closing bracket. next = begin.endGroup; while (token.next != next) { token = token.next; } } break; } token = next; } if (parameterCount == 0) { rewriteAndRecover( token, fasta.messageEmptyNamedParameterList, new SyntheticStringToken( TokenType.IDENTIFIER, '', token.next.charOffset, 0)); token = parseFormalParameter(token, FormalParameterKind.optionalNamed, kind); ++parameterCount; } token = token.next; assert(optional('}', token)); listener.endOptionalFormalParameters(parameterCount, begin, token); return token; } /// ``` /// qualified: /// identifier qualifiedRest* /// ; /// ``` Token parseQualified(Token token, IdentifierContext context, IdentifierContext continuationContext) { token = ensureIdentifier(token, context); while (optional('.', token.next)) { token = parseQualifiedRest(token, continuationContext); } return token; } /// ``` /// qualifiedRestOpt: /// qualifiedRest? /// ; /// ``` Token parseQualifiedRestOpt( Token token, IdentifierContext continuationContext) { if (optional('.', token.next)) { return parseQualifiedRest(token, continuationContext); } else { return token; } } /// ``` /// qualifiedRest: /// '.' identifier /// ; /// ``` Token parseQualifiedRest(Token token, IdentifierContext context) { token = token.next; assert(optional('.', token)); Token period = token; token = ensureIdentifier(token, context); listener.handleQualified(period); return token; } Token skipBlock(Token token) { // The scanner ensures that `{` always has a closing `}`. return ensureBlock(token, null, null).endGroup; } /// ``` /// enumType: /// metadata 'enum' id '{' metadata id [',' metadata id]* [','] '}' /// ; /// ``` Token parseEnum(Token enumKeyword) { assert(optional('enum', enumKeyword)); listener.beginEnum(enumKeyword); Token token = ensureIdentifier(enumKeyword, IdentifierContext.enumDeclaration); Token leftBrace = token.next; int count = 0; if (optional('{', leftBrace)) { token = leftBrace; while (true) { Token next = token.next; if (optional('}', next)) { token = next; if (count == 0) { reportRecoverableError(token, fasta.messageEnumDeclarationEmpty); } break; } token = parseMetadataStar(token); token = ensureIdentifier(token, IdentifierContext.enumValueDeclaration); next = token.next; count++; if (optional(',', next)) { token = next; } else if (optional('}', next)) { token = next; break; } else { // Recovery Token endGroup = leftBrace.endGroup; if (endGroup.isSynthetic) { // The scanner did not place the synthetic '}' correctly. token = rewriter.moveSynthetic(token, endGroup); break; } else if (next.isIdentifier) { // If the next token is an identifier, assume a missing comma. // TODO(danrubel): Consider improved recovery for missing `}` // both here and when the scanner inserts a synthetic `}` // for situations such as `enum Letter {a, b Letter e;`. reportRecoverableError( next, fasta.templateExpectedButGot.withArguments(',')); } else { // Otherwise assume a missing `}` and exit the loop reportRecoverableError( next, fasta.templateExpectedButGot.withArguments('}')); token = leftBrace.endGroup; break; } } } } else { // TODO(danrubel): merge this error message with missing class/mixin body leftBrace = ensureBlock(token, fasta.templateExpectedEnumBody, null); token = leftBrace.endGroup; } assert(optional('}', token)); listener.endEnum(enumKeyword, leftBrace, count); return token; } Token parseClassOrNamedMixinApplication( Token abstractToken, Token classKeyword) { assert(optional('class', classKeyword)); Token begin = abstractToken ?? classKeyword; listener.beginClassOrNamedMixinApplicationPrelude(begin); Token name = ensureIdentifier( classKeyword, IdentifierContext.classOrMixinOrExtensionDeclaration); Token token = computeTypeParamOrArg(name, true, true).parseVariables(name, this); if (optional('=', token.next)) { listener.beginNamedMixinApplication(begin, abstractToken, name); return parseNamedMixinApplication(token, begin, classKeyword); } else { listener.beginClassDeclaration(begin, abstractToken, name); return parseClass(token, begin, classKeyword, name.lexeme); } } Token parseNamedMixinApplication( Token token, Token begin, Token classKeyword) { Token equals = token = token.next; assert(optional('=', equals)); token = computeType(token, true).ensureTypeNotVoid(token, this); token = parseMixinApplicationRest(token); Token implementsKeyword = null; if (optional('implements', token.next)) { implementsKeyword = token.next; token = parseTypeList(implementsKeyword); } token = ensureSemicolon(token); listener.endNamedMixinApplication( begin, classKeyword, equals, implementsKeyword, token); return token; } /// Parse the portion of a class declaration (not a mixin application) that /// follows the end of the type parameters. /// /// ``` /// classDefinition: /// metadata abstract? 'class' identifier typeParameters? /// (superclass mixins?)? interfaces? /// '{' (metadata classMemberDefinition)* '}' | /// metadata abstract? 'class' mixinApplicationClass /// ; /// ``` Token parseClass( Token token, Token begin, Token classKeyword, String className) { Token start = token; token = parseClassHeaderOpt(token, begin, classKeyword); if (!optional('{', token.next)) { // Recovery token = parseClassHeaderRecovery(start, begin, classKeyword); ensureBlock(token, null, 'class declaration'); } token = parseClassOrMixinOrExtensionBody( token, DeclarationKind.Class, className); listener.endClassDeclaration(begin, token); return token; } Token parseClassHeaderOpt(Token token, Token begin, Token classKeyword) { token = parseClassExtendsOpt(token); token = parseWithClauseOpt(token); token = parseClassOrMixinImplementsOpt(token); Token nativeToken; if (optional('native', token.next)) { nativeToken = token.next; token = parseNativeClause(token); } listener.handleClassHeader(begin, classKeyword, nativeToken); return token; } /// Recover given out-of-order clauses in a class header. Token parseClassHeaderRecovery(Token token, Token begin, Token classKeyword) { final Listener primaryListener = listener; final ClassHeaderRecoveryListener recoveryListener = new ClassHeaderRecoveryListener(); // Reparse to determine which clauses have already been parsed // but intercept the events so they are not sent to the primary listener. listener = recoveryListener; token = parseClassHeaderOpt(token, begin, classKeyword); bool hasExtends = recoveryListener.extendsKeyword != null; bool hasImplements = recoveryListener.implementsKeyword != null; bool hasWith = recoveryListener.withKeyword != null; // Update the recovery listener to forward subsequent events // to the primary listener. recoveryListener.listener = primaryListener; // Parse additional out-of-order clauses Token start; do { start = token; // Check for extraneous token in the middle of a class header. token = skipUnexpectedTokenOpt( token, const <String>['extends', 'with', 'implements', '{']); // During recovery, clauses are parsed in the same order // and generate the same events as in the parseClassHeader method above. recoveryListener.clear(); if (token.next.isKeywordOrIdentifier && const ['extend', 'on'].contains(token.next.lexeme)) { reportRecoverableError( token.next, fasta.templateExpectedInstead.withArguments('extends')); Token incorrectExtendsKeyword = token.next; token = computeType(incorrectExtendsKeyword, true) .ensureTypeNotVoid(incorrectExtendsKeyword, this); listener.handleClassExtends(incorrectExtendsKeyword); } else { token = parseClassExtendsOpt(token); } if (recoveryListener.extendsKeyword != null) { if (hasExtends) { reportRecoverableError( recoveryListener.extendsKeyword, fasta.messageMultipleExtends); } else { if (hasWith) { reportRecoverableError(recoveryListener.extendsKeyword, fasta.messageWithBeforeExtends); } else if (hasImplements) { reportRecoverableError(recoveryListener.extendsKeyword, fasta.messageImplementsBeforeExtends); } hasExtends = true; } } token = parseWithClauseOpt(token); if (recoveryListener.withKeyword != null) { if (hasWith) { reportRecoverableError( recoveryListener.withKeyword, fasta.messageMultipleWith); } else { if (hasImplements) { reportRecoverableError(recoveryListener.withKeyword, fasta.messageImplementsBeforeWith); } hasWith = true; } } token = parseClassOrMixinImplementsOpt(token); if (recoveryListener.implementsKeyword != null) { if (hasImplements) { reportRecoverableError(recoveryListener.implementsKeyword, fasta.messageMultipleImplements); } else { hasImplements = true; } } listener.handleRecoverClassHeader(); // Exit if a class body is detected, or if no progress has been made } while (!optional('{', token.next) && start != token); listener = primaryListener; return token; } Token parseClassExtendsOpt(Token token) { Token next = token.next; if (optional('extends', next)) { Token extendsKeyword = next; token = computeType(next, true).ensureTypeNotVoid(next, this); listener.handleClassExtends(extendsKeyword); } else { listener.handleNoType(token); listener.handleClassExtends(null); } return token; } /// ``` /// implementsClause: /// 'implements' typeName (',' typeName)* /// ; /// ``` Token parseClassOrMixinImplementsOpt(Token token) { Token implementsKeyword; int interfacesCount = 0; if (optional('implements', token.next)) { implementsKeyword = token.next; do { token = computeType(token.next, true).ensureTypeNotVoid(token.next, this); ++interfacesCount; } while (optional(',', token.next)); } listener.handleClassOrMixinImplements(implementsKeyword, interfacesCount); return token; } /// Parse a mixin declaration. /// /// ``` /// mixinDeclaration: /// metadata? 'mixin' [SimpleIdentifier] [TypeParameterList]? /// [OnClause]? [ImplementsClause]? '{' [ClassMember]* '}' /// ; /// ``` Token parseMixin(Token mixinKeyword) { assert(optional('mixin', mixinKeyword)); listener.beginClassOrNamedMixinApplicationPrelude(mixinKeyword); Token name = ensureIdentifier( mixinKeyword, IdentifierContext.classOrMixinOrExtensionDeclaration); Token headerStart = computeTypeParamOrArg(name, true, true).parseVariables(name, this); listener.beginMixinDeclaration(mixinKeyword, name); Token token = parseMixinHeaderOpt(headerStart, mixinKeyword); if (!optional('{', token.next)) { // Recovery token = parseMixinHeaderRecovery(token, mixinKeyword, headerStart); ensureBlock(token, null, 'mixin declaration'); } token = parseClassOrMixinOrExtensionBody( token, DeclarationKind.Mixin, name.lexeme); listener.endMixinDeclaration(mixinKeyword, token); return token; } Token parseMixinHeaderOpt(Token token, Token mixinKeyword) { token = parseMixinOnOpt(token); token = parseClassOrMixinImplementsOpt(token); listener.handleMixinHeader(mixinKeyword); return token; } Token parseMixinHeaderRecovery( Token token, Token mixinKeyword, Token headerStart) { final Listener primaryListener = listener; final MixinHeaderRecoveryListener recoveryListener = new MixinHeaderRecoveryListener(); // Reparse to determine which clauses have already been parsed // but intercept the events so they are not sent to the primary listener. listener = recoveryListener; token = parseMixinHeaderOpt(headerStart, mixinKeyword); bool hasOn = recoveryListener.onKeyword != null; bool hasImplements = recoveryListener.implementsKeyword != null; // Update the recovery listener to forward subsequent events // to the primary listener. recoveryListener.listener = primaryListener; // Parse additional out-of-order clauses Token start; do { start = token; // Check for extraneous token in the middle of a class header. token = skipUnexpectedTokenOpt( token, const <String>['on', 'implements', '{']); // During recovery, clauses are parsed in the same order and // generate the same events as in the parseMixinHeaderOpt method above. recoveryListener.clear(); if (token.next.isKeywordOrIdentifier && const ['extend', 'extends'].contains(token.next.lexeme)) { reportRecoverableError( token.next, fasta.templateExpectedInstead.withArguments('on')); token = parseMixinOn(token); } else { token = parseMixinOnOpt(token); } if (recoveryListener.onKeyword != null) { if (hasOn) { reportRecoverableError( recoveryListener.onKeyword, fasta.messageMultipleOnClauses); } else { if (hasImplements) { reportRecoverableError( recoveryListener.onKeyword, fasta.messageImplementsBeforeOn); } hasOn = true; } } token = parseClassOrMixinImplementsOpt(token); if (recoveryListener.implementsKeyword != null) { if (hasImplements) { reportRecoverableError(recoveryListener.implementsKeyword, fasta.messageMultipleImplements); } else { hasImplements = true; } } listener.handleRecoverMixinHeader(); // Exit if a mixin body is detected, or if no progress has been made } while (!optional('{', token.next) && start != token); listener = primaryListener; return token; } /// ``` /// onClause: /// 'on' typeName (',' typeName)* /// ; /// ``` Token parseMixinOnOpt(Token token) { if (!optional('on', token.next)) { listener.handleMixinOn(null, 0); return token; } return parseMixinOn(token); } Token parseMixinOn(Token token) { Token onKeyword = token.next; // During recovery, the [onKeyword] can be "extend" or "extends" assert(optional('on', onKeyword) || optional('extends', onKeyword) || onKeyword.lexeme == 'extend'); int typeCount = 0; do { token = computeType(token.next, true).ensureTypeNotVoid(token.next, this); ++typeCount; } while (optional(',', token.next)); listener.handleMixinOn(onKeyword, typeCount); return token; } /// ``` /// 'extension' <identifier>? <typeParameters>? 'on' <type> '?'? // `{' // <memberDeclaration>* // `}' /// ``` Token parseExtension(Token extensionKeyword) { assert(optional('extension', extensionKeyword)); Token token = extensionKeyword; listener.beginExtensionDeclarationPrelude(extensionKeyword); Token name = token.next; if (name.isIdentifier && !optional('on', name)) { token = name; } else { name = null; } token = computeTypeParamOrArg(token, true).parseVariables(token, this); listener.beginExtensionDeclaration(extensionKeyword, name); Token onKeyword = token.next; if (!optional('on', onKeyword)) { // Recovery if (optional('extends', onKeyword) || optional('implements', onKeyword) || optional('with', onKeyword)) { reportRecoverableError( onKeyword, fasta.templateExpectedInstead.withArguments('on')); } else { reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('on')); onKeyword = rewriter.insertSyntheticKeyword(token, Keyword.ON); } } TypeInfo typeInfo = computeType(onKeyword, true); token = typeInfo.ensureTypeOrVoid(onKeyword, this); if (!optional('{', token.next)) { // Recovery Token next = token.next; while (!next.isEof) { if (optional(',', next) || optional('extends', next) || optional('implements', next) || optional('on', next) || optional('with', next)) { // Report an error and skip `,` or specific keyword // optionally followed by an identifier reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); token = next; next = token.next; if (next.isIdentifier) { token = next; next = token.next; } } else { break; } } ensureBlock(token, null, 'extension declaration'); } token = parseClassOrMixinOrExtensionBody( token, DeclarationKind.Extension, name?.lexeme); listener.endExtensionDeclaration(extensionKeyword, onKeyword, token); return token; } Token parseStringPart(Token token) { Token next = token.next; if (next.kind != STRING_TOKEN) { reportRecoverableErrorWithToken(next, fasta.templateExpectedString); next = rewriter.insertToken(token, new SyntheticStringToken(TokenType.STRING, '', next.charOffset)); } listener.handleStringPart(next); return next; } /// Insert a synthetic identifier after the given [token] and create an error /// message based on the given [context]. Return the synthetic identifier that /// was inserted. Token insertSyntheticIdentifier(Token token, IdentifierContext context, {Message message, Token messageOnToken}) { Token next = token.next; reportRecoverableError(messageOnToken ?? next, message ?? context.recoveryTemplate.withArguments(next)); return rewriter.insertSyntheticIdentifier(token); } /// Parse a simple identifier at the given [token], and return the identifier /// that was parsed. /// /// If the token is not an identifier, or is not appropriate for use as an /// identifier in the given [context], create a synthetic identifier, report /// an error, and return the synthetic identifier. Token ensureIdentifier(Token token, IdentifierContext context) { assert(context != null); Token identifier = token.next; if (identifier.kind != IDENTIFIER_TOKEN) { identifier = context.ensureIdentifier(token, this); assert(identifier != null); assert(identifier.isKeywordOrIdentifier); } listener.handleIdentifier(identifier, context); return identifier; } bool notEofOrValue(String value, Token token) { return !identical(token.kind, EOF_TOKEN) && !identical(value, token.stringValue); } Token parseTypeVariablesOpt(Token token) { return computeTypeParamOrArg(token, true).parseVariables(token, this); } /// Parse a top level field or function. /// /// This method is only invoked from outside the parser. As a result, this /// method takes the next token to be consumed rather than the last consumed /// token and returns the token after the last consumed token rather than the /// last consumed token. Token parseTopLevelMember(Token token) { token = parseMetadataStar(syntheticPreviousToken(token)); return parseTopLevelMemberImpl(token).next; } Token parseTopLevelMemberImpl(Token token) { Token beforeStart = token; Token next = token.next; listener.beginTopLevelMember(next); Token externalToken; Token lateToken; Token varFinalOrConst; if (isModifier(next)) { if (optional('external', next)) { externalToken = token = next; next = token.next; } if (isModifier(next)) { if (optional('final', next)) { varFinalOrConst = token = next; next = token.next; } else if (optional('var', next)) { varFinalOrConst = token = next; next = token.next; } else if (optional('const', next)) { varFinalOrConst = token = next; next = token.next; } else if (optional('late', next)) { lateToken = token = next; next = token.next; if (isModifier(next) && optional('final', next)) { varFinalOrConst = token = next; next = token.next; } } if (isModifier(next)) { // Recovery if (varFinalOrConst != null && (optional('final', next) || optional('var', next) || optional('const', next))) { // If another `var`, `final`, or `const` then fall through // to parse that as part of the next top level declaration. } else { ModifierRecoveryContext context = new ModifierRecoveryContext(this) ..externalToken = externalToken ..lateToken = lateToken ..varFinalOrConst = varFinalOrConst; token = context.parseTopLevelModifiers(token); next = token.next; externalToken = context.externalToken; lateToken = context.lateToken; varFinalOrConst = context.varFinalOrConst; context = null; } } } } Token beforeType = token; TypeInfo typeInfo = computeType(token, false, true); token = typeInfo.skipType(token); next = token.next; Token getOrSet; String value = next.stringValue; if (identical(value, 'get') || identical(value, 'set')) { if (next.next.isIdentifier) { getOrSet = token = next; next = token.next; } } if (next.type != TokenType.IDENTIFIER) { value = next.stringValue; if (identical(value, 'factory') || identical(value, 'operator')) { // `factory` and `operator` can be used as an identifier. value = next.next.stringValue; if (getOrSet == null && !identical(value, '(') && !identical(value, '{') && !identical(value, '<') && !identical(value, '=>') && !identical(value, '=') && !identical(value, ';') && !identical(value, ',')) { // Recovery value = next.stringValue; if (identical(value, 'factory')) { reportRecoverableError( next, fasta.messageFactoryTopLevelDeclaration); } else { reportRecoverableError(next, fasta.messageTopLevelOperator); if (next.next.isOperator) { token = next; next = token.next; if (optional('(', next.next)) { rewriter.insertSyntheticIdentifier( next, '#synthetic_identifier_${next.charOffset}'); } } } listener.handleInvalidTopLevelDeclaration(next); return next; } // Fall through and continue parsing } else if (!next.isIdentifier) { // Recovery if (next.isKeyword) { // Fall through to parse the keyword as the identifier. // ensureIdentifier will report the error. } else if (token == beforeStart) { // Ensure we make progress. return parseInvalidTopLevelDeclaration(token); } else { // Looks like a declaration missing an identifier. // Insert synthetic identifier and fall through. insertSyntheticIdentifier(token, IdentifierContext.methodDeclaration); next = token.next; } } } // At this point, `token` is beforeName. next = next.next; value = next.stringValue; if (getOrSet != null || identical(value, '(') || identical(value, '{') || identical(value, '<') || identical(value, '.') || identical(value, '=>')) { if (varFinalOrConst != null) { if (optional('var', varFinalOrConst)) { reportRecoverableError(varFinalOrConst, fasta.messageVarReturnType); } else { reportRecoverableErrorWithToken( varFinalOrConst, fasta.templateExtraneousModifier); } } else if (lateToken != null) { reportRecoverableErrorWithToken( lateToken, fasta.templateExtraneousModifier); } return parseTopLevelMethod(beforeStart, externalToken, beforeType, typeInfo, getOrSet, token.next); } if (getOrSet != null) { reportRecoverableErrorWithToken( getOrSet, fasta.templateExtraneousModifier); } return parseFields( beforeStart, externalToken, null, null, lateToken, varFinalOrConst, beforeType, typeInfo, token.next, DeclarationKind.TopLevel); } Token parseFields( Token beforeStart, Token externalToken, Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, Token beforeType, TypeInfo typeInfo, Token name, DeclarationKind kind) { if (externalToken != null) { reportRecoverableError(externalToken, fasta.messageExternalField); } if (covariantToken != null) { if (varFinalOrConst != null && optional('final', varFinalOrConst)) { reportRecoverableError(covariantToken, fasta.messageFinalAndCovariant); covariantToken = null; } } if (typeInfo == noType) { if (varFinalOrConst == null && lateToken == null) { reportRecoverableError(name, fasta.messageMissingConstFinalVarOrType); } } else { if (varFinalOrConst != null && optional('var', varFinalOrConst)) { reportRecoverableError(varFinalOrConst, fasta.messageTypeAfterVar); } } Token token = typeInfo.parseType(beforeType, this); assert(token.next == name); IdentifierContext context = kind == DeclarationKind.TopLevel ? IdentifierContext.topLevelVariableDeclaration : IdentifierContext.fieldDeclaration; Token firstName = name = ensureIdentifier(token, context); int fieldCount = 1; token = parseFieldInitializerOpt(name, name, lateToken, varFinalOrConst, kind); while (optional(',', token.next)) { name = ensureIdentifier(token.next, context); token = parseFieldInitializerOpt( name, name, lateToken, varFinalOrConst, kind); ++fieldCount; } Token semicolon = token.next; if (optional(';', semicolon)) { token = semicolon; } else { // Recovery if (kind == DeclarationKind.TopLevel && beforeType.next.isIdentifier && beforeType.next.lexeme == 'extension') { // Looks like an extension method // TODO(danrubel): Remove when extension methods are enabled by default // because then 'extension' will be interpreted as a built-in // and this code will never be executed reportRecoverableError( beforeType.next, fasta.templateExperimentNotEnabled .withArguments('extension-methods')); token = rewriter.insertSyntheticToken(token, TokenType.SEMICOLON); } else { token = ensureSemicolon(token); } } switch (kind) { case DeclarationKind.TopLevel: listener.endTopLevelFields(staticToken, covariantToken, lateToken, varFinalOrConst, fieldCount, beforeStart.next, token); break; case DeclarationKind.Class: listener.endClassFields(staticToken, covariantToken, lateToken, varFinalOrConst, fieldCount, beforeStart.next, token); break; case DeclarationKind.Mixin: listener.endMixinFields(staticToken, covariantToken, lateToken, varFinalOrConst, fieldCount, beforeStart.next, token); break; case DeclarationKind.Extension: if (staticToken == null) { reportRecoverableError( firstName, fasta.messageExtensionDeclaresInstanceField); } listener.endExtensionFields(staticToken, covariantToken, lateToken, varFinalOrConst, fieldCount, beforeStart.next, token); break; } return token; } Token parseTopLevelMethod(Token beforeStart, Token externalToken, Token beforeType, TypeInfo typeInfo, Token getOrSet, Token name) { listener.beginTopLevelMethod(beforeStart, externalToken); Token token = typeInfo.parseType(beforeType, this); assert(token.next == (getOrSet ?? name)); name = ensureIdentifier( getOrSet ?? token, IdentifierContext.topLevelFunctionDeclaration); bool isGetter = false; if (getOrSet == null) { token = parseMethodTypeVar(name); } else { isGetter = optional("get", getOrSet); token = name; listener.handleNoTypeVariables(token.next); } token = parseGetterOrFormalParameters( token, name, isGetter, MemberKind.TopLevelMethod); AsyncModifier savedAsyncModifier = asyncState; Token asyncToken = token.next; token = parseAsyncModifierOpt(token); if (getOrSet != null && !inPlainSync && optional("set", getOrSet)) { reportRecoverableError(asyncToken, fasta.messageSetterNotSync); } bool isExternal = externalToken != null; if (isExternal && !optional(';', token.next)) { reportRecoverableError( externalToken, fasta.messageExternalMethodWithBody); } token = parseFunctionBody(token, false, isExternal); asyncState = savedAsyncModifier; listener.endTopLevelMethod(beforeStart.next, getOrSet, token); return token; } Token parseMethodTypeVar(Token name) { if (!optional('<', name.next)) { return noTypeParamOrArg.parseVariables(name, this); } TypeParamOrArgInfo typeVar = computeTypeParamOrArg(name, true); Token token = typeVar.parseVariables(name, this); if (optional('=', token.next)) { // Recovery token = token.next; reportRecoverableErrorWithToken(token, fasta.templateUnexpectedToken); } return token; } Token parseFieldInitializerOpt(Token token, Token name, Token lateToken, Token varFinalOrConst, DeclarationKind kind) { Token next = token.next; if (optional('=', next)) { Token assignment = next; listener.beginFieldInitializer(next); token = parseExpression(next); listener.endFieldInitializer(assignment, token.next); } else { if (varFinalOrConst != null && !name.isSynthetic) { if (optional("const", varFinalOrConst)) { reportRecoverableError( name, fasta.templateConstFieldWithoutInitializer .withArguments(name.lexeme)); } else if (kind == DeclarationKind.TopLevel && optional("final", varFinalOrConst) && lateToken == null) { reportRecoverableError( name, fasta.templateFinalFieldWithoutInitializer .withArguments(name.lexeme)); } } listener.handleNoFieldInitializer(token.next); } return token; } Token parseVariableInitializerOpt(Token token) { if (optional('=', token.next)) { Token assignment = token.next; listener.beginVariableInitializer(assignment); token = parseExpression(assignment); listener.endVariableInitializer(assignment); } else { listener.handleNoVariableInitializer(token.next); } return token; } Token parseInitializersOpt(Token token) { if (optional(':', token.next)) { return parseInitializers(token.next); } else { listener.handleNoInitializers(); return token; } } /// ``` /// initializers: /// ':' initializerListEntry (',' initializerListEntry)* /// ; /// ``` Token parseInitializers(Token token) { Token begin = token; assert(optional(':', begin)); listener.beginInitializers(begin); int count = 0; bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = false; Token next = begin; while (true) { token = parseInitializer(next); ++count; next = token.next; if (!optional(',', next)) { // Recovery: Found an identifier which could be // 1) missing preceding `,` thus it's another initializer, or // 2) missing preceding `;` thus it's a class member, or // 3) missing preceding '{' thus it's a statement if (optional('assert', next)) { next = next.next; if (!optional('(', next)) { break; } // Looks like assert expression ... fall through to insert comma } else if (!next.isIdentifier && !optional('this', next)) { // An identifier that wasn't an initializer. Break. break; } else { if (optional('this', next)) { next = next.next; if (!optional('.', next)) { break; } next = next.next; if (!next.isIdentifier && !optional('assert', next)) { break; } } next = next.next; if (!optional('=', next)) { break; } // Looks like field assignment... fall through to insert comma } // TODO(danrubel): Consider enhancing this to indicate that we are // expecting one of `,` or `;` or `{` reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments(',')); next = rewriter.insertSyntheticToken(token, TokenType.COMMA); } } mayParseFunctionExpressions = old; listener.endInitializers(count, begin, token.next); return token; } /// ``` /// initializerListEntry: /// 'super' ('.' identifier)? arguments | /// fieldInitializer | /// assertion /// ; /// /// fieldInitializer: /// ('this' '.')? identifier '=' conditionalExpression cascadeSection* /// ; /// ``` Token parseInitializer(Token token) { Token next = token.next; listener.beginInitializer(next); Token beforeExpression = token; if (optional('assert', next)) { token = parseAssert(token, Assert.Initializer); listener.endInitializer(token.next); return token; } else if (optional('super', next)) { return parseSuperInitializerExpression(token); } else if (optional('this', next)) { token = next; next = token.next; if (optional('.', next)) { token = next; next = token.next; if (next.isIdentifier) { token = next; } else { // Recovery token = insertSyntheticIdentifier( token, IdentifierContext.fieldInitializer); } next = token.next; if (optional('=', next)) { return parseInitializerExpressionRest(beforeExpression); } } if (optional('(', next)) { token = parseInitializerExpressionRest(beforeExpression); next = token.next; if (optional('{', next) || optional('=>', next)) { reportRecoverableError( next, fasta.messageRedirectingConstructorWithBody); } return token; } // Recovery if (optional('this', token)) { // TODO(danrubel): Consider a better error message indicating that // `this.<fieldname>=` is expected. reportRecoverableError( next, fasta.templateExpectedButGot.withArguments('.')); rewriter.insertSyntheticToken(token, TokenType.PERIOD); token = rewriter.insertSyntheticIdentifier(token.next); next = token.next; } // Fall through to recovery } else if (next.isIdentifier) { Token next2 = next.next; if (optional('=', next2)) { return parseInitializerExpressionRest(token); } // Recovery: If this looks like an expression, // then fall through to insert the LHS and `=` of the assignment, // otherwise insert an `=` and synthetic identifier. if (!next2.isOperator && !optional('.', next2)) { token = rewriter.insertSyntheticToken(next, TokenType.EQ); token = insertSyntheticIdentifier(token, IdentifierContext.expression, message: fasta.messageMissingAssignmentInInitializer, messageOnToken: next); return parseInitializerExpressionRest(beforeExpression); } } else { // Recovery: Insert a synthetic assignment. token = insertSyntheticIdentifier( token, IdentifierContext.fieldInitializer, message: fasta.messageExpectedAnInitializer, messageOnToken: token); token = rewriter.insertSyntheticToken(token, TokenType.EQ); token = rewriter.insertSyntheticIdentifier(token); return parseInitializerExpressionRest(beforeExpression); } // Recovery: // Insert a synthetic identifier and assignment operator // to ensure that the expression is indeed an assignment. // Failing to do so causes this test to fail: // pkg/front_end/testcases/regress/issue_31192.dart // TODO(danrubel): Investigate better recovery. token = insertSyntheticIdentifier( beforeExpression, IdentifierContext.fieldInitializer, message: fasta.messageMissingAssignmentInInitializer); rewriter.insertSyntheticToken(token, TokenType.EQ); return parseInitializerExpressionRest(beforeExpression); } /// Parse the `super` initializer: /// ``` /// 'super' ('.' identifier)? arguments ; /// ``` Token parseSuperInitializerExpression(final Token start) { Token token = start.next; assert(optional('super', token)); Token next = token.next; if (optional('.', next)) { token = next; next = token.next; if (next.kind != IDENTIFIER_TOKEN) { next = IdentifierContext.expressionContinuation .ensureIdentifier(token, this); } token = next; next = token.next; } if (!optional('(', next)) { // Recovery if (optional('?.', next)) { // An error for `super?.` is reported in parseSuperExpression. token = next; next = token.next; if (!next.isIdentifier) { // Insert a synthetic identifier but don't report another error. next = rewriter.insertSyntheticIdentifier(token); } token = next; next = token.next; } if (optional('=', next)) { if (optional('super', token)) { // parseExpression will report error on assignment to super } else { reportRecoverableError( token, fasta.messageFieldInitializedOutsideDeclaringClass); } } else if (!optional('(', next)) { reportRecoverableError( next, fasta.templateExpectedAfterButGot.withArguments('(')); rewriter.insertParens(token, false); } } return parseInitializerExpressionRest(start); } Token parseInitializerExpressionRest(Token token) { token = parseExpression(token); listener.endInitializer(token.next); return token; } /// If the next token is an opening curly brace, return it. Otherwise, use the /// given [template] or [blockKind] to report an error, insert an opening and /// a closing curly brace, and return the newly inserted opening curly brace. /// If [template] and [blockKind] are `null`, then use /// a default error message instead. Token ensureBlock(Token token, Template<Message Function(Token token)> template, String blockKind) { Token next = token.next; if (optional('{', next)) return next; if (template == null) { if (blockKind == null) { // TODO(danrubel): rename ExpectedButGot to ExpectedBefore reportRecoverableError( next, fasta.templateExpectedButGot.withArguments('{')); } else { // TODO(danrubel): rename ExpectedClassOrMixinBody // to ExpectedDeclarationOrClauseBody reportRecoverableError(token, fasta.templateExpectedClassOrMixinBody.withArguments(blockKind)); } } else { reportRecoverableError(next, template.withArguments(next)); } return insertBlock(token); } Token insertBlock(Token token) { Token next = token.next; BeginToken beginGroup = rewriter.insertToken(token, new SyntheticBeginToken(TokenType.OPEN_CURLY_BRACKET, next.offset)); Token endGroup = rewriter.insertToken(beginGroup, new SyntheticToken(TokenType.CLOSE_CURLY_BRACKET, next.offset)); beginGroup.endGroup = endGroup; return beginGroup; } /// If the next token is a closing parenthesis, return it. /// Otherwise, report an error and return the closing parenthesis /// associated with the specified open parenthesis. Token ensureCloseParen(Token token, Token openParen) { Token next = token.next; if (optional(')', next)) { return next; } if (openParen.endGroup.isSynthetic) { // Scanner has already reported a missing `)` error, // but placed the `)` in the wrong location, so move it. return rewriter.moveSynthetic(token, openParen.endGroup); } // TODO(danrubel): Pass in context for better error message. reportRecoverableError( next, fasta.templateExpectedButGot.withArguments(')')); // Scanner guarantees a closing parenthesis // TODO(danrubel): Improve recovery by having callers parse tokens // between `token` and `openParen.endGroup`. return openParen.endGroup; } /// If the next token is a colon, return it. Otherwise, report an /// error, insert a synthetic colon, and return the inserted colon. Token ensureColon(Token token) { Token next = token.next; if (optional(':', next)) return next; Message message = fasta.templateExpectedButGot.withArguments(':'); Token newToken = new SyntheticToken(TokenType.COLON, next.charOffset); return rewriteAndRecover(token, message, newToken); } /// If the token after [token] is a not literal string, /// then insert a synthetic literal string. /// Call `parseLiteralString` and return the result. Token ensureLiteralString(Token token) { Token next = token.next; if (!identical(next.kind, STRING_TOKEN)) { Message message = fasta.templateExpectedString.withArguments(next); Token newToken = new SyntheticStringToken(TokenType.STRING, '""', next.charOffset, 0); rewriteAndRecover(token, message, newToken); } return parseLiteralString(token); } /// If the token after [token] is a semi-colon, return it. /// Otherwise, report an error, insert a synthetic semi-colon, /// and return the inserted semi-colon. Token ensureSemicolon(Token token) { // TODO(danrubel): Once all expect(';'...) call sites have been converted // to use this method, remove similar semicolon recovery code // from the handleError method in element_listener.dart. Token next = token.next; if (optional(';', next)) return next; // Find a token on the same line as where the ';' should be inserted. // Reporting the error on this token makes it easier // for users to understand and fix the error. reportRecoverableError(findPreviousNonZeroLengthToken(token), fasta.templateExpectedAfterButGot.withArguments(';')); return rewriter.insertSyntheticToken(token, TokenType.SEMICOLON); } /// Report an error at the token after [token] that has the given [message]. /// Insert the [newToken] after [token] and return [newToken]. Token rewriteAndRecover(Token token, Message message, Token newToken) { reportRecoverableError(token.next, message); return rewriter.insertToken(token, newToken); } /// Replace the token after [token] with `[` followed by `]` /// and return [token]. Token rewriteSquareBrackets(Token token) { Token next = token.next; assert(optional('[]', next)); Token replacement = link( new BeginToken(TokenType.OPEN_SQUARE_BRACKET, next.offset), new Token(TokenType.CLOSE_SQUARE_BRACKET, next.offset + 1)); rewriter.replaceTokenFollowing(token, replacement); return token; } /// Report the given token as unexpected and return the next token if the next /// token is one of the [expectedNext], otherwise just return the given token. Token skipUnexpectedTokenOpt(Token token, List<String> expectedNext) { Token next = token.next; if (next.keyword == null) { final String nextValue = next.next.stringValue; for (String expectedValue in expectedNext) { if (identical(nextValue, expectedValue)) { reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); return next; } } } return token; } Token parseNativeClause(Token token) { Token nativeToken = token = token.next; assert(optional('native', nativeToken)); bool hasName = false; if (token.next.kind == STRING_TOKEN) { hasName = true; token = parseLiteralString(token); } listener.handleNativeClause(nativeToken, hasName); reportRecoverableError( nativeToken, fasta.messageNativeClauseShouldBeAnnotation); return token; } Token skipClassOrMixinOrExtensionBody(Token token) { // The scanner ensures that `{` always has a closing `}`. return ensureBlock(token, null, null); } /// ``` /// classBody: /// '{' classMember* '}' /// ; /// ``` Token parseClassOrMixinOrExtensionBody( Token token, DeclarationKind kind, String enclosingDeclarationName) { Token begin = token = token.next; assert(optional('{', token)); listener.beginClassOrMixinBody(kind, token); int count = 0; while (notEofOrValue('}', token.next)) { token = parseClassOrMixinOrExtensionMemberImpl( token, kind, enclosingDeclarationName); ++count; } token = token.next; assert(optional('}', token)); listener.endClassOrMixinBody(kind, count, begin, token); return token; } bool isUnaryMinus(Token token) => token.kind == IDENTIFIER_TOKEN && token.lexeme == 'unary' && optional('-', token.next); /// Parse a class member. /// /// This method is only invoked from outside the parser. As a result, this /// method takes the next token to be consumed rather than the last consumed /// token and returns the token after the last consumed token rather than the /// last consumed token. Token parseClassMember(Token token, String className) { return parseClassOrMixinOrExtensionMemberImpl( syntheticPreviousToken(token), DeclarationKind.Class, className) .next; } /// Parse a mixin member. /// /// This method is only invoked from outside the parser. As a result, this /// method takes the next token to be consumed rather than the last consumed /// token and returns the token after the last consumed token rather than the /// last consumed token. Token parseMixinMember(Token token, String mixinName) { return parseClassOrMixinOrExtensionMemberImpl( syntheticPreviousToken(token), DeclarationKind.Mixin, mixinName) .next; } /// Parse an extension member. /// /// This method is only invoked from outside the parser. As a result, this /// method takes the next token to be consumed rather than the last consumed /// token and returns the token after the last consumed token rather than the /// last consumed token. Token parseExtensionMember(Token token, String extensionName) { return parseClassOrMixinOrExtensionMemberImpl(syntheticPreviousToken(token), DeclarationKind.Extension, extensionName) .next; } /// ``` /// classMember: /// fieldDeclaration | /// constructorDeclaration | /// methodDeclaration /// ; /// /// mixinMember: /// fieldDeclaration | /// methodDeclaration /// ; /// /// extensionMember: /// staticFieldDeclaration | /// methodDeclaration /// ; /// ``` Token parseClassOrMixinOrExtensionMemberImpl( Token token, DeclarationKind kind, String enclosingDeclarationName) { Token beforeStart = token = parseMetadataStar(token); Token covariantToken; Token externalToken; Token lateToken; Token staticToken; Token varFinalOrConst; Token next = token.next; if (isModifier(next)) { if (optional('external', next)) { externalToken = token = next; next = token.next; } if (isModifier(next)) { if (optional('static', next)) { staticToken = token = next; next = token.next; } else if (optional('covariant', next)) { covariantToken = token = next; next = token.next; } if (isModifier(next)) { if (optional('final', next)) { varFinalOrConst = token = next; next = token.next; } else if (optional('var', next)) { varFinalOrConst = token = next; next = token.next; } else if (optional('const', next) && covariantToken == null) { varFinalOrConst = token = next; next = token.next; } else if (optional('late', next)) { lateToken = token = next; next = token.next; if (isModifier(next) && optional('final', next)) { varFinalOrConst = token = next; next = token.next; } } if (isModifier(next)) { ModifierRecoveryContext context = new ModifierRecoveryContext(this) ..covariantToken = covariantToken ..externalToken = externalToken ..lateToken = lateToken ..staticToken = staticToken ..varFinalOrConst = varFinalOrConst; token = context.parseClassMemberModifiers(token); next = token.next; covariantToken = context.covariantToken; externalToken = context.externalToken; lateToken = context.lateToken; staticToken = context.staticToken; varFinalOrConst = context.varFinalOrConst; context = null; } } } } listener.beginMember(); Token beforeType = token; TypeInfo typeInfo = computeType(token, false, true); token = typeInfo.skipType(token); next = token.next; Token getOrSet; if (next.type != TokenType.IDENTIFIER) { String value = next.stringValue; if (identical(value, 'get') || identical(value, 'set')) { if (next.next.isIdentifier) { getOrSet = token = next; next = token.next; } // Fall through to continue parsing `get` or `set` as an identifier. } else if (identical(value, 'factory')) { Token next2 = next.next; if (next2.isIdentifier || next2.isModifier) { if (beforeType != token) { reportRecoverableError(token, fasta.messageTypeBeforeFactory); } token = parseFactoryMethod(token, kind, beforeStart, externalToken, staticToken ?? covariantToken, varFinalOrConst); listener.endMember(); return token; } // Fall through to continue parsing `factory` as an identifier. } else if (identical(value, 'operator')) { Token next2 = next.next; TypeParamOrArgInfo typeParam = computeTypeParamOrArg(next); // `operator` can be used as an identifier as in // `int operator<T>()` or `int operator = 2` if (next2.isUserDefinableOperator && typeParam == noTypeParamOrArg) { token = parseMethod( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, getOrSet, token.next, kind, enclosingDeclarationName); listener.endMember(); return token; } else if (optional('===', next2) || optional('!==', next2) || (next2.isOperator && !optional('=', next2) && !optional('<', next2))) { // Recovery: Invalid operator return parseInvalidOperatorDeclaration( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, kind); } else if (isUnaryMinus(next2)) { // Recovery token = parseMethod( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, getOrSet, token.next, kind, enclosingDeclarationName); listener.endMember(); return token; } // Fall through to continue parsing `operator` as an identifier. } else if (!next.isIdentifier || (identical(value, 'typedef') && token == beforeStart && next.next.isIdentifier)) { // Recovery return recoverFromInvalidMember( token, beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, getOrSet, kind, enclosingDeclarationName); } } else if (typeInfo == noType && varFinalOrConst == null) { Token next2 = next.next; if (next2.isUserDefinableOperator && next2.endGroup == null) { String value = next2.next.stringValue; if (identical(value, '(') || identical(value, '{') || identical(value, '=>')) { // Recovery: Missing `operator` keyword return parseInvalidOperatorDeclaration( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, kind); } } } // At this point, token is before the name, and next is the name next = next.next; String value = next.stringValue; if (getOrSet != null || identical(value, '(') || identical(value, '{') || identical(value, '<') || identical(value, '.') || identical(value, '=>')) { token = parseMethod( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, getOrSet, token.next, kind, enclosingDeclarationName); } else { if (getOrSet != null) { reportRecoverableErrorWithToken( getOrSet, fasta.templateExtraneousModifier); } token = parseFields( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, token.next, kind); } listener.endMember(); return token; } Token parseMethod( Token beforeStart, Token externalToken, Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, Token beforeType, TypeInfo typeInfo, Token getOrSet, Token name, DeclarationKind kind, String enclosingDeclarationName) { if (lateToken != null) { reportRecoverableErrorWithToken( lateToken, fasta.templateExtraneousModifier); } bool isOperator = false; if (getOrSet == null && optional('operator', name)) { Token operator = name.next; if (operator.isOperator || identical(operator.kind, EQ_EQ_EQ_TOKEN) || identical(operator.kind, BANG_EQ_EQ_TOKEN) || isUnaryMinus(operator)) { isOperator = true; } } if (staticToken != null) { if (isOperator) { reportRecoverableError(staticToken, fasta.messageStaticOperator); staticToken = null; } } else if (covariantToken != null) { if (getOrSet == null || optional('get', getOrSet)) { reportRecoverableError(covariantToken, fasta.messageCovariantMember); covariantToken = null; } } if (varFinalOrConst != null) { if (optional('const', varFinalOrConst)) { if (getOrSet != null) { reportRecoverableErrorWithToken( varFinalOrConst, fasta.templateExtraneousModifier); varFinalOrConst = null; } } else if (optional('var', varFinalOrConst)) { reportRecoverableError(varFinalOrConst, fasta.messageVarReturnType); varFinalOrConst = null; } else { assert(optional('final', varFinalOrConst)); reportRecoverableErrorWithToken( varFinalOrConst, fasta.templateExtraneousModifier); varFinalOrConst = null; } } // TODO(danrubel): Consider parsing the name before calling beginMethod // rather than passing the name token into beginMethod. listener.beginMethod(externalToken, staticToken, covariantToken, varFinalOrConst, getOrSet, name); Token token = typeInfo.parseType(beforeType, this); assert(token.next == (getOrSet ?? name)); token = getOrSet ?? token; if (isOperator) { token = parseOperatorName(token); } else { token = ensureIdentifier(token, IdentifierContext.methodDeclaration); if (getOrSet == null) { token = parseQualifiedRestOpt( token, IdentifierContext.methodDeclarationContinuation); } } bool isGetter = false; if (getOrSet == null) { token = parseMethodTypeVar(token); } else { isGetter = optional("get", getOrSet); listener.handleNoTypeVariables(token.next); } Token beforeParam = token; Token beforeInitializers = parseGetterOrFormalParameters( token, name, isGetter, staticToken != null ? MemberKind.StaticMethod : MemberKind.NonStaticMethod); token = parseInitializersOpt(beforeInitializers); if (token == beforeInitializers) beforeInitializers = null; AsyncModifier savedAsyncModifier = asyncState; Token asyncToken = token.next; token = parseAsyncModifierOpt(token); if (getOrSet != null && !inPlainSync && optional("set", getOrSet)) { reportRecoverableError(asyncToken, fasta.messageSetterNotSync); } final Token bodyStart = token.next; if (externalToken != null) { if (!optional(';', bodyStart)) { reportRecoverableError(bodyStart, fasta.messageExternalMethodWithBody); } } if (optional('=', bodyStart)) { reportRecoverableError(bodyStart, fasta.messageRedirectionInNonFactory); token = parseRedirectingFactoryBody(token); } else { token = parseFunctionBody(token, false, (staticToken == null || externalToken != null) && inPlainSync); } asyncState = savedAsyncModifier; bool isConstructor = false; if (optional('.', name.next) || beforeInitializers != null) { isConstructor = true; if (name.lexeme != enclosingDeclarationName) { // Recovery: The name does not match, // but the name is prefixed or the declaration contains initializers. // Report an error and continue with invalid name. // TODO(danrubel): report invalid constructor name // Currently multiple listeners report this error, but that logic should // be removed and the error reported here instead. } if (getOrSet != null) { // Recovery if (optional('.', name.next)) { // Unexpected get/set before constructor. // Report an error and skip over the token. // TODO(danrubel): report an error on get/set token // This is currently reported by listeners other than AstBuilder. // It should be reported here rather than in the listeners. } else { isConstructor = false; if (beforeInitializers != null) { // Unexpected initializers after get/set declaration. // Report an error on the initializers // and continue with the get/set declaration. // TODO(danrubel): report invalid initializers error // Currently multiple listeners report this error, but that logic // should be removed and the error reported here instead. } } } } else if (name.lexeme == enclosingDeclarationName) { if (getOrSet != null) { // Recovery: The get/set member name is invalid. // Report an error and continue with invalid name. // TODO(danrubel): report invalid get/set member name // Currently multiple listeners report this error, but that logic should // be removed and the error reported here instead. } else { isConstructor = true; } } if (isConstructor) { // // constructor // if (staticToken != null) { reportRecoverableError(staticToken, fasta.messageStaticConstructor); } switch (kind) { case DeclarationKind.Class: // TODO(danrubel): Remove getOrSet from constructor events listener.endClassConstructor(getOrSet, beforeStart.next, beforeParam.next, beforeInitializers?.next, token); break; case DeclarationKind.Mixin: reportRecoverableError(name, fasta.messageMixinDeclaresConstructor); listener.endMixinConstructor(getOrSet, beforeStart.next, beforeParam.next, beforeInitializers?.next, token); break; case DeclarationKind.Extension: reportRecoverableError( name, fasta.messageExtensionDeclaresConstructor); listener.endExtensionConstructor(getOrSet, beforeStart.next, beforeParam.next, beforeInitializers?.next, token); break; case DeclarationKind.TopLevel: throw "Internal error: TopLevel constructor."; break; } } else { // // method // if (varFinalOrConst != null) { assert(optional('const', varFinalOrConst)); reportRecoverableError(varFinalOrConst, fasta.messageConstMethod); } switch (kind) { case DeclarationKind.Class: // TODO(danrubel): Remove beginInitializers token from method events listener.endClassMethod(getOrSet, beforeStart.next, beforeParam.next, beforeInitializers?.next, token); break; case DeclarationKind.Mixin: listener.endMixinMethod(getOrSet, beforeStart.next, beforeParam.next, beforeInitializers?.next, token); break; case DeclarationKind.Extension: if (optional(';', bodyStart) && externalToken == null) { reportRecoverableError(isOperator ? name.next : name, fasta.messageExtensionDeclaresAbstractMember); } listener.endExtensionMethod(getOrSet, beforeStart.next, beforeParam.next, beforeInitializers?.next, token); break; case DeclarationKind.TopLevel: throw "Internal error: TopLevel method."; break; } } return token; } Token parseFactoryMethod(Token token, DeclarationKind kind, Token beforeStart, Token externalToken, Token staticOrCovariant, Token varFinalOrConst) { Token factoryKeyword = token = token.next; assert(optional('factory', factoryKeyword)); if (!isValidTypeReference(token.next)) { // Recovery ModifierRecoveryContext context = new ModifierRecoveryContext(this) ..externalToken = externalToken ..staticOrCovariant = staticOrCovariant ..varFinalOrConst = varFinalOrConst; token = context.parseModifiersAfterFactory(token); externalToken = context.externalToken; staticOrCovariant = context.staticToken ?? context.covariantToken; varFinalOrConst = context.varFinalOrConst; context = null; } if (staticOrCovariant != null) { reportRecoverableErrorWithToken( staticOrCovariant, fasta.templateExtraneousModifier); } if (varFinalOrConst != null && !optional('const', varFinalOrConst)) { reportRecoverableErrorWithToken( varFinalOrConst, fasta.templateExtraneousModifier); varFinalOrConst = null; } listener.beginFactoryMethod(beforeStart, externalToken, varFinalOrConst); token = ensureIdentifier(token, IdentifierContext.methodDeclaration); token = parseQualifiedRestOpt( token, IdentifierContext.methodDeclarationContinuation); token = parseMethodTypeVar(token); token = parseFormalParametersRequiredOpt(token, MemberKind.Factory); Token asyncToken = token.next; token = parseAsyncModifierOpt(token); Token next = token.next; if (!inPlainSync) { reportRecoverableError(asyncToken, fasta.messageFactoryNotSync); } if (optional('=', next)) { if (externalToken != null) { reportRecoverableError(next, fasta.messageExternalFactoryRedirection); } token = parseRedirectingFactoryBody(token); } else if (externalToken != null) { if (!optional(';', next)) { reportRecoverableError(next, fasta.messageExternalFactoryWithBody); } token = parseFunctionBody(token, false, true); } else { if (varFinalOrConst != null && !optional('native', next)) { if (optional('const', varFinalOrConst)) { reportRecoverableError(varFinalOrConst, fasta.messageConstFactory); } } token = parseFunctionBody(token, false, false); } switch (kind) { case DeclarationKind.Class: listener.endClassFactoryMethod(beforeStart.next, factoryKeyword, token); break; case DeclarationKind.Mixin: reportRecoverableError( factoryKeyword, fasta.messageMixinDeclaresConstructor); listener.endMixinFactoryMethod(beforeStart.next, factoryKeyword, token); break; case DeclarationKind.Extension: reportRecoverableError( factoryKeyword, fasta.messageExtensionDeclaresConstructor); listener.endExtensionFactoryMethod( beforeStart.next, factoryKeyword, token); break; case DeclarationKind.TopLevel: throw "Internal error: TopLevel factory."; break; } return token; } Token parseOperatorName(Token token) { Token beforeToken = token; token = token.next; assert(optional('operator', token)); Token next = token.next; if (next.isUserDefinableOperator) { if (computeTypeParamOrArg(token) != noTypeParamOrArg) { // `operator` is being used as an identifier. // For example: `int operator<T>(foo) => 0;` listener.handleIdentifier(token, IdentifierContext.methodDeclaration); return token; } else { listener.handleOperatorName(token, next); return next; } } else if (optional('(', next)) { return ensureIdentifier(beforeToken, IdentifierContext.operatorName); } else if (isUnaryMinus(next)) { // Recovery reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); next = next.next; listener.handleOperatorName(token, next); return next; } else { // Recovery // Scanner reports an error for `===` and `!==`. if (next.type != TokenType.EQ_EQ_EQ && next.type != TokenType.BANG_EQ_EQ) { // The user has specified an invalid operator name. // Report the error, accept the invalid operator name, and move on. reportRecoverableErrorWithToken(next, fasta.templateInvalidOperator); } listener.handleInvalidOperatorName(token, next); return next; } } Token parseFunctionExpression(Token token) { Token beginToken = token.next; listener.beginFunctionExpression(beginToken); token = parseFormalParametersRequiredOpt(token, MemberKind.Local); token = parseAsyncOptBody(token, true, false); listener.endFunctionExpression(beginToken, token.next); return token; } Token parseFunctionLiteral( Token start, Token beforeName, Token name, TypeInfo typeInfo, TypeParamOrArgInfo typeParam, IdentifierContext context) { Token formals = typeParam.parseVariables(name, this); listener.beginNamedFunctionExpression(start.next); typeInfo.parseType(start, this); return parseNamedFunctionRest(beforeName, start.next, formals, true); } /// Parses the rest of a named function declaration starting from its [name] /// but then skips any type parameters and continue parsing from [formals] /// (the formal parameters). /// /// If [isFunctionExpression] is true, this method parses the rest of named /// function expression which isn't legal syntax in Dart. Useful for /// recovering from Javascript code being pasted into a Dart program, as it /// will interpret `function foo() {}` as a named function expression with /// return type `function` and name `foo`. /// /// Precondition: the parser has previously generated these events: /// /// - Type variables. /// - `beginLocalFunctionDeclaration` if [isFunctionExpression] is false, /// otherwise `beginNamedFunctionExpression`. /// - Return type. Token parseNamedFunctionRest( Token beforeName, Token begin, Token formals, bool isFunctionExpression) { Token token = beforeName.next; listener.beginFunctionName(token); token = ensureIdentifier(beforeName, IdentifierContext.localFunctionDeclaration) .next; if (isFunctionExpression) { reportRecoverableError( beforeName.next, fasta.messageNamedFunctionExpression); } listener.endFunctionName(begin, token); token = parseFormalParametersRequiredOpt(formals, MemberKind.Local); token = parseInitializersOpt(token); token = parseAsyncOptBody(token, isFunctionExpression, false); if (isFunctionExpression) { listener.endNamedFunctionExpression(token); } else { listener.endLocalFunctionDeclaration(token); } return token; } /// Parses a function body optionally preceded by an async modifier (see /// [parseAsyncModifierOpt]). This method is used in both expression context /// (when [ofFunctionExpression] is true) and statement context. In statement /// context (when [ofFunctionExpression] is false), and if the function body /// is on the form `=> expression`, a trailing semicolon is required. /// /// It's an error if there's no function body unless [allowAbstract] is true. Token parseAsyncOptBody( Token token, bool ofFunctionExpression, bool allowAbstract) { AsyncModifier savedAsyncModifier = asyncState; token = parseAsyncModifierOpt(token); token = parseFunctionBody(token, ofFunctionExpression, allowAbstract); asyncState = savedAsyncModifier; return token; } Token parseConstructorReference(Token token, [TypeParamOrArgInfo typeArg]) { Token start = ensureIdentifier(token, IdentifierContext.constructorReference); listener.beginConstructorReference(start); token = parseQualifiedRestOpt( start, IdentifierContext.constructorReferenceContinuation); typeArg ??= computeTypeParamOrArg(token); token = typeArg.parseArguments(token, this); Token period = null; if (optional('.', token.next)) { period = token.next; token = ensureIdentifier(period, IdentifierContext.constructorReferenceContinuationAfterTypeArguments); } else { listener.handleNoConstructorReferenceContinuationAfterTypeArguments( token.next); } listener.endConstructorReference(start, period, token.next); return token; } Token parseRedirectingFactoryBody(Token token) { token = token.next; assert(optional('=', token)); listener.beginRedirectingFactoryBody(token); Token equals = token; token = parseConstructorReference(token); token = ensureSemicolon(token); listener.endRedirectingFactoryBody(equals, token); return token; } Token skipFunctionBody(Token token, bool isExpression, bool allowAbstract) { assert(!isExpression); token = skipAsyncModifier(token); Token next = token.next; if (optional('native', next)) { Token nativeToken = next; // TODO(danrubel): skip the native clause rather than parsing it // or remove this code completely when we remove support // for the `native` clause. token = parseNativeClause(token); next = token.next; if (optional(';', next)) { listener.handleNativeFunctionBodySkipped(nativeToken, next); return token.next; } listener.handleNativeFunctionBodyIgnored(nativeToken, next); // Fall through to recover and skip function body } String value = next.stringValue; if (identical(value, ';')) { token = next; if (!allowAbstract) { reportRecoverableError(token, fasta.messageExpectedBody); } listener.handleNoFunctionBody(token); } else if (identical(value, '=>')) { token = parseExpression(next); // There ought to be a semicolon following the expression, but we check // before advancing in order to be consistent with the way the method // [parseFunctionBody] recovers when the semicolon is missing. if (optional(';', token.next)) { token = token.next; } listener.handleFunctionBodySkipped(token, true); } else if (identical(value, '=')) { token = next; reportRecoverableError(token, fasta.messageExpectedBody); token = parseExpression(token); // There ought to be a semicolon following the expression, but we check // before advancing in order to be consistent with the way the method // [parseFunctionBody] recovers when the semicolon is missing. if (optional(';', token.next)) { token = token.next; } listener.handleFunctionBodySkipped(token, true); } else { token = skipBlock(token); listener.handleFunctionBodySkipped(token, false); } return token; } /// Parses a function body. This method is used in both expression context /// (when [ofFunctionExpression] is true) and statement context. In statement /// context (when [ofFunctionExpression] is false), and if the function body /// is on the form `=> expression`, a trailing semicolon is required. /// /// It's an error if there's no function body unless [allowAbstract] is true. Token parseFunctionBody( Token token, bool ofFunctionExpression, bool allowAbstract) { Token next = token.next; if (optional('native', next)) { Token nativeToken = next; token = parseNativeClause(token); next = token.next; if (optional(';', next)) { listener.handleNativeFunctionBody(nativeToken, next); return next; } reportRecoverableError(next, fasta.messageExternalMethodWithBody); listener.handleNativeFunctionBodyIgnored(nativeToken, next); // Ignore the native keyword and fall through to parse the body } if (optional(';', next)) { if (!allowAbstract) { reportRecoverableError(next, fasta.messageExpectedBody); } listener.handleEmptyFunctionBody(next); return next; } else if (optional('=>', next)) { return parseExpressionFunctionBody(next, ofFunctionExpression); } else if (optional('=', next)) { // Recover from a bad factory method. reportRecoverableError(next, fasta.messageExpectedBody); next = rewriter.insertToken( next, new SyntheticToken(TokenType.FUNCTION, next.next.charOffset)); Token begin = next; token = parseExpression(next); if (!ofFunctionExpression) { token = ensureSemicolon(token); listener.handleExpressionFunctionBody(begin, token); } else { listener.handleExpressionFunctionBody(begin, null); } return token; } Token begin = next; int statementCount = 0; if (!optional('{', next)) { // Recovery // If `return` used instead of `=>`, then report an error and continue if (optional('return', next)) { reportRecoverableError(next, fasta.messageExpectedBody); next = rewriter.insertToken( next, new SyntheticToken(TokenType.FUNCTION, next.next.charOffset)); return parseExpressionFunctionBody(next, ofFunctionExpression); } // If there is a stray simple identifier in the function expression // because the user is typing (e.g. `() asy => null;`) // then report an error, skip the token, and continue parsing. if (next.isKeywordOrIdentifier && optional('=>', next.next)) { reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); return parseExpressionFunctionBody(next.next, ofFunctionExpression); } if (next.isKeywordOrIdentifier && optional('{', next.next)) { reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); token = next; begin = next = token.next; // Fall through to parse the block. } else { token = ensureBlock(token, fasta.templateExpectedFunctionBody, null); listener.handleInvalidFunctionBody(token); return token.endGroup; } } LoopState savedLoopState = loopState; loopState = LoopState.OutsideLoop; listener.beginBlockFunctionBody(begin); token = next; while (notEofOrValue('}', token.next)) { Token startToken = token.next; token = parseStatement(token); if (identical(token.next, startToken)) { // No progress was made, so we report the current token as being invalid // and move forward. reportRecoverableError( token, fasta.templateUnexpectedToken.withArguments(token)); token = token.next; } ++statementCount; } token = token.next; assert(optional('}', token)); listener.endBlockFunctionBody(statementCount, begin, token); loopState = savedLoopState; return token; } Token parseExpressionFunctionBody(Token token, bool ofFunctionExpression) { assert(optional('=>', token)); Token begin = token; token = parseExpression(token); if (!ofFunctionExpression) { token = ensureSemicolon(token); listener.handleExpressionFunctionBody(begin, token); } else { listener.handleExpressionFunctionBody(begin, null); } if (inGenerator) { listener.handleInvalidStatement( begin, fasta.messageGeneratorReturnsValue); } return token; } Token skipAsyncModifier(Token token) { String value = token.next.stringValue; if (identical(value, 'async')) { token = token.next; value = token.next.stringValue; if (identical(value, '*')) { token = token.next; } } else if (identical(value, 'sync')) { token = token.next; value = token.next.stringValue; if (identical(value, '*')) { token = token.next; } } return token; } Token parseAsyncModifierOpt(Token token) { Token async; Token star; asyncState = AsyncModifier.Sync; Token next = token.next; if (optional('async', next)) { async = token = next; next = token.next; if (optional('*', next)) { asyncState = AsyncModifier.AsyncStar; star = next; token = next; } else { asyncState = AsyncModifier.Async; } } else if (optional('sync', next)) { async = token = next; next = token.next; if (optional('*', next)) { asyncState = AsyncModifier.SyncStar; star = next; token = next; } else { reportRecoverableError(async, fasta.messageInvalidSyncModifier); } } listener.handleAsyncModifier(async, star); if (!inPlainSync && optional(';', token.next)) { reportRecoverableError(token.next, fasta.messageAbstractNotSync); } return token; } int statementDepth = 0; Token parseStatement(Token token) { if (statementDepth++ > 500) { // This happens for degenerate programs, for example, a lot of nested // if-statements. The language test deep_nesting2_negative_test, for // example, provokes this. return recoverFromStackOverflow(token); } Token result = parseStatementX(token); statementDepth--; return result; } Token parseStatementX(Token token) { if (identical(token.next.kind, IDENTIFIER_TOKEN)) { if (optional(':', token.next.next)) { return parseLabeledStatement(token); } return parseExpressionStatementOrDeclarationAfterModifiers( token, token, null, null, null, false); } final String value = token.next.stringValue; if (identical(value, '{')) { // The scanner ensures that `{` always has a closing `}`. return parseBlock(token, null); } else if (identical(value, 'return')) { return parseReturnStatement(token); } else if (identical(value, 'var') || identical(value, 'final')) { Token varOrFinal = token.next; if (!isModifier(varOrFinal.next)) { return parseExpressionStatementOrDeclarationAfterModifiers( varOrFinal, token, null, varOrFinal, null, false); } return parseExpressionStatementOrDeclaration(token); } else if (identical(value, 'late')) { Token lateToken = token.next; if (!isModifier(lateToken.next)) { return parseExpressionStatementOrDeclarationAfterModifiers( lateToken, token, lateToken, null, null, false); } return parseExpressionStatementOrDeclaration(token); } else if (identical(value, 'if')) { return parseIfStatement(token); } else if (identical(value, 'await') && optional('for', token.next.next)) { return parseForStatement(token.next, token.next); } else if (identical(value, 'for')) { return parseForStatement(token, null); } else if (identical(value, 'rethrow')) { return parseRethrowStatement(token); } else if (identical(value, 'while')) { return parseWhileStatement(token); } else if (identical(value, 'do')) { return parseDoWhileStatement(token); } else if (identical(value, 'try')) { return parseTryStatement(token); } else if (identical(value, 'switch')) { return parseSwitchStatement(token); } else if (identical(value, 'break')) { return parseBreakStatement(token); } else if (identical(value, 'continue')) { return parseContinueStatement(token); } else if (identical(value, 'assert')) { return parseAssertStatement(token); } else if (identical(value, ';')) { return parseEmptyStatement(token); } else if (identical(value, 'yield')) { switch (asyncState) { case AsyncModifier.Sync: if (optional(':', token.next.next)) { return parseLabeledStatement(token); } return parseExpressionStatementOrDeclaration(token); case AsyncModifier.SyncStar: case AsyncModifier.AsyncStar: return parseYieldStatement(token); case AsyncModifier.Async: reportRecoverableError(token.next, fasta.messageYieldNotGenerator); return parseYieldStatement(token); } throw "Internal error: Unknown asyncState: '$asyncState'."; } else if (identical(value, 'const')) { return parseExpressionStatementOrConstDeclaration(token); } else if (identical(value, 'await')) { if (inPlainSync) { if (!looksLikeAwaitExpression(token)) { return parseExpressionStatementOrDeclaration(token); } // Recovery: looks like an expression preceded by `await` // but not inside an async context. // Fall through to parseExpressionStatement // and parseAwaitExpression will report the error. } return parseExpressionStatement(token); } else if (identical(value, 'set') && token.next.next.isIdentifier) { // Recovery: invalid use of `set` reportRecoverableErrorWithToken( token.next, fasta.templateUnexpectedToken); return parseStatementX(token.next); } else if (token.next.isIdentifier) { if (optional(':', token.next.next)) { return parseLabeledStatement(token); } return parseExpressionStatementOrDeclaration(token); } else { return parseExpressionStatementOrDeclaration(token); } } /// ``` /// yieldStatement: /// 'yield' expression? ';' /// ; /// ``` Token parseYieldStatement(Token token) { Token begin = token = token.next; assert(optional('yield', token)); listener.beginYieldStatement(begin); Token starToken; if (optional('*', token.next)) { starToken = token = token.next; } token = parseExpression(token); token = ensureSemicolon(token); listener.endYieldStatement(begin, starToken, token); return token; } /// ``` /// returnStatement: /// 'return' expression? ';' /// ; /// ``` Token parseReturnStatement(Token token) { Token begin = token = token.next; assert(optional('return', token)); listener.beginReturnStatement(begin); Token next = token.next; if (optional(';', next)) { listener.endReturnStatement(false, begin, next); return next; } token = parseExpression(token); token = ensureSemicolon(token); listener.endReturnStatement(true, begin, token); if (inGenerator) { listener.handleInvalidStatement( begin, fasta.messageGeneratorReturnsValue); } return token; } /// ``` /// label: /// identifier ':' /// ; /// ``` Token parseLabel(Token token) { assert(token.next.isIdentifier); token = ensureIdentifier(token, IdentifierContext.labelDeclaration).next; assert(optional(':', token)); listener.handleLabel(token); return token; } /// ``` /// statement: /// label* nonLabelledStatement /// ; /// ``` Token parseLabeledStatement(Token token) { Token next = token.next; assert(next.isIdentifier); assert(optional(':', next.next)); int labelCount = 0; do { token = parseLabel(token); next = token.next; labelCount++; } while (next.isIdentifier && optional(':', next.next)); listener.beginLabeledStatement(next, labelCount); token = parseStatement(token); listener.endLabeledStatement(labelCount); return token; } /// ``` /// expressionStatement: /// expression? ';' /// ; /// ``` /// /// Note: This method can fail to make progress. If there is neither an /// expression nor a semi-colon, then a synthetic identifier and synthetic /// semicolon will be inserted before [token] and the semicolon will be /// returned. Token parseExpressionStatement(Token token) { // TODO(brianwilkerson): If the next token is not the start of a valid // expression, then this method shouldn't report that we have an expression // statement. token = parseExpression(token); token = ensureSemicolon(token); listener.handleExpressionStatement(token); return token; } int expressionDepth = 0; Token parseExpression(Token token) { if (expressionDepth++ > 500) { // This happens in degenerate programs, for example, with a lot of nested // list literals. This is provoked by, for example, the language test // deep_nesting1_negative_test. Token next = token.next; reportRecoverableError(next, fasta.messageStackOverflow); // Recovery Token endGroup = next.endGroup; if (endGroup != null) { while (!next.isEof && !identical(next, endGroup)) { token = next; next = token.next; } } else { while (!isOneOf(next, const [')', ']', '}', ';'])) { token = next; next = token.next; } } if (!token.isEof) { token = rewriter.insertSyntheticIdentifier(token); listener.handleIdentifier(token, IdentifierContext.expression); } } else { token = optional('throw', token.next) ? parseThrowExpression(token, true) : parsePrecedenceExpression(token, ASSIGNMENT_PRECEDENCE, true); } expressionDepth--; return token; } Token parseExpressionWithoutCascade(Token token) { return optional('throw', token.next) ? parseThrowExpression(token, false) : parsePrecedenceExpression(token, ASSIGNMENT_PRECEDENCE, false); } Token parseConditionalExpressionRest(Token token) { Token question = token = token.next; assert(optional('?', question)); listener.beginConditionalExpression(token); token = parseExpressionWithoutCascade(token); Token colon = ensureColon(token); listener.handleConditionalExpressionColon(); token = parseExpressionWithoutCascade(colon); listener.endConditionalExpression(question, colon); return token; } Token parsePrecedenceExpression( Token token, int precedence, bool allowCascades) { assert(precedence >= 1); assert(precedence <= SELECTOR_PRECEDENCE); token = parseUnaryExpression(token, allowCascades); TypeParamOrArgInfo typeArg = computeMethodTypeArguments(token); if (typeArg != noTypeParamOrArg) { // For example a(b)<T>(c), where token is before '<'. token = typeArg.parseArguments(token, this); assert(optional('(', token.next)); } Token next = token.next; TokenType type = next.type; int tokenLevel = _computePrecedence(next); for (int level = tokenLevel; level >= precedence; --level) { int lastBinaryExpressionLevel = -1; Token lastCascade; while (identical(tokenLevel, level)) { Token operator = next; if (identical(tokenLevel, CASCADE_PRECEDENCE)) { if (!allowCascades) { return token; } else if (lastCascade != null && optional('?..', next)) { reportRecoverableError( next, fasta.messageNullAwareCascadeOutOfOrder); } lastCascade = next; token = parseCascadeExpression(token); } else if (identical(tokenLevel, ASSIGNMENT_PRECEDENCE)) { // Right associative, so we recurse at the same precedence // level. Token next = token.next; token = optional('throw', next.next) ? parseThrowExpression(next, false) : parsePrecedenceExpression(next, level, allowCascades); listener.handleAssignmentExpression(operator); } else if (identical(tokenLevel, POSTFIX_PRECEDENCE)) { if ((identical(type, TokenType.PLUS_PLUS)) || (identical(type, TokenType.MINUS_MINUS))) { listener.handleUnaryPostfixAssignmentExpression(token.next); token = next; } else if (identical(type, TokenType.BANG)) { listener.handleNonNullAssertExpression(next); token = next; } } else if (identical(tokenLevel, SELECTOR_PRECEDENCE)) { if (identical(type, TokenType.PERIOD) || identical(type, TokenType.QUESTION_PERIOD)) { // Left associative, so we recurse at the next higher precedence // level. However, SELECTOR_PRECEDENCE is the highest level, so we // should just call [parseUnaryExpression] directly. However, a // unary expression isn't legal after a period, so we call // [parsePrimary] instead. token = parsePrimary( token.next, IdentifierContext.expressionContinuation); listener.endBinaryExpression(operator); } else if (identical(type, TokenType.OPEN_PAREN) || identical(type, TokenType.OPEN_SQUARE_BRACKET) || identical(type, TokenType.QUESTION_PERIOD_OPEN_SQUARE_BRACKET)) { token = parseArgumentOrIndexStar(token, typeArg); } else if (identical(type, TokenType.INDEX)) { BeginToken replacement = link( new BeginToken(TokenType.OPEN_SQUARE_BRACKET, next.charOffset, next.precedingComments), new Token(TokenType.CLOSE_SQUARE_BRACKET, next.charOffset + 1)); rewriter.replaceTokenFollowing(token, replacement); replacement.endToken = replacement.next; token = parseArgumentOrIndexStar(token, noTypeParamOrArg); } else if (identical(type, TokenType.BANG)) { listener.handleNonNullAssertExpression(token.next); token = next; } else { // Recovery reportRecoverableErrorWithToken( token.next, fasta.templateUnexpectedToken); token = next; } } else if (identical(type, TokenType.IS)) { token = parseIsOperatorRest(token); } else if (identical(type, TokenType.AS)) { token = parseAsOperatorRest(token); } else if (identical(type, TokenType.QUESTION)) { token = parseConditionalExpressionRest(token); } else { if (level == EQUALITY_PRECEDENCE || level == RELATIONAL_PRECEDENCE) { // We don't allow (a == b == c) or (a < b < c). if (lastBinaryExpressionLevel == level) { // Report an error, then continue parsing as if it is legal. reportRecoverableError( next, fasta.messageEqualityCannotBeEqualityOperand); } else { // Set a flag to catch subsequent binary expressions of this type. lastBinaryExpressionLevel = level; } } listener.beginBinaryExpression(next); // Left associative, so we recurse at the next higher // precedence level. token = parsePrecedenceExpression(token.next, level + 1, allowCascades); listener.endBinaryExpression(operator); } next = token.next; type = next.type; tokenLevel = _computePrecedence(next); } } return token; } int _computePrecedence(Token token) { TokenType type = token.type; if (identical(type, TokenType.BANG)) { // The '!' has prefix precedence but here it's being used as a // postfix operator to assert the expression has a non-null value. TokenType nextType = token.next.type; if (identical(nextType, TokenType.PERIOD) || identical(nextType, TokenType.OPEN_PAREN) || identical(nextType, TokenType.OPEN_SQUARE_BRACKET)) { return SELECTOR_PRECEDENCE; } return POSTFIX_PRECEDENCE; } return type.precedence; } Token parseCascadeExpression(Token token) { Token cascadeOperator = token = token.next; assert(optional('..', cascadeOperator) || optional('?..', cascadeOperator)); listener.beginCascade(cascadeOperator); if (optional('[', token.next)) { token = parseArgumentOrIndexStar(token, noTypeParamOrArg); } else { token = parseSend(token, IdentifierContext.expressionContinuation); listener.endBinaryExpression(cascadeOperator); } Token next = token.next; Token mark; do { mark = token; if (optional('.', next) || optional('?.', next)) { Token period = next; token = parseSend(next, IdentifierContext.expressionContinuation); next = token.next; listener.endBinaryExpression(period); } TypeParamOrArgInfo typeArg = computeMethodTypeArguments(token); if (typeArg != noTypeParamOrArg) { // For example a(b)..<T>(c), where token is '<'. token = typeArg.parseArguments(token, this); next = token.next; assert(optional('(', next)); } token = parseArgumentOrIndexStar(token, typeArg); next = token.next; } while (!identical(mark, token)); if (identical(next.type.precedence, ASSIGNMENT_PRECEDENCE)) { Token assignment = next; token = parseExpressionWithoutCascade(next); listener.handleAssignmentExpression(assignment); } listener.endCascade(); return token; } Token parseUnaryExpression(Token token, bool allowCascades) { String value = token.next.stringValue; // Prefix: if (identical(value, 'await')) { if (inPlainSync) { if (!looksLikeAwaitExpression(token)) { return parsePrimary(token, IdentifierContext.expression); } // Recovery: Looks like an expression preceded by `await`. // Fall through and let parseAwaitExpression report the error. } return parseAwaitExpression(token, allowCascades); } else if (identical(value, '+')) { // Dart no longer allows prefix-plus. rewriteAndRecover( token, // TODO(danrubel): Consider reporting "missing identifier" instead. fasta.messageUnsupportedPrefixPlus, new SyntheticStringToken( TokenType.IDENTIFIER, '', token.next.offset)); return parsePrimary(token, IdentifierContext.expression); } else if ((identical(value, '!')) || (identical(value, '-')) || (identical(value, '~'))) { Token operator = token.next; // Right associative, so we recurse at the same precedence // level. token = parsePrecedenceExpression( token.next, POSTFIX_PRECEDENCE, allowCascades); listener.handleUnaryPrefixExpression(operator); return token; } else if ((identical(value, '++')) || identical(value, '--')) { // TODO(ahe): Validate this is used correctly. Token operator = token.next; // Right associative, so we recurse at the same precedence // level. token = parsePrecedenceExpression( token.next, POSTFIX_PRECEDENCE, allowCascades); listener.handleUnaryPrefixAssignmentExpression(operator); return token; } else if (token.next.isIdentifier) { Token identifier = token.next; if (optional(".", identifier.next)) { identifier = identifier.next.next; } if (identifier.isIdentifier) { // Looking at `identifier ('.' identifier)?`. if (optional("<", identifier.next)) { TypeParamOrArgInfo typeArg = computeTypeParamOrArg(identifier); if (typeArg != noTypeParamOrArg) { Token endTypeArguments = typeArg.skip(identifier); if (optional(".", endTypeArguments.next)) { return parseImplicitCreationExpression(token, typeArg); } } } } } return parsePrimary(token, IdentifierContext.expression); } Token parseArgumentOrIndexStar(Token token, TypeParamOrArgInfo typeArg) { Token next = token.next; Token beginToken = next; while (true) { if (optional('[', next) || optional('?.[', next)) { assert(typeArg == noTypeParamOrArg); Token openSquareBracket = next; bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = true; token = parseExpression(next); next = token.next; mayParseFunctionExpressions = old; if (!optional(']', next)) { // Recovery reportRecoverableError( next, fasta.templateExpectedButGot.withArguments(']')); // Scanner ensures a closing ']' Token endGroup = openSquareBracket.endGroup; if (endGroup.isSynthetic) { // Scanner inserted closing ']' in the wrong place, so move it. next = rewriter.moveSynthetic(token, endGroup); } else { // Skip over unexpected tokens to where the user placed the `]`. next = endGroup; } } listener.handleIndexedExpression(openSquareBracket, next); token = next; typeArg = computeMethodTypeArguments(token); if (typeArg != noTypeParamOrArg) { // For example a[b]<T>(c), where token is before '<'. token = typeArg.parseArguments(token, this); assert(optional('(', token.next)); } next = token.next; } else if (optional('(', next)) { if (typeArg == noTypeParamOrArg) { listener.handleNoTypeArguments(next); } token = parseArguments(token); listener.handleSend(beginToken, token); typeArg = computeMethodTypeArguments(token); if (typeArg != noTypeParamOrArg) { // For example a(b)<T>(c), where token is before '<'. token = typeArg.parseArguments(token, this); assert(optional('(', token.next)); } next = token.next; } else { break; } } return token; } Token parsePrimary(Token token, IdentifierContext context) { final int kind = token.next.kind; if (kind == IDENTIFIER_TOKEN) { return parseSendOrFunctionLiteral(token, context); } else if (kind == INT_TOKEN || kind == HEXADECIMAL_TOKEN) { return parseLiteralInt(token); } else if (kind == DOUBLE_TOKEN) { return parseLiteralDouble(token); } else if (kind == STRING_TOKEN) { return parseLiteralString(token); } else if (kind == HASH_TOKEN) { return parseLiteralSymbol(token); } else if (kind == KEYWORD_TOKEN) { final String value = token.next.stringValue; if (identical(value, "true") || identical(value, "false")) { return parseLiteralBool(token); } else if (identical(value, "null")) { return parseLiteralNull(token); } else if (identical(value, "this")) { return parseThisExpression(token, context); } else if (identical(value, "super")) { return parseSuperExpression(token, context); } else if (identical(value, "new")) { return parseNewExpression(token); } else if (identical(value, "const")) { return parseConstExpression(token); } else if (identical(value, "void")) { return parseSendOrFunctionLiteral(token, context); } else if (!inPlainSync && (identical(value, "yield") || identical(value, "async"))) { // Fall through to the recovery code. } else if (identical(value, "assert")) { return parseAssert(token, Assert.Expression); } else if (token.next.isIdentifier) { return parseSendOrFunctionLiteral(token, context); } else if (identical(value, "return")) { // Recovery token = token.next; reportRecoverableErrorWithToken(token, fasta.templateUnexpectedToken); return parsePrimary(token, context); } else { // Fall through to the recovery code. } } else if (kind == OPEN_PAREN_TOKEN) { return parseParenthesizedExpressionOrFunctionLiteral(token); } else if (kind == OPEN_SQUARE_BRACKET_TOKEN || optional('[]', token.next)) { listener.handleNoTypeArguments(token.next); return parseLiteralListSuffix(token, null); } else if (kind == OPEN_CURLY_BRACKET_TOKEN) { listener.handleNoTypeArguments(token.next); return parseLiteralSetOrMapSuffix(token, null); } else if (kind == LT_TOKEN) { return parseLiteralListSetMapOrFunction(token, null); } else { // Fall through to the recovery code. } // // Recovery code. // return parseSend(token, context); } Token parseParenthesizedExpressionOrFunctionLiteral(Token token) { Token next = token.next; assert(optional('(', next)); Token nextToken = next.endGroup.next; int kind = nextToken.kind; if (mayParseFunctionExpressions) { if ((identical(kind, FUNCTION_TOKEN) || identical(kind, OPEN_CURLY_BRACKET_TOKEN))) { listener.handleNoTypeVariables(next); return parseFunctionExpression(token); } else if (identical(kind, KEYWORD_TOKEN) || identical(kind, IDENTIFIER_TOKEN)) { if (optional('async', nextToken) || optional('sync', nextToken)) { listener.handleNoTypeVariables(next); return parseFunctionExpression(token); } // Recovery // If there is a stray simple identifier in the function expression // because the user is typing (e.g. `() asy {}`) then continue parsing // and allow parseFunctionExpression to report an unexpected token. kind = nextToken.next.kind; if ((identical(kind, FUNCTION_TOKEN) || identical(kind, OPEN_CURLY_BRACKET_TOKEN))) { listener.handleNoTypeVariables(next); return parseFunctionExpression(token); } } } bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = true; token = parseParenthesizedExpression(token); mayParseFunctionExpressions = old; return token; } Token ensureParenthesizedCondition(Token token) { Token openParen = token.next; if (!optional('(', openParen)) { // Recover reportRecoverableError( openParen, fasta.templateExpectedToken.withArguments('(')); openParen = rewriter.insertParens(token, false); } token = parseExpressionInParenthesisRest(openParen); listener.handleParenthesizedCondition(openParen); return token; } Token parseParenthesizedExpression(Token token) { Token begin = token.next; token = parseExpressionInParenthesis(token); listener.handleParenthesizedExpression(begin); return token; } Token parseExpressionInParenthesis(Token token) { return parseExpressionInParenthesisRest(token.next); } Token parseExpressionInParenthesisRest(Token token) { assert(optional('(', token)); BeginToken begin = token; token = parseExpression(token); token = ensureCloseParen(token, begin); assert(optional(')', token)); return token; } Token parseThisExpression(Token token, IdentifierContext context) { Token thisToken = token = token.next; assert(optional('this', thisToken)); listener.handleThisExpression(thisToken, context); Token next = token.next; if (optional('(', next)) { // Constructor forwarding. listener.handleNoTypeArguments(next); token = parseArguments(token); listener.handleSend(thisToken, token.next); } return token; } Token parseSuperExpression(Token token, IdentifierContext context) { Token superToken = token = token.next; assert(optional('super', token)); listener.handleSuperExpression(superToken, context); Token next = token.next; if (optional('(', next)) { // Super constructor. listener.handleNoTypeArguments(next); token = parseArguments(token); listener.handleSend(superToken, token.next); } else if (optional("?.", next)) { reportRecoverableError(next, fasta.messageSuperNullAware); } return token; } /// This method parses the portion of a list literal starting with the left /// square bracket. /// /// ``` /// listLiteral: /// 'const'? typeArguments? '[' (expressionList ','?)? ']' /// ; /// ``` /// /// Provide a [constKeyword] if the literal is preceded by 'const', or `null` /// if not. This is a suffix parser because it is assumed that type arguments /// have been parsed, or `listener.handleNoTypeArguments` has been executed. Token parseLiteralListSuffix(Token token, Token constKeyword) { Token beforeToken = token; Token beginToken = token = token.next; assert(optional('[', token) || optional('[]', token)); int count = 0; if (optional('[]', token)) { token = rewriteSquareBrackets(beforeToken).next; listener.handleLiteralList(0, token, constKeyword, token.next); return token.next; } bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = true; while (true) { Token next = token.next; if (optional(']', next)) { token = next; break; } int ifCount = 0; LiteralEntryInfo info = computeLiteralEntry(token); while (info != null) { if (info.hasEntry) { token = parseExpression(token); } else { token = info.parse(token, this); } ifCount += info.ifConditionDelta; info = info.computeNext(token); } next = token.next; ++count; if (!optional(',', next)) { if (optional(']', next)) { token = next; break; } // Recovery if (!looksLikeLiteralEntry(next)) { if (beginToken.endGroup.isSynthetic) { // The scanner has already reported an error, // but inserted `]` in the wrong place. token = rewriter.moveSynthetic(token, beginToken.endGroup); } else { // Report an error and jump to the end of the list. reportRecoverableError( next, fasta.templateExpectedButGot.withArguments(']')); token = beginToken.endGroup; } break; } // This looks like the start of an expression. // Report an error, insert the comma, and continue parsing. SyntheticToken comma = new SyntheticToken(TokenType.COMMA, next.offset); Message message = ifCount > 0 ? fasta.messageExpectedElseOrComma : fasta.templateExpectedButGot.withArguments(','); next = rewriteAndRecover(token, message, comma); } token = next; } mayParseFunctionExpressions = old; listener.handleLiteralList(count, beginToken, constKeyword, token); return token; } /// This method parses the portion of a set or map literal that starts with /// the left curly brace when there are no leading type arguments. Token parseLiteralSetOrMapSuffix(Token token, Token constKeyword) { Token leftBrace = token = token.next; assert(optional('{', leftBrace)); Token next = token.next; if (optional('}', next)) { listener.handleLiteralSetOrMap(0, leftBrace, constKeyword, next, false); return next; } final bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = true; int count = 0; // TODO(danrubel): hasSetEntry parameter exists for replicating existing // behavior and will be removed once unified collection has been enabled bool hasSetEntry; while (true) { int ifCount = 0; LiteralEntryInfo info = computeLiteralEntry(token); if (info == simpleEntry) { // TODO(danrubel): Remove this section and use the while loop below // once hasSetEntry is no longer needed. token = parseExpression(token); bool isMapEntry = optional(':', token.next); hasSetEntry ??= !isMapEntry; if (isMapEntry) { Token colon = token.next; token = parseExpression(colon); listener.handleLiteralMapEntry(colon, token.next); } } else { while (info != null) { if (info.hasEntry) { token = parseExpression(token); if (optional(':', token.next)) { Token colon = token.next; token = parseExpression(colon); listener.handleLiteralMapEntry(colon, token.next); } } else { token = info.parse(token, this); } ifCount += info.ifConditionDelta; info = info.computeNext(token); } } ++count; next = token.next; Token comma; if (optional(',', next)) { comma = token = next; next = token.next; } if (optional('}', next)) { listener.handleLiteralSetOrMap( count, leftBrace, constKeyword, next, hasSetEntry ?? false); mayParseFunctionExpressions = old; return next; } if (comma == null) { // Recovery if (looksLikeLiteralEntry(next)) { // If this looks like the start of an expression, // then report an error, insert the comma, and continue parsing. // TODO(danrubel): Consider better error message SyntheticToken comma = new SyntheticToken(TokenType.COMMA, next.offset); Message message = ifCount > 0 ? fasta.messageExpectedElseOrComma : fasta.templateExpectedButGot.withArguments(','); token = rewriteAndRecover(token, message, comma); } else { reportRecoverableError( next, fasta.templateExpectedButGot.withArguments('}')); // Scanner guarantees a closing curly bracket next = leftBrace.endGroup; listener.handleLiteralSetOrMap( count, leftBrace, constKeyword, next, hasSetEntry ?? false); mayParseFunctionExpressions = old; return next; } } } } /// formalParameterList functionBody. /// /// This is a suffix parser because it is assumed that type arguments have /// been parsed, or `listener.handleNoTypeArguments(..)` has been executed. Token parseLiteralFunctionSuffix(Token token) { assert(optional('(', token.next)); // Scanner ensures `(` has matching `)`. Token next = token.next.endGroup.next; int kind = next.kind; if (!identical(kind, FUNCTION_TOKEN) && !identical(kind, OPEN_CURLY_BRACKET_TOKEN) && (!identical(kind, KEYWORD_TOKEN) || !optional('async', next) && !optional('sync', next))) { reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); } return parseFunctionExpression(token); } /// genericListLiteral | genericMapLiteral | genericFunctionLiteral. /// /// Where /// genericListLiteral ::= typeArguments '[' (expressionList ','?)? ']' /// genericMapLiteral ::= /// typeArguments '{' (mapLiteralEntry (',' mapLiteralEntry)* ','?)? '}' /// genericFunctionLiteral ::= /// typeParameters formalParameterList functionBody /// Provide token for [constKeyword] if preceded by 'const', null if not. Token parseLiteralListSetMapOrFunction( final Token start, Token constKeyword) { assert(optional('<', start.next)); TypeParamOrArgInfo typeParamOrArg = computeTypeParamOrArg(start, true); Token token = typeParamOrArg.skip(start); Token next = token.next; if (optional('(', next)) { if (constKeyword != null) { reportRecoverableErrorWithToken( constKeyword, fasta.templateUnexpectedToken); } token = typeParamOrArg.parseVariables(start, this); return parseLiteralFunctionSuffix(token); } token = typeParamOrArg.parseArguments(start, this); if (optional('{', next)) { if (typeParamOrArg.typeArgumentCount > 2) { listener.handleRecoverableError( fasta.messageSetOrMapLiteralTooManyTypeArguments, start.next, token); } return parseLiteralSetOrMapSuffix(token, constKeyword); } if (!optional('[', next) && !optional('[]', next)) { // TODO(danrubel): Improve this error message. reportRecoverableError( next, fasta.templateExpectedButGot.withArguments('[')); rewriter.insertSyntheticToken(token, TokenType.INDEX); } return parseLiteralListSuffix(token, constKeyword); } /// ``` /// mapLiteralEntry: /// expression ':' expression | /// 'if' '(' expression ')' mapLiteralEntry ( 'else' mapLiteralEntry )? | /// 'await'? 'for' '(' forLoopParts ')' mapLiteralEntry | /// ( '...' | '...?' ) expression /// ; /// ``` Token parseMapLiteralEntry(Token token) { // Assume the listener rejects non-string keys. // TODO(brianwilkerson): Change the assumption above by moving error // checking into the parser, making it possible to recover. LiteralEntryInfo info = computeLiteralEntry(token); while (info != null) { if (info.hasEntry) { token = parseExpression(token); Token colon = ensureColon(token); token = parseExpression(colon); // TODO remove unused 2nd parameter listener.handleLiteralMapEntry(colon, token.next); } else { token = info.parse(token, this); } info = info.computeNext(token); } return token; } Token parseSendOrFunctionLiteral(Token token, IdentifierContext context) { if (!mayParseFunctionExpressions) { return parseSend(token, context); } TypeInfo typeInfo = computeType(token, false); Token beforeName = typeInfo.skipType(token); Token name = beforeName.next; if (name.isIdentifier) { TypeParamOrArgInfo typeParam = computeTypeParamOrArg(name); Token next = typeParam.skip(name).next; if (optional('(', next)) { if (looksLikeFunctionBody(next.endGroup.next)) { return parseFunctionLiteral( token, beforeName, name, typeInfo, typeParam, context); } } } return parseSend(token, context); } Token ensureArguments(Token token) { Token next = token.next; if (!optional('(', next)) { reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('(')); next = rewriter.insertParens(token, false); } return parseArgumentsRest(next); } Token parseConstructorInvocationArguments(Token token) { Token next = token.next; if (!optional('(', next)) { // Recovery: Check for invalid type parameters TypeParamOrArgInfo typeArg = computeTypeParamOrArg(token); if (typeArg == noTypeParamOrArg) { reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('(')); } else { reportRecoverableError( token, fasta.messageConstructorWithTypeArguments); token = typeArg.parseArguments(token, this); listener.handleInvalidTypeArguments(token); next = token.next; } if (!optional('(', next)) { next = rewriter.insertParens(token, false); } } return parseArgumentsRest(next); } /// ``` /// newExpression: /// 'new' type ('.' identifier)? arguments /// ; /// ``` Token parseNewExpression(Token token) { Token newKeyword = token.next; assert(optional('new', newKeyword)); listener.beginNewExpression(newKeyword); token = parseConstructorReference(newKeyword); token = parseConstructorInvocationArguments(token); listener.endNewExpression(newKeyword); return token; } Token parseImplicitCreationExpression( Token token, TypeParamOrArgInfo typeArg) { Token begin = token; listener.beginImplicitCreationExpression(token); token = parseConstructorReference(token, typeArg); token = parseConstructorInvocationArguments(token); listener.endImplicitCreationExpression(begin); return token; } /// This method parses a list or map literal that is known to start with the /// keyword 'const'. /// /// ``` /// listLiteral: /// 'const'? typeArguments? '[' (expressionList ','?)? ']' /// ; /// /// mapLiteral: /// 'const'? typeArguments? /// '{' (mapLiteralEntry (',' mapLiteralEntry)* ','?)? '}' /// ; /// /// mapLiteralEntry: /// expression ':' expression /// ; /// ``` Token parseConstExpression(Token token) { Token constKeyword = token = token.next; assert(optional('const', constKeyword)); Token next = token.next; final String value = next.stringValue; if ((identical(value, '[')) || (identical(value, '[]'))) { listener.beginConstLiteral(next); listener.handleNoTypeArguments(next); token = parseLiteralListSuffix(token, constKeyword); listener.endConstLiteral(token.next); return token; } if (identical(value, '{')) { listener.beginConstLiteral(next); listener.handleNoTypeArguments(next); token = parseLiteralSetOrMapSuffix(token, constKeyword); listener.endConstLiteral(token.next); return token; } if (identical(value, '<')) { listener.beginConstLiteral(next); token = parseLiteralListSetMapOrFunction(token, constKeyword); listener.endConstLiteral(token.next); return token; } listener.beginConstExpression(constKeyword); token = parseConstructorReference(token); token = parseConstructorInvocationArguments(token); listener.endConstExpression(constKeyword); return token; } /// ``` /// intLiteral: /// integer /// ; /// ``` Token parseLiteralInt(Token token) { token = token.next; assert(identical(token.kind, INT_TOKEN) || identical(token.kind, HEXADECIMAL_TOKEN)); listener.handleLiteralInt(token); return token; } /// ``` /// doubleLiteral: /// double /// ; /// ``` Token parseLiteralDouble(Token token) { token = token.next; assert(identical(token.kind, DOUBLE_TOKEN)); listener.handleLiteralDouble(token); return token; } /// ``` /// stringLiteral: /// (multilineString | singleLineString)+ /// ; /// ``` Token parseLiteralString(Token token) { assert(identical(token.next.kind, STRING_TOKEN)); bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = true; token = parseSingleLiteralString(token); int count = 1; while (identical(token.next.kind, STRING_TOKEN)) { token = parseSingleLiteralString(token); count++; } if (count > 1) { listener.handleStringJuxtaposition(count); } mayParseFunctionExpressions = old; return token; } /// ``` /// symbolLiteral: /// '#' (operator | (identifier ('.' identifier)*)) /// ; /// ``` Token parseLiteralSymbol(Token token) { Token hashToken = token = token.next; assert(optional('#', hashToken)); listener.beginLiteralSymbol(hashToken); Token next = token.next; if (next.isUserDefinableOperator) { listener.handleOperator(next); listener.endLiteralSymbol(hashToken, 1); return next; } else if (optional('void', next)) { listener.handleSymbolVoid(next); listener.endLiteralSymbol(hashToken, 1); return next; } else { int count = 1; token = ensureIdentifier(token, IdentifierContext.literalSymbol); while (optional('.', token.next)) { count++; token = ensureIdentifier( token.next, IdentifierContext.literalSymbolContinuation); } listener.endLiteralSymbol(hashToken, count); return token; } } Token parseSingleLiteralString(Token token) { token = token.next; assert(identical(token.kind, STRING_TOKEN)); listener.beginLiteralString(token); // Parsing the prefix, for instance 'x of 'x${id}y${id}z' int interpolationCount = 0; Token next = token.next; int kind = next.kind; while (kind != EOF_TOKEN) { if (identical(kind, STRING_INTERPOLATION_TOKEN)) { // Parsing ${expression}. token = parseExpression(next).next; if (!optional('}', token)) { reportRecoverableError( token, fasta.templateExpectedButGot.withArguments('}')); token = next.endGroup; } listener.handleInterpolationExpression(next, token); } else if (identical(kind, STRING_INTERPOLATION_IDENTIFIER_TOKEN)) { // Parsing $identifier. token = parseIdentifierExpression(next); listener.handleInterpolationExpression(next, null); } else { break; } ++interpolationCount; // Parsing the infix/suffix, for instance y and z' of 'x${id}y${id}z' token = parseStringPart(token); next = token.next; kind = next.kind; } listener.endLiteralString(interpolationCount, next); return token; } Token parseIdentifierExpression(Token token) { Token next = token.next; if (next.kind == KEYWORD_TOKEN && identical(next.stringValue, "this")) { listener.handleThisExpression(next, IdentifierContext.expression); return next; } else { return parseSend(token, IdentifierContext.expression); } } /// ``` /// booleanLiteral: /// 'true' | /// 'false' /// ; /// ``` Token parseLiteralBool(Token token) { token = token.next; assert(optional('false', token) || optional('true', token)); listener.handleLiteralBool(token); return token; } /// ``` /// nullLiteral: /// 'null' /// ; /// ``` Token parseLiteralNull(Token token) { token = token.next; assert(optional('null', token)); listener.handleLiteralNull(token); return token; } Token parseSend(Token token, IdentifierContext context) { Token beginToken = token = ensureIdentifier(token, context); TypeParamOrArgInfo typeArg = computeMethodTypeArguments(token); if (typeArg != noTypeParamOrArg) { token = typeArg.parseArguments(token, this); } else { listener.handleNoTypeArguments(token.next); } token = parseArgumentsOpt(token); listener.handleSend(beginToken, token.next); return token; } Token skipArgumentsOpt(Token token) { Token next = token.next; listener.handleNoArguments(next); if (optional('(', next)) { return next.endGroup; } else { return token; } } Token parseArgumentsOpt(Token token) { Token next = token.next; if (!optional('(', next)) { listener.handleNoArguments(next); return token; } else { return parseArguments(token); } } /// ``` /// arguments: /// '(' (argumentList ','?)? ')' /// ; /// /// argumentList: /// namedArgument (',' namedArgument)* | /// expressionList (',' namedArgument)* /// ; /// /// namedArgument: /// label expression /// ; /// ``` Token parseArguments(Token token) { return parseArgumentsRest(token.next); } Token parseArgumentsRest(Token token) { Token begin = token; assert(optional('(', begin)); listener.beginArguments(begin); int argumentCount = 0; bool hasSeenNamedArgument = false; bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = true; while (true) { Token next = token.next; if (optional(')', next)) { token = next; break; } Token colon = null; if (optional(':', next.next)) { token = ensureIdentifier(token, IdentifierContext.namedArgumentReference) .next; colon = token; hasSeenNamedArgument = true; } else if (hasSeenNamedArgument) { // Positional argument after named argument. reportRecoverableError(next, fasta.messagePositionalAfterNamedArgument); } token = parseExpression(token); next = token.next; if (colon != null) listener.handleNamedArgument(colon); ++argumentCount; if (!optional(',', next)) { if (optional(')', next)) { token = next; break; } // Recovery if (looksLikeExpressionStart(next)) { // If this looks like the start of an expression, // then report an error, insert the comma, and continue parsing. next = rewriteAndRecover( token, fasta.templateExpectedButGot.withArguments(','), new SyntheticToken(TokenType.COMMA, next.offset)); } else { token = ensureCloseParen(token, begin); break; } } token = next; } assert(optional(')', token)); mayParseFunctionExpressions = old; listener.endArguments(argumentCount, begin, token); return token; } /// ``` /// typeTest:: /// 'is' '!'? type /// ; /// ``` Token parseIsOperatorRest(Token token) { Token operator = token = token.next; assert(optional('is', operator)); Token not = null; if (optional('!', token.next)) { not = token = token.next; } TypeInfo typeInfo = computeTypeAfterIsOrAs(token); token = typeInfo.ensureTypeNotVoid(token, this); listener.handleIsOperator(operator, not); return skipChainedAsIsOperators(token); } TypeInfo computeTypeAfterIsOrAs(Token token) { TypeInfo typeInfo = computeType(token, true); if (typeInfo.isNullable) { Token next = typeInfo.skipType(token).next; if (!isOneOfOrEof(next, const [')', '?', ';', 'is', 'as'])) { // TODO(danrubel): investigate other situations // where `?` should be considered part of the type info // rather than the start of a conditional expression. typeInfo = typeInfo.asNonNullable; } } return typeInfo; } /// ``` /// typeCast: /// 'as' type /// ; /// ``` Token parseAsOperatorRest(Token token) { Token operator = token = token.next; assert(optional('as', operator)); TypeInfo typeInfo = computeTypeAfterIsOrAs(token); token = typeInfo.ensureTypeNotVoid(token, this); listener.handleAsOperator(operator); return skipChainedAsIsOperators(token); } Token skipChainedAsIsOperators(Token token) { while (true) { Token next = token.next; String value = next.stringValue; if (!identical(value, 'is') && !identical(value, 'as')) { return token; } // The is- and as-operators cannot be chained. // TODO(danrubel): Consider a better error message. reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken); if (optional('!', next.next)) { next = next.next; } TypeInfo typeInfo = computeTypeAfterIsOrAs(next); token = typeInfo.skipType(next); next = token.next; value = next.stringValue; } } /// Returns true if [token] could be the start of a function declaration /// without a return type. bool looksLikeLocalFunction(Token token) { if (token.isIdentifier) { if (optional('<', token.next)) { TypeParamOrArgInfo typeParam = computeTypeParamOrArg(token); if (typeParam == noTypeParamOrArg) { return false; } token = typeParam.skip(token); } token = token.next; if (optional('(', token)) { token = token.endGroup.next; return optional('{', token) || optional('=>', token) || optional('async', token) || optional('sync', token); } else if (optional('=>', token)) { // Recovery: Looks like a local function that is missing parenthesis. return true; } } return false; } /// Returns true if [token] could be the start of a function body. bool looksLikeFunctionBody(Token token) { return optional('{', token) || optional('=>', token) || optional('async', token) || optional('sync', token); } Token parseExpressionStatementOrConstDeclaration(final Token start) { Token constToken = start.next; assert(optional('const', constToken)); if (!isModifier(constToken.next)) { TypeInfo typeInfo = computeType(constToken, false); if (typeInfo == noType) { Token next = constToken.next; if (!next.isIdentifier) { return parseExpressionStatement(start); } next = next.next; if (!(optional('=', next) || // Recovery next.isKeywordOrIdentifier || optional(';', next) || optional(',', next) || optional('{', next))) { return parseExpressionStatement(start); } } return parseExpressionStatementOrDeclarationAfterModifiers( constToken, start, null, constToken, typeInfo, false); } return parseExpressionStatementOrDeclaration(start); } /// This method has two modes based upon [onlyParseVariableDeclarationStart]. /// /// If [onlyParseVariableDeclarationStart] is `false` (the default) then this /// method will parse a local variable declaration, a local function, /// or an expression statement, and then return the last consumed token. /// /// If [onlyParseVariableDeclarationStart] is `true` then this method /// will only parse the metadata, modifiers, and type of a local variable /// declaration if it exists. It is the responsibility of the caller to /// call [parseVariablesDeclarationRest] to finish parsing the local variable /// declaration. If a local variable declaration is not found then this /// method will return [start]. Token parseExpressionStatementOrDeclaration(final Token start, [bool onlyParseVariableDeclarationStart = false]) { Token token = start; Token next = token.next; if (optional('@', next)) { token = parseMetadataStar(token); next = token.next; } Token lateToken; Token varFinalOrConst; if (isModifier(next)) { if (optional('var', next) || optional('final', next) || optional('const', next)) { varFinalOrConst = token = token.next; next = token.next; } else if (optional('late', next)) { lateToken = token = next; next = token.next; if (isModifier(next) && (optional('var', next) || optional('final', next))) { varFinalOrConst = token = next; next = token.next; } } if (isModifier(next)) { // Recovery ModifierRecoveryContext context = new ModifierRecoveryContext(this) ..lateToken = lateToken ..varFinalOrConst = varFinalOrConst; token = context.parseVariableDeclarationModifiers(token); next = token.next; lateToken = context.lateToken; varFinalOrConst = context.varFinalOrConst; context = null; } } return parseExpressionStatementOrDeclarationAfterModifiers(token, start, lateToken, varFinalOrConst, null, onlyParseVariableDeclarationStart); } /// See [parseExpressionStatementOrDeclaration] Token parseExpressionStatementOrDeclarationAfterModifiers( final Token beforeType, final Token start, final Token lateToken, Token varFinalOrConst, TypeInfo typeInfo, bool onlyParseVariableDeclarationStart) { typeInfo ??= computeType(beforeType, false); Token token = typeInfo.skipType(beforeType); Token next = token.next; if (onlyParseVariableDeclarationStart) { if (lateToken != null) { reportRecoverableErrorWithToken( lateToken, fasta.templateExtraneousModifier); } } else { if (looksLikeLocalFunction(next)) { // Parse a local function declaration. if (varFinalOrConst != null) { reportRecoverableErrorWithToken( varFinalOrConst, fasta.templateExtraneousModifier); } else if (lateToken != null) { reportRecoverableErrorWithToken( lateToken, fasta.templateExtraneousModifier); } if (!optional('@', start.next)) { listener.beginMetadataStar(start.next); listener.endMetadataStar(0); } Token beforeFormals = computeTypeParamOrArg(next).parseVariables(next, this); listener.beginLocalFunctionDeclaration(start.next); token = typeInfo.parseType(beforeType, this); return parseNamedFunctionRest(token, start.next, beforeFormals, false); } } if (beforeType == start && typeInfo.isNullable && typeInfo.couldBeExpression) { assert(optional('?', token)); assert(next.isKeywordOrIdentifier); if (!next.isIdentifier) { reportRecoverableError( next, fasta.templateExpectedIdentifier.withArguments(next)); next = rewriter.insertSyntheticIdentifier(next); } Token afterIdentifier = next.next; // // found <typeref> `?` <identifier> // with no annotations or modifiers preceeding it // if (optional('=', afterIdentifier)) { // // look past the next expression // to determine if this is part of a conditional expression // Listener originalListener = listener; listener = new ForwardingListener(); // TODO(danrubel): consider using TokenStreamGhostWriter here Token afterExpression = parseExpressionWithoutCascade(afterIdentifier).next; listener = originalListener; if (optional(':', afterExpression)) { // Looks like part of a conditional expression. // Drop the type information and reset the last consumed token. typeInfo = noType; token = start; next = token.next; } } else if (!afterIdentifier.isKeyword && !isOneOfOrEof(afterIdentifier, const [';', ',', ')'])) { // Looks like part of a conditional expression. // Drop the type information and reset the last consumed token. typeInfo = noType; token = start; next = token.next; } } if (token == start) { // If no annotation, modifier, or type, and this is not a local function // then this must be an expression statement. if (onlyParseVariableDeclarationStart) { return start; } else { return parseExpressionStatement(start); } } if (next.type.isBuiltIn && beforeType == start && typeInfo.couldBeExpression) { // Detect expressions such as identifier `as` identifier // and treat those as expressions. if (optional('as', next) || optional('is', next)) { int kind = next.next.kind; if (EQ_TOKEN != kind && SEMICOLON_TOKEN != kind && COMMA_TOKEN != kind) { if (onlyParseVariableDeclarationStart) { if (!optional('in', next.next)) { return start; } } else { return parseExpressionStatement(start); } } } } if (next.isIdentifier) { // Only report these errors if there is an identifier. If there is not an // identifier, then allow ensureIdentifier to report an error // and don't report errors here. if (varFinalOrConst == null) { if (typeInfo == noType && lateToken == null) { reportRecoverableError(next, fasta.messageMissingConstFinalVarOrType); } } else if (optional('var', varFinalOrConst)) { if (typeInfo != noType) { reportRecoverableError(varFinalOrConst, fasta.messageTypeAfterVar); } } } if (!optional('@', start.next)) { listener.beginMetadataStar(start.next); listener.endMetadataStar(0); } token = typeInfo.parseType(beforeType, this); next = token.next; listener.beginVariablesDeclaration(next, lateToken, varFinalOrConst); if (!onlyParseVariableDeclarationStart) { token = parseVariablesDeclarationRest(token, true); } return token; } Token parseVariablesDeclarationRest(Token token, bool endWithSemicolon) { int count = 1; token = parseOptionallyInitializedIdentifier(token); while (optional(',', token.next)) { token = parseOptionallyInitializedIdentifier(token.next); ++count; } if (endWithSemicolon) { Token semicolon = ensureSemicolon(token); listener.endVariablesDeclaration(count, semicolon); return semicolon; } else { listener.endVariablesDeclaration(count, null); return token; } } Token parseOptionallyInitializedIdentifier(Token token) { Token nameToken = ensureIdentifier(token, IdentifierContext.localVariableDeclaration); listener.beginInitializedIdentifier(nameToken); token = parseVariableInitializerOpt(nameToken); listener.endInitializedIdentifier(nameToken); return token; } /// ``` /// ifStatement: /// 'if' '(' expression ')' statement ('else' statement)? /// ; /// ``` Token parseIfStatement(Token token) { Token ifToken = token.next; assert(optional('if', ifToken)); listener.beginIfStatement(ifToken); token = ensureParenthesizedCondition(ifToken); listener.beginThenStatement(token.next); token = parseStatement(token); listener.endThenStatement(token); Token elseToken = null; if (optional('else', token.next)) { elseToken = token.next; listener.beginElseStatement(elseToken); token = parseStatement(elseToken); listener.endElseStatement(elseToken); } listener.endIfStatement(ifToken, elseToken); return token; } /// ``` /// forStatement: /// 'await'? 'for' '(' forLoopParts ')' statement /// ; /// /// forLoopParts: /// localVariableDeclaration ';' expression? ';' expressionList? /// | expression? ';' expression? ';' expressionList? /// | localVariableDeclaration 'in' expression /// | identifier 'in' expression /// ; /// /// forInitializerStatement: /// localVariableDeclaration | /// expression? ';' /// ; /// ``` Token parseForStatement(Token token, Token awaitToken) { Token forToken = token = token.next; assert(awaitToken == null || optional('await', awaitToken)); assert(optional('for', token)); listener.beginForStatement(forToken); token = parseForLoopPartsStart(awaitToken, forToken); Token identifier = token.next; token = parseForLoopPartsMid(token, awaitToken, forToken); if (optional('in', token.next) || optional(':', token.next)) { // Process `for ( ... in ... )` return parseForInRest(token, awaitToken, forToken, identifier); } else { // Process `for ( ... ; ... ; ... )` return parseForRest(awaitToken, token, forToken); } } /// Parse the start of a for loop control structure /// from the open parenthesis up to but not including the identifier. Token parseForLoopPartsStart(Token awaitToken, Token forToken) { Token leftParenthesis = forToken.next; if (!optional('(', leftParenthesis)) { // Recovery reportRecoverableError( leftParenthesis, fasta.templateExpectedButGot.withArguments('(')); BeginToken openParen = rewriter.insertToken( forToken, new SyntheticBeginToken( TokenType.OPEN_PAREN, leftParenthesis.offset)); Token token; if (awaitToken != null) { token = rewriter.insertSyntheticIdentifier(openParen); token = rewriter.insertSyntheticKeyword(token, Keyword.IN); token = rewriter.insertSyntheticIdentifier(token); } else { token = rewriter.insertSyntheticToken(openParen, TokenType.SEMICOLON); token = rewriter.insertSyntheticToken(token, TokenType.SEMICOLON); } openParen.endGroup = token = rewriter.insertToken(token, new SyntheticToken(TokenType.CLOSE_PAREN, leftParenthesis.offset)); token = rewriter.insertSyntheticIdentifier(token); rewriter.insertSyntheticToken(token, TokenType.SEMICOLON); leftParenthesis = openParen; } // Pass `true` so that the [parseExpressionStatementOrDeclaration] only // parses the metadata, modifiers, and type of a local variable // declaration if it exists. This enables capturing [beforeIdentifier] // for later error reporting. return parseExpressionStatementOrDeclaration(leftParenthesis, true); } /// Parse the remainder of the local variable declaration /// or an expression if no local variable declaration was found. Token parseForLoopPartsMid(Token token, Token awaitToken, Token forToken) { if (token != forToken.next) { token = parseVariablesDeclarationRest(token, false); listener.handleForInitializerLocalVariableDeclaration(token); } else if (optional(';', token.next)) { listener.handleForInitializerEmptyStatement(token.next); } else { token = parseExpression(token); listener.handleForInitializerExpressionStatement(token); } Token next = token.next; if (optional(';', next)) { if (awaitToken != null) { reportRecoverableError(awaitToken, fasta.messageInvalidAwaitFor); } } else if (!optional('in', next)) { // Recovery if (optional(':', next)) { reportRecoverableError(next, fasta.messageColonInPlaceOfIn); } else if (awaitToken != null) { reportRecoverableError( next, fasta.templateExpectedButGot.withArguments('in')); token.setNext( new SyntheticKeywordToken(Keyword.IN, next.offset)..setNext(next)); } } return token; } /// This method parses the portion of the forLoopParts that starts with the /// first semicolon (the one that terminates the forInitializerStatement). /// /// ``` /// forLoopParts: /// localVariableDeclaration ';' expression? ';' expressionList? /// | expression? ';' expression? ';' expressionList? /// | localVariableDeclaration 'in' expression /// | identifier 'in' expression /// ; /// ``` Token parseForRest(Token awaitToken, Token token, Token forToken) { token = parseForLoopPartsRest(token, forToken, awaitToken); listener.beginForStatementBody(token.next); LoopState savedLoopState = loopState; loopState = LoopState.InsideLoop; token = parseStatement(token); loopState = savedLoopState; listener.endForStatementBody(token.next); listener.endForStatement(token.next); return token; } Token parseForLoopPartsRest(Token token, Token forToken, Token awaitToken) { Token leftParenthesis = forToken.next; assert(optional('for', forToken)); assert(optional('(', leftParenthesis)); Token leftSeparator = ensureSemicolon(token); if (optional(';', leftSeparator.next)) { token = parseEmptyStatement(leftSeparator); } else { token = parseExpressionStatement(leftSeparator); } int expressionCount = 0; while (true) { Token next = token.next; if (optional(')', next)) { token = next; break; } token = parseExpression(token).next; ++expressionCount; if (!optional(',', token)) { break; } } if (token != leftParenthesis.endGroup) { reportRecoverableErrorWithToken(token, fasta.templateUnexpectedToken); token = leftParenthesis.endGroup; } listener.handleForLoopParts( forToken, leftParenthesis, leftSeparator, expressionCount); return token; } /// This method parses the portion of the forLoopParts that starts with the /// keyword 'in'. For the sake of recovery, we accept a colon in place of the /// keyword. /// /// ``` /// forLoopParts: /// localVariableDeclaration ';' expression? ';' expressionList? /// | expression? ';' expression? ';' expressionList? /// | localVariableDeclaration 'in' expression /// | identifier 'in' expression /// ; /// ``` Token parseForInRest( Token token, Token awaitToken, Token forToken, Token identifier) { token = parseForInLoopPartsRest(token, awaitToken, forToken, identifier); listener.beginForInBody(token.next); LoopState savedLoopState = loopState; loopState = LoopState.InsideLoop; token = parseStatement(token); loopState = savedLoopState; listener.endForInBody(token.next); listener.endForIn(token.next); return token; } Token parseForInLoopPartsRest( Token token, Token awaitToken, Token forToken, Token identifier) { Token inKeyword = token.next; assert(optional('for', forToken)); assert(optional('(', forToken.next)); assert(optional('in', inKeyword) || optional(':', inKeyword)); if (!identifier.isIdentifier) { reportRecoverableErrorWithToken( identifier, fasta.templateExpectedIdentifier); } else if (identifier != token) { if (optional('=', identifier.next)) { reportRecoverableError( identifier.next, fasta.messageInitializedVariableInForEach); } else { reportRecoverableErrorWithToken( identifier.next, fasta.templateUnexpectedToken); } } else if (awaitToken != null && !inAsync) { // TODO(danrubel): consider reporting the error on awaitToken reportRecoverableError(inKeyword, fasta.messageAwaitForNotAsync); } listener.beginForInExpression(inKeyword.next); token = parseExpression(inKeyword); token = ensureCloseParen(token, forToken.next); listener.endForInExpression(token); listener.handleForInLoopParts( awaitToken, forToken, forToken.next, inKeyword); return token; } /// ``` /// whileStatement: /// 'while' '(' expression ')' statement /// ; /// ``` Token parseWhileStatement(Token token) { Token whileToken = token.next; assert(optional('while', whileToken)); listener.beginWhileStatement(whileToken); token = ensureParenthesizedCondition(whileToken); listener.beginWhileStatementBody(token.next); LoopState savedLoopState = loopState; loopState = LoopState.InsideLoop; token = parseStatement(token); loopState = savedLoopState; listener.endWhileStatementBody(token.next); listener.endWhileStatement(whileToken, token.next); return token; } /// ``` /// doStatement: /// 'do' statement 'while' '(' expression ')' ';' /// ; /// ``` Token parseDoWhileStatement(Token token) { Token doToken = token.next; assert(optional('do', doToken)); listener.beginDoWhileStatement(doToken); listener.beginDoWhileStatementBody(doToken.next); LoopState savedLoopState = loopState; loopState = LoopState.InsideLoop; token = parseStatement(doToken); loopState = savedLoopState; listener.endDoWhileStatementBody(token); Token whileToken = token.next; if (!optional('while', whileToken)) { reportRecoverableError( whileToken, fasta.templateExpectedButGot.withArguments('while')); whileToken = rewriter.insertSyntheticKeyword(token, Keyword.WHILE); } token = ensureParenthesizedCondition(whileToken); token = ensureSemicolon(token); listener.endDoWhileStatement(doToken, whileToken, token); return token; } /// ``` /// block: /// '{' statement* '}' /// ; /// ``` Token parseBlock(Token token, String blockKind) { Token begin = token = ensureBlock(token, null, blockKind); listener.beginBlock(begin); int statementCount = 0; Token startToken = token.next; while (notEofOrValue('}', startToken)) { token = parseStatement(token); if (identical(token.next, startToken)) { // No progress was made, so we report the current token as being invalid // and move forward. token = token.next; reportRecoverableError( token, fasta.templateUnexpectedToken.withArguments(token)); } ++statementCount; startToken = token.next; } token = token.next; assert(optional('}', token)); listener.endBlock(statementCount, begin, token); return token; } Token parseInvalidBlock(Token token) { Token begin = token.next; assert(optional('{', begin)); // Parse and report the invalid block, but suppress errors // because an error has already been reported by the caller. Listener originalListener = listener; listener = new ForwardingListener(listener)..forwardErrors = false; // The scanner ensures that `{` always has a closing `}`. token = parseBlock(token, null); listener = originalListener; listener.handleInvalidTopLevelBlock(begin); return token; } /// Determine if the following tokens look like an 'await' expression /// and not a local variable or local function declaration. bool looksLikeAwaitExpression(Token token) { token = token.next; assert(optional('await', token)); token = token.next; // TODO(danrubel): Consider parsing the potential expression following // the `await` token once doing so does not modify the token stream. // For now, use simple look ahead and ensure no false positives. if (token.isIdentifier) { token = token.next; if (optional('(', token)) { token = token.endGroup.next; if (isOneOf(token, [';', '.', '..', '?', '?.'])) { return true; } } else if (isOneOf(token, ['.', ')', ']'])) { return true; } } return false; } /// ``` /// awaitExpression: /// 'await' unaryExpression /// ; /// ``` Token parseAwaitExpression(Token token, bool allowCascades) { Token awaitToken = token.next; assert(optional('await', awaitToken)); listener.beginAwaitExpression(awaitToken); token = parsePrecedenceExpression( awaitToken, POSTFIX_PRECEDENCE, allowCascades); if (inAsync) { listener.endAwaitExpression(awaitToken, token.next); } else { fasta.MessageCode errorCode = fasta.messageAwaitNotAsync; reportRecoverableError(awaitToken, errorCode); listener.endInvalidAwaitExpression(awaitToken, token.next, errorCode); } return token; } /// ``` /// throwExpression: /// 'throw' expression /// ; /// /// throwExpressionWithoutCascade: /// 'throw' expressionWithoutCascade /// ; /// ``` Token parseThrowExpression(Token token, bool allowCascades) { Token throwToken = token.next; assert(optional('throw', throwToken)); if (optional(';', throwToken.next)) { // TODO(danrubel): Find a better way to intercept the parseExpression // recovery to generate this error message rather than explicitly // checking the next token as we are doing here. reportRecoverableError( throwToken.next, fasta.messageMissingExpressionInThrow); rewriter.insertToken( throwToken, new SyntheticStringToken( TokenType.STRING, '""', throwToken.next.charOffset, 0)); } token = allowCascades ? parseExpression(throwToken) : parseExpressionWithoutCascade(throwToken); listener.handleThrowExpression(throwToken, token.next); return token; } /// ``` /// rethrowStatement: /// 'rethrow' ';' /// ; /// ``` Token parseRethrowStatement(Token token) { Token throwToken = token.next; assert(optional('rethrow', throwToken)); listener.beginRethrowStatement(throwToken); token = ensureSemicolon(throwToken); listener.endRethrowStatement(throwToken, token); return token; } /// ``` /// tryStatement: /// 'try' block (onPart+ finallyPart? | finallyPart) /// ; /// /// onPart: /// catchPart block | /// 'on' type catchPart? block /// ; /// /// catchPart: /// 'catch' '(' identifier (',' identifier)? ')' /// ; /// /// finallyPart: /// 'finally' block /// ; /// ``` Token parseTryStatement(Token token) { Token tryKeyword = token.next; assert(optional('try', tryKeyword)); listener.beginTryStatement(tryKeyword); Token lastConsumed = parseBlock(tryKeyword, 'try statement'); token = lastConsumed.next; int catchCount = 0; String value = token.stringValue; while (identical(value, 'catch') || identical(value, 'on')) { listener.beginCatchClause(token); Token onKeyword = null; if (identical(value, 'on')) { // 'on' type catchPart? onKeyword = token; lastConsumed = computeType(token, true).ensureTypeNotVoid(token, this); token = lastConsumed.next; value = token.stringValue; } Token catchKeyword = null; Token comma = null; if (identical(value, 'catch')) { catchKeyword = token; Token openParens = catchKeyword.next; if (!optional("(", openParens)) { reportRecoverableError(openParens, fasta.messageCatchSyntax); openParens = rewriter.insertParens(catchKeyword, true); } Token exceptionName = openParens.next; if (exceptionName.kind != IDENTIFIER_TOKEN) { exceptionName = IdentifierContext.catchParameter .ensureIdentifier(openParens, this); } if (optional(")", exceptionName.next)) { // OK: `catch (identifier)`. } else { comma = exceptionName.next; if (!optional(",", comma)) { // Recovery if (!exceptionName.isSynthetic) { reportRecoverableError(comma, fasta.messageCatchSyntax); } // TODO(danrubel): Consider inserting `on` clause if // exceptionName is preceded by type and followed by a comma. // Then this // } catch (E e, t) { // will recover to // } on E catch (e, t) { // with a detailed explanation for the user in the error // indicating what they should do to fix the code. // TODO(danrubel): Consider inserting synthetic identifier if // exceptionName is a non-synthetic identifier followed by `.`. // Then this // } catch ( // e.f(); // will recover to // } catch (_s_) {} // e.f(); // rather than // } catch (e) {} // _s_.f(); if (openParens.endGroup.isSynthetic) { // The scanner did not place the synthetic ')' correctly. rewriter.moveSynthetic(exceptionName, openParens.endGroup); comma = null; } else { comma = rewriter.insertSyntheticToken(exceptionName, TokenType.COMMA); } } if (comma != null) { Token traceName = comma.next; if (traceName.kind != IDENTIFIER_TOKEN) { traceName = IdentifierContext.catchParameter .ensureIdentifier(comma, this); } if (!optional(")", traceName.next)) { // Recovery if (!traceName.isSynthetic) { reportRecoverableError( traceName.next, fasta.messageCatchSyntaxExtraParameters); } if (openParens.endGroup.isSynthetic) { // The scanner did not place the synthetic ')' correctly. rewriter.moveSynthetic(traceName, openParens.endGroup); } } } } lastConsumed = parseFormalParameters(catchKeyword, MemberKind.Catch); token = lastConsumed.next; } listener.endCatchClause(token); lastConsumed = parseBlock(lastConsumed, 'catch clause'); token = lastConsumed.next; ++catchCount; listener.handleCatchBlock(onKeyword, catchKeyword, comma); value = token.stringValue; // while condition } Token finallyKeyword = null; if (optional('finally', token)) { finallyKeyword = token; lastConsumed = parseBlock(token, 'finally clause'); token = lastConsumed.next; listener.handleFinallyBlock(finallyKeyword); } else { if (catchCount == 0) { reportRecoverableError(tryKeyword, fasta.messageOnlyTry); } } listener.endTryStatement(catchCount, tryKeyword, finallyKeyword); return lastConsumed; } /// ``` /// switchStatement: /// 'switch' parenthesizedExpression switchBlock /// ; /// ``` Token parseSwitchStatement(Token token) { Token switchKeyword = token.next; assert(optional('switch', switchKeyword)); listener.beginSwitchStatement(switchKeyword); token = ensureParenthesizedCondition(switchKeyword); LoopState savedLoopState = loopState; if (loopState == LoopState.OutsideLoop) { loopState = LoopState.InsideSwitch; } token = parseSwitchBlock(token); loopState = savedLoopState; listener.endSwitchStatement(switchKeyword, token); return token; } /// ``` /// switchBlock: /// '{' switchCase* defaultCase? '}' /// ; /// ``` Token parseSwitchBlock(Token token) { Token beginSwitch = token = ensureBlock(token, null, 'switch statement'); listener.beginSwitchBlock(beginSwitch); int caseCount = 0; Token defaultKeyword = null; Token colonAfterDefault = null; while (notEofOrValue('}', token.next)) { Token beginCase = token.next; int expressionCount = 0; int labelCount = 0; Token peek = peekPastLabels(beginCase); while (true) { // Loop until we find something that can't be part of a switch case. String value = peek.stringValue; if (identical(value, 'default')) { while (!identical(token.next, peek)) { token = parseLabel(token); labelCount++; } if (defaultKeyword != null) { reportRecoverableError( token.next, fasta.messageSwitchHasMultipleDefaults); } defaultKeyword = token.next; colonAfterDefault = token = ensureColon(defaultKeyword); peek = token.next; break; } else if (identical(value, 'case')) { while (!identical(token.next, peek)) { token = parseLabel(token); labelCount++; } Token caseKeyword = token.next; if (defaultKeyword != null) { reportRecoverableError( caseKeyword, fasta.messageSwitchHasCaseAfterDefault); } listener.beginCaseExpression(caseKeyword); token = parseExpression(caseKeyword); token = ensureColon(token); listener.endCaseExpression(token); listener.handleCaseMatch(caseKeyword, token); expressionCount++; peek = peekPastLabels(token.next); } else if (expressionCount > 0) { break; } else { // Recovery reportRecoverableError( peek, fasta.templateExpectedToken.withArguments("case")); Token endGroup = beginSwitch.endGroup; while (token.next != endGroup) { token = token.next; } peek = peekPastLabels(token.next); break; } } token = parseStatementsInSwitchCase(token, peek, beginCase, labelCount, expressionCount, defaultKeyword, colonAfterDefault); ++caseCount; } token = token.next; listener.endSwitchBlock(caseCount, beginSwitch, token); assert(optional('}', token)); return token; } /// Peek after the following labels (if any). The following token /// is used to determine if the labels belong to a statement or a /// switch case. Token peekPastLabels(Token token) { while (token.isIdentifier && optional(':', token.next)) { token = token.next.next; } return token; } /// Parse statements after a switch `case:` or `default:`. Token parseStatementsInSwitchCase( Token token, Token peek, Token begin, int labelCount, int expressionCount, Token defaultKeyword, Token colonAfterDefault) { listener.beginSwitchCase(labelCount, expressionCount, begin); // Finally zero or more statements. int statementCount = 0; while (!identical(token.next.kind, EOF_TOKEN)) { String value = peek.stringValue; if ((identical(value, 'case')) || (identical(value, 'default')) || ((identical(value, '}')) && (identical(token.next, peek)))) { // A label just before "}" will be handled as a statement error. break; } else { Token startToken = token.next; token = parseStatement(token); Token next = token.next; if (identical(next, startToken)) { // No progress was made, so we report the current token as being // invalid and move forward. reportRecoverableError( next, fasta.templateUnexpectedToken.withArguments(next)); token = next; } ++statementCount; } peek = peekPastLabels(token.next); } listener.endSwitchCase(labelCount, expressionCount, defaultKeyword, colonAfterDefault, statementCount, begin, token.next); return token; } /// ``` /// breakStatement: /// 'break' identifier? ';' /// ; /// ``` Token parseBreakStatement(Token token) { Token breakKeyword = token = token.next; assert(optional('break', breakKeyword)); bool hasTarget = false; if (token.next.isIdentifier) { token = ensureIdentifier(token, IdentifierContext.labelReference); hasTarget = true; } else if (!isBreakAllowed) { reportRecoverableError(breakKeyword, fasta.messageBreakOutsideOfLoop); } token = ensureSemicolon(token); listener.handleBreakStatement(hasTarget, breakKeyword, token); return token; } /// ``` /// assertion: /// 'assert' '(' expression (',' expression)? ','? ')' /// ; /// ``` Token parseAssert(Token token, Assert kind) { token = token.next; assert(optional('assert', token)); listener.beginAssert(token, kind); Token assertKeyword = token; Token leftParenthesis = token.next; if (!optional('(', leftParenthesis)) { // Recovery reportRecoverableError( leftParenthesis, fasta.templateExpectedButGot.withArguments('(')); leftParenthesis = rewriter.insertParens(token, true); } token = leftParenthesis; Token commaToken = null; bool old = mayParseFunctionExpressions; mayParseFunctionExpressions = true; token = parseExpression(token); if (optional(',', token.next)) { token = token.next; if (!optional(')', token.next)) { commaToken = token; token = parseExpression(token); if (optional(',', token.next)) { // Trailing comma is ignored. token = token.next; } } } Token endGroup = leftParenthesis.endGroup; if (token.next == endGroup) { token = endGroup; } else { // Recovery if (endGroup.isSynthetic) { // The scanner did not place the synthetic ')' correctly, so move it. token = rewriter.moveSynthetic(token, endGroup); } else { reportRecoverableErrorWithToken( token.next, fasta.templateUnexpectedToken); token = endGroup; } } assert(optional(')', token)); mayParseFunctionExpressions = old; if (kind == Assert.Expression) { reportRecoverableError(assertKeyword, fasta.messageAssertAsExpression); } else if (kind == Assert.Statement) { ensureSemicolon(token); } listener.endAssert( assertKeyword, kind, leftParenthesis, commaToken, token.next); return token; } /// ``` /// assertStatement: /// assertion ';' /// ; /// ``` Token parseAssertStatement(Token token) { assert(optional('assert', token.next)); // parseAssert ensures that there is a trailing semicolon. return parseAssert(token, Assert.Statement).next; } /// ``` /// continueStatement: /// 'continue' identifier? ';' /// ; /// ``` Token parseContinueStatement(Token token) { Token continueKeyword = token = token.next; assert(optional('continue', continueKeyword)); bool hasTarget = false; if (token.next.isIdentifier) { token = ensureIdentifier(token, IdentifierContext.labelReference); hasTarget = true; if (!isContinueWithLabelAllowed) { reportRecoverableError( continueKeyword, fasta.messageContinueOutsideOfLoop); } } else if (!isContinueAllowed) { reportRecoverableError( continueKeyword, loopState == LoopState.InsideSwitch ? fasta.messageContinueWithoutLabelInCase : fasta.messageContinueOutsideOfLoop); } token = ensureSemicolon(token); listener.handleContinueStatement(hasTarget, continueKeyword, token); return token; } /// ``` /// emptyStatement: /// ';' /// ; /// ``` Token parseEmptyStatement(Token token) { token = token.next; assert(optional(';', token)); listener.handleEmptyStatement(token); return token; } /// Given a token ([beforeToken]) that is known to be before another [token], /// return the token that is immediately before the [token]. Token previousToken(Token beforeToken, Token token) { Token next = beforeToken.next; while (next != token && next != beforeToken) { beforeToken = next; next = beforeToken.next; } return beforeToken; } /// Recover from finding an operator declaration missing the `operator` /// keyword. The metadata for the member, if any, has already been parsed /// (and events have already been generated). Token parseInvalidOperatorDeclaration( Token beforeStart, Token externalToken, Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, Token beforeType, DeclarationKind kind) { TypeInfo typeInfo = computeType(beforeType, true, true); Token beforeName = typeInfo.skipType(beforeType); Token next = beforeName.next; if (optional('operator', next)) { next = next.next; } else { reportRecoverableError(next, fasta.messageMissingOperatorKeyword); rewriter.insertSyntheticKeyword(beforeName, Keyword.OPERATOR); } assert((next.isOperator && next.endGroup == null) || optional('===', next) || optional('!==', next)); Token token = parseMethod( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, null, beforeName.next, kind, null); listener.endMember(); return token; } /// Recover from finding an invalid class member. The metadata for the member, /// if any, has already been parsed (and events have already been generated). /// The member was expected to start with the token after [token]. Token recoverFromInvalidMember( Token token, Token beforeStart, Token externalToken, Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, Token beforeType, TypeInfo typeInfo, Token getOrSet, DeclarationKind kind, String enclosingDeclarationName) { Token next = token.next; String value = next.stringValue; if (identical(value, 'class')) { return reportAndSkipClassInClass(next); } else if (identical(value, 'enum')) { return reportAndSkipEnumInClass(next); } else if (identical(value, 'typedef')) { return reportAndSkipTypedefInClass(next); } else if (next.isOperator && next.endGroup == null) { return parseInvalidOperatorDeclaration( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, kind); } if (getOrSet != null || identical(value, '(') || identical(value, '=>') || identical(value, '{')) { token = parseMethod( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, getOrSet, token.next, kind, enclosingDeclarationName); } else if (token == beforeStart) { // TODO(danrubel): Provide a more specific error message for extra ';'. reportRecoverableErrorWithToken(next, fasta.templateExpectedClassMember); listener.handleInvalidMember(next); if (!identical(value, '}')) { // Ensure we make progress. token = next; } } else { token = parseFields( beforeStart, externalToken, staticToken, covariantToken, lateToken, varFinalOrConst, beforeType, typeInfo, token.next, kind); } listener.endMember(); return token; } /// Report that the nesting depth of the code being parsed is too large for /// the parser to safely handle. Return the next `}` or EOF. Token recoverFromStackOverflow(Token token) { Token next = token.next; reportRecoverableError(next, fasta.messageStackOverflow); next = rewriter.insertSyntheticToken(token, TokenType.SEMICOLON); listener.handleEmptyStatement(next); while (notEofOrValue('}', next)) { token = next; next = token.next; } return token; } void reportRecoverableError(Token token, Message message) { // Find a non-synthetic token on which to report the error. token = findNonZeroLengthToken(token); listener.handleRecoverableError(message, token, token); } void reportRecoverableErrorWithToken( Token token, Template<_MessageWithArgument<Token>> template) { // Find a non-synthetic token on which to report the error. token = findNonZeroLengthToken(token); listener.handleRecoverableError( template.withArguments(token), token, token); } Token reportAllErrorTokens(Token token) { while (token is ErrorToken) { listener.handleErrorToken(token); token = token.next; } return token; } Token skipErrorTokens(Token token) { while (token is ErrorToken) { token = token.next; } return token; } Token parseInvalidTopLevelDeclaration(Token token) { Token next = token.next; reportRecoverableErrorWithToken( next, optional(';', next) ? fasta.templateUnexpectedToken : fasta.templateExpectedDeclaration); if (optional('{', next)) { next = parseInvalidBlock(token); } listener.handleInvalidTopLevelDeclaration(next); return next; } Token reportAndSkipClassInClass(Token token) { assert(optional('class', token)); reportRecoverableError(token, fasta.messageClassInClass); listener.handleInvalidMember(token); Token next = token.next; // If the declaration appears to be a valid class declaration // then skip the entire declaration so that we only generate the one // error (above) rather than a plethora of unhelpful errors. if (next.isIdentifier) { // skip class name token = next; next = token.next; // TODO(danrubel): consider parsing (skipping) the class header // with a recovery listener so that no events are generated if (optional('{', next) && next.endGroup != null) { // skip class body token = next.endGroup; } } return token; } Token reportAndSkipEnumInClass(Token token) { assert(optional('enum', token)); reportRecoverableError(token, fasta.messageEnumInClass); listener.handleInvalidMember(token); Token next = token.next; // If the declaration appears to be a valid enum declaration // then skip the entire declaration so that we only generate the one // error (above) rather than a plethora of unhelpful errors. if (next.isIdentifier) { // skip enum name token = next; next = token.next; if (optional('{', next) && next.endGroup != null) { // TODO(danrubel): Consider replacing this `skip enum` functionality // with something that can parse and resolve the declaration // even though it is in a class context token = next.endGroup; } } return token; } Token reportAndSkipTypedefInClass(Token token) { assert(optional('typedef', token)); reportRecoverableError(token, fasta.messageTypedefInClass); listener.handleInvalidMember(token); // TODO(brianwilkerson): If the declaration appears to be a valid typedef // then skip the entire declaration so that we generate a single error // (above) rather than many unhelpful errors. return token; } /// Create a short token chain from the [beginToken] and [endToken] and return /// the [beginToken]. Token link(BeginToken beginToken, Token endToken) { beginToken.setNext(endToken); beginToken.endGroup = endToken; return beginToken; } /// Create and return a token whose next token is the given [token]. Token syntheticPreviousToken(Token token) { // Return the previous token if there is one so that any token inserted // before `token` will be properly inserted into the token stream. // TODO(danrubel): remove this once all methods have been converted to // use and return the last token consumed and the `previous` field // has been removed. if (token.previous != null) { return token.previous; } Token before = new Token.eof(-1); before.next = token; return before; } /// Return the first dartdoc comment token preceding the given token /// or `null` if no dartdoc token is found. Token findDartDoc(Token token) { Token comments = token.precedingComments; Token dartdoc = null; bool isMultiline = false; while (comments != null) { String lexeme = comments.lexeme; if (lexeme.startsWith('///')) { if (!isMultiline) { dartdoc = comments; isMultiline = true; } } else if (lexeme.startsWith('/**')) { dartdoc = comments; isMultiline = false; } comments = comments.next; } return dartdoc; } /// Parse the comment references in a sequence of comment tokens /// where [dartdoc] (not null) is the first token in the sequence. /// Return the number of comment references parsed. int parseCommentReferences(Token dartdoc) { return dartdoc.lexeme.startsWith('///') ? parseReferencesInSingleLineComments(dartdoc) : parseReferencesInMultiLineComment(dartdoc); } /// Parse the comment references in a multi-line comment token. /// Return the number of comment references parsed. int parseReferencesInMultiLineComment(Token multiLineDoc) { String comment = multiLineDoc.lexeme; assert(comment.startsWith('/**')); int count = 0; int length = comment.length; int start = 3; bool inCodeBlock = false; int codeBlock = comment.indexOf('```', 3); if (codeBlock == -1) { codeBlock = length; } while (start < length) { if (isWhitespace(comment.codeUnitAt(start))) { ++start; continue; } int end = comment.indexOf('\n', start); if (end == -1) { end = length; } if (codeBlock < end) { inCodeBlock = !inCodeBlock; codeBlock = comment.indexOf('```', end); if (codeBlock == -1) { codeBlock = length; } } if (!inCodeBlock && !comment.startsWith('* ', start)) { count += parseCommentReferencesInText(multiLineDoc, start, end); } start = end + 1; } return count; } /// Parse the comment references in a sequence of single line comment tokens /// where [token] is the first comment token in the sequence. /// Return the number of comment references parsed. int parseReferencesInSingleLineComments(Token token) { int count = 0; bool inCodeBlock = false; while (token != null && !token.isEof) { String comment = token.lexeme; if (comment.startsWith('///')) { if (comment.indexOf('```', 3) != -1) { inCodeBlock = !inCodeBlock; } if (!inCodeBlock && !comment.startsWith('/// ')) { count += parseCommentReferencesInText(token, 3, comment.length); } } token = token.next; } return count; } /// Parse the comment references in the text between [start] inclusive /// and [end] exclusive. Return a count indicating how many were parsed. int parseCommentReferencesInText(Token commentToken, int start, int end) { String comment = commentToken.lexeme; int count = 0; int index = start; while (index < end) { int ch = comment.codeUnitAt(index); if (ch == 0x5B /* `[` */) { ++index; if (index < end && comment.codeUnitAt(index) == 0x3A /* `:` */) { // Skip old-style code block. index = comment.indexOf(':]', index + 1) + 1; if (index == 0 || index > end) { break; } } else { int referenceStart = index; index = comment.indexOf(']', index); if (index == -1 || index >= end) { // Recovery: terminating ']' is not typed yet. index = findReferenceEnd(comment, referenceStart, end); } if (ch != 0x27 /* `'` */ && ch != 0x22 /* `"` */) { if (isLinkText(comment, index)) { // TODO(brianwilkerson) Handle the case where there's a library // URI in the link text. } else { listener.handleCommentReferenceText( comment.substring(referenceStart, index), commentToken.charOffset + referenceStart); ++count; } } } } else if (ch == 0x60 /* '`' */) { // Skip inline code block if there is both starting '`' and ending '`' int endCodeBlock = comment.indexOf('`', index + 1); if (endCodeBlock != -1 && endCodeBlock < end) { index = endCodeBlock; } } ++index; } return count; } /// Given a comment reference without a closing `]`, /// search for a possible place where `]` should be. int findReferenceEnd(String comment, int index, int end) { // Find the end of the identifier if there is one if (index >= end || !isLetter(comment.codeUnitAt(index))) { return index; } while (index < end && isLetterOrDigit(comment.codeUnitAt(index))) { ++index; } // Check for a trailing `.` if (index >= end || comment.codeUnitAt(index) != 0x2E /* `.` */) { return index; } ++index; // Find end of the identifier after the `.` if (index >= end || !isLetter(comment.codeUnitAt(index))) { return index; } ++index; while (index < end && isLetterOrDigit(comment.codeUnitAt(index))) { ++index; } return index; } /// Parse the tokens in a single comment reference and generate either a /// `handleCommentReference` or `handleNoCommentReference` event. /// Return `true` if a comment reference was successfully parsed. bool parseOneCommentReference(Token token, int referenceOffset) { Token begin = token; Token newKeyword = null; if (optional('new', token)) { newKeyword = token; token = token.next; } Token prefix, period; if (token.isIdentifier && optional('.', token.next)) { prefix = token; period = token.next; token = period.next; } if (token.isEof) { // Recovery: Insert a synthetic identifier for code completion token = rewriter.insertSyntheticIdentifier( period ?? newKeyword ?? syntheticPreviousToken(token)); if (begin == token.next) { begin = token; } } Token operatorKeyword = null; if (optional('operator', token)) { operatorKeyword = token; token = token.next; } if (token.isUserDefinableOperator) { if (token.next.isEof) { parseOneCommentReferenceRest( begin, referenceOffset, newKeyword, prefix, period, token); return true; } } else { token = operatorKeyword ?? token; if (token.next.isEof) { if (token.isIdentifier) { parseOneCommentReferenceRest( begin, referenceOffset, newKeyword, prefix, period, token); return true; } Keyword keyword = token.keyword; if (newKeyword == null && prefix == null && (keyword == Keyword.THIS || keyword == Keyword.NULL || keyword == Keyword.TRUE || keyword == Keyword.FALSE)) { // TODO(brianwilkerson) If we want to support this we will need to // extend the definition of CommentReference to take an expression // rather than an identifier. For now we just ignore it to reduce the // number of errors produced, but that's probably not a valid long // term approach. } } } listener.handleNoCommentReference(); return false; } void parseOneCommentReferenceRest( Token begin, int referenceOffset, Token newKeyword, Token prefix, Token period, Token identifierOrOperator) { // Adjust the token offsets to match the enclosing comment token. Token token = begin; do { token.offset += referenceOffset; token = token.next; } while (!token.isEof); listener.handleCommentReference( newKeyword, prefix, period, identifierOrOperator); } /// Given that we have just found bracketed text within the given [comment], /// look to see whether that text is (a) followed by a parenthesized link /// address, (b) followed by a colon, or (c) followed by optional whitespace /// and another square bracket. The [rightIndex] is the index of the right /// bracket. Return `true` if the bracketed text is followed by a link /// address. /// /// This method uses the syntax described by the /// <a href="http://daringfireball.net/projects/markdown/syntax">markdown</a> /// project. bool isLinkText(String comment, int rightIndex) { int length = comment.length; int index = rightIndex + 1; if (index >= length) { return false; } int ch = comment.codeUnitAt(index); if (ch == 0x28 || ch == 0x3A) { return true; } while (isWhitespace(ch)) { index = index + 1; if (index >= length) { return false; } ch = comment.codeUnitAt(index); } return ch == 0x5B; } } // TODO(ahe): Remove when analyzer supports generalized function syntax. typedef _MessageWithArgument<T> = Message Function(T);
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/modifier_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 '../../scanner/token.dart' show Keyword, Token; import '../messages.dart' as fasta; import 'formal_parameter_kind.dart'; import 'member_kind.dart' show MemberKind; import 'parser.dart' show Parser; import 'util.dart' show optional; bool isModifier(Token token) { if (!token.isModifier) { return false; } else if (token.type.isBuiltIn) { // A built-in keyword can only be a modifier as long as it is // followed by another keyword or an identifier. Otherwise, it is the // identifier. // // For example, `external` is a modifier in this declaration: // external Foo foo(); // but is the identifier in this declaration // external() => true; // and in // for (final external in list) { } Token next = token.next; Keyword keyword = next.keyword; if (keyword == null && !next.isIdentifier || keyword == Keyword.IN) { return false; } } return true; } /// This class is used to parse modifiers in most locations where modifiers /// can occur, but does not call handleModifier or handleModifiers. class ModifierRecoveryContext { final Parser parser; Token abstractToken; Token constToken; Token covariantToken; Token externalToken; Token finalToken; Token lateToken; Token requiredToken; Token staticToken; Token varToken; // Set `true` when parsing modifiers after the `factory` token. bool afterFactory = false; // TODO(danrubel): Replace [ModifierRecoveryContext] and [ModifierContext] // with this class. ModifierRecoveryContext(this.parser); set staticOrCovariant(Token staticOrCovariant) { if (staticOrCovariant == null) { covariantToken = null; staticToken = null; } else if (optional('covariant', staticOrCovariant)) { covariantToken = staticOrCovariant; staticToken = null; } else if (optional('static', staticOrCovariant)) { covariantToken = null; staticToken = staticOrCovariant; } else { throw "Internal error: " "Unexpected staticOrCovariant '$staticOrCovariant'."; } } Token get varFinalOrConst => varToken ?? finalToken ?? constToken; set varFinalOrConst(Token varFinalOrConst) { if (varFinalOrConst == null) { varToken = null; finalToken = null; constToken = null; } else if (optional('var', varFinalOrConst)) { varToken = varFinalOrConst; finalToken = null; constToken = null; } else if (optional('final', varFinalOrConst)) { varToken = null; finalToken = varFinalOrConst; constToken = null; } else if (optional('const', varFinalOrConst)) { varToken = null; finalToken = null; constToken = varFinalOrConst; } else { throw "Internal error: Unexpected varFinalOrConst '$varFinalOrConst'."; } } /// Parse modifiers for class methods and fields. Token parseClassMemberModifiers(Token token) { token = parseModifiers(token); if (abstractToken != null) { parser.reportRecoverableError( abstractToken, fasta.messageAbstractClassMember); } reportExtraneousModifier(requiredToken); return token; } /// Parse modifiers for formal parameters. Token parseFormalParameterModifiers( Token token, FormalParameterKind parameterKind, MemberKind memberKind) { token = parseModifiers(token); if (parameterKind != FormalParameterKind.optionalNamed) { reportExtraneousModifier(requiredToken); } if (memberKind == MemberKind.StaticMethod || memberKind == MemberKind.TopLevelMethod) { reportExtraneousModifier(this.covariantToken); this.covariantToken = null; } if (constToken != null) { reportExtraneousModifier(constToken); } else if (memberKind == MemberKind.GeneralizedFunctionType) { if (varFinalOrConst != null) { parser.reportRecoverableError( varFinalOrConst, fasta.messageFunctionTypedParameterVar); } } reportExtraneousModifier(abstractToken); reportExtraneousModifier(externalToken); reportExtraneousModifier(lateToken); reportExtraneousModifier(staticToken); return token; } /// Parse modifiers after the `factory` token. Token parseModifiersAfterFactory(Token token) { afterFactory = true; token = parseModifiers(token); if (abstractToken != null) { parser.reportRecoverableError( abstractToken, fasta.messageAbstractClassMember); } reportExtraneousModifier(lateToken); reportExtraneousModifier(requiredToken); return token; } /// Parse modifiers for top level functions and fields. Token parseTopLevelModifiers(Token token) { token = parseModifiers(token); reportExtraneousModifier(abstractToken); reportExtraneousModifier(covariantToken); reportExtraneousModifier(requiredToken); reportExtraneousModifier(staticToken); return token; } /// Parse modifiers for variable declarations. Token parseVariableDeclarationModifiers(Token token) { token = parseModifiers(token); reportExtraneousModifier(abstractToken); reportExtraneousModifier(covariantToken); reportExtraneousModifier(externalToken); reportExtraneousModifier(requiredToken); reportExtraneousModifier(staticToken); return token; } /// Parse modifiers during recovery when modifiers are out of order /// or invalid. Typically clients call methods like /// [parseClassMemberModifiers] which in turn calls this method, /// rather than calling this method directly. /// /// The various modifier token parameters represent tokens of modifiers /// that have already been parsed prior to recovery. The [staticOrCovariant] /// parameter is for convenience if caller has a token that may be either /// `static` or `covariant`. The first non-null parameter of /// [staticOrCovariant], [staticToken], or [covariantToken] will be used, /// in that order, and the others ignored. Token parseModifiers(Token token) { // Process invalid and out-of-order modifiers Token next = token.next; while (true) { final String value = next.stringValue; if (isModifier(next)) { if (identical('abstract', value)) { token = parseAbstract(token); } else if (identical('const', value)) { token = parseConst(token); } else if (identical('covariant', value)) { token = parseCovariant(token); } else if (identical('external', value)) { token = parseExternal(token); } else if (identical('final', value)) { token = parseFinal(token); } else if (identical('late', value)) { token = parseLate(token); } else if (identical('required', value)) { token = parseRequired(token); } else if (identical('static', value)) { token = parseStatic(token); } else if (identical('var', value)) { token = parseVar(token); } else { throw 'Internal Error: Unhandled modifier: $value'; } } else if (afterFactory && identical('factory', value)) { parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); token = next; } else { break; } next = token.next; } return token; } Token parseAbstract(Token token) { Token next = token.next; assert(optional('abstract', next)); if (abstractToken == null) { abstractToken = next; return next; } // Recovery parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); return next; } Token parseConst(Token token) { Token next = token.next; assert(optional('const', next)); if (varFinalOrConst == null && covariantToken == null) { constToken = next; if (afterFactory) { reportModifierOutOfOrder(next, 'factory'); } else if (lateToken != null) { reportConflictingModifiers(next, lateToken); } return next; } // Recovery if (constToken != null) { parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); } else if (covariantToken != null) { reportConflictingModifiers(next, covariantToken); } else if (finalToken != null) { parser.reportRecoverableError(next, fasta.messageConstAndFinal); } else if (varToken != null) { reportConflictingModifiers(next, varToken); } else { throw 'Internal Error: Unexpected varFinalOrConst: $varFinalOrConst'; } return next; } Token parseCovariant(Token token) { Token next = token.next; assert(optional('covariant', next)); if (constToken == null && covariantToken == null && staticToken == null && !afterFactory) { covariantToken = next; if (varToken != null) { reportModifierOutOfOrder(next, varToken.lexeme); } else if (finalToken != null) { reportModifierOutOfOrder(next, finalToken.lexeme); } else if (lateToken != null) { reportModifierOutOfOrder(next, lateToken.lexeme); } return next; } // Recovery if (covariantToken != null) { parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); } else if (afterFactory) { reportExtraneousModifier(next); } else if (constToken != null) { reportConflictingModifiers(next, constToken); } else if (staticToken != null) { parser.reportRecoverableError(next, fasta.messageCovariantAndStatic); } else { throw 'Internal Error: Unhandled recovery: $next'; } return next; } Token parseExternal(Token token) { Token next = token.next; assert(optional('external', next)); if (externalToken == null) { externalToken = next; if (afterFactory) { reportModifierOutOfOrder(next, 'factory'); } else if (constToken != null) { reportModifierOutOfOrder(next, constToken.lexeme); } else if (staticToken != null) { reportModifierOutOfOrder(next, staticToken.lexeme); } else if (lateToken != null) { reportModifierOutOfOrder(next, lateToken.lexeme); } return next; } // Recovery parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); return next; } Token parseFinal(Token token) { Token next = token.next; assert(optional('final', next)); if (varFinalOrConst == null && !afterFactory) { finalToken = next; return next; } // Recovery if (finalToken != null) { parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); } else if (afterFactory) { reportExtraneousModifier(next); } else if (constToken != null) { parser.reportRecoverableError(next, fasta.messageConstAndFinal); } else if (varToken != null) { parser.reportRecoverableError(next, fasta.messageFinalAndVar); } else if (lateToken != null) { reportModifierOutOfOrder(next, lateToken.lexeme); } else { throw 'Internal Error: Unexpected varFinalOrConst: $varFinalOrConst'; } return next; } Token parseLate(Token token) { Token next = token.next; assert(optional('late', next)); if (lateToken == null) { lateToken = next; if (constToken != null) { reportConflictingModifiers(next, constToken); } else if (varToken != null) { reportModifierOutOfOrder(next, varToken.lexeme); } else if (finalToken != null) { reportModifierOutOfOrder(next, finalToken.lexeme); } return next; } // Recovery parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); return next; } Token parseRequired(Token token) { Token next = token.next; assert(optional('required', next)); if (requiredToken == null) { requiredToken = next; if (constToken != null) { reportModifierOutOfOrder(requiredToken, constToken.lexeme); } else if (covariantToken != null) { reportModifierOutOfOrder(requiredToken, covariantToken.lexeme); } else if (finalToken != null) { reportModifierOutOfOrder(requiredToken, finalToken.lexeme); } else if (varToken != null) { reportModifierOutOfOrder(requiredToken, varToken.lexeme); } return next; } // Recovery parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); return next; } Token parseStatic(Token token) { Token next = token.next; assert(optional('static', next)); if (covariantToken == null && staticToken == null && !afterFactory) { staticToken = next; if (constToken != null) { reportModifierOutOfOrder(next, constToken.lexeme); } else if (finalToken != null) { reportModifierOutOfOrder(next, finalToken.lexeme); } else if (varToken != null) { reportModifierOutOfOrder(next, varToken.lexeme); } else if (lateToken != null) { reportModifierOutOfOrder(next, lateToken.lexeme); } return next; } // Recovery if (covariantToken != null) { parser.reportRecoverableError(next, fasta.messageCovariantAndStatic); } else if (staticToken != null) { parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); } else if (afterFactory) { reportExtraneousModifier(next); } else { throw 'Internal Error: Unhandled recovery: $next'; } return next; } Token parseVar(Token token) { Token next = token.next; assert(optional('var', next)); if (varFinalOrConst == null && !afterFactory) { varToken = next; return next; } // Recovery if (varToken != null) { parser.reportRecoverableErrorWithToken( next, fasta.templateDuplicatedModifier); } else if (afterFactory) { reportExtraneousModifier(next); } else if (constToken != null) { reportConflictingModifiers(next, constToken); } else if (finalToken != null) { parser.reportRecoverableError(next, fasta.messageFinalAndVar); } else { throw 'Internal Error: Unexpected varFinalOrConst: $varFinalOrConst'; } return next; } void reportConflictingModifiers(Token modifier, Token earlierModifier) { parser.reportRecoverableError( modifier, fasta.templateConflictingModifiers .withArguments(modifier.lexeme, earlierModifier.lexeme)); } void reportExtraneousModifier(Token modifier) { if (modifier != null) { parser.reportRecoverableErrorWithToken( modifier, fasta.templateExtraneousModifier); } } void reportModifierOutOfOrder(Token modifier, String beforeModifier) { parser.reportRecoverableError( modifier, fasta.templateModifierOutOfOrder .withArguments(modifier.lexeme, beforeModifier)); } }
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/parser_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 file. library fasta.parser.main; import 'dart:convert' show LineSplitter, utf8; import 'dart:io' show File; import '../../scanner/token.dart' show Token; import '../scanner/io.dart' show readBytesFromFileSync; import '../scanner.dart' show scan; import 'listener.dart' show Listener; import 'top_level_parser.dart' show TopLevelParser; import 'identifier_context.dart' show IdentifierContext; class DebugListener extends Listener { void handleIdentifier(Token token, IdentifierContext context) { logEvent("Identifier: ${token.lexeme}"); } void logEvent(String name) { print(name); } } mainEntryPoint(List<String> arguments) async { for (String argument in arguments) { if (argument.startsWith("@")) { Uri uri = Uri.base.resolve(argument.substring(1)); await for (String file in new File.fromUri(uri) .openRead() .cast<List<int>>() .transform(utf8.decoder) .transform(const LineSplitter())) { outLine(uri.resolve(file)); } } else { outLine(Uri.base.resolve(argument)); } } } void outLine(Uri uri) { new TopLevelParser(new DebugListener()) .parseUnit(scan(readBytesFromFileSync(uri)).tokens); }
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/type_info.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.type_info; import '../../scanner/token.dart' show Token, TokenType; import '../scanner/token_constants.dart' show IDENTIFIER_TOKEN, KEYWORD_TOKEN; import 'parser.dart' show Parser; import 'type_info_impl.dart'; import 'util.dart' show isOneOf, optional; /// [TypeInfo] provides information collected by [computeType] /// about a particular type reference. abstract class TypeInfo { /// Return type info representing the receiver without the trailing `?` /// or the receiver if the receiver does not represent a nullable type. TypeInfo get asNonNullable; /// Return `true` if the tokens comprising the type represented by the /// receiver could be interpreted as a valid standalone expression. /// For example, `A` or `A.b` could be interpreted as type references /// or expressions, while `A<T>` only looks like a type reference. bool get couldBeExpression; /// Return true if the receiver has a trailing `?`. bool get isNullable; /// Call this function when the token after [token] must be a type (not void). /// This function will call the appropriate event methods on the [Parser]'s /// listener to handle the type, inserting a synthetic type reference if /// necessary. This may modify the token stream when parsing `>>` or `>>>` /// or `>>>=` in valid code or during recovery. Token ensureTypeNotVoid(Token token, Parser parser); /// Call this function when the token after [token] must be a type or void. /// This function will call the appropriate event methods on the [Parser]'s /// listener to handle the type, inserting a synthetic type reference if /// necessary. This may modify the token stream when parsing `>>` or `>>>` /// or `>>>=` in valid code or during recovery. Token ensureTypeOrVoid(Token token, Parser parser); /// Call this function to parse an optional type (not void) after [token]. /// This function will call the appropriate event methods on the [Parser]'s /// listener to handle the type. This may modify the token stream /// when parsing `>>` or `>>>` or `>>>=` in valid code or during recovery. Token parseTypeNotVoid(Token token, Parser parser); /// Call this function to parse an optional type or void after [token]. /// This function will call the appropriate event methods on the [Parser]'s /// listener to handle the type. This may modify the token stream /// when parsing `>>` or `>>>` or `>>>=` in valid code or during recovery. Token parseType(Token token, Parser parser); /// Call this function with the [token] before the type to obtain /// the last token in the type. If there is no type, then this method /// will return [token]. This does not modify the token stream. Token skipType(Token token); } /// [TypeParamOrArgInfo] provides information collected by /// [computeTypeParamOrArg] about a particular group of type arguments /// or type parameters. abstract class TypeParamOrArgInfo { const TypeParamOrArgInfo(); /// Return `true` if the receiver represents a single type argument bool get isSimpleTypeArgument => false; /// Return the number of type arguments int get typeArgumentCount; /// Return the simple type associated with this simple type argument /// or throw an exception if this is not a simple type argument. TypeInfo get typeInfo { throw "Internal error: $runtimeType is not a SimpleTypeArgument."; } /// Call this function to parse optional type arguments after [token]. /// This function will call the appropriate event methods on the [Parser]'s /// listener to handle the arguments. This may modify the token stream /// when parsing `>>` or `>>>` or `>>>=` in valid code or during recovery. Token parseArguments(Token token, Parser parser); /// Call this function to parse optional type parameters /// (also known as type variables) after [token]. /// This function will call the appropriate event methods on the [Parser]'s /// listener to handle the parameters. This may modify the token stream /// when parsing `>>` or `>>>` or `>>>=` in valid code or during recovery. Token parseVariables(Token token, Parser parser); /// Call this function with the [token] before the type var to obtain /// the last token in the type var. If there is no type var, then this method /// will return [token]. This does not modify the token stream. Token skip(Token token); } /// [NoType] is a specialized [TypeInfo] returned by [computeType] when /// there is no type information in the source. const TypeInfo noType = const NoType(); /// [NoTypeParamOrArg] is a specialized [TypeParamOrArgInfo] returned by /// [computeTypeParamOrArg] when no type parameters or arguments are found. const TypeParamOrArgInfo noTypeParamOrArg = const NoTypeParamOrArg(); /// [VoidType] is a specialized [TypeInfo] returned by [computeType] when /// `void` appears in the source. const TypeInfo voidType = const VoidType(); bool isGeneralizedFunctionType(Token token) { return optional('Function', token) && (optional('<', token.next) || optional('(', token.next)); } bool isValidTypeReference(Token token) { int kind = token.kind; if (IDENTIFIER_TOKEN == kind) return true; if (KEYWORD_TOKEN == kind) { TokenType type = token.type; String value = type.lexeme; return type.isPseudo || (type.isBuiltIn && optional('.', token.next)) || (identical(value, 'dynamic')) || (identical(value, 'void')); } return false; } /// Called by the parser to obtain information about a possible type reference /// that follows [token]. This does not modify the token stream. /// /// If [inDeclaration] is `true`, then this will more aggressively recover /// given unbalanced `<` `>` and invalid parameters or arguments. TypeInfo computeType(final Token token, bool required, [bool inDeclaration = false]) { Token next = token.next; if (!isValidTypeReference(next)) { if (next.type.isBuiltIn) { TypeParamOrArgInfo typeParamOrArg = computeTypeParamOrArg(next, inDeclaration); if (typeParamOrArg != noTypeParamOrArg) { // Recovery: built-in `<` ... `>` if (required || looksLikeName(typeParamOrArg.skip(next).next)) { return new ComplexTypeInfo(token, typeParamOrArg) .computeBuiltinOrVarAsType(required); } } else if (required || isGeneralizedFunctionType(next.next)) { String value = next.stringValue; if ((!identical('get', value) && !identical('set', value) && !identical('factory', value) && !identical('operator', value) && !(identical('typedef', value) && next.next.isIdentifier))) { return new ComplexTypeInfo(token, typeParamOrArg) .computeBuiltinOrVarAsType(required); } } } else if (required) { // Recovery if (optional('.', next)) { // Looks like prefixed type missing the prefix return new ComplexTypeInfo( token, computeTypeParamOrArg(next, inDeclaration)) .computePrefixedType(required); } else if (optional('var', next) && isOneOf(next.next, const ['<', ',', '>'])) { return new ComplexTypeInfo( token, computeTypeParamOrArg(next, inDeclaration)) .computeBuiltinOrVarAsType(required); } } return noType; } if (optional('void', next)) { next = next.next; if (isGeneralizedFunctionType(next)) { // `void` `Function` ... return new ComplexTypeInfo(token, noTypeParamOrArg) .computeVoidGFT(required); } // `void` return voidType; } if (isGeneralizedFunctionType(next)) { // `Function` ... return new ComplexTypeInfo(token, noTypeParamOrArg) .computeNoTypeGFT(token, required); } // We've seen an identifier. TypeParamOrArgInfo typeParamOrArg = computeTypeParamOrArg(next, inDeclaration); if (typeParamOrArg != noTypeParamOrArg) { if (typeParamOrArg.isSimpleTypeArgument) { // We've seen identifier `<` identifier `>` next = typeParamOrArg.skip(next).next; if (optional('?', next)) { next = next.next; if (!isGeneralizedFunctionType(next)) { if ((required || looksLikeName(next)) && typeParamOrArg == simpleTypeArgument1) { // identifier `<` identifier `>` `?` identifier return simpleNullableTypeWith1Argument; } // identifier `<` identifier `>` `?` non-identifier return noType; } } else if (!isGeneralizedFunctionType(next)) { if (required || looksLikeName(next)) { // identifier `<` identifier `>` identifier return typeParamOrArg.typeInfo; } // identifier `<` identifier `>` non-identifier return noType; } } // TODO(danrubel): Consider adding a const for // identifier `<` identifier `,` identifier `>` // if that proves to be a common case. // identifier `<` ... `>` return new ComplexTypeInfo(token, typeParamOrArg) .computeSimpleWithTypeArguments(required); } assert(typeParamOrArg == noTypeParamOrArg); next = next.next; if (optional('.', next)) { next = next.next; if (isValidTypeReference(next)) { // We've seen identifier `.` identifier typeParamOrArg = computeTypeParamOrArg(next, inDeclaration); next = next.next; if (typeParamOrArg == noTypeParamOrArg) { if (optional('?', next)) { next = next.next; if (!isGeneralizedFunctionType(next)) { if (required || looksLikeName(next)) { // identifier `.` identifier `?` identifier // TODO(danrubel): consider adding PrefixedNullableType // Fall through to build complex type } else { // identifier `.` identifier `?` non-identifier return noType; } } } else { if (!isGeneralizedFunctionType(next)) { if (required || looksLikeName(next)) { // identifier `.` identifier identifier return prefixedType; } else { // identifier `.` identifier non-identifier return noType; } } } } // identifier `.` identifier return new ComplexTypeInfo(token, typeParamOrArg) .computePrefixedType(required); } // identifier `.` non-identifier if (required) { typeParamOrArg = computeTypeParamOrArg(token.next.next, inDeclaration); return new ComplexTypeInfo(token, typeParamOrArg) .computePrefixedType(required); } return noType; } assert(typeParamOrArg == noTypeParamOrArg); if (isGeneralizedFunctionType(next)) { // identifier `Function` return new ComplexTypeInfo(token, noTypeParamOrArg) .computeIdentifierGFT(required); } if (optional('?', next)) { next = next.next; if (isGeneralizedFunctionType(next)) { // identifier `?` Function `(` return new ComplexTypeInfo(token, noTypeParamOrArg) .computeIdentifierQuestionGFT(required); } else if (required || looksLikeName(next)) { // identifier `?` return simpleNullableType; } } else if (required || looksLikeName(next)) { // identifier identifier return simpleType; } return noType; } /// Called by the parser to obtain information about a possible group of type /// parameters or type arguments that follow [token]. /// This does not modify the token stream. /// /// If [inDeclaration] is `true`, then this will more aggressively recover /// given unbalanced `<` `>` and invalid parameters or arguments. TypeParamOrArgInfo computeTypeParamOrArg(Token token, [bool inDeclaration = false, bool allowsVariance = false]) { Token beginGroup = token.next; if (!optional('<', beginGroup)) { return noTypeParamOrArg; } // identifier `<` `void` `>` and `<` `dynamic` `>` // are handled by ComplexTypeInfo. Token next = beginGroup.next; if ((next.kind == IDENTIFIER_TOKEN || next.type.isPseudo)) { if (optional('>', next.next)) { return simpleTypeArgument1; } else if (optional('>>', next.next)) { return simpleTypeArgument1GtGt; } else if (optional('>=', next.next)) { return simpleTypeArgument1GtEq; } } else if (optional('(', next)) { return noTypeParamOrArg; } // TODO(danrubel): Consider adding additional const for common situations. return new ComplexTypeParamOrArgInfo(token, inDeclaration, allowsVariance) .compute(); } /// Called by the parser to obtain information about a possible group of type /// type arguments that follow [token] and that are followed by '('. /// Returns the type arguments if [token] matches '<' type (',' type)* '>' '(', /// and otherwise returns [noTypeParamOrArg]. The final '(' is not part of the /// grammar construct `typeArguments`, but it is required here such that type /// arguments in generic method invocations can be recognized, and as few as /// possible other constructs will pass (e.g., 'a < C, D > 3'). TypeParamOrArgInfo computeMethodTypeArguments(Token token) { TypeParamOrArgInfo typeArg = computeTypeParamOrArg(token); return optional('(', typeArg.skip(token).next) ? typeArg : noTypeParamOrArg; }
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/type_info_impl.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.type_info_impl; import '../../scanner/token.dart' show SyntheticToken, Token, TokenType; import '../fasta_codes.dart' as fasta; import '../scanner/token_constants.dart' show IDENTIFIER_TOKEN; import '../util/link.dart' show Link; import 'forwarding_listener.dart' show ForwardingListener; import 'identifier_context.dart' show IdentifierContext; import 'member_kind.dart' show MemberKind; import 'listener.dart' show Listener; import 'parser.dart' show Parser; import 'type_info.dart'; import 'util.dart' show optional, skipMetadata, splitGtEq, splitGtFromGtGtEq, splitGtFromGtGtGt, splitGtFromGtGtGtEq, splitGtGt, syntheticGt; /// [SimpleType] is a specialized [TypeInfo] returned by [computeType] /// when there is a single identifier as the type reference. const TypeInfo simpleType = const SimpleType(); /// [SimpleNullableType] is a specialized [TypeInfo] returned by [computeType] /// when there is a single identifier followed by `?` as the type reference. const TypeInfo simpleNullableType = const SimpleNullableType(); /// [PrefixedType] is a specialized [TypeInfo] returned by [computeType] /// when the type reference is of the form: identifier `.` identifier. const TypeInfo prefixedType = const PrefixedType(); /// [SimpleTypeWith1Argument] is a specialized [TypeInfo] returned by /// [computeType] when the type reference is of the form: /// identifier `<` identifier `>`. const TypeInfo simpleTypeWith1Argument = const SimpleTypeWith1Argument(simpleTypeArgument1); /// [SimpleTypeWith1Argument] is a specialized [TypeInfo] returned by /// [computeType] when the type reference is of the form: /// identifier `<` identifier `>=`. const TypeInfo simpleTypeWith1ArgumentGtEq = const SimpleTypeWith1Argument(simpleTypeArgument1GtEq); /// [SimpleTypeWith1Argument] is a specialized [TypeInfo] returned by /// [computeType] when the type reference is of the form: /// identifier `<` identifier `>>`. const TypeInfo simpleTypeWith1ArgumentGtGt = const SimpleTypeWith1Argument(simpleTypeArgument1GtGt); /// [SimpleNullableTypeWith1Argument] is a specialized [TypeInfo] returned by /// [computeType] when the type reference is of the form: /// identifier `<` identifier `>` `?`. const TypeInfo simpleNullableTypeWith1Argument = const SimpleNullableTypeWith1Argument(); /// [SimpleTypeArgument1] is a specialized [TypeParamOrArgInfo] returned by /// [computeTypeParamOrArg] when the type reference is of the form: /// `<` identifier `>`. const TypeParamOrArgInfo simpleTypeArgument1 = const SimpleTypeArgument1(); /// [SimpleTypeArgument1] is a specialized [TypeParamOrArgInfo] returned by /// [computeTypeParamOrArg] when the type reference is of the form: /// `<` identifier `>=`. const TypeParamOrArgInfo simpleTypeArgument1GtEq = const SimpleTypeArgument1GtEq(); /// [SimpleTypeArgument1] is a specialized [TypeParamOrArgInfo] returned by /// [computeTypeParamOrArg] when the type reference is of the form: /// `<` identifier `>>`. const TypeParamOrArgInfo simpleTypeArgument1GtGt = const SimpleTypeArgument1GtGt(); /// See documentation on the [noType] const. class NoType implements TypeInfo { const NoType(); @override TypeInfo get asNonNullable => this; @override bool get couldBeExpression => false; @override bool get isNullable => false; @override Token ensureTypeNotVoid(Token token, Parser parser) { parser.reportRecoverableErrorWithToken( token.next, fasta.templateExpectedType); parser.rewriter.insertSyntheticIdentifier(token); return simpleType.parseType(token, parser); } @override Token ensureTypeOrVoid(Token token, Parser parser) => ensureTypeNotVoid(token, parser); @override Token parseTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseType(Token token, Parser parser) { parser.listener.handleNoType(token); return token; } @override Token skipType(Token token) { return token; } } /// See documentation on the [prefixedType] const. class PrefixedType implements TypeInfo { const PrefixedType(); @override TypeInfo get asNonNullable => this; @override bool get couldBeExpression => true; @override bool get isNullable => false; @override Token ensureTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token ensureTypeOrVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseType(Token token, Parser parser) { Token start = token = token.next; assert(token.isKeywordOrIdentifier); Listener listener = parser.listener; listener.handleIdentifier(token, IdentifierContext.prefixedTypeReference); Token period = token = token.next; assert(optional('.', token)); token = token.next; assert(token.isKeywordOrIdentifier); listener.handleIdentifier( token, IdentifierContext.typeReferenceContinuation); listener.handleQualified(period); listener.handleNoTypeArguments(token.next); listener.handleType(start, null); return token; } @override Token skipType(Token token) { return token.next.next.next; } } /// See documentation on the [simpleNullableTypeWith1Argument] const. class SimpleNullableTypeWith1Argument extends SimpleTypeWith1Argument { const SimpleNullableTypeWith1Argument() : super(simpleTypeArgument1); @override TypeInfo get asNonNullable => simpleTypeWith1Argument; @override bool get isNullable => true; @override Token parseTypeRest(Token start, Token token, Parser parser) { token = token.next; assert(optional('?', token)); parser.listener.handleType(start, token); return token; } @override Token skipType(Token token) { token = super.skipType(token).next; assert(optional('?', token)); return token; } } /// See documentation on the [simpleTypeWith1Argument] const. class SimpleTypeWith1Argument implements TypeInfo { final TypeParamOrArgInfo typeArg; const SimpleTypeWith1Argument(this.typeArg); @override TypeInfo get asNonNullable => this; @override bool get couldBeExpression => false; @override bool get isNullable => false; @override Token ensureTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token ensureTypeOrVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseType(Token token, Parser parser) { Token start = token = token.next; assert(token.isKeywordOrIdentifier); parser.listener.handleIdentifier(token, IdentifierContext.typeReference); token = typeArg.parseArguments(token, parser); return parseTypeRest(start, token, parser); } Token parseTypeRest(Token start, Token token, Parser parser) { parser.listener.handleType(start, null); return token; } @override Token skipType(Token token) { token = token.next; assert(token.isKeywordOrIdentifier); return typeArg.skip(token); } } /// See documentation on the [simpleNullableType] const. class SimpleNullableType extends SimpleType { const SimpleNullableType(); @override TypeInfo get asNonNullable => simpleType; @override bool get isNullable => true; @override Token parseTypeRest(Token start, Parser parser) { Token token = start.next; assert(optional('?', token)); parser.listener.handleType(start, token); return token; } @override Token skipType(Token token) { return token.next.next; } } /// See documentation on the [simpleType] const. class SimpleType implements TypeInfo { const SimpleType(); @override TypeInfo get asNonNullable => this; @override bool get couldBeExpression => true; @override bool get isNullable => false; @override Token ensureTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token ensureTypeOrVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseType(Token token, Parser parser) { token = token.next; assert(isValidTypeReference(token)); parser.listener.handleIdentifier(token, IdentifierContext.typeReference); token = noTypeParamOrArg.parseArguments(token, parser); return parseTypeRest(token, parser); } Token parseTypeRest(Token token, Parser parser) { parser.listener.handleType(token, null); return token; } @override Token skipType(Token token) { return token.next; } } /// See documentation on the [voidType] const. class VoidType implements TypeInfo { const VoidType(); @override TypeInfo get asNonNullable => this; @override bool get couldBeExpression => false; @override bool get isNullable => false; @override Token ensureTypeNotVoid(Token token, Parser parser) { // Report an error, then parse `void` as if it were a type name. parser.reportRecoverableError(token.next, fasta.messageInvalidVoid); return simpleType.parseTypeNotVoid(token, parser); } @override Token ensureTypeOrVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseTypeNotVoid(Token token, Parser parser) => ensureTypeNotVoid(token, parser); @override Token parseType(Token token, Parser parser) { token = token.next; parser.listener.handleVoidKeyword(token); return token; } @override Token skipType(Token token) { return token.next; } } bool looksLikeName(Token token) => token.kind == IDENTIFIER_TOKEN || optional('this', token) || (token.isIdentifier && // Although `typedef` is a legal identifier, // type `typedef` identifier is not legal and in this situation // `typedef` is probably a separate declaration. (!optional('typedef', token) || !token.next.isIdentifier)); /// When missing a comma, determine if the given token looks like it should /// be part of a collection of type parameters or arguments. bool looksLikeTypeParamOrArg(bool inDeclaration, Token token) { if (inDeclaration && token.kind == IDENTIFIER_TOKEN) { Token next = token.next; if (next.kind == IDENTIFIER_TOKEN || optional(',', next) || isCloser(next)) { return true; } } return false; } /// Instances of [ComplexTypeInfo] are returned by [computeType] to represent /// type references that cannot be represented by the constants above. class ComplexTypeInfo implements TypeInfo { /// The first token in the type reference. Token start; /// Type arguments were seen during analysis. final TypeParamOrArgInfo typeArguments; /// The token before the trailing question mark or `null` if either /// 1) there is no trailing question mark, or /// 2) the trailing question mark is not part of the type reference. Token beforeQuestionMark; /// The last token in the type reference. Token end; /// The `Function` tokens before the start of type variables of function types /// as seen during analysis. Link<Token> typeVariableStarters = const Link<Token>(); /// If the receiver represents a generalized function type then this indicates /// whether it has a return type, otherwise this is `null`. bool gftHasReturnType; ComplexTypeInfo(Token beforeStart, this.typeArguments) : this.start = beforeStart.next { assert(typeArguments != null); } ComplexTypeInfo._nonNullable(this.start, this.typeArguments, this.end, this.typeVariableStarters, this.gftHasReturnType); @override TypeInfo get asNonNullable { return beforeQuestionMark == null ? this : new ComplexTypeInfo._nonNullable(start, typeArguments, beforeQuestionMark, typeVariableStarters, gftHasReturnType); } @override bool get couldBeExpression => typeArguments == noTypeParamOrArg && typeVariableStarters.isEmpty; @override bool get isNullable => beforeQuestionMark != null; @override Token ensureTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token ensureTypeOrVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseTypeNotVoid(Token token, Parser parser) => parseType(token, parser); @override Token parseType(Token token, Parser parser) { assert(identical(token.next, start)); if (optional('.', start)) { // Recovery: Insert missing identifier without sending events start = parser.insertSyntheticIdentifier( token, IdentifierContext.prefixedTypeReference); } final List<Token> typeVariableEndGroups = <Token>[]; for (Link<Token> t = typeVariableStarters; t.isNotEmpty; t = t.tail) { typeVariableEndGroups.add( computeTypeParamOrArg(t.head, true).parseVariables(t.head, parser)); parser.listener.beginFunctionType(start); } if (gftHasReturnType == false) { // A function type without return type. // Push the non-existing return type first. The loop below will // generate the full type. noType.parseType(token, parser); } else { Token typeRefOrPrefix = token.next; if (optional('void', typeRefOrPrefix)) { token = voidType.parseType(token, parser); } else { if (!optional('.', typeRefOrPrefix) && !optional('.', typeRefOrPrefix.next)) { token = parser.ensureIdentifier(token, IdentifierContext.typeReference); } else { token = parser.ensureIdentifier( token, IdentifierContext.prefixedTypeReference); token = parser.parseQualifiedRest( token, IdentifierContext.typeReferenceContinuation); if (token.isSynthetic && end == typeRefOrPrefix.next) { // Recovery: Update `end` if a synthetic identifier was inserted. end = token; } } token = typeArguments.parseArguments(token, parser); // Only consume the `?` if it is part of the complex type Token questionMark = token.next; if (optional('?', questionMark) && (typeVariableEndGroups.isNotEmpty || beforeQuestionMark != null)) { token = questionMark; } else { questionMark = null; } parser.listener.handleType(typeRefOrPrefix, questionMark); } } int endGroupIndex = typeVariableEndGroups.length - 1; for (Link<Token> t = typeVariableStarters; t.isNotEmpty; t = t.tail) { token = token.next; assert(optional('Function', token)); Token functionToken = token; if (optional("<", token.next)) { // Skip type parameters, they were parsed above. token = typeVariableEndGroups[endGroupIndex]; assert(optional('>', token)); } token = parser.parseFormalParametersRequiredOpt( token, MemberKind.GeneralizedFunctionType); // Only consume the `?` if it is part of the complex type Token questionMark = token.next; if (optional('?', questionMark) && (endGroupIndex > 0 || beforeQuestionMark != null)) { token = questionMark; } else { questionMark = null; } --endGroupIndex; parser.listener.endFunctionType(functionToken, questionMark); } // There are two situations in which the [token] != [end]: // Valid code: identifier `<` identifier `<` identifier `>>` // where `>>` is replaced by two tokens. // Invalid code: identifier `<` identifier identifier `>` // where a synthetic `>` is inserted between the identifiers. assert(identical(token, end) || optional('>', token)); // During recovery, [token] may be a synthetic that was inserted in the // middle of the type reference. end = token; return token; } @override Token skipType(Token token) { return end; } /// Given `Function` non-identifier, compute the type /// and return the receiver or one of the [TypeInfo] constants. TypeInfo computeNoTypeGFT(Token beforeStart, bool required) { assert(optional('Function', start)); assert(beforeStart.next == start); computeRest(beforeStart, required); if (gftHasReturnType == null) { return required ? simpleType : noType; } assert(end != null); return this; } /// Given void `Function` non-identifier, compute the type /// and return the receiver or one of the [TypeInfo] constants. TypeInfo computeVoidGFT(bool required) { assert(optional('void', start)); assert(optional('Function', start.next)); computeRest(start, required); if (gftHasReturnType == null) { return voidType; } assert(end != null); return this; } /// Given identifier `Function` non-identifier, compute the type /// and return the receiver or one of the [TypeInfo] constants. TypeInfo computeIdentifierGFT(bool required) { assert(isValidTypeReference(start)); assert(optional('Function', start.next)); computeRest(start, required); if (gftHasReturnType == null) { return simpleType; } assert(end != null); return this; } /// Given identifier `?` `Function` non-identifier, compute the type /// and return the receiver or one of the [TypeInfo] constants. TypeInfo computeIdentifierQuestionGFT(bool required) { assert(isValidTypeReference(start)); assert(optional('?', start.next)); assert(optional('Function', start.next.next)); computeRest(start, required); if (gftHasReturnType == null) { return simpleNullableType; } assert(end != null); return this; } /// Given a builtin, return the receiver so that parseType will report /// an error for the builtin used as a type. TypeInfo computeBuiltinOrVarAsType(bool required) { assert(start.type.isBuiltIn || optional('var', start)); end = typeArguments.skip(start); computeRest(end, required); assert(end != null); return this; } /// Given identifier `<` ... `>`, compute the type /// and return the receiver or one of the [TypeInfo] constants. TypeInfo computeSimpleWithTypeArguments(bool required) { assert(isValidTypeReference(start)); assert(optional('<', start.next)); assert(typeArguments != noTypeParamOrArg); end = typeArguments.skip(start); computeRest(end, required); if (!required && !looksLikeName(end.next) && gftHasReturnType == null) { return noType; } assert(end != null); return this; } /// Given identifier `.` identifier (or `.` identifier or identifier `.` /// for recovery), compute the type and return the receiver or one of the /// [TypeInfo] constants. TypeInfo computePrefixedType(bool required) { Token token = start; if (!optional('.', token)) { assert(token.isKeywordOrIdentifier); token = token.next; } assert(optional('.', token)); if (token.next.isKeywordOrIdentifier) { token = token.next; } end = typeArguments.skip(token); computeRest(end, required); if (!required && !looksLikeName(end.next) && gftHasReturnType == null) { return noType; } assert(end != null); return this; } void computeRest(Token token, bool required) { if (optional('?', token.next)) { beforeQuestionMark = token; end = token = token.next; } token = token.next; while (optional('Function', token)) { Token typeVariableStart = token; // TODO(danrubel): Consider caching TypeParamOrArgInfo token = computeTypeParamOrArg(token, true).skip(token); token = token.next; if (!optional('(', token)) { break; // Not a function type. } token = token.endGroup; if (token == null) { break; // Not a function type. } if (!required) { Token next = token.next; if (optional('?', next)) { next = next.next; } if (!(next.isIdentifier || optional('this', next))) { break; // `Function` used as the name in a function declaration. } } assert(optional(')', token)); gftHasReturnType ??= typeVariableStart != start; typeVariableStarters = typeVariableStarters.prepend(typeVariableStart); beforeQuestionMark = null; end = token; token = token.next; if (optional('?', token)) { beforeQuestionMark = end; end = token; token = token.next; } } } } /// See [noTypeParamOrArg]. class NoTypeParamOrArg extends TypeParamOrArgInfo { const NoTypeParamOrArg(); @override int get typeArgumentCount => 0; @override Token parseArguments(Token token, Parser parser) { parser.listener.handleNoTypeArguments(token.next); return token; } @override Token parseVariables(Token token, Parser parser) { parser.listener.handleNoTypeVariables(token.next); return token; } @override Token skip(Token token) => token; } class SimpleTypeArgument1 extends TypeParamOrArgInfo { const SimpleTypeArgument1(); @override bool get isSimpleTypeArgument => true; @override int get typeArgumentCount => 1; @override TypeInfo get typeInfo => simpleTypeWith1Argument; @override Token parseArguments(Token token, Parser parser) { Token beginGroup = token.next; assert(optional('<', beginGroup)); Token endGroup = parseEndGroup(beginGroup, beginGroup.next); Listener listener = parser.listener; listener.beginTypeArguments(beginGroup); simpleType.parseType(beginGroup, parser); parser.listener.endTypeArguments(1, beginGroup, endGroup); return endGroup; } @override Token parseVariables(Token token, Parser parser) { Token beginGroup = token.next; assert(optional('<', beginGroup)); token = beginGroup.next; Token endGroup = parseEndGroup(beginGroup, token); Listener listener = parser.listener; listener.beginTypeVariables(beginGroup); listener.beginMetadataStar(token); listener.endMetadataStar(0); listener.handleIdentifier(token, IdentifierContext.typeVariableDeclaration); listener.beginTypeVariable(token); listener.handleTypeVariablesDefined(token, 1); listener.handleNoType(token); listener.endTypeVariable(endGroup, 0, null, null); listener.endTypeVariables(beginGroup, endGroup); return endGroup; } @override Token skip(Token token) { token = token.next; assert(optional('<', token)); token = token.next; assert(token.isKeywordOrIdentifier); return skipEndGroup(token); } Token skipEndGroup(Token token) { token = token.next; assert(optional('>', token)); return token; } Token parseEndGroup(Token beginGroup, Token token) { token = token.next; assert(optional('>', token)); return token; } } class SimpleTypeArgument1GtEq extends SimpleTypeArgument1 { const SimpleTypeArgument1GtEq(); @override TypeInfo get typeInfo => simpleTypeWith1ArgumentGtEq; Token skipEndGroup(Token token) { token = token.next; assert(optional('>=', token)); return splitGtEq(token); } Token parseEndGroup(Token beginGroup, Token beforeEndGroup) { Token endGroup = beforeEndGroup.next; if (!optional('>', endGroup)) { endGroup = splitGtEq(endGroup); endGroup.next.setNext(endGroup.next.next); } beforeEndGroup.setNext(endGroup); return endGroup; } } class SimpleTypeArgument1GtGt extends SimpleTypeArgument1 { const SimpleTypeArgument1GtGt(); @override TypeInfo get typeInfo => simpleTypeWith1ArgumentGtGt; Token skipEndGroup(Token token) { token = token.next; assert(optional('>>', token)); return splitGtGt(token); } Token parseEndGroup(Token beginGroup, Token beforeEndGroup) { Token endGroup = beforeEndGroup.next; if (!optional('>', endGroup)) { endGroup = splitGtGt(endGroup); endGroup.next.setNext(endGroup.next.next); } beforeEndGroup.setNext(endGroup); return endGroup; } } class ComplexTypeParamOrArgInfo extends TypeParamOrArgInfo { /// The first token in the type var. final Token start; /// If [inDeclaration] is `true`, then this will more aggressively recover /// given unbalanced `<` `>` and invalid parameters or arguments. final bool inDeclaration; // Only support variance parsing if it makes sense. // Allows parsing of variance for certain structures. // See https://github.com/dart-lang/language/issues/524 final bool allowsVariance; @override int typeArgumentCount; /// The `>` token which ends the type parameter or argument. /// This closer may be synthetic, points to the next token in the stream, /// is only used when skipping over the type parameters or arguments, /// and may not be part of the token stream. Token skipEnd; ComplexTypeParamOrArgInfo( Token token, this.inDeclaration, this.allowsVariance) : assert(optional('<', token.next)), assert(inDeclaration != null), assert(allowsVariance != null), start = token.next; /// Parse the tokens and return the receiver or [noTypeParamOrArg] if there /// are no type parameters or arguments. This does not modify the token /// stream. TypeParamOrArgInfo compute() { Token token; Token next = start; typeArgumentCount = 0; while (true) { TypeInfo typeInfo = computeType(next, true, inDeclaration); if (typeInfo == noType) { while (typeInfo == noType && optional('@', next.next)) { next = skipMetadata(next); typeInfo = computeType(next, true, inDeclaration); } if (typeInfo == noType) { if (next == start && !inDeclaration && !isCloser(next.next)) { return noTypeParamOrArg; } if (!optional(',', next.next)) { token = next; next = token.next; break; } } assert(typeInfo != noType || optional(',', next.next)); // Fall through to process type (if any) and consume `,` } ++typeArgumentCount; token = typeInfo.skipType(next); next = token.next; if (optional('extends', next)) { token = computeType(next, true, inDeclaration).skipType(next); next = token.next; } if (!optional(',', next)) { skipEnd = splitCloser(next); if (skipEnd != null) { return this; } if (!inDeclaration) { return noTypeParamOrArg; } // Recovery if (!looksLikeTypeParamOrArg(inDeclaration, next)) { break; } // Looks like missing comma. Continue looping. next = token; } } // Recovery skipEnd = splitCloser(next); if (skipEnd == null) { if (optional('(', next)) { token = next.endGroup; next = token.next; } skipEnd = splitCloser(next); if (skipEnd == null) { skipEnd = splitCloser(next.next); } if (skipEnd == null) { skipEnd = syntheticGt(next); } } return this; } @override Token parseArguments(Token token, Parser parser) { assert(identical(token.next, start)); Token next = start; parser.listener.beginTypeArguments(start); int count = 0; while (true) { TypeInfo typeInfo = computeType(next, true, inDeclaration); if (typeInfo == noType) { // Recovery while (typeInfo == noType && optional('@', next.next)) { parser.reportRecoverableErrorWithToken( next.next, fasta.templateUnexpectedToken); next = skipMetadata(next); typeInfo = computeType(next, true, inDeclaration); } // Fall through to process type (if any) and consume `,` } token = typeInfo.ensureTypeOrVoid(next, parser); next = token.next; ++count; if (!optional(',', next)) { if (parseCloser(token)) { break; } // Recovery if (!looksLikeTypeParamOrArg(inDeclaration, next)) { token = parseUnexpectedEnd(token, true, parser); break; } // Missing comma. Report error, insert comma, and continue looping. next = parseMissingComma(token, parser); } } Token endGroup = token.next; parser.listener.endTypeArguments(count, start, endGroup); return endGroup; } @override Token parseVariables(Token token, Parser parser) { assert(identical(token.next, start)); Token next = start; Listener listener = parser.listener; listener.beginTypeVariables(start); int count = 0; Link<Token> typeStarts = const Link<Token>(); Link<TypeInfo> superTypeInfos = const Link<TypeInfo>(); Link<Token> variances = const Link<Token>(); while (true) { token = parser.parseMetadataStar(next); Token variance = next.next; Token identifier = variance.next; if (allowsVariance && isVariance(variance) && identifier != null && identifier.isKeywordOrIdentifier) { variances = variances.prepend(variance); // Recovery for multiple variance modifiers while (isVariance(identifier) && identifier.next != null && identifier.next.isKeywordOrIdentifier) { // Report an error and skip actual identifier parser.reportRecoverableError( identifier, fasta.messageMultipleVarianceModifiers); variance = variance.next; identifier = identifier.next; } token = variance; } else { variances = variances.prepend(null); } next = parser.ensureIdentifier( token, IdentifierContext.typeVariableDeclaration); token = next; listener.beginTypeVariable(token); typeStarts = typeStarts.prepend(token); next = token.next; if (optional('extends', next)) { TypeInfo typeInfo = computeType(next, true, inDeclaration); token = typeInfo.skipType(next); next = token.next; superTypeInfos = superTypeInfos.prepend(typeInfo); } else { superTypeInfos = superTypeInfos.prepend(null); } ++count; if (!optional(',', next)) { if (isCloser(token)) { break; } // Recovery if (!looksLikeTypeParamOrArg(inDeclaration, next)) { break; } // Missing comma. Report error, insert comma, and continue looping. next = parseMissingComma(token, parser); } } assert(count > 0); assert(typeStarts.slowLength() == count); assert(superTypeInfos.slowLength() == count); assert(variances.slowLength() == count); listener.handleTypeVariablesDefined(token, count); token = null; while (typeStarts.isNotEmpty) { Token token2 = typeStarts.head; TypeInfo typeInfo = superTypeInfos.head; Token variance = variances.head; if (variance != null) { listener.handleVarianceModifier(variance); } Token extendsOrSuper = null; Token next2 = token2.next; if (typeInfo != null) { assert(optional('extends', next2)); extendsOrSuper = next2; token2 = typeInfo.ensureTypeNotVoid(next2, parser); next2 = token2.next; } else { assert(!optional('extends', next2)); listener.handleNoType(token2); } // Type variables are "completed" in reverse order, so capture the last // consumed token from the first "completed" type variable. token ??= token2; listener.endTypeVariable(next2, --count, extendsOrSuper, variance); typeStarts = typeStarts.tail; superTypeInfos = superTypeInfos.tail; variances = variances.tail; } if (!parseCloser(token)) { token = parseUnexpectedEnd(token, false, parser); } Token endGroup = token.next; listener.endTypeVariables(start, endGroup); return endGroup; } Token parseMissingComma(Token token, Parser parser) { Token next = token.next; parser.reportRecoverableError( next, fasta.templateExpectedButGot.withArguments(',')); return parser.rewriter.insertToken( token, new SyntheticToken(TokenType.COMMA, next.charOffset)); } Token parseUnexpectedEnd(Token token, bool isArguments, Parser parser) { Token next = token.next; bool errorReported = token.isSynthetic || (next.isSynthetic && !next.isEof); bool typeFollowsExtends = false; if (optional('extends', next)) { if (!errorReported) { parser.reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('>')); errorReported = true; } token = next; next = token.next; typeFollowsExtends = isValidTypeReference(next); if (parseCloser(token)) { return token; } } if (typeFollowsExtends || optional('dynamic', next) || optional('void', next) || optional('Function', next)) { TypeInfo invalidType = computeType(token, true); if (invalidType != noType) { if (!errorReported) { parser.reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('>')); errorReported = true; } // Parse the type so that the token stream is properly modified, // but ensure that parser events are ignored by replacing the listener. final Listener originalListener = parser.listener; parser.listener = new ForwardingListener(); token = invalidType.parseType(token, parser); next = token.next; parser.listener = originalListener; if (parseCloser(token)) { return token; } } } TypeParamOrArgInfo invalidTypeVar = computeTypeParamOrArg(token, inDeclaration); if (invalidTypeVar != noTypeParamOrArg) { if (!errorReported) { parser.reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('>')); errorReported = true; } // Parse the type so that the token stream is properly modified, // but ensure that parser events are ignored by replacing the listener. final Listener originalListener = parser.listener; parser.listener = new ForwardingListener(); token = isArguments ? invalidTypeVar.parseArguments(token, parser) : invalidTypeVar.parseVariables(token, parser); next = token.next; parser.listener = originalListener; if (parseCloser(token)) { return token; } } if (optional('(', next) && next.endGroup != null) { if (!errorReported) { // Only report an error if one has not already been reported. parser.reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('>')); errorReported = true; } token = next.endGroup; next = token.next; if (parseCloser(token)) { return token; } } if (!errorReported) { // Only report an error if one has not already been reported. parser.reportRecoverableError( token, fasta.templateExpectedAfterButGot.withArguments('>')); } if (parseCloser(next)) { return next; } Token endGroup = start.endGroup; if (endGroup != null) { while (token.next != endGroup && !token.isEof) { token = token.next; } } else { endGroup = syntheticGt(next); endGroup.setNext(next); token.setNext(endGroup); } return token; } @override Token skip(Token token) { assert(skipEnd != null); return skipEnd; } } // Return `true` if [token] is one of `in`, `inout`, or `out` bool isVariance(Token token) { return optional('in', token) || optional('inout', token) || optional('out', token); } /// Return `true` if [token] is one of `>`, `>>`, `>>>`, `>=`, `>>=`, or `>>>=`. bool isCloser(Token token) { final String value = token.stringValue; return identical(value, '>') || identical(value, '>>') || identical(value, '>=') || identical(value, '>>>') || identical(value, '>>=') || identical(value, '>>>='); } /// If [beforeCloser].next is one of `>`, `>>`, `>>>`, `>=`, `>>=`, or `>>>=` /// then update the token stream and return `true`. bool parseCloser(Token beforeCloser) { Token unsplit = beforeCloser.next; Token split = splitCloser(unsplit); if (split == unsplit) { return true; } else if (split == null) { return false; } split.next.setNext(unsplit.next); beforeCloser.setNext(split); return true; } /// If [closer] is `>` then return it. /// If [closer] is one of `>>`, `>>>`, `>=`, `>>=`, or `>>>=` then split /// the token and return the leading `>` without updating the token stream. /// If [closer] is none of the above, then return null; Token splitCloser(Token closer) { String value = closer.stringValue; if (identical(value, '>')) { return closer; } else if (identical(value, '>>')) { return splitGtGt(closer); } else if (identical(value, '>=')) { return splitGtEq(closer); } else if (identical(value, '>>>')) { return splitGtFromGtGtGt(closer); } else if (identical(value, '>>=')) { return splitGtFromGtGtEq(closer); } else if (identical(value, '>>>=')) { return splitGtFromGtGtGtEq(closer); } 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/parser/literal_entry_info.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 '../scanner.dart'; import 'identifier_context.dart'; import 'literal_entry_info_impl.dart'; import 'parser.dart'; import 'util.dart'; /// [simpleEntry] is the first step for parsing a literal entry /// without any control flow or spread collection operator. const LiteralEntryInfo simpleEntry = const LiteralEntryInfo(true, 0); /// [LiteralEntryInfo] represents steps for processing an entry /// in a literal list, map, or set. These steps will handle parsing /// both control flow and spreadable operators, and indicate /// when the client should parse the literal entry. /// /// Clients should parse a single entry in a list, set, or map like this: /// ``` /// LiteralEntryInfo info = computeLiteralEntry(token); /// while (info != null) { /// if (info.hasEntry) { /// ... parse expression (`:` expression)? ... /// token = lastConsumedToken; /// } else { /// token = info.parse(token, parser); /// } /// info = info.computeNext(token); /// } /// ``` class LiteralEntryInfo { /// `true` if an entry should be parsed by the caller /// or `false` if this object's [parse] method should be called. final bool hasEntry; /// Used for recovery, this indicates /// +1 for an `if` condition and -1 for `else`. final int ifConditionDelta; const LiteralEntryInfo(this.hasEntry, this.ifConditionDelta); /// Parse the control flow and spread collection aspects of this entry. Token parse(Token token, Parser parser) { throw hasEntry ? 'Internal Error: should not call parse' : 'Internal Error: $runtimeType should implement parse'; } /// Returns the next step when parsing an entry or `null` if none. LiteralEntryInfo computeNext(Token token) => null; } /// Compute the [LiteralEntryInfo] for the literal list, map, or set entry. LiteralEntryInfo computeLiteralEntry(Token token) { Token next = token.next; if (optional('if', next)) { return ifCondition; } else if (optional('for', next) || (optional('await', next) && optional('for', next.next))) { return new ForCondition(); } else if (optional('...', next) || optional('...?', next)) { return spreadOperator; } return simpleEntry; } /// Return `true` if the given [token] should be treated like the start of /// a literal entry in a list, set, or map for the purposes of recovery. bool looksLikeLiteralEntry(Token token) => looksLikeExpressionStart(token) || optional('...', token) || optional('...?', token) || optional('if', token) || optional('for', token) || (optional('await', token) && optional('for', token.next));
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/forwarding_listener.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 '../messages.dart'; import '../parser.dart'; import '../scanner.dart'; class ForwardingListener implements Listener { Listener listener; bool forwardErrors = true; ForwardingListener([this.listener]); @override set suppressParseErrors(bool value) { listener?.suppressParseErrors = value; } @override Uri get uri => listener?.uri; @override void beginArguments(Token token) { listener?.beginArguments(token); } @override void beginAssert(Token assertKeyword, Assert kind) { listener?.beginAssert(assertKeyword, kind); } @override void beginAwaitExpression(Token token) { listener?.beginAwaitExpression(token); } @override void beginBinaryExpression(Token token) { listener?.beginBinaryExpression(token); } @override void beginBlock(Token token) { listener?.beginBlock(token); } @override void beginBlockFunctionBody(Token token) { listener?.beginBlockFunctionBody(token); } @override void beginCascade(Token token) { listener?.beginCascade(token); } @override void beginCaseExpression(Token caseKeyword) { listener?.beginCaseExpression(caseKeyword); } @override void beginCatchClause(Token token) { listener?.beginCatchClause(token); } @override void beginClassDeclaration(Token begin, Token abstractToken, Token name) { listener?.beginClassDeclaration(begin, abstractToken, name); } @override void beginClassOrMixinBody(DeclarationKind kind, Token token) { listener?.beginClassOrMixinBody(kind, token); } @override void beginClassOrNamedMixinApplicationPrelude(Token token) { listener?.beginClassOrNamedMixinApplicationPrelude(token); } @override void beginCombinators(Token token) { listener?.beginCombinators(token); } @override void beginCompilationUnit(Token token) { listener?.beginCompilationUnit(token); } @override void beginConditionalExpression(Token question) { listener?.beginConditionalExpression(question); } @override void beginConditionalUri(Token ifKeyword) { listener?.beginConditionalUri(ifKeyword); } @override void beginConditionalUris(Token token) { listener?.beginConditionalUris(token); } @override void beginConstExpression(Token constKeyword) { listener?.beginConstExpression(constKeyword); } @override void beginConstLiteral(Token token) { listener?.beginConstLiteral(token); } @override void beginConstructorReference(Token start) { listener?.beginConstructorReference(start); } @override void beginDoWhileStatement(Token token) { listener?.beginDoWhileStatement(token); } @override void beginDoWhileStatementBody(Token token) { listener?.beginDoWhileStatementBody(token); } @override void beginElseStatement(Token token) { listener?.beginElseStatement(token); } @override void beginEnum(Token enumKeyword) { listener?.beginEnum(enumKeyword); } @override void beginExport(Token token) { listener?.beginExport(token); } @override void beginExtensionDeclarationPrelude(Token extensionKeyword) { listener?.beginExtensionDeclarationPrelude(extensionKeyword); } @override void beginExtensionDeclaration(Token extensionKeyword, Token name) { listener?.beginExtensionDeclaration(extensionKeyword, name); } @override void beginFactoryMethod( Token lastConsumed, Token externalToken, Token constToken) { listener?.beginFactoryMethod(lastConsumed, externalToken, constToken); } @override void beginFieldInitializer(Token token) { listener?.beginFieldInitializer(token); } @override void beginForControlFlow(Token awaitToken, Token forToken) { listener?.beginForControlFlow(awaitToken, forToken); } @override void beginForInBody(Token token) { listener?.beginForInBody(token); } @override void beginForInExpression(Token token) { listener?.beginForInExpression(token); } @override void beginFormalParameter(Token token, MemberKind kind, Token requiredToken, Token covariantToken, Token varFinalOrConst) { listener?.beginFormalParameter( token, kind, requiredToken, covariantToken, varFinalOrConst); } @override void beginFormalParameterDefaultValueExpression() { listener?.beginFormalParameterDefaultValueExpression(); } @override void beginFormalParameters(Token token, MemberKind kind) { listener?.beginFormalParameters(token, kind); } @override void beginForStatement(Token token) { listener?.beginForStatement(token); } @override void beginForStatementBody(Token token) { listener?.beginForStatementBody(token); } @override void beginFunctionExpression(Token token) { listener?.beginFunctionExpression(token); } @override void beginFunctionName(Token token) { listener?.beginFunctionName(token); } @override void beginFunctionType(Token beginToken) { listener?.beginFunctionType(beginToken); } @override void beginFunctionTypeAlias(Token token) { listener?.beginFunctionTypeAlias(token); } @override void beginFunctionTypedFormalParameter(Token token) { listener?.beginFunctionTypedFormalParameter(token); } @override void beginHide(Token hideKeyword) { listener?.beginHide(hideKeyword); } @override void beginIfControlFlow(Token ifToken) { listener?.beginIfControlFlow(ifToken); } @override void beginIfStatement(Token token) { listener?.beginIfStatement(token); } @override void beginImplicitCreationExpression(Token token) { listener?.beginImplicitCreationExpression(token); } @override void beginImport(Token importKeyword) { listener?.beginImport(importKeyword); } @override void beginInitializedIdentifier(Token token) { listener?.beginInitializedIdentifier(token); } @override void beginInitializer(Token token) { listener?.beginInitializer(token); } @override void beginInitializers(Token token) { listener?.beginInitializers(token); } @override void beginLabeledStatement(Token token, int labelCount) { listener?.beginLabeledStatement(token, labelCount); } @override void beginLibraryName(Token token) { listener?.beginLibraryName(token); } @override void beginLiteralString(Token token) { listener?.beginLiteralString(token); } @override void beginLiteralSymbol(Token token) { listener?.beginLiteralSymbol(token); } @override void beginLocalFunctionDeclaration(Token token) { listener?.beginLocalFunctionDeclaration(token); } @override void beginMember() { listener?.beginMember(); } @override void beginMetadata(Token token) { listener?.beginMetadata(token); } @override void beginMetadataStar(Token token) { listener?.beginMetadataStar(token); } @override void beginMethod(Token externalToken, Token staticToken, Token covariantToken, Token varFinalOrConst, Token getOrSet, Token name) { listener?.beginMethod(externalToken, staticToken, covariantToken, varFinalOrConst, getOrSet, name); } @override void beginMixinDeclaration(Token mixinKeyword, Token name) { listener?.beginMixinDeclaration(mixinKeyword, name); } @override void beginNamedFunctionExpression(Token token) { listener?.beginNamedFunctionExpression(token); } @override void beginNamedMixinApplication( Token begin, Token abstractToken, Token name) { listener?.beginNamedMixinApplication(begin, abstractToken, name); } @override void beginNewExpression(Token token) { listener?.beginNewExpression(token); } @override void beginOptionalFormalParameters(Token token) { listener?.beginOptionalFormalParameters(token); } @override void beginPart(Token token) { listener?.beginPart(token); } @override void beginPartOf(Token token) { listener?.beginPartOf(token); } @override void beginRedirectingFactoryBody(Token token) { listener?.beginRedirectingFactoryBody(token); } @override void beginRethrowStatement(Token token) { listener?.beginRethrowStatement(token); } @override void beginReturnStatement(Token token) { listener?.beginReturnStatement(token); } @override void beginShow(Token showKeyword) { listener?.beginShow(showKeyword); } @override void beginSwitchBlock(Token token) { listener?.beginSwitchBlock(token); } @override void beginSwitchCase(int labelCount, int expressionCount, Token firstToken) { listener?.beginSwitchCase(labelCount, expressionCount, firstToken); } @override void beginSwitchStatement(Token token) { listener?.beginSwitchStatement(token); } @override void beginThenControlFlow(Token token) { listener?.beginThenControlFlow(token); } @override void beginThenStatement(Token token) { listener?.beginThenStatement(token); } @override void beginTopLevelMember(Token token) { listener?.beginTopLevelMember(token); } @override void beginTopLevelMethod(Token lastConsumed, Token externalToken) { listener?.beginTopLevelMethod(lastConsumed, externalToken); } @override void beginTryStatement(Token token) { listener?.beginTryStatement(token); } @override void beginTypeArguments(Token token) { listener?.beginTypeArguments(token); } @override void beginTypeList(Token token) { listener?.beginTypeList(token); } @override void beginTypeVariable(Token token) { listener?.beginTypeVariable(token); } @override void beginTypeVariables(Token token) { listener?.beginTypeVariables(token); } @override void beginVariableInitializer(Token token) { listener?.beginVariableInitializer(token); } @override void beginVariablesDeclaration( Token token, Token lateToken, Token varFinalOrConst) { listener?.beginVariablesDeclaration(token, lateToken, varFinalOrConst); } @override void beginWhileStatement(Token token) { listener?.beginWhileStatement(token); } @override void beginWhileStatementBody(Token token) { listener?.beginWhileStatementBody(token); } @override void beginYieldStatement(Token token) { listener?.beginYieldStatement(token); } @override void discardTypeReplacedWithCommentTypeAssign() { listener?.discardTypeReplacedWithCommentTypeAssign(); } @override void endArguments(int count, Token beginToken, Token endToken) { listener?.endArguments(count, beginToken, endToken); } @override void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis, Token commaToken, Token semicolonToken) { listener?.endAssert( assertKeyword, kind, leftParenthesis, commaToken, semicolonToken); } @override void endAwaitExpression(Token beginToken, Token endToken) { listener?.endAwaitExpression(beginToken, endToken); } @override void endBinaryExpression(Token token) { listener?.endBinaryExpression(token); } @override void endBlock(int count, Token beginToken, Token endToken) { listener?.endBlock(count, beginToken, endToken); } @override void endBlockFunctionBody(int count, Token beginToken, Token endToken) { listener?.endBlockFunctionBody(count, beginToken, endToken); } @override void endCascade() { listener?.endCascade(); } @override void endCaseExpression(Token colon) { listener?.endCaseExpression(colon); } @override void endCatchClause(Token token) { listener?.endCatchClause(token); } @override void endClassConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { listener?.endClassConstructor( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endClassDeclaration(Token beginToken, Token endToken) { listener?.endClassDeclaration(beginToken, endToken); } @override void endClassFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { listener?.endClassFactoryMethod(beginToken, factoryKeyword, endToken); } @override void endClassFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { listener?.endClassFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } @override void endClassMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { listener?.endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endClassOrMixinBody( DeclarationKind kind, int memberCount, Token beginToken, Token endToken) { listener?.endClassOrMixinBody(kind, memberCount, beginToken, endToken); } @override void endCombinators(int count) { listener?.endCombinators(count); } @override void endCompilationUnit(int count, Token token) { listener?.endCompilationUnit(count, token); } @override void endConditionalExpression(Token question, Token colon) { listener?.endConditionalExpression(question, colon); } @override void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) { listener?.endConditionalUri(ifKeyword, leftParen, equalSign); } @override void endConditionalUris(int count) { listener?.endConditionalUris(count); } @override void endConstExpression(Token token) { listener?.endConstExpression(token); } @override void endConstLiteral(Token token) { listener?.endConstLiteral(token); } @override void endConstructorReference( Token start, Token periodBeforeName, Token endToken) { listener?.endConstructorReference(start, periodBeforeName, endToken); } @override void endDoWhileStatement( Token doKeyword, Token whileKeyword, Token endToken) { listener?.endDoWhileStatement(doKeyword, whileKeyword, endToken); } @override void endDoWhileStatementBody(Token token) { listener?.endDoWhileStatementBody(token); } @override void endElseStatement(Token token) { listener?.endElseStatement(token); } @override void endEnum(Token enumKeyword, Token leftBrace, int count) { listener?.endEnum(enumKeyword, leftBrace, count); } @override void endExport(Token exportKeyword, Token semicolon) { listener?.endExport(exportKeyword, semicolon); } @override void endExtensionConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { listener?.endExtensionConstructor( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endExtensionDeclaration( Token extensionKeyword, Token onKeyword, Token token) { listener?.endExtensionDeclaration(extensionKeyword, onKeyword, token); } @override void endExtensionFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { listener?.endExtensionFactoryMethod(beginToken, factoryKeyword, endToken); } @override void endExtensionFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { listener?.endExtensionFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } @override void endExtensionMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { listener?.endExtensionMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endFieldInitializer(Token assignment, Token token) { listener?.endFieldInitializer(assignment, token); } @override void endForControlFlow(Token token) { listener?.endForControlFlow(token); } @override void endForIn(Token endToken) { listener?.endForIn(endToken); } @override void endForInBody(Token token) { listener?.endForInBody(token); } @override void endForInControlFlow(Token token) { listener?.endForInControlFlow(token); } @override void endForInExpression(Token token) { listener?.endForInExpression(token); } @override void endFormalParameter( Token thisKeyword, Token periodAfterThis, Token nameToken, Token initializerStart, Token initializerEnd, FormalParameterKind kind, MemberKind memberKind) { listener?.endFormalParameter(thisKeyword, periodAfterThis, nameToken, initializerStart, initializerEnd, kind, memberKind); } @override void endFormalParameterDefaultValueExpression() { listener?.endFormalParameterDefaultValueExpression(); } @override void endFormalParameters( int count, Token beginToken, Token endToken, MemberKind kind) { listener?.endFormalParameters(count, beginToken, endToken, kind); } @override void endForStatement(Token endToken) { listener?.endForStatement(endToken); } @override void endForStatementBody(Token token) { listener?.endForStatementBody(token); } @override void endFunctionExpression(Token beginToken, Token token) { listener?.endFunctionExpression(beginToken, token); } @override void endFunctionName(Token beginToken, Token token) { listener?.endFunctionName(beginToken, token); } @override void endFunctionType(Token functionToken, Token questionMark) { listener?.endFunctionType(functionToken, questionMark); } @override void endFunctionTypeAlias( Token typedefKeyword, Token equals, Token endToken) { listener?.endFunctionTypeAlias(typedefKeyword, equals, endToken); } @override void endFunctionTypedFormalParameter(Token nameToken, Token question) { listener?.endFunctionTypedFormalParameter(nameToken, question); } @override void endHide(Token hideKeyword) { listener?.endHide(hideKeyword); } @override void endIfControlFlow(Token token) { listener?.endIfControlFlow(token); } @override void endIfElseControlFlow(Token token) { listener?.endIfElseControlFlow(token); } @override void endIfStatement(Token ifToken, Token elseToken) { listener?.endIfStatement(ifToken, elseToken); } @override void endImplicitCreationExpression(Token token) { listener?.endImplicitCreationExpression(token); } @override void endImport(Token importKeyword, Token semicolon) { listener?.endImport(importKeyword, semicolon); } @override void endInitializedIdentifier(Token nameToken) { listener?.endInitializedIdentifier(nameToken); } @override void endInitializer(Token token) { listener?.endInitializer(token); } @override void endInitializers(int count, Token beginToken, Token endToken) { listener?.endInitializers(count, beginToken, endToken); } @override void endInvalidAwaitExpression( Token beginToken, Token endToken, MessageCode errorCode) { listener?.endInvalidAwaitExpression(beginToken, endToken, errorCode); } @override void endLabeledStatement(int labelCount) { listener?.endLabeledStatement(labelCount); } @override void endLibraryName(Token libraryKeyword, Token semicolon) { listener?.endLibraryName(libraryKeyword, semicolon); } @override void endLiteralString(int interpolationCount, Token endToken) { listener?.endLiteralString(interpolationCount, endToken); } @override void endLiteralSymbol(Token hashToken, int identifierCount) { listener?.endLiteralSymbol(hashToken, identifierCount); } @override void endLocalFunctionDeclaration(Token endToken) { listener?.endLocalFunctionDeclaration(endToken); } @override void endMember() { listener?.endMember(); } @override void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) { listener?.endMetadata(beginToken, periodBeforeName, endToken); } @override void endMetadataStar(int count) { listener?.endMetadataStar(count); } @override void endMixinConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { listener?.endMixinConstructor( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endMixinDeclaration(Token mixinKeyword, Token endToken) { listener?.endMixinDeclaration(mixinKeyword, endToken); } @override void endMixinFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { listener?.endMixinFactoryMethod(beginToken, factoryKeyword, endToken); } @override void endMixinFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { listener?.endMixinFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } @override void endMixinMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { listener?.endMixinMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endNamedFunctionExpression(Token endToken) { listener?.endNamedFunctionExpression(endToken); } @override void endNamedMixinApplication(Token begin, Token classKeyword, Token equals, Token implementsKeyword, Token endToken) { listener?.endNamedMixinApplication( begin, classKeyword, equals, implementsKeyword, endToken); } @override void endNewExpression(Token token) { listener?.endNewExpression(token); } @override void endOptionalFormalParameters( int count, Token beginToken, Token endToken) { listener?.endOptionalFormalParameters(count, beginToken, endToken); } @override void endPart(Token partKeyword, Token semicolon) { listener?.endPart(partKeyword, semicolon); } @override void endPartOf( Token partKeyword, Token ofKeyword, Token semicolon, bool hasName) { listener?.endPartOf(partKeyword, ofKeyword, semicolon, hasName); } @override void endRedirectingFactoryBody(Token beginToken, Token endToken) { listener?.endRedirectingFactoryBody(beginToken, endToken); } @override void endRethrowStatement(Token rethrowToken, Token endToken) { listener?.endRethrowStatement(rethrowToken, endToken); } @override void endReturnStatement( bool hasExpression, Token beginToken, Token endToken) { listener?.endReturnStatement(hasExpression, beginToken, endToken); } @override void endShow(Token showKeyword) { listener?.endShow(showKeyword); } @override void endSwitchBlock(int caseCount, Token beginToken, Token endToken) { listener?.endSwitchBlock(caseCount, beginToken, endToken); } @override void endSwitchCase( int labelCount, int expressionCount, Token defaultKeyword, Token colonAfterDefault, int statementCount, Token firstToken, Token endToken) { listener?.endSwitchCase(labelCount, expressionCount, defaultKeyword, colonAfterDefault, statementCount, firstToken, endToken); } @override void endSwitchStatement(Token switchKeyword, Token endToken) { listener?.endSwitchStatement(switchKeyword, endToken); } @override void endThenStatement(Token token) { listener?.endThenStatement(token); } @override void endTopLevelDeclaration(Token token) { listener?.endTopLevelDeclaration(token); } @override void endTopLevelFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { listener?.endTopLevelFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } @override void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) { listener?.endTopLevelMethod(beginToken, getOrSet, endToken); } @override void endTryStatement(int catchCount, Token tryKeyword, Token finallyKeyword) { listener?.endTryStatement(catchCount, tryKeyword, finallyKeyword); } @override void endTypeArguments(int count, Token beginToken, Token endToken) { listener?.endTypeArguments(count, beginToken, endToken); } @override void endTypeList(int count) { listener?.endTypeList(count); } @override void endTypeVariable( Token token, int index, Token extendsOrSuper, Token variance) { listener?.endTypeVariable(token, index, extendsOrSuper, variance); } @override void endTypeVariables(Token beginToken, Token endToken) { listener?.endTypeVariables(beginToken, endToken); } @override void endVariableInitializer(Token assignmentOperator) { listener?.endVariableInitializer(assignmentOperator); } @override void endVariablesDeclaration(int count, Token endToken) { listener?.endVariablesDeclaration(count, endToken); } @override void endWhileStatement(Token whileKeyword, Token endToken) { listener?.endWhileStatement(whileKeyword, endToken); } @override void endWhileStatementBody(Token token) { listener?.endWhileStatementBody(token); } @override void endYieldStatement(Token yieldToken, Token starToken, Token endToken) { listener?.endYieldStatement(yieldToken, starToken, endToken); } @override void handleAsOperator(Token operator) { listener?.handleAsOperator(operator); } @override void handleAssignmentExpression(Token token) { listener?.handleAssignmentExpression(token); } @override void handleAsyncModifier(Token asyncToken, Token starToken) { listener?.handleAsyncModifier(asyncToken, starToken); } @override void handleBreakStatement( bool hasTarget, Token breakKeyword, Token endToken) { listener?.handleBreakStatement(hasTarget, breakKeyword, endToken); } @override void handleCaseMatch(Token caseKeyword, Token colon) { listener?.handleCaseMatch(caseKeyword, colon); } @override void handleCatchBlock(Token onKeyword, Token catchKeyword, Token comma) { listener?.handleCatchBlock(onKeyword, catchKeyword, comma); } @override void handleClassExtends(Token extendsKeyword) { listener?.handleClassExtends(extendsKeyword); } @override void handleClassHeader(Token begin, Token classKeyword, Token nativeToken) { listener?.handleClassHeader(begin, classKeyword, nativeToken); } @override void handleClassNoWithClause() { listener?.handleClassNoWithClause(); } @override void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { listener?.handleClassOrMixinImplements(implementsKeyword, interfacesCount); } @override void handleClassWithClause(Token withKeyword) { listener?.handleClassWithClause(withKeyword); } @override void handleCommentReference( Token newKeyword, Token prefix, Token period, Token token) { listener?.handleCommentReference(newKeyword, prefix, period, token); } @override void handleCommentReferenceText(String referenceSource, int referenceOffset) { listener?.handleCommentReferenceText(referenceSource, referenceOffset); } @override void handleConditionalExpressionColon() { listener?.handleConditionalExpressionColon(); } @override void handleContinueStatement( bool hasTarget, Token continueKeyword, Token endToken) { listener?.handleContinueStatement(hasTarget, continueKeyword, endToken); } @override void handleDirectivesOnly() { listener?.handleDirectivesOnly(); } @override void handleDottedName(int count, Token firstIdentifier) { listener?.handleDottedName(count, firstIdentifier); } @override void handleElseControlFlow(Token elseToken) { listener?.handleElseControlFlow(elseToken); } @override void handleEmptyFunctionBody(Token semicolon) { listener?.handleEmptyFunctionBody(semicolon); } @override void handleEmptyStatement(Token token) { listener?.handleEmptyStatement(token); } @override void handleErrorToken(ErrorToken token) { listener?.handleErrorToken(token); } @override void handleExpressionFunctionBody(Token arrowToken, Token endToken) { listener?.handleExpressionFunctionBody(arrowToken, endToken); } @override void handleExpressionStatement(Token token) { listener?.handleExpressionStatement(token); } @override void handleExtraneousExpression(Token token, Message message) { listener?.handleExtraneousExpression(token, message); } @override void handleFinallyBlock(Token finallyKeyword) { listener?.handleFinallyBlock(finallyKeyword); } @override void handleForInitializerEmptyStatement(Token token) { listener?.handleForInitializerEmptyStatement(token); } @override void handleForInitializerExpressionStatement(Token token) { listener?.handleForInitializerExpressionStatement(token); } @override void handleForInitializerLocalVariableDeclaration(Token token) { listener?.handleForInitializerLocalVariableDeclaration(token); } @override void handleForInLoopParts(Token awaitToken, Token forToken, Token leftParenthesis, Token inKeyword) { listener?.handleForInLoopParts( awaitToken, forToken, leftParenthesis, inKeyword); } @override void handleForLoopParts(Token forKeyword, Token leftParen, Token leftSeparator, int updateExpressionCount) { listener?.handleForLoopParts( forKeyword, leftParen, leftSeparator, updateExpressionCount); } @override void handleFormalParameterWithoutValue(Token token) { listener?.handleFormalParameterWithoutValue(token); } @override void handleFunctionBodySkipped(Token token, bool isExpressionBody) { listener?.handleFunctionBodySkipped(token, isExpressionBody); } @override void handleIdentifier(Token token, IdentifierContext context) { listener?.handleIdentifier(token, context); } @override void handleIdentifierList(int count) { listener?.handleIdentifierList(count); } @override void handleImportPrefix(Token deferredKeyword, Token asKeyword) { listener?.handleImportPrefix(deferredKeyword, asKeyword); } @override void handleIndexedExpression( Token openSquareBracket, Token closeSquareBracket) { listener?.handleIndexedExpression(openSquareBracket, closeSquareBracket); } @override void handleInterpolationExpression(Token leftBracket, Token rightBracket) { listener?.handleInterpolationExpression(leftBracket, rightBracket); } @override void handleInvalidExpression(Token token) { listener?.handleInvalidExpression(token); } @override void handleInvalidFunctionBody(Token token) { listener?.handleInvalidFunctionBody(token); } @override void handleInvalidMember(Token endToken) { listener?.handleInvalidMember(endToken); } @override void handleInvalidOperatorName(Token operatorKeyword, Token token) { listener?.handleInvalidOperatorName(operatorKeyword, token); } @override void handleInvalidStatement(Token token, Message message) { listener?.handleInvalidStatement(token, message); } void handleInvalidTopLevelBlock(Token token) { listener?.handleInvalidTopLevelBlock(token); } @override void handleInvalidTopLevelDeclaration(Token endToken) { listener?.handleInvalidTopLevelDeclaration(endToken); } @override void handleInvalidTypeArguments(Token token) { listener?.handleInvalidTypeArguments(token); } @override void handleInvalidTypeReference(Token token) { listener?.handleInvalidTypeReference(token); } @override void handleIsOperator(Token isOperator, Token not) { listener?.handleIsOperator(isOperator, not); } @override void handleLabel(Token token) { listener?.handleLabel(token); } @override void handleLiteralBool(Token token) { listener?.handleLiteralBool(token); } @override void handleLiteralDouble(Token token) { listener?.handleLiteralDouble(token); } @override void handleLiteralInt(Token token) { listener?.handleLiteralInt(token); } @override void handleLiteralList( int count, Token beginToken, Token constKeyword, Token endToken) { listener?.handleLiteralList(count, beginToken, constKeyword, endToken); } @override void handleLiteralMapEntry(Token colon, Token endToken) { listener?.handleLiteralMapEntry(colon, endToken); } @override void handleLiteralNull(Token token) { listener?.handleLiteralNull(token); } @override void handleLiteralSetOrMap( int count, Token leftBrace, Token constKeyword, Token rightBrace, // TODO(danrubel): hasSetEntry parameter exists for replicating existing // behavior and will be removed once unified collection has been enabled bool hasSetEntry, ) { listener?.handleLiteralSetOrMap( count, leftBrace, constKeyword, rightBrace, hasSetEntry); } @override void handleMixinHeader(Token mixinKeyword) { listener?.handleMixinHeader(mixinKeyword); } @override void handleMixinOn(Token onKeyword, int typeCount) { listener?.handleMixinOn(onKeyword, typeCount); } @override void handleNamedArgument(Token colon) { listener?.handleNamedArgument(colon); } @override void handleNamedMixinApplicationWithClause(Token withKeyword) { listener?.handleNamedMixinApplicationWithClause(withKeyword); } @override void handleNativeClause(Token nativeToken, bool hasName) { listener?.handleNativeClause(nativeToken, hasName); } @override void handleNativeFunctionBody(Token nativeToken, Token semicolon) { listener?.handleNativeFunctionBody(nativeToken, semicolon); } @override void handleNativeFunctionBodyIgnored(Token nativeToken, Token semicolon) { listener?.handleNativeFunctionBodyIgnored(nativeToken, semicolon); } @override void handleNativeFunctionBodySkipped(Token nativeToken, Token semicolon) { listener?.handleNativeFunctionBodySkipped(nativeToken, semicolon); } @override void handleNoArguments(Token token) { listener?.handleNoArguments(token); } @override void handleNoCommentReference() { listener?.handleNoCommentReference(); } @override void handleNoConstructorReferenceContinuationAfterTypeArguments(Token token) { listener?.handleNoConstructorReferenceContinuationAfterTypeArguments(token); } @override void handleNoFieldInitializer(Token token) { listener?.handleNoFieldInitializer(token); } @override void handleNoFormalParameters(Token token, MemberKind kind) { listener?.handleNoFormalParameters(token, kind); } @override void handleNoFunctionBody(Token token) { listener?.handleNoFunctionBody(token); } @override void handleNoInitializers() { listener?.handleNoInitializers(); } @override void handleNoName(Token token) { listener?.handleNoName(token); } @override void handleNonNullAssertExpression(Token bang) { listener?.handleNonNullAssertExpression(bang); } @override void handleNoType(Token lastConsumed) { listener?.handleNoType(lastConsumed); } @override void handleNoTypeArguments(Token token) { listener?.handleNoTypeArguments(token); } @override void handleNoTypeVariables(Token token) { listener?.handleNoTypeVariables(token); } @override void handleNoVariableInitializer(Token token) { listener?.handleNoVariableInitializer(token); } @override void handleOperator(Token token) { listener?.handleOperator(token); } @override void handleOperatorName(Token operatorKeyword, Token token) { listener?.handleOperatorName(operatorKeyword, token); } @override void handleParenthesizedCondition(Token token) { listener?.handleParenthesizedCondition(token); } @override void handleParenthesizedExpression(Token token) { listener?.handleParenthesizedExpression(token); } @override void handleQualified(Token period) { listener?.handleQualified(period); } @override void handleRecoverableError( Message message, Token startToken, Token endToken) { if (forwardErrors) { listener?.handleRecoverableError(message, startToken, endToken); } } @override void handleRecoverClassHeader() { listener?.handleRecoverClassHeader(); } @override void handleRecoverImport(Token semicolon) { listener?.handleRecoverImport(semicolon); } @override void handleRecoverMixinHeader() { listener?.handleRecoverMixinHeader(); } @override void handleScript(Token token) { listener?.handleScript(token); } @override void handleSend(Token beginToken, Token endToken) { listener?.handleSend(beginToken, endToken); } @override void handleSpreadExpression(Token spreadToken) { listener?.handleSpreadExpression(spreadToken); } @override void handleStringJuxtaposition(int literalCount) { listener?.handleStringJuxtaposition(literalCount); } @override void handleStringPart(Token token) { listener?.handleStringPart(token); } @override void handleSuperExpression(Token token, IdentifierContext context) { listener?.handleSuperExpression(token, context); } @override void handleSymbolVoid(Token token) { listener?.handleSymbolVoid(token); } @override void handleThisExpression(Token token, IdentifierContext context) { listener?.handleThisExpression(token, context); } @override void handleThrowExpression(Token throwToken, Token endToken) { listener?.handleThrowExpression(throwToken, endToken); } @override void handleType(Token beginToken, Token questionMark) { listener?.handleType(beginToken, questionMark); } @override void handleTypeVariablesDefined(Token token, int count) { listener?.handleTypeVariablesDefined(token, count); } @override void handleUnaryPostfixAssignmentExpression(Token token) { listener?.handleUnaryPostfixAssignmentExpression(token); } @override void handleUnaryPrefixAssignmentExpression(Token token) { listener?.handleUnaryPrefixAssignmentExpression(token); } @override void handleUnaryPrefixExpression(Token token) { listener?.handleUnaryPrefixExpression(token); } @override void handleUnescapeError( Message message, Token location, int offset, int length) { listener?.handleUnescapeError(message, location, offset, length); } @override void handleValuedFormalParameter(Token equals, Token token) { listener?.handleValuedFormalParameter(equals, token); } @override void handleVarianceModifier(Token variance) { listener?.handleVarianceModifier(variance); } @override void handleVoidKeyword(Token token) { listener?.handleVoidKeyword(token); } @override void logEvent(String name) { listener?.logEvent(name); } @override void reportErrorIfNullableType(Token questionMark) { listener?.reportErrorIfNullableType(questionMark); } @override void reportNonNullableModifierError(Token modifierToken) { listener?.reportNonNullableModifierError(modifierToken); } @override void reportNonNullAssertExpressionNotEnabled(Token bang) { listener?.reportNonNullAssertExpressionNotEnabled(bang); } @override void reportVarianceModifierNotEnabled(Token variance) { listener?.reportVarianceModifierNotEnabled(variance); } }
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/class_member_parser.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.parser.class_member_parser; import '../../scanner/token.dart' show Token; import 'error_delegation_listener.dart' show ErrorDelegationListener; import 'listener.dart' show Listener; import 'parser.dart' show Parser; /// Parser similar to [TopLevelParser] but also parses class members (excluding /// their bodies). class ClassMemberParser extends Parser { Parser skipParser; ClassMemberParser(Listener listener) : super(listener); @override Token parseExpression(Token token) { return skipExpression(token); } @override Token parseIdentifierExpression(Token token) { return token.next; } Token skipExpression(Token token) { // TODO(askesc): We listen to errors occurring during expression parsing, // since the parser may rewrite the token stream such that the error is // not triggered during the second parse. // When the parser supports not doing token stream rewriting, use that // feature together with a no-op listener instead. skipParser ??= new Parser(new ErrorDelegationListener(listener)); skipParser.mayParseFunctionExpressions = mayParseFunctionExpressions; skipParser.asyncState = asyncState; skipParser.loopState = loopState; return skipParser.parseExpression(token); } // This method is overridden for two reasons: // 1. Avoid generating events for arguments. // 2. Avoid calling skip expression for each argument (which doesn't work). Token parseArgumentsOpt(Token token) => skipArgumentsOpt(token); Token parseFunctionBody(Token token, bool isExpression, bool allowAbstract) { return skipFunctionBody(token, isExpression, allowAbstract); } @override Token parseInvalidBlock(Token token) => skipBlock(token); }
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/formal_parameter_kind.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.formal_parameter_kind; // TODO(johnniwinther): Update this to support required named arguments. enum FormalParameterKind { mandatory, optionalNamed, optionalPositional, } bool isMandatoryFormalParameterKind(FormalParameterKind type) { return FormalParameterKind.mandatory == type; } bool isOptionalNamedFormalParameterKind(FormalParameterKind type) { return FormalParameterKind.optionalNamed == type; } bool isOptionalPositionalFormalParameterKind(FormalParameterKind type) { return FormalParameterKind.optionalPositional == 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/parser/async_modifier.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.async_modifier; enum AsyncModifier { Sync, SyncStar, Async, AsyncStar, }
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/parser_error.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.parser_error; import '../fasta_codes.dart' show Message; import '../scanner.dart' show Token; class ParserError { /// Character offset from the beginning of file where this error starts. final int beginOffset; /// Character offset from the beginning of file where this error ends. final int endOffset; final Message message; ParserError(this.beginOffset, this.endOffset, this.message); ParserError.fromTokens(Token begin, Token end, Message message) : this(begin.charOffset, end.charOffset + end.charCount, message); String toString() => "@${beginOffset}: ${message.message}\n${message.tip}"; }
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/listener.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.parser.listener; import '../../scanner/token.dart' show Token; import '../fasta_codes.dart' show Message, MessageCode, templateExperimentNotEnabled; import '../quote.dart' show UnescapeErrorListener; import '../scanner/error_token.dart' show ErrorToken; import 'assert.dart' show Assert; import 'formal_parameter_kind.dart' show FormalParameterKind; import 'identifier_context.dart' show IdentifierContext; import 'declaration_kind.dart' show DeclarationKind; import 'member_kind.dart' show MemberKind; import 'util.dart' show optional; /// A parser event listener that does nothing except throw exceptions /// on parser errors. /// /// Events are methods that begin with one of: `begin`, `end`, or `handle`. /// /// Events starting with `begin` and `end` come in pairs. Normally, a /// `beginFoo` event is followed by an `endFoo` event. There's a few exceptions /// documented below. /// /// Events starting with `handle` are used when isn't possible to have a begin /// event. class Listener implements UnescapeErrorListener { Uri get uri => null; void logEvent(String name) {} set suppressParseErrors(bool value) {} void beginArguments(Token token) {} void endArguments(int count, Token beginToken, Token endToken) { logEvent("Arguments"); } /// Handle async modifiers `async`, `async*`, `sync`. void handleAsyncModifier(Token asyncToken, Token starToken) { logEvent("AsyncModifier"); } void beginAwaitExpression(Token token) {} void endAwaitExpression(Token beginToken, Token endToken) { logEvent("AwaitExpression"); } void endInvalidAwaitExpression( Token beginToken, Token endToken, MessageCode errorCode) { logEvent("InvalidAwaitExpression"); } void beginBlock(Token token) {} void endBlock(int count, Token beginToken, Token endToken) { logEvent("Block"); } /// Called to handle a block that has been parsed but is not associated /// with any top level function declaration. Substructures: /// - block void handleInvalidTopLevelBlock(Token token) {} void beginCascade(Token token) {} void endCascade() { logEvent("Cascade"); } void beginCaseExpression(Token caseKeyword) {} void endCaseExpression(Token colon) { logEvent("CaseExpression"); } /// Handle the start of the body of a class, mixin or extension declaration /// beginning at [token]. The actual kind of declaration is indicated by /// [kind]. void beginClassOrMixinBody(DeclarationKind kind, Token token) {} /// Handle the end of the body of a class, mixin or extension declaration. /// The only substructures are the class, mixin or extension members. /// /// The actual kind of declaration is indicated by [kind]. void endClassOrMixinBody( DeclarationKind kind, int memberCount, Token beginToken, Token endToken) { logEvent("ClassOrMixinBody"); } /// Called before parsing a class or named mixin application. /// /// At this point only the `class` keyword have been seen, so we know a /// declaration is coming but not its name or type parameter declarations. void beginClassOrNamedMixinApplicationPrelude(Token token) {} /// Handle the beginning of a class declaration. /// [begin] may be the same as [name], or may point to modifiers /// (or extraneous modifiers in the case of recovery) preceding [name]. /// /// At this point we have parsed the name and type parameter declarations. void beginClassDeclaration(Token begin, Token abstractToken, Token name) {} /// Handle an extends clause in a class declaration. Substructures: /// - supertype (may be a mixin application) void handleClassExtends(Token extendsKeyword) { logEvent("ClassExtends"); } /// Handle an implements clause in a class or mixin declaration. /// Substructures: /// - implemented types void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { logEvent("ClassImplements"); } /// Handle the header of a class declaration. Substructures: /// - metadata /// - modifiers /// - class name /// - type variables /// - supertype /// - with clause /// - implemented types /// - native clause void handleClassHeader(Token begin, Token classKeyword, Token nativeToken) { logEvent("ClassHeader"); } /// Handle recovery associated with a class header. /// This may be called multiple times after [handleClassHeader] /// to recover information about the previous class header. /// The substructures are a subset of /// and in the same order as [handleClassHeader]: /// - supertype /// - with clause /// - implemented types void handleRecoverClassHeader() { logEvent("RecoverClassHeader"); } /// Handle the end of a class declaration. Substructures: /// - class header /// - class body void endClassDeclaration(Token beginToken, Token endToken) { logEvent("ClassDeclaration"); } /// Handle the beginning of a mixin declaration. void beginMixinDeclaration(Token mixinKeyword, Token name) {} /// Handle an on clause in a mixin declaration. Substructures: /// - implemented types void handleMixinOn(Token onKeyword, int typeCount) { logEvent("MixinOn"); } /// Handle the header of a mixin declaration. Substructures: /// - metadata /// - mixin name /// - type variables /// - on types /// - implemented types void handleMixinHeader(Token mixinKeyword) { logEvent("MixinHeader"); } /// Handle recovery associated with a mixin header. /// This may be called multiple times after [handleMixinHeader] /// to recover information about the previous mixin header. /// The substructures are a subset of /// and in the same order as [handleMixinHeader] /// - on types /// - implemented types void handleRecoverMixinHeader() { logEvent("RecoverMixinHeader"); } /// Handle the end of a mixin declaration. Substructures: /// - mixin header /// - class or mixin body void endMixinDeclaration(Token mixinKeyword, Token endToken) { logEvent("MixinDeclaration"); } /// Handle the beginning of an extension methods declaration. Substructures: /// - metadata /// /// At this point only the `extension` keyword have been seen, so we know a /// declaration is coming but not its name or type parameter declarations. void beginExtensionDeclarationPrelude(Token extensionKeyword) {} /// Handle the beginning of an extension methods declaration. Substructures: /// - type variables /// /// At this point we have parsed the name and type parameter declarations. void beginExtensionDeclaration(Token extensionKeyword, Token name) {} /// Handle the end of an extension methods declaration. Substructures: /// - substructures from [beginExtensionDeclaration] /// - on type /// - body void endExtensionDeclaration( Token extensionKeyword, Token onKeyword, Token token) { logEvent('ExtensionDeclaration'); } void beginCombinators(Token token) {} void endCombinators(int count) { logEvent("Combinators"); } void beginCompilationUnit(Token token) {} /// This method exists for analyzer compatibility only /// and will be removed once analyzer/fasta integration is complete. /// /// This is called when [parseDirectives] has parsed all directives /// and is skipping the remainder of the file. Substructures: /// - metadata void handleDirectivesOnly() {} void endCompilationUnit(int count, Token token) { logEvent("CompilationUnit"); } void beginConstLiteral(Token token) {} void endConstLiteral(Token token) { logEvent("ConstLiteral"); } void beginConstructorReference(Token start) {} void endConstructorReference( Token start, Token periodBeforeName, Token endToken) { logEvent("ConstructorReference"); } void beginDoWhileStatement(Token token) {} void endDoWhileStatement( Token doKeyword, Token whileKeyword, Token endToken) { logEvent("DoWhileStatement"); } void beginDoWhileStatementBody(Token token) {} void endDoWhileStatementBody(Token token) { logEvent("DoWhileStatementBody"); } void beginWhileStatementBody(Token token) {} void endWhileStatementBody(Token token) { logEvent("WhileStatementBody"); } void beginEnum(Token enumKeyword) {} /// Handle the end of an enum declaration. Substructures: /// - Metadata /// - Enum name (identifier) /// - [count] times: /// - Enum value (identifier) void endEnum(Token enumKeyword, Token leftBrace, int count) { logEvent("Enum"); } void beginExport(Token token) {} /// Handle the end of an export directive. Substructures: /// - metadata /// - uri /// - conditional uris /// - combinators void endExport(Token exportKeyword, Token semicolon) { logEvent("Export"); } /// Called by [Parser] after parsing an extraneous expression as error /// recovery. For a stack-based listener, the suggested action is to discard /// an expression from the stack. void handleExtraneousExpression(Token token, Message message) { logEvent("ExtraneousExpression"); } void handleExpressionStatement(Token token) { logEvent("ExpressionStatement"); } void beginFactoryMethod( Token lastConsumed, Token externalToken, Token constToken) {} void endClassFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { logEvent("ClassFactoryMethod"); } void endMixinFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassFactoryMethod(beginToken, factoryKeyword, endToken); } void endExtensionFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassFactoryMethod(beginToken, factoryKeyword, endToken); } void beginFormalParameter(Token token, MemberKind kind, Token requiredToken, Token covariantToken, Token varFinalOrConst) {} void endFormalParameter( Token thisKeyword, Token periodAfterThis, Token nameToken, Token initializerStart, Token initializerEnd, FormalParameterKind kind, MemberKind memberKind) { logEvent("FormalParameter"); } void handleNoFormalParameters(Token token, MemberKind kind) { logEvent("NoFormalParameters"); } void beginFormalParameters(Token token, MemberKind kind) {} void endFormalParameters( int count, Token beginToken, Token endToken, MemberKind kind) { logEvent("FormalParameters"); } /// Handle the end of a class field declaration. Substructures: /// - Metadata /// - Modifiers /// - Type /// - Variable declarations (count times) /// /// Doesn't have a corresponding begin event, use [beginMember] instead. void endClassFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { logEvent("Fields"); } /// Handle the end of a mixin field declaration. Substructures: /// - Metadata /// - Modifiers /// - Type /// - Variable declarations (count times) /// /// Doesn't have a corresponding begin event, use [beginMember] instead. void endMixinFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } /// Handle the end of a extension field declaration. Substructures: /// - Metadata /// - Modifiers /// - Type /// - Variable declarations (count times) /// /// Doesn't have a corresponding begin event, use [beginMember] instead. void endExtensionFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } /// Marks that the grammar term `forInitializerStatement` has been parsed and /// it was an empty statement. void handleForInitializerEmptyStatement(Token token) { logEvent("ForInitializerEmptyStatement"); } /// Marks that the grammar term `forInitializerStatement` has been parsed and /// it was an expression statement. void handleForInitializerExpressionStatement(Token token) { logEvent("ForInitializerExpressionStatement"); } /// Marks that the grammar term `forInitializerStatement` has been parsed and /// it was a `localVariableDeclaration`. void handleForInitializerLocalVariableDeclaration(Token token) { logEvent("ForInitializerLocalVariableDeclaration"); } /// Marks the start of a for statement which is ended by either /// [endForStatement] or [endForIn]. void beginForStatement(Token token) {} /// Marks the end of parsing the control structure of a for statement /// or for control flow entry up to and including the closing parenthesis. /// `for` `(` initialization `;` condition `;` updaters `)` void handleForLoopParts(Token forKeyword, Token leftParen, Token leftSeparator, int updateExpressionCount) {} void endForStatement(Token endToken) { logEvent("ForStatement"); } void beginForStatementBody(Token token) {} void endForStatementBody(Token token) { logEvent("ForStatementBody"); } /// Marks the end of parsing the control structure of a for-in statement /// or for control flow entry up to and including the closing parenthesis. /// `for` `(` (type)? identifier `in` iterator `)` void handleForInLoopParts(Token awaitToken, Token forToken, Token leftParenthesis, Token inKeyword) {} // One of the two possible corresponding end events for [beginForStatement]. void endForIn(Token endToken) { logEvent("ForIn"); } void beginForInExpression(Token token) {} void endForInExpression(Token token) { logEvent("ForInExpression"); } void beginForInBody(Token token) {} void endForInBody(Token token) { logEvent("ForInBody"); } /// Handle the beginning of a named function expression which isn't legal /// syntax in Dart. Useful for recovering from Javascript code being pasted /// into a Dart program, as it will interpret `function foo() {}` as a named /// function expression with return type `function` and name `foo`. /// /// Substructures: /// - Type variables void beginNamedFunctionExpression(Token token) {} /// A named function expression which isn't legal syntax in Dart. /// Useful for recovering from Javascript code being pasted into a Dart /// program, as it will interpret `function foo() {}` as a named function /// expression with return type `function` and name `foo`. /// /// Substructures: /// - Type variables /// - Modifiers /// - Return type /// - Name /// - Formals /// - Initializers /// - Async modifier /// - Function body (block or arrow expression). void endNamedFunctionExpression(Token endToken) { logEvent("NamedFunctionExpression"); } /// Handle the beginning of a local function declaration. Substructures: /// - Metadata /// - Type variables void beginLocalFunctionDeclaration(Token token) {} /// A function declaration. /// /// Substructures: /// - Metadata /// - Type variables /// - Return type /// - Name /// - Type variables /// - Formals /// - Initializers /// - Async modifier /// - Function body (block or arrow expression). void endLocalFunctionDeclaration(Token endToken) { logEvent("FunctionDeclaration"); } /// This method is invoked when the parser sees that a function has a /// block function body. This method is not invoked for empty or expression /// function bodies, see the corresponding methods [handleEmptyFunctionBody] /// and [handleExpressionFunctionBody]. void beginBlockFunctionBody(Token token) {} /// This method is invoked by the parser after it finished parsing a block /// function body. This method is not invoked for empty or expression /// function bodies, see the corresponding methods [handleEmptyFunctionBody] /// and [handleExpressionFunctionBody]. The [beginToken] is the '{' token, /// and the [endToken] is the '}' token of the block. The number of /// statements is given as the [count] parameter. void endBlockFunctionBody(int count, Token beginToken, Token endToken) { logEvent("BlockFunctionBody"); } void handleNoFunctionBody(Token token) { logEvent("NoFunctionBody"); } /// Handle the end of a function body that was skipped by the parser. /// /// The boolean [isExpressionBody] indicates whether the function body that /// was skipped used "=>" syntax. void handleFunctionBodySkipped(Token token, bool isExpressionBody) {} void beginFunctionName(Token token) {} void endFunctionName(Token beginToken, Token token) { logEvent("FunctionName"); } void beginFunctionTypeAlias(Token token) {} /// Handle the end of a typedef declaration. /// /// If [equals] is null, then we have the following substructures: /// - Metadata /// - Return type /// - Name (identifier) /// - Alias type variables /// - Formal parameters /// /// If [equals] is not null, then the have the following substructures: /// - Metadata /// - Name (identifier) /// - Alias type variables /// - Type (FunctionTypeAnnotation) void endFunctionTypeAlias( Token typedefKeyword, Token equals, Token endToken) { logEvent("FunctionTypeAlias"); } /// Handle the end of a with clause (e.g. "with B, C"). /// Substructures: /// - mixin types (TypeList) void handleClassWithClause(Token withKeyword) { logEvent("ClassWithClause"); } /// Handle the absence of a with clause. void handleClassNoWithClause() { logEvent("ClassNoWithClause"); } /// Handle the beginning of a named mixin application. /// [beginToken] may be the same as [name], or may point to modifiers /// (or extraneous modifiers in the case of recovery) preceding [name]. /// /// At this point we have parsed the name and type parameter declarations. void beginNamedMixinApplication( Token begin, Token abstractToken, Token name) {} /// Handle a named mixin application with clause (e.g. "A with B, C"). /// Substructures: /// - supertype /// - mixin types (TypeList) void handleNamedMixinApplicationWithClause(Token withKeyword) { logEvent("NamedMixinApplicationWithClause"); } /// Handle the end of a named mixin declaration. Substructures: /// - metadata /// - modifiers /// - class name /// - type variables /// - supertype /// - with clause /// - implemented types (TypeList) /// /// TODO(paulberry,ahe): it seems inconsistent that for a named mixin /// application, the implemented types are a TypeList, whereas for a class /// declaration, each implemented type is listed separately on the stack, and /// the number of implemented types is passed as a parameter. void endNamedMixinApplication(Token begin, Token classKeyword, Token equals, Token implementsKeyword, Token endToken) { logEvent("NamedMixinApplication"); } void beginHide(Token hideKeyword) {} /// Handle the end of a "hide" combinator. Substructures: /// - hidden names (IdentifierList) void endHide(Token hideKeyword) { logEvent("Hide"); } void handleIdentifierList(int count) { logEvent("IdentifierList"); } void beginTypeList(Token token) {} void endTypeList(int count) { logEvent("TypeList"); } void beginIfStatement(Token token) {} void endIfStatement(Token ifToken, Token elseToken) { logEvent("IfStatement"); } void beginThenStatement(Token token) {} void endThenStatement(Token token) { logEvent("ThenStatement"); } void beginElseStatement(Token token) {} void endElseStatement(Token token) { logEvent("ElseStatement"); } void beginImport(Token importKeyword) {} /// Signals that the current import is deferred and/or has a prefix /// depending upon whether [deferredKeyword] and [asKeyword] /// are not `null` respectively. Substructures: /// - prefix identifier (only if asKeyword != null) void handleImportPrefix(Token deferredKeyword, Token asKeyword) { logEvent("ImportPrefix"); } /// Handle the end of an import directive. Substructures: /// - metadata /// - uri /// - conditional uris /// - prefix identifier /// - combinators void endImport(Token importKeyword, Token semicolon) { logEvent("Import"); } /// Handle recovery associated with an import directive. /// This may be called multiple times after [endImport] /// to recover information about the previous import directive. /// The substructures are a subset of and in the same order as [endImport]: /// - conditional uris /// - prefix identifier /// - combinators void handleRecoverImport(Token semicolon) { logEvent("ImportRecovery"); } void beginConditionalUris(Token token) {} void endConditionalUris(int count) { logEvent("ConditionalUris"); } void beginConditionalUri(Token ifKeyword) {} /// Handle the end of a conditional URI construct. Substructures: /// - Dotted name /// - Condition (literal string; only if [equalSign] != null) /// - URI (literal string) void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) { logEvent("ConditionalUri"); } void handleDottedName(int count, Token firstIdentifier) { logEvent("DottedName"); } void beginImplicitCreationExpression(Token token) {} void endImplicitCreationExpression(Token token) { logEvent("ImplicitCreationExpression"); } void beginInitializedIdentifier(Token token) {} void endInitializedIdentifier(Token nameToken) { logEvent("InitializedIdentifier"); } void beginFieldInitializer(Token token) {} /// Handle the end of a field initializer. Substructures: /// - Initializer expression void endFieldInitializer(Token assignment, Token token) { logEvent("FieldInitializer"); } /// Handle the lack of a field initializer. void handleNoFieldInitializer(Token token) { logEvent("NoFieldInitializer"); } void beginVariableInitializer(Token token) {} /// Handle the end of a variable initializer. Substructures: /// - Initializer expression. void endVariableInitializer(Token assignmentOperator) { logEvent("VariableInitializer"); } /// Used when a variable has no initializer. void handleNoVariableInitializer(Token token) { logEvent("NoVariableInitializer"); } void beginInitializer(Token token) {} void endInitializer(Token token) { logEvent("ConstructorInitializer"); } void beginInitializers(Token token) {} void endInitializers(int count, Token beginToken, Token endToken) { logEvent("Initializers"); } void handleNoInitializers() { logEvent("NoInitializers"); } /// Called after the listener has recovered from an invalid expression. The /// parser will resume parsing from [token]. Exactly where the parser will /// resume parsing is unspecified. void handleInvalidExpression(Token token) { logEvent("InvalidExpression"); } /// Called after the listener has recovered from an invalid function /// body. The parser expected an open curly brace `{` and will resume parsing /// from [token] as if a function body had preceded it. void handleInvalidFunctionBody(Token token) { logEvent("InvalidFunctionBody"); } /// Called after the listener has recovered from an invalid type. The parser /// expected an identifier, and will resume parsing type arguments from /// [token]. void handleInvalidTypeReference(Token token) { logEvent("InvalidTypeReference"); } void handleLabel(Token token) { logEvent("Label"); } void beginLabeledStatement(Token token, int labelCount) {} void endLabeledStatement(int labelCount) { logEvent("LabeledStatement"); } void beginLibraryName(Token token) {} /// Handle the end of a library directive. Substructures: /// - Metadata /// - Library name (a qualified identifier) void endLibraryName(Token libraryKeyword, Token semicolon) { logEvent("LibraryName"); } void handleLiteralMapEntry(Token colon, Token endToken) { logEvent("LiteralMapEntry"); } void beginLiteralString(Token token) {} void handleInterpolationExpression(Token leftBracket, Token rightBracket) {} void endLiteralString(int interpolationCount, Token endToken) { logEvent("LiteralString"); } void handleStringJuxtaposition(int literalCount) { logEvent("StringJuxtaposition"); } void beginMember() {} /// Handle an invalid member declaration. Substructures: /// - metadata void handleInvalidMember(Token endToken) { logEvent("InvalidMember"); } /// This event is added for convenience. Normally, one should override /// [endClassFields], [endMixinFields], [endExtensionFields], /// [endClassMethod], [endMixinMethod], [endExtensionMethod], /// [endClassConstructor], [endMixinConstructor], /// or [endExtensionConstructor] instead. void endMember() { logEvent("Member"); } /// Handle the beginning of a method declaration. Substructures: /// - metadata void beginMethod(Token externalToken, Token staticToken, Token covariantToken, Token varFinalOrConst, Token getOrSet, Token name) {} /// Handle the end of a class method declaration. Substructures: /// - metadata /// - return type /// - method name (identifier, possibly qualified) /// - type variables /// - formal parameters /// - initializers /// - async marker /// - body void endClassMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { logEvent("ClassMethod"); } /// Handle the end of a mixin method declaration. Substructures: /// - metadata /// - return type /// - method name (identifier, possibly qualified) /// - type variables /// - formal parameters /// - initializers /// - async marker /// - body void endMixinMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } /// Handle the end of a extension method declaration. Substructures: /// - metadata /// - return type /// - method name (identifier, possibly qualified) /// - type variables /// - formal parameters /// - initializers /// - async marker /// - body void endExtensionMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } /// Handle the end of a class constructor declaration. Substructures: /// - metadata /// - return type /// - method name (identifier, possibly qualified) /// - type variables /// - formal parameters /// - initializers /// - async marker /// - body void endClassConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } /// Handle the end of a mixin constructor declaration. Substructures: /// - metadata /// - return type /// - method name (identifier, possibly qualified) /// - type variables /// - formal parameters /// - initializers /// - async marker /// - body void endMixinConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } /// Handle the end of a extension constructor declaration. Substructures: /// - metadata /// - return type /// - method name (identifier, possibly qualified) /// - type variables /// - formal parameters /// - initializers /// - async marker /// - body void endExtensionConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { // TODO(danrubel): push implementation into subclasses endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } void beginMetadataStar(Token token) {} void endMetadataStar(int count) { logEvent("MetadataStar"); } void beginMetadata(Token token) {} /// Handle the end of a metadata annotation. Substructures: /// - Identifier /// - Type arguments /// - Constructor name (only if [periodBeforeName] is not `null`) /// - Arguments void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) { logEvent("Metadata"); } void beginOptionalFormalParameters(Token token) {} void endOptionalFormalParameters( int count, Token beginToken, Token endToken) { logEvent("OptionalFormalParameters"); } void beginPart(Token token) {} /// Handle the end of a part directive. Substructures: /// - metadata /// - uri void endPart(Token partKeyword, Token semicolon) { logEvent("Part"); } void beginPartOf(Token token) {} /// Handle the end of a "part of" directive. Substructures: /// - Metadata /// - Library name (a qualified identifier) /// /// If [hasName] is true, this part refers to its library by name, otherwise, /// by URI. void endPartOf( Token partKeyword, Token ofKeyword, Token semicolon, bool hasName) { logEvent("PartOf"); } void beginRedirectingFactoryBody(Token token) {} void endRedirectingFactoryBody(Token beginToken, Token endToken) { logEvent("RedirectingFactoryBody"); } void beginReturnStatement(Token token) {} /// Handle the end of a `native` function. /// The [handleNativeClause] event is sent prior to this event. void handleNativeFunctionBody(Token nativeToken, Token semicolon) { logEvent("NativeFunctionBody"); } /// Called after the [handleNativeClause] event when the parser determines /// that the native clause should be discarded / ignored. /// For example, this method is called a native clause is followed by /// a function body. void handleNativeFunctionBodyIgnored(Token nativeToken, Token semicolon) { logEvent("NativeFunctionBodyIgnored"); } /// Handle the end of a `native` function that was skipped by the parser. /// The [handleNativeClause] event is sent prior to this event. void handleNativeFunctionBodySkipped(Token nativeToken, Token semicolon) { logEvent("NativeFunctionBodySkipped"); } /// This method is invoked when a function has the empty body. void handleEmptyFunctionBody(Token semicolon) { logEvent("EmptyFunctionBody"); } /// This method is invoked when parser finishes parsing the corresponding /// expression of the expression function body. void handleExpressionFunctionBody(Token arrowToken, Token endToken) { logEvent("ExpressionFunctionBody"); } void endReturnStatement( bool hasExpression, Token beginToken, Token endToken) { logEvent("ReturnStatement"); } void handleSend(Token beginToken, Token endToken) { logEvent("Send"); } void beginShow(Token showKeyword) {} /// Handle the end of a "show" combinator. Substructures: /// - shown names (IdentifierList) void endShow(Token showKeyword) { logEvent("Show"); } void beginSwitchStatement(Token token) {} void endSwitchStatement(Token switchKeyword, Token endToken) { logEvent("SwitchStatement"); } void beginSwitchBlock(Token token) {} void endSwitchBlock(int caseCount, Token beginToken, Token endToken) { logEvent("SwitchBlock"); } void beginLiteralSymbol(Token token) {} void endLiteralSymbol(Token hashToken, int identifierCount) { logEvent("LiteralSymbol"); } void handleThrowExpression(Token throwToken, Token endToken) { logEvent("ThrowExpression"); } void beginRethrowStatement(Token token) {} void endRethrowStatement(Token rethrowToken, Token endToken) { logEvent("RethrowStatement"); } /// This event is added for convenience. Normally, one should use /// [endClassDeclaration], [endNamedMixinApplication], [endEnum], /// [endFunctionTypeAlias], [endLibraryName], [endImport], [endExport], /// [endPart], [endPartOf], [endTopLevelFields], or [endTopLevelMethod]. void endTopLevelDeclaration(Token token) { logEvent("TopLevelDeclaration"); } /// Called by the [Parser] when it recovers from an invalid top level /// declaration, where [endToken] is the last token in the declaration /// This is called after the begin/end metadata star events, /// and is followed by [endTopLevelDeclaration]. /// /// Substructures: /// - metadata void handleInvalidTopLevelDeclaration(Token endToken) { logEvent("InvalidTopLevelDeclaration"); } /// Marks the beginning of a top level field or method declaration. /// Doesn't have a corresponding end event. /// See [endTopLevelFields] and [endTopLevelMethod]. void beginTopLevelMember(Token token) {} /// Handle the end of a top level variable declaration. Substructures: /// - Metadata /// - Type /// - Repeated [count] times: /// - Variable name (identifier) /// - Field initializer /// Doesn't have a corresponding begin event. /// Use [beginTopLevelMember] instead. void endTopLevelFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { logEvent("TopLevelFields"); } void beginTopLevelMethod(Token lastConsumed, Token externalToken) {} /// Handle the end of a top level method. Substructures: /// - metadata /// - modifiers /// - return type /// - identifier /// - type variables /// - formal parameters /// - async marker /// - body void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) { logEvent("TopLevelMethod"); } void beginTryStatement(Token token) {} void handleCaseMatch(Token caseKeyword, Token colon) { logEvent("CaseMatch"); } void beginCatchClause(Token token) {} void endCatchClause(Token token) { logEvent("CatchClause"); } void handleCatchBlock(Token onKeyword, Token catchKeyword, Token comma) { logEvent("CatchBlock"); } void handleFinallyBlock(Token finallyKeyword) { logEvent("FinallyBlock"); } void endTryStatement(int catchCount, Token tryKeyword, Token finallyKeyword) { logEvent("TryStatement"); } void handleType(Token beginToken, Token questionMark) { logEvent("Type"); } /// Called when parser encounters a '!' /// used as a non-null postfix assertion in an expression. void handleNonNullAssertExpression(Token bang) { logEvent("NonNullAssertExpression"); } // TODO(danrubel): Remove this once all listeners have been updated // to properly handle nullable types void reportErrorIfNullableType(Token questionMark) { if (questionMark != null) { assert(optional('?', questionMark)); handleRecoverableError( templateExperimentNotEnabled.withArguments('non-nullable'), questionMark, questionMark); } } // TODO(danrubel): Remove this once all listeners have been updated // to properly handle nullable types void reportNonNullableModifierError(Token modifierToken) { if (modifierToken != null) { handleRecoverableError( templateExperimentNotEnabled.withArguments('non-nullable'), modifierToken, modifierToken); } } // TODO(danrubel): Remove this once all listeners have been updated // to properly handle non-null assert expressions void reportNonNullAssertExpressionNotEnabled(Token bang) { handleRecoverableError( templateExperimentNotEnabled.withArguments('non-nullable'), bang, bang); } void handleNoName(Token token) { logEvent("NoName"); } void beginFunctionType(Token beginToken) {} /// Handle the end of a generic function type declaration. /// /// Substructures: /// - Type variables /// - Return type /// - Formal parameters void endFunctionType(Token functionToken, Token questionMark) { logEvent("FunctionType"); } void beginTypeArguments(Token token) {} void endTypeArguments(int count, Token beginToken, Token endToken) { logEvent("TypeArguments"); } /// After endTypeArguments has been called, /// this event is called if those type arguments are invalid. void handleInvalidTypeArguments(Token token) { logEvent("NoTypeArguments"); } void handleNoTypeArguments(Token token) { logEvent("NoTypeArguments"); } /// Handle the begin of a type formal parameter (e.g. "X extends Y"). /// Substructures: /// - Metadata /// - Name (identifier) void beginTypeVariable(Token token) {} /// Called when [beginTypeVariable] has been called for all of the variables /// in a group, and before [endTypeVariable] has been called for any of the /// variables in that same group. void handleTypeVariablesDefined(Token token, int count) {} /// Handle the end of a type formal parameter (e.g. "X extends Y") /// where [index] is the index of the type variable in the list of /// type variables being declared. /// /// Substructures: /// - Type bound /// /// See [beginTypeVariable] for additional substructures. void endTypeVariable( Token token, int index, Token extendsOrSuper, Token variance) { logEvent("TypeVariable"); } void beginTypeVariables(Token token) {} void endTypeVariables(Token beginToken, Token endToken) { logEvent("TypeVariables"); } void handleVarianceModifier(Token variance) { logEvent("VarianceModifier"); } void reportVarianceModifierNotEnabled(Token variance) { if (variance != null) { handleRecoverableError( templateExperimentNotEnabled.withArguments('variance'), variance, variance); } } void beginFunctionExpression(Token token) {} /// Handle the end of a function expression (e.g. "() { ... }"). /// Substructures: /// - Type variables /// - Formal parameters /// - Async marker /// - Body void endFunctionExpression(Token beginToken, Token token) { logEvent("FunctionExpression"); } /// Handle the start of a variables declaration. Substructures: /// - Metadata /// - Type void beginVariablesDeclaration( Token token, Token lateToken, Token varFinalOrConst) {} void endVariablesDeclaration(int count, Token endToken) { logEvent("VariablesDeclaration"); } void beginWhileStatement(Token token) {} void endWhileStatement(Token whileKeyword, Token endToken) { logEvent("WhileStatement"); } void handleAsOperator(Token operator) { logEvent("AsOperator"); } void handleAssignmentExpression(Token token) { logEvent("AssignmentExpression"); } /// Called when the parser encounters a binary operator, in between the LHS /// and RHS subexpressions. /// /// Not called when the binary operator is `.`, `?.`, or `..`. void beginBinaryExpression(Token token) {} void endBinaryExpression(Token token) { logEvent("BinaryExpression"); } /// Called when the parser encounters a `?` operator and begins parsing a /// conditional expression. void beginConditionalExpression(Token question) {} /// Called when the parser encounters a `:` operator in a conditional /// expression. void handleConditionalExpressionColon() {} /// Called when the parser finishes processing a conditional expression. void endConditionalExpression(Token question, Token colon) { logEvent("ConditionalExpression"); } void beginConstExpression(Token constKeyword) {} void endConstExpression(Token token) { logEvent("ConstExpression"); } /// Called before parsing a "for" control flow list, set, or map entry. void beginForControlFlow(Token awaitToken, Token forToken) {} /// Called after parsing a "for" control flow list, set, or map entry. void endForControlFlow(Token token) { logEvent('endForControlFlow'); } /// Called after parsing a "for-in" control flow list, set, or map entry. void endForInControlFlow(Token token) { logEvent('endForInControlFlow'); } /// Called before parsing an `if` control flow list, set, or map entry. void beginIfControlFlow(Token ifToken) {} /// Called before parsing the `then` portion of an `if` control flow list, /// set, or map entry. void beginThenControlFlow(Token token) {} /// Called before parsing the `else` portion of an `if` control flow list, /// set, or map entry. void handleElseControlFlow(Token elseToken) { logEvent("ElseControlFlow"); } /// Called after parsing an `if` control flow list, set, or map entry. /// Substructures: /// - if conditional expression /// - expression void endIfControlFlow(Token token) { logEvent("endIfControlFlow"); } /// Called after parsing an if-else control flow list, set, or map entry. /// Substructures: /// - if conditional expression /// - then expression /// - else expression void endIfElseControlFlow(Token token) { logEvent("endIfElseControlFlow"); } /// Called after parsing a list, set, or map entry that starts with /// one of the spread collection tokens `...` or `...?`. Substructures: /// - expression void handleSpreadExpression(Token spreadToken) { logEvent("SpreadExpression"); } /// Handle the start of a function typed formal parameter. Substructures: /// - type variables void beginFunctionTypedFormalParameter(Token token) {} /// Handle the end of a function typed formal parameter. Substructures: /// - type variables /// - return type /// - formal parameters void endFunctionTypedFormalParameter(Token nameToken, Token question) { logEvent("FunctionTypedFormalParameter"); } /// Handle an identifier token. /// /// [context] indicates what kind of construct the identifier appears in. void handleIdentifier(Token token, IdentifierContext context) { logEvent("Identifier"); } void handleIndexedExpression( Token openSquareBracket, Token closeSquareBracket) { logEvent("IndexedExpression"); } void handleIsOperator(Token isOperator, Token not) { logEvent("IsOperator"); } void handleLiteralBool(Token token) { logEvent("LiteralBool"); } void handleBreakStatement( bool hasTarget, Token breakKeyword, Token endToken) { logEvent("BreakStatement"); } void handleContinueStatement( bool hasTarget, Token continueKeyword, Token endToken) { logEvent("ContinueStatement"); } void handleEmptyStatement(Token token) { logEvent("EmptyStatement"); } void beginAssert(Token assertKeyword, Assert kind) {} void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis, Token commaToken, Token semicolonToken) { logEvent("Assert"); } /** Called with either the token containing a double literal, or * an immediately preceding "unary plus" token. */ void handleLiteralDouble(Token token) { logEvent("LiteralDouble"); } /** Called with either the token containing an integer literal, * or an immediately preceding "unary plus" token. */ void handleLiteralInt(Token token) { logEvent("LiteralInt"); } void handleLiteralList( int count, Token leftBracket, Token constKeyword, Token rightBracket) { logEvent("LiteralList"); } void handleLiteralSetOrMap( int count, Token leftBrace, Token constKeyword, Token rightBrace, // TODO(danrubel): hasSetEntry parameter exists for replicating existing // behavior and will be removed once unified collection has been enabled bool hasSetEntry, ) { logEvent('LiteralSetOrMap'); } void handleLiteralNull(Token token) { logEvent("LiteralNull"); } void handleNativeClause(Token nativeToken, bool hasName) { logEvent("NativeClause"); } void handleNamedArgument(Token colon) { logEvent("NamedArgument"); } void beginNewExpression(Token token) {} void endNewExpression(Token token) { logEvent("NewExpression"); } void handleNoArguments(Token token) { logEvent("NoArguments"); } void handleNoConstructorReferenceContinuationAfterTypeArguments(Token token) { logEvent("NoConstructorReferenceContinuationAfterTypeArguments"); } void handleNoType(Token lastConsumed) { logEvent("NoType"); } void handleNoTypeVariables(Token token) { logEvent("NoTypeVariables"); } void handleOperator(Token token) { logEvent("Operator"); } void handleSymbolVoid(Token token) { logEvent("SymbolVoid"); } /// Handle the end of a construct of the form "operator <token>". void handleOperatorName(Token operatorKeyword, Token token) { logEvent("OperatorName"); } /// Handle the end of a construct of the form "operator <token>" /// where <token> is not a valid operator token. void handleInvalidOperatorName(Token operatorKeyword, Token token) { logEvent("InvalidOperatorName"); } /// Handle the condition in a control structure: /// - if statement /// - do while loop /// - switch statement /// - while loop void handleParenthesizedCondition(Token token) { logEvent("ParenthesizedCondition"); } /// Handle a parenthesized expression. /// These may be within the condition expression of a control structure /// but will not be the condition of a control structure. void handleParenthesizedExpression(Token token) { logEvent("ParenthesizedExpression"); } /// Handle a construct of the form "identifier.identifier" occurring in a part /// of the grammar where expressions in general are not allowed. /// Substructures: /// - Qualified identifier (before the period) /// - Identifier (after the period) void handleQualified(Token period) { logEvent("Qualified"); } void handleStringPart(Token token) { logEvent("StringPart"); } void handleSuperExpression(Token token, IdentifierContext context) { logEvent("SuperExpression"); } void beginSwitchCase(int labelCount, int expressionCount, Token firstToken) {} void endSwitchCase( int labelCount, int expressionCount, Token defaultKeyword, Token colonAfterDefault, int statementCount, Token firstToken, Token endToken) { logEvent("SwitchCase"); } void handleThisExpression(Token token, IdentifierContext context) { logEvent("ThisExpression"); } void handleUnaryPostfixAssignmentExpression(Token token) { logEvent("UnaryPostfixAssignmentExpression"); } void handleUnaryPrefixExpression(Token token) { logEvent("UnaryPrefixExpression"); } void handleUnaryPrefixAssignmentExpression(Token token) { logEvent("UnaryPrefixAssignmentExpression"); } void beginFormalParameterDefaultValueExpression() {} void endFormalParameterDefaultValueExpression() { logEvent("FormalParameterDefaultValueExpression"); } void handleValuedFormalParameter(Token equals, Token token) { logEvent("ValuedFormalParameter"); } void handleFormalParameterWithoutValue(Token token) { logEvent("FormalParameterWithoutValue"); } void handleVoidKeyword(Token token) { logEvent("VoidKeyword"); } void beginYieldStatement(Token token) {} void endYieldStatement(Token yieldToken, Token starToken, Token endToken) { logEvent("YieldStatement"); } /// The parser noticed a syntax error, but was able to recover from it. The /// error should be reported using the [message], and the code between the /// beginning of the [startToken] and the end of the [endToken] should be /// highlighted. The [startToken] and [endToken] can be the same token. void handleRecoverableError( Message message, Token startToken, Token endToken) {} /// The parser encountered an [ErrorToken] representing an error /// from the scanner but recovered from it. By default, the error is reported /// by calling [handleRecoverableError] with the message associated /// with the error [token]. void handleErrorToken(ErrorToken token) { handleRecoverableError(token.assertionMessage, token, token); } @override void handleUnescapeError( Message message, Token location, int stringOffset, int length) { handleRecoverableError(message, location, location); } /// Signals to the listener that the previous statement contained a semantic /// error (described by the given [message]). This method can also be called /// after [handleExpressionFunctionBody], in which case it signals that the /// implicit return statement of the function contained a semantic error. void handleInvalidStatement(Token token, Message message) { handleRecoverableError(message, token, token); } void handleScript(Token token) { logEvent("Script"); } /// A type has been just parsed, and the parser noticed that the next token /// has a type substitution comment /*=T*. So, the type that has been just /// parsed should be discarded, and a new type should be parsed instead. void discardTypeReplacedWithCommentTypeAssign() {} /// A single comment reference has been found /// where [referenceSource] is the text between the `[` and `]` /// and [referenceOffset] is the character offset in the token stream. /// /// This event is generated by the parser when the parser's /// `parseCommentReferences` method is called. For further processing, /// a listener may scan the [referenceSource] and then pass the resulting /// token stream to the parser's `parseOneCommentReference` method. void handleCommentReferenceText(String referenceSource, int referenceOffset) { logEvent("CommentReferenceText"); } /// A single comment reference has been parsed. /// * [newKeyword] may be null. /// * [prefix] and [period] are either both tokens or both `null`. /// * [token] can be an identifier or an operator. /// /// This event is generated by the parser when the parser's /// `parseOneCommentReference` method is called. void handleCommentReference( Token newKeyword, Token prefix, Token period, Token token) {} /// This event is generated by the parser when the parser's /// `parseOneCommentReference` method is called. void handleNoCommentReference() {} }
0