Use the version of the front_end package under //dart.
Change-Id: I33910190f4f897203c9d115af054e876e99fa4d3
diff --git a/importer/importer.py b/importer/importer.py
index 46df943..f14b145 100755
--- a/importer/importer.py
+++ b/importer/importer.py
@@ -26,6 +26,7 @@
LOCAL_PACKAGES = {
'analyzer': '//dart/pkg/analyzer',
'flutter': '//lib/flutter/packages/flutter',
+ 'front_end': '//dart/pkg/front_end',
'func' : '//dart/third_party/pkg/func',
'kernel': '//dart/pkg/kernel',
'linter': '//dart/third_party/pkg/linter',
diff --git a/pub/bazel_worker/e2e_test/bin/async_worker.dart b/pub/bazel_worker/e2e_test/bin/async_worker.dart
new file mode 100644
index 0000000..e2d0536
--- /dev/null
+++ b/pub/bazel_worker/e2e_test/bin/async_worker.dart
@@ -0,0 +1,11 @@
+// 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';
+
+import 'package:e2e_test/async_worker.dart';
+
+Future main() async {
+ await new ExampleAsyncWorker().run();
+}
diff --git a/pub/bazel_worker/e2e_test/bin/sync_worker.dart b/pub/bazel_worker/e2e_test/bin/sync_worker.dart
new file mode 100644
index 0000000..e87b1c8
--- /dev/null
+++ b/pub/bazel_worker/e2e_test/bin/sync_worker.dart
@@ -0,0 +1,9 @@
+// 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:e2e_test/sync_worker.dart';
+
+void main() {
+ new ExampleSyncWorker().run();
+}
diff --git a/pub/flutter_flux/BUILD.gn b/pub/flutter_flux/BUILD.gn
index 1dcbee0..bc073ad 100644
--- a/pub/flutter_flux/BUILD.gn
+++ b/pub/flutter_flux/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for flutter_flux-4.0.0
+# This file is generated by importer.py for flutter_flux-4.0.1
import("//build/dart/dart_package.gni")
diff --git a/pub/flutter_flux/example/README.md b/pub/flutter_flux/example/README.md
index a1ac1de..d40ee65 100644
--- a/pub/flutter_flux/example/README.md
+++ b/pub/flutter_flux/example/README.md
@@ -7,5 +7,4 @@
Then do this:
1. `cd chat_app`
-2. `pub get`
-3. `flutter run`
+2. `flutter run`
diff --git a/pub/flutter_flux/example/chat_app/lib/main.dart b/pub/flutter_flux/example/chat_app/lib/main.dart
index de90abc..bc76832 100644
--- a/pub/flutter_flux/example/chat_app/lib/main.dart
+++ b/pub/flutter_flux/example/chat_app/lib/main.dart
@@ -105,7 +105,7 @@
@override
Widget build(BuildContext context) {
- final ChatMessage message = config.message;
+ final ChatMessage message = widget.message;
return new SizeTransition(
sizeFactor: _animation,
axisAlignment: 0.0,
diff --git a/pub/flutter_flux/lib/src/store_watcher.dart b/pub/flutter_flux/lib/src/store_watcher.dart
index d6133da..0b85ae0 100644
--- a/pub/flutter_flux/lib/src/store_watcher.dart
+++ b/pub/flutter_flux/lib/src/store_watcher.dart
@@ -59,7 +59,7 @@
@override
void initState() {
- config.initStores(listenToStore);
+ widget.initStores(listenToStore);
super.initState();
}
@@ -78,7 +78,7 @@
@override
Widget build(BuildContext context) {
- return config.build(context, _storeTokens);
+ return widget.build(context, _storeTokens);
}
}
diff --git a/pub/flutter_flux/pubspec.yaml b/pub/flutter_flux/pubspec.yaml
index 3c5acba..b116a52 100644
--- a/pub/flutter_flux/pubspec.yaml
+++ b/pub/flutter_flux/pubspec.yaml
@@ -1,7 +1,7 @@
# Important: Use "flutter packages get", not "pub get".
name: flutter_flux
author: Flutter Authors <flutter-dev@googlegroups.com>
-version: 4.0.0
+version: 4.0.1
description: Flux library for Flutter, featuring unidirectional dataflow inspired by reflux and Facebook's flux architecture.
homepage: https://github.com/flutter/flutter_flux
dependencies:
@@ -10,7 +10,7 @@
sdk: flutter
dev_dependencies:
- quiver: ^0.21.4
+ quiver: ^0.24.0
rate_limit: ^0.1.0
test: ^0.12.13
flutter_test:
diff --git a/pub/front_end/.analysis_options b/pub/front_end/.analysis_options
deleted file mode 100644
index f0ac32f..0000000
--- a/pub/front_end/.analysis_options
+++ /dev/null
@@ -1,4 +0,0 @@
-analyzer:
- strong-mode: true
- language:
- enableSuperMixins: true
diff --git a/pub/front_end/.history/pubspec_20170131134120.yaml b/pub/front_end/.history/pubspec_20170131134120.yaml
deleted file mode 100644
index 5f15860..0000000
--- a/pub/front_end/.history/pubspec_20170131134120.yaml
+++ /dev/null
@@ -1,18 +0,0 @@
-name: front_end
-version: 0.1.0-alpha.1
-author: Dart Team <misc@dartlang.org>
-description: Front end for compilation of Dart code.
-homepage: https://github.com/dart-lang/sdk/tree/master/pkg/front_end
-environment:
- sdk: '>=1.12.0 <2.0.0'
-dependencies:
- analyzer: 0.30.0-alpha.1
- path: '^1.3.9'
- source_span: '^1.2.3'
-dev_dependencies:
- # TODO(sigmund): update to a version constraint once we roll the latest kernel
- # to the repo.
- kernel: {path: ../../pkg/kernel}
- package_config: '^1.0.0'
- test: ^0.12.0
- test_reflective_loader: ^0.1.0
diff --git a/pub/front_end/.vscode/settings.json b/pub/front_end/.vscode/settings.json
deleted file mode 100644
index 14a8645..0000000
--- a/pub/front_end/.vscode/settings.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "files.exclude": {}
-}
\ No newline at end of file
diff --git a/pub/front_end/BUILD.gn b/pub/front_end/BUILD.gn
deleted file mode 100644
index 1f24e3a..0000000
--- a/pub/front_end/BUILD.gn
+++ /dev/null
@@ -1,17 +0,0 @@
-# This file is generated by importer.py for front_end-0.1.0-alpha.1
-
-import("//build/dart/dart_package.gni")
-
-dart_package("front_end") {
- package_name = "front_end"
-
- source_dir = "lib"
-
- disable_analysis = true
-
- deps = [
- "//third_party/dart-pkg/pub/path",
- "//dart/pkg/analyzer",
- "//third_party/dart-pkg/pub/source_span",
- ]
-}
diff --git a/pub/front_end/LICENSE b/pub/front_end/LICENSE
deleted file mode 100644
index 82e9b52..0000000
--- a/pub/front_end/LICENSE
+++ /dev/null
@@ -1,26 +0,0 @@
-Copyright 2016, the Dart project authors. All rights reserved.
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials provided
- with the distribution.
- * Neither the name of Google Inc. nor the names of its
- contributors may be used to endorse or promote products derived
- from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pub/front_end/README.md b/pub/front_end/README.md
deleted file mode 100644
index 2b5ed61..0000000
--- a/pub/front_end/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Front end for Dart
-
-This package provides a low-level API for use by compiler back ends that wish to
-implement the Dart language. It is intended for eventual use by dev_compiler,
-dart2js, and the Dart VM. In addition, it will share implementation details
-with the analyzer package--this will be accomplished by having the analyzer
-package import (and re-export) parts of this package's private implementation.
-
-End-users should use the [dartanalyzer][analyzercli] command-line tool to
-analyze their Dart code.
-
-Integrators that want to write tools that analyze Dart code should use the
-[analyzer] package.
diff --git a/pub/front_end/lib/compilation_error.dart b/pub/front_end/lib/compilation_error.dart
deleted file mode 100644
index 5e30da1..0000000
--- a/pub/front_end/lib/compilation_error.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// Defines the API for the front end to communicate information about
-/// compilation errors to clients.
-library front_end.compilation_error;
-
-import 'package:source_span/source_span.dart' show SourceSpan;
-
-/// A single error that occurred during compilation, and information about where
-/// it occurred.
-///
-/// TODO(paulberry): add a reference to the analyzer error code.
-///
-/// Not intended to be implemented or extended by clients.
-abstract class CompilationError {
- /// A text description of how the user can fix the error. May be `null`.
- String get correction;
-
- /// The source span where the error occurred.
- SourceSpan get span;
-
- /// A text description of the compile error.
- String get message;
-}
diff --git a/pub/front_end/lib/compiler_options.dart b/pub/front_end/lib/compiler_options.dart
deleted file mode 100644
index 5c0cb11..0000000
--- a/pub/front_end/lib/compiler_options.dart
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library front_end.compiler_options;
-
-import 'compilation_error.dart';
-import 'file_system.dart';
-import 'physical_file_system.dart';
-
-/// Default error handler used by [CompielerOptions.onError].
-void defaultErrorHandler(CompilationError error) => throw error;
-
-/// Callback used to report errors encountered during compilation.
-typedef void ErrorHandler(CompilationError error);
-
-/// Front-end options relevant to compiler back ends.
-///
-/// Not intended to be implemented or extended by clients.
-class CompilerOptions {
- /// The URI of the root of the Dart SDK (typically a "file:" URI).
- ///
- /// If `null`, the SDK will be searched for using
- /// [Platform.resolvedExecutable] as a starting point.
- ///
- /// This option is mutually exclusive with [sdkSummary].
- Uri sdkRoot;
-
- /// Callback to which compilation errors should be delivered.
- ///
- /// By default, the first error will be reported by throwing an exception of
- /// type [CompilationError].
- ErrorHandler onError = defaultErrorHandler;
-
- /// URI of the ".packages" file (typically a "file:" URI).
- ///
- /// If `null`, the ".packages" file will be found via the standard
- /// package_config search algorithm.
- ///
- /// If the URI's path component is empty (e.g. `new Uri()`), no packages file
- /// will be used.
- Uri packagesFileUri;
-
- /// URIs of input summary files (excluding the SDK summary; typically these
- /// will be "file:" URIs). These files should all be linked summaries. They
- /// should also be closed, in the sense that any libraries they reference
- /// should also appear in [inputSummaries] or [sdkSummary].
- List<Uri> inputSummaries = [];
-
- /// URI of the SDK summary file (typically a "file:" URI).
- ///
- /// This should be a linked summary. If `null`, the SDK summary will be
- /// searched for at a default location within [sdkRoot].
- ///
- /// This option is mutually exclusive with [sdkRoot]. TODO(paulberry): if the
- /// VM does not contain a pickled copy of the SDK, we might need to change
- /// this.
- Uri sdkSummary;
-
- /// URI override map.
- ///
- /// This is a map from URIs that might appear in import/export/part statements
- /// to URIs that should be used to locate the corresponding files in the
- /// [fileSystem]. Any URI override listed in this map takes precedence over
- /// the URI resolution that would be implied by the packages file (see
- /// [packagesFileUri]) and/or [multiRoots].
- ///
- /// If a URI is not listed in this map, then the normal URI resolution
- /// algorithm will be used.
- ///
- /// TODO(paulberry): transition analyzer and dev_compiler to use the
- /// "multi-root:" mechanism, and then remove this.
- @deprecated
- Map<Uri, Uri> uriOverride = {};
-
- /// Multi-roots.
- ///
- /// Any Uri that resolves to "multi-root:///$rest" will be searched for
- /// at "$root/$rest", where "$root" is drawn from this list.
- ///
- /// Intended use: if the user has a Bazel workspace located at path
- /// "$workspace", this could be set to the file URIs corresponding to the
- /// paths for "$workspace", "$workspace/bazel-bin",
- /// and "$workspace/bazel-genfiles", effectively overlaying source and
- /// generated files.
- List<Uri> multiRoots = [];
-
- /// The declared variables for use by configurable imports and constant
- /// evaluation.
- Map<String, String> declaredVariables;
-
- /// The [FileSystem] which should be used by the front end to access files.
- ///
- /// All file system access performed by the front end goes through this
- /// mechanism, with one exception: if no value is specified for
- /// [packagesFileUri], the packages file is located using the actual physical
- /// file system. TODO(paulberry): fix this.
- FileSystem fileSystem = PhysicalFileSystem.instance;
-
- /// Whether to generate code for the SDK when compiling a whole-program.
- bool compileSdk = false;
-
- /// Whether a modular build compiles only the files listed explicitly or if it
- /// compiles dependencies as well.
- ///
- /// This option is intended only for modular APIs like `kernelForBuildUnit`.
- /// These APIs by default ensure that builds are hermetic, where all files
- /// that will be compiled are listed explicitly and all other dependencies
- /// are covered by summary files.
- ///
- /// When this option is true, these APIs will treat any dependency that is
- /// not described in a summary as if it was explictly listed as an input.
- bool chaseDependencies = false;
-
- /// Whether to intepret Dart sources in strong-mode.
- bool strongMode = true;
-
- // All options below are target-specific options.
- //
- // TODO(sigmund): revisit the right layout for these options. We might want to
- // split them out into a separate bag of options or provide factories for
- // common combinations of these options.
-
- /// Patch files to apply on the core libraries for a specific target platform.
- ///
- /// Keys on this map are expected to be `dart:*` URIs. The values can be
- /// either absolute or relative URIs. Absolute URIs are read directly, while
- /// relative URIs are resolved from the [sdkRoot].
- Map<Uri, List<Uri>> targetPatches = {};
-}
diff --git a/pub/front_end/lib/dependency_grapher.dart b/pub/front_end/lib/dependency_grapher.dart
deleted file mode 100644
index 6120490..0000000
--- a/pub/front_end/lib/dependency_grapher.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-
-import 'package:front_end/compiler_options.dart';
-import 'package:front_end/src/base/processed_options.dart';
-import 'package:front_end/src/dependency_grapher_impl.dart' as impl;
-
-/// Generates a representation of the dependency graph of a program.
-///
-/// Given the Uri of one or more files, this function follows `import`,
-/// `export`, and `part` declarations to discover a graph of all files involved
-/// in the program.
-Future<Graph> graphForProgram(List<Uri> sources, CompilerOptions options) {
- var processedOptions = new ProcessedOptions(options);
- return impl.graphForProgram(sources, processedOptions);
-}
-
-/// A representation of the dependency graph of a program.
-///
-/// Not intended to be extended, implemented, or mixed in by clients.
-class Graph {
- /// A list of all library cycles in the program, in topologically sorted order
- /// (each cycle only depends on libraries in the cycles that precede it).
- final topologicallySortedCycles = <LibraryCycleNode>[];
-}
-
-/// A representation of a single library cycle in the dependency graph of a
-/// program.
-///
-/// Not intended to be extended, implemented, or mixed in by clients.
-class LibraryCycleNode {
- /// A map of all the libraries in the cycle, keyed by the URI of their
- /// defining compilation unit.
- final libraries = <Uri, LibraryNode>{};
-}
-
-/// A representation of a single library in the dependency graph of a program.
-///
-/// Not intended to be extended, implemented, or mixed in by clients.
-class LibraryNode {
- /// The URI of this library's defining compilation unit.
- final Uri uri;
-
- /// A list of the URIs of all of this library's "part" files.
- final parts = <Uri>[];
-
- /// A list of all the other libraries this library directly depends on.
- final dependencies = <LibraryNode>[];
-
- LibraryNode(this.uri);
-}
diff --git a/pub/front_end/lib/file_system.dart b/pub/front_end/lib/file_system.dart
deleted file mode 100644
index 6e57c26..0000000
--- a/pub/front_end/lib/file_system.dart
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library front_end.file_system;
-
-import 'dart:async';
-
-import 'package:path/path.dart' as path;
-
-/// Abstract interface to file system operations.
-///
-/// All front end interaction with the file system goes through this interface;
-/// this makes it possible for clients to use the front end in a way that
-/// doesn't require file system access (e.g. to run unit tests, or to run
-/// inside a browser).
-///
-/// Not intended to be implemented or extended by clients.
-abstract class FileSystem {
- /// Returns a path context suitable for use with this [FileSystem].
- ///
- /// TODO(paulberry): try to eliminate all usages of this. Since the
- /// FileSystem API now uses URIs rather than paths, it should not be needed.
- path.Context get context;
-
- /// Returns a [FileSystemEntity] corresponding to the given [uri].
- ///
- /// Uses of `..` and `.` in the URI are normalized before returning.
- ///
- /// If the URI scheme is not supported by this file system, an [Error] will be
- /// thrown.
- ///
- /// Does not check whether a file or folder exists at the given location.
- FileSystemEntity entityForUri(Uri uri);
-}
-
-/// Abstract representation of a file system entity that may or may not exist.
-///
-/// Instances of this class have suitable implementations of equality tests and
-/// hashCode.
-///
-/// Not intended to be implemented or extended by clients.
-abstract class FileSystemEntity {
- /// Returns the absolute normalized URI represented by this file system
- /// entity.
- ///
- /// Note: this is not necessarily the same as the URI that was passed to
- /// [FileSystem.entityForUri], since the URI might have been normalized.
- Uri get uri;
-
- /// Attempts to access this file system entity as a file and read its contents
- /// as raw bytes.
- ///
- /// If an error occurs while attempting to read the file (e.g. because no such
- /// file exists, or the entity is a directory), the future is completed with
- /// an [Exception].
- Future<List<int>> readAsBytes();
-
- /// Attempts to access this file system entity as a file and read its contents
- /// as a string.
- ///
- /// The file is assumed to be UTF-8 encoded.
- ///
- /// If an error occurs while attempting to read the file (e.g. because no such
- /// file exists, the entity is a directory, or the file is not valid UTF-8),
- /// the future is completed with an [Exception].
- Future<String> readAsString();
-}
diff --git a/pub/front_end/lib/incremental_kernel_generator.dart b/pub/front_end/lib/incremental_kernel_generator.dart
deleted file mode 100644
index 3b3b429..0000000
--- a/pub/front_end/lib/incremental_kernel_generator.dart
+++ /dev/null
@@ -1,102 +0,0 @@
-// 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';
-
-import 'package:front_end/src/base/processed_options.dart';
-import 'package:front_end/src/incremental_kernel_generator_impl.dart';
-import 'package:kernel/kernel.dart';
-
-import 'compiler_options.dart';
-
-/// Represents the difference between "old" and "new" states of a program.
-///
-/// Not intended to be implemented or extended by clients.
-class DeltaProgram {
- /// The new state of the program.
- ///
- /// Libraries whose kernel representation is known to be unchanged since the
- /// last [DeltaProgram] are not included.
- final Map<Uri, Program> newState;
-
- DeltaProgram(this.newState);
-
- /// TODO(paulberry): add information about libraries that were removed.
-}
-
-/// Interface for generating an initial kernel representation of a program and
-/// keeping it up to date as incremental changes are made.
-///
-/// This class maintains an internal "previous program state"; each
-/// time [computeDelta] is called, it updates the previous program state and
-/// produces a representation of what has changed. When there are few changes,
-/// a call to [computeDelta] should be much faster than compiling the whole
-/// program from scratch.
-///
-/// This class also maintains a set of "valid sources", which is a (possibly
-/// empty) subset of the sources constituting the previous program state. Files
-/// in this set are assumed to be unchanged since the last call to
-/// [computeDelta].
-///
-/// Behavior is undefined if the client does not obey the following concurrency
-/// restrictions:
-/// - no two invocations of [computeDelta] may be outstanding at any given time.
-/// - neither [invalidate] nor [invalidateAll] may be called while an invocation
-/// of [computeDelta] is outstanding.
-///
-/// Not intended to be implemented or extended by clients.
-abstract class IncrementalKernelGenerator {
- /// Creates an [IncrementalKernelGenerator] which is prepared to generate
- /// kernel representations of the program whose main library is in the given
- /// [source].
- ///
- /// No file system access is performed by this constructor; the initial
- /// "previous program state" is an empty program containing no code, and the
- /// initial set of valid sources is empty. To obtain a kernel representation
- /// of the program, call [computeDelta].
- factory IncrementalKernelGenerator(Uri source, CompilerOptions options) =>
- new IncrementalKernelGeneratorImpl(source, new ProcessedOptions(options));
-
- /// Generates a kernel representation of the changes to the program, assuming
- /// that all valid sources are unchanged since the last call to
- /// [computeDelta].
- ///
- /// Source files in the set of valid sources are guaranteed not to be re-read
- /// from disk; they are assumed to be unchanged regardless of the state of the
- /// filesystem.
- ///
- /// If [watch] is not `null`, then when a source file is first used
- /// by [computeDelta], [watch] is called with the Uri of that source
- /// file and `used` == `true` indicating that the source file is being
- /// used when compiling the program. The content of the file is not read
- /// until the Future returned by [watch] completes. If during a subsequent
- /// call to [computeDelta], a source file that was being used is no longer
- /// used, then [watch] is called with the Uri of that source file and
- /// `used` == `false` indicating that the source file is no longer needed.
- /// Multiple invocations of [watch] may be running concurrently.
- ///
- /// If the future completes successfully, the previous file state is updated
- /// and the set of valid sources is set to the set of all sources in the
- /// program.
- ///
- /// If the future completes with an error (due to errors in the compiled
- /// source code), the caller may consider the previous file state and the set
- /// of valid sources to be unchanged; this means that once the user fixes the
- /// errors, it is safe to call [computeDelta] again.
- Future<DeltaProgram> computeDelta({Future<Null> watch(Uri uri, bool used)});
-
- /// Remove any source file(s) associated with the given file path from the set
- /// of valid sources. This guarantees that those files will be re-read on the
- /// next call to [computeDelta]).
- void invalidate(String path);
-
- /// Remove all source files from the set of valid sources. This guarantees
- /// that all files will be re-read on the next call to [computeDelta].
- ///
- /// Note that this does not erase the previous program state; the next time
- /// [computeDelta] is called, if parts of the program are discovered to be
- /// unchanged, parts of the previous program state will still be re-used to
- /// speed up compilation.
- void invalidateAll();
-}
diff --git a/pub/front_end/lib/incremental_resolved_ast_generator.dart b/pub/front_end/lib/incremental_resolved_ast_generator.dart
deleted file mode 100644
index daeb8c1..0000000
--- a/pub/front_end/lib/incremental_resolved_ast_generator.dart
+++ /dev/null
@@ -1,98 +0,0 @@
-// 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';
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:front_end/src/base/processed_options.dart';
-import 'package:front_end/src/incremental_resolved_ast_generator_impl.dart';
-
-import 'compiler_options.dart';
-
-/// Represents the difference between "old" and "new" states of a program.
-///
-/// Not intended to be implemented or extended by clients.
-class DeltaLibraries {
- /// The new state of the program, as a two-layer map.
- ///
- /// The outer map key is the library URI. The inner map key is the
- /// compilation unit (part) URI. The map values are the resolved compilation
- /// units.
- ///
- /// Libraries whose resolved AST is known to be unchanged since the last
- /// [DeltaLibraries] are not included.
- final Map<Uri, Map<Uri, CompilationUnit>> newState;
-
- DeltaLibraries(this.newState);
-
- /// TODO(paulberry): add information about libraries that were removed.
-}
-
-/// Interface for generating an initial resolved representation of a program and
-/// keeping it up to date as incremental changes are made.
-///
-/// This class maintains an internal "previous program state"; each
-/// time [computeDelta] is called, it updates the previous program state and
-/// produces a representation of what has changed. When there are few changes,
-/// a call to [computeDelta] should be much faster than compiling the whole
-/// program from scratch.
-///
-/// This class also maintains a set of "valid sources", which is a (possibly
-/// empty) subset of the sources constituting the previous program state. Files
-/// in this set are assumed to be unchanged since the last call to
-/// [computeDelta].
-///
-/// Behavior is undefined if the client does not obey the following concurrency
-/// restrictions:
-/// - no two invocations of [computeDelta] may be outstanding at any given time.
-/// - neither [invalidate] nor [invalidateAll] may be called while an invocation
-/// of [computeDelta] is outstanding.
-///
-/// Not intended to be implemented or extended by clients.
-abstract class IncrementalResolvedAstGenerator {
- /// Creates an [IncrementalResolvedAstGenerator] which is prepared to generate
- /// resolved ASTs for the program whose main library is in the given
- /// [source].
- ///
- /// No file system access is performed by this constructor; the initial
- /// "previous program state" is an empty program containing no code, and the
- /// initial set of valid sources is empty. To obtain a resolved AST
- /// representation of the program, call [computeDelta].
- factory IncrementalResolvedAstGenerator(
- Uri source, CompilerOptions options) =>
- new IncrementalResolvedAstGeneratorImpl(
- source, new ProcessedOptions(options));
-
- /// Generates a resolved AST representation of the changes to the program,
- /// assuming that all valid sources are unchanged since the last call to
- /// [computeDelta].
- ///
- /// Source files in the set of valid sources are guaranteed not to be re-read
- /// from disk; they are assumed to be unchanged regardless of the state of the
- /// filesystem.
- ///
- /// If the future completes successfully, the previous file state is updated
- /// and the set of valid sources is set to the set of all sources in the
- /// program.
- ///
- /// If the future completes with an error (due to errors in the compiled
- /// source code), the caller may consider the previous file state and the set
- /// of valid sources to be unchanged; this means that once the user fixes the
- /// errors, it is safe to call [computeDelta] again.
- Future<DeltaLibraries> computeDelta();
-
- /// Remove any source file(s) associated with the given file path from the set
- /// of valid sources. This guarantees that those files will be re-read on the
- /// next call to [computeDelta]).
- void invalidate(String path);
-
- /// Remove all source files from the set of valid sources. This guarantees
- /// that all files will be re-read on the next call to [computeDelta].
- ///
- /// Note that this does not erase the previous program state; the next time
- /// [computeDelta] is called, if parts of the program are discovered to be
- /// unchanged, parts of the previous program state will still be re-used to
- /// speed up compilation.
- void invalidateAll();
-}
diff --git a/pub/front_end/lib/kernel_generator.dart b/pub/front_end/lib/kernel_generator.dart
deleted file mode 100644
index 0ae2fb3..0000000
--- a/pub/front_end/lib/kernel_generator.dart
+++ /dev/null
@@ -1,198 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// Defines the front-end API for converting source code to Dart Kernel objects.
-library front_end.kernel_generator;
-
-import 'compilation_error.dart';
-import 'compiler_options.dart';
-import 'dart:async';
-
-import 'package:analyzer/src/generated/source.dart' show SourceKind;
-import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl;
-import 'package:analyzer/src/summary/package_bundle_reader.dart'
- show InSummarySource;
-// TODO(sigmund): move loader logic under front_end/lib/src/kernel/
-import 'package:kernel/analyzer/loader.dart';
-import 'package:kernel/kernel.dart';
-import 'package:source_span/source_span.dart' show SourceSpan;
-
-/// Generates a kernel representation of the program whose main library is in
-/// the given [source].
-///
-/// Intended for whole program (non-modular) compilation.
-///
-/// Given the Uri of a file containing a program's `main` method, this function
-/// follows `import`, `export`, and `part` declarations to discover the whole
-/// program, and converts the result to Dart Kernel format.
-///
-/// If `compileSdk` in [options] is true, the generated program will include
-/// code for the SDK.
-///
-/// If summaries are provided in [options], they may be used to speed up
-/// analysis. If in addition `compileSdk` is false, this will speed up
-/// compilation, as no source of the sdk will be generated. Note however, that
-/// summaries for application code can also speed up analysis, but they will not
-/// take the place of Dart source code (since the Dart source code is still
-/// needed to access the contents of method bodies).
-Future<Program> kernelForProgram(Uri source, CompilerOptions options) async {
- var loader = await _createLoader(options, entry: source);
- // TODO(sigmund): delete this. At this time we have no need to explicitly list
- // VM libraries, since they are normally found by chasing dependencies.
- // `dart:_builtin` is an exception because it is used by the kernel
- // transformers to inform the VM about where the main entrypoint is. This is
- // expected to change, and we should be able to remove these lines at that
- // point. We check for the presense of `dart:developer` in the targetPatches
- // to ensure we only load this library while running on the VM.
- if (options.compileSdk &&
- options.targetPatches.containsKey(Uri.parse('dart:developer'))) {
- loader.loadLibrary(Uri.parse('dart:_builtin'));
- }
- // TODO(sigmund): merge what we have in loadEverything and the logic below in
- // kernelForBuildUnit so there is a single place where we crawl for
- // dependencies.
- Program program = loader.loadProgram(source, compileSdk: options.compileSdk);
- _reportErrors(loader.errors, options.onError);
- return program;
-}
-
-/// Generates a kernel representation for a build unit.
-///
-/// Intended for modular compilation.
-///
-/// The build unit by default contains only the source files in [sources]
-/// (including library and part files), but if
-/// [CompilerOptions.chaseDependencies] is true, it may include some additional
-/// source files. All of the library files are transformed into Dart Kernel
-/// Library objects.
-///
-/// By default, the compilation process is hermetic, meaning that the only files
-/// which will be read are those listed in [sources],
-/// [CompilerOptions.inputSummaries], and [CompilerOptions.sdkSummary]. If a
-/// source file attempts to refer to a file which is not obtainable from these
-/// URIs, that will result in an error, even if the file exists on the
-/// filesystem.
-///
-/// When [CompilerOptions.chaseDependencies] is true, this default behavior
-/// changes, and any dependency of [sources] that is not listed in
-/// [CompilerOptions.inputSummaries] and [CompilerOptions.sdkSummary] is treated
-/// as an additional source file for the build unit.
-///
-/// Any `part` declarations found in [sources] must refer to part files which
-/// are also listed in the build unit sources, otherwise an error results. (It
-/// is not permitted to refer to a part file declared in another build unit).
-///
-/// The return value is a [Program] object with no main method set.
-/// TODO(paulberry): would it be better to define a data type in kernel to
-/// represent a bundle of all the libraries in a given build unit?
-///
-/// TODO(paulberry): does additional information need to be output to allow the
-/// caller to match up referenced elements to the summary files they were
-/// obtained from?
-Future<Program> kernelForBuildUnit(
- List<Uri> sources, CompilerOptions options) async {
- var repository = new Repository();
- var loader = await _createLoader(options, repository: repository);
- var context = loader.context;
-
- // Process every library in the build unit.
- for (var uri in sources) {
- var source = context.sourceFactory.forUri2(uri);
- // We ignore part files, those are handled by their enclosing library.
- if (context.computeKindOf(source) == SourceKind.PART) {
- // TODO(sigmund): record it and ensure that this part is within a provided
- // library.
- continue;
- }
- loader.loadLibrary(uri);
- }
-
- // Check whether all dependencies were included in [sources].
- // TODO(sigmund): we should look for dependencies using import, export, and
- // part directives intead of relying on the dartk-loader. In particular, if a
- // library is imported but not used, the logic below will not detect it.
- for (int i = 0; i < repository.libraries.length; ++i) {
- // Note: we don't use a for-in loop because repository.libraries grows as
- // the loader processes libraries.
- var lib = repository.libraries[i];
- var source = context.sourceFactory.forUri2(lib.importUri);
- if (source is InSummarySource) continue;
- if (options.chaseDependencies) {
- loader.ensureLibraryIsLoaded(lib);
- } else if (lib.isExternal) {
- // Default behavior: the build should be hermetic and all dependencies
- // should be listed.
- options.onError(new _DartkError('hermetic build error: '
- 'no source or summary was given for ${lib.importUri}'));
- }
- }
-
- Program program = new Program(repository.libraries);
- _reportErrors(loader.errors, options.onError);
- return program;
-}
-
-/// Create a [DartLoader] using the provided [options].
-///
-/// If [options] contain no configuration to resolve `.packages`, the [entry]
-/// file will be used to search for a `.packages` file.
-Future<DartLoader> _createLoader(CompilerOptions options,
- {Repository repository, Uri entry}) async {
- var kernelOptions = _convertOptions(options);
- var packages = await createPackages(
- _uriToPath(options.packagesFileUri, options),
- discoveryPath: entry?.path);
- var loader = new DartLoader(
- repository ?? new Repository(), kernelOptions, packages);
- var patchPaths = <String, List<String>>{};
-
- // TODO(sigmund,paulberry): use ProcessedOptions so that we can resolve the
- // URIs correctly even if sdkRoot is inferred and not specified explicitly.
- String resolve(Uri patch) =>
- options.fileSystem.context.fromUri(options.sdkRoot.resolveUri(patch));
-
- options.targetPatches.forEach((uri, patches) {
- patchPaths['$uri'] = patches.map(resolve).toList();
- });
- AnalysisOptionsImpl analysisOptions = loader.context.analysisOptions;
- analysisOptions.patchPaths = patchPaths;
- return loader;
-}
-
-DartOptions _convertOptions(CompilerOptions options) {
- return new DartOptions(
- strongMode: options.strongMode,
- sdk: _uriToPath(options.sdkRoot, options),
- // TODO(sigmund): make it possible to use summaries and still compile the
- // sdk sources.
- sdkSummary:
- options.compileSdk ? null : _uriToPath(options.sdkSummary, options),
- packagePath: _uriToPath(options.packagesFileUri, options),
- customUriMappings: options.uriOverride,
- declaredVariables: options.declaredVariables);
-}
-
-void _reportErrors(List errors, ErrorHandler onError) {
- if (onError == null) return;
- for (var error in errors) {
- onError(new _DartkError(error));
- }
-}
-
-String _uriToPath(Uri uri, CompilerOptions options) {
- if (uri == null) return null;
- if (uri.scheme != 'file') {
- throw new StateError('Only file URIs are supported');
- }
- return options.fileSystem.context.fromUri(uri);
-}
-
-// TODO(sigmund): delete this class. Dartk should not format errors itself, we
-// should just pass them along.
-class _DartkError implements CompilationError {
- String get correction => null;
- SourceSpan get span => null;
- final String message;
- _DartkError(this.message);
-}
diff --git a/pub/front_end/lib/memory_file_system.dart b/pub/front_end/lib/memory_file_system.dart
deleted file mode 100644
index e7382ad..0000000
--- a/pub/front_end/lib/memory_file_system.dart
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library front_end.memory_file_system;
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:typed_data';
-
-import 'package:path/path.dart' as p;
-
-import 'file_system.dart';
-
-/// Concrete implementation of [FileSystem] which performs its operations on an
-/// in-memory virtual file system.
-///
-/// Not intended to be implemented or extended by clients.
-class MemoryFileSystem implements FileSystem {
- @override
- final p.Context context;
-
- final Map<Uri, Uint8List> _files = {};
-
- /// The "current directory" in the in-memory virtual file system.
- ///
- /// This is used to convert relative URIs to absolute URIs.
- ///
- /// Always ends in a trailing '/'.
- Uri currentDirectory;
-
- MemoryFileSystem(this.context, Uri currentDirectory)
- : currentDirectory = _addTrailingSlash(currentDirectory);
-
- @override
- MemoryFileSystemEntity entityForUri(Uri uri) {
- return new MemoryFileSystemEntity._(
- this, currentDirectory.resolveUri(uri).normalizePath());
- }
-
- static Uri _addTrailingSlash(Uri uri) {
- if (!uri.path.endsWith('/')) {
- uri = uri.replace(path: uri.path + '/');
- }
- return uri;
- }
-}
-
-/// Concrete implementation of [FileSystemEntity] for use by
-/// [MemoryFileSystem].
-class MemoryFileSystemEntity implements FileSystemEntity {
- final MemoryFileSystem _fileSystem;
-
- @override
- final Uri uri;
-
- MemoryFileSystemEntity._(this._fileSystem, this.uri);
-
- @override
- int get hashCode => uri.hashCode;
-
- @override
- bool operator ==(Object other) =>
- other is MemoryFileSystemEntity &&
- other.uri == uri &&
- identical(other._fileSystem, _fileSystem);
-
- @override
- Future<List<int>> readAsBytes() async {
- List<int> contents = _fileSystem._files[uri];
- if (contents != null) {
- return contents.toList();
- }
- throw new Exception('File does not exist');
- }
-
- @override
- Future<String> readAsString() async {
- List<int> contents = await readAsBytes();
- return UTF8.decode(contents);
- }
-
- /// Writes the given raw bytes to this file system entity.
- ///
- /// If no file exists, one is created. If a file exists already, it is
- /// overwritten.
- void writeAsBytesSync(List<int> bytes) {
- _fileSystem._files[uri] = new Uint8List.fromList(bytes);
- }
-
- /// Writes the given string to this file system entity.
- ///
- /// The string is encoded as UTF-8.
- ///
- /// If no file exists, one is created. If a file exists already, it is
- /// overwritten.
- void writeAsStringSync(String s) {
- // Note: the return type of UTF8.encode is List<int>, but in practice it
- // always returns Uint8List. We rely on that for efficiency, so that we
- // don't have to make an extra copy.
- _fileSystem._files[uri] = UTF8.encode(s) as Uint8List;
- }
-}
diff --git a/pub/front_end/lib/physical_file_system.dart b/pub/front_end/lib/physical_file_system.dart
deleted file mode 100644
index f90abc9..0000000
--- a/pub/front_end/lib/physical_file_system.dart
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library front_end.physical_file_system;
-
-import 'dart:async';
-import 'dart:io' as io;
-
-import 'package:path/path.dart' as p;
-
-import 'file_system.dart';
-
-/// Concrete implementation of [FileSystem] which performs its operations using
-/// I/O.
-///
-/// Not intended to be implemented or extended by clients.
-class PhysicalFileSystem implements FileSystem {
- static final PhysicalFileSystem instance = new PhysicalFileSystem._();
-
- PhysicalFileSystem._();
-
- @override
- p.Context get context => p.context;
-
- @override
- FileSystemEntity entityForUri(Uri uri) {
- if (uri.scheme != 'file' && uri.scheme != '') {
- throw new ArgumentError('File URI expected');
- }
- return new _PhysicalFileSystemEntity(Uri.base.resolveUri(uri));
- }
-}
-
-/// Concrete implementation of [FileSystemEntity] for use by
-/// [PhysicalFileSystem].
-class _PhysicalFileSystemEntity implements FileSystemEntity {
- @override
- final Uri uri;
-
- _PhysicalFileSystemEntity(this.uri);
-
- @override
- int get hashCode => uri.hashCode;
-
- @override
- bool operator ==(Object other) =>
- other is _PhysicalFileSystemEntity && other.uri == uri;
-
- @override
- Future<List<int>> readAsBytes() => new io.File.fromUri(uri).readAsBytes();
-
- @override
- Future<String> readAsString() => new io.File.fromUri(uri).readAsString();
-}
diff --git a/pub/front_end/lib/resolved_ast_generator.dart b/pub/front_end/lib/resolved_ast_generator.dart
deleted file mode 100644
index 4b37d38..0000000
--- a/pub/front_end/lib/resolved_ast_generator.dart
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// Defines a front-end API for converting source code to resolved ASTs.
-///
-/// Note: this entire library is deprecated. It is provided as a migration path
-/// until dev_compiler supports Dart Kernel. Once dev_compiler has been
-/// converted to use Dart Kernel, this functionality will be removed.
-@deprecated
-library front_end.resolved_ast_generator;
-
-import 'dart:async';
-import 'compiler_options.dart';
-import 'package:analyzer/dart/ast/ast.dart' show CompilationUnit;
-import 'package:analyzer/dart/element/element.dart' show LibraryElement;
-
-/// Processes the build unit whose source files are in [sources].
-///
-/// Intended for modular compilation.
-///
-/// [sources] should be the complete set of source files for a build unit
-/// (including both library and part files). All of the library files are
-/// compiled to resolved ASTs.
-///
-/// The compilation process is hermetic, meaning that the only files which will
-/// be read are those listed in [sources], [CompilerOptions.inputSummaries], and
-/// [CompilerOptions.sdkSummary]. If a source file attempts to refer to a file
-/// which is not obtainable from these paths, that will result in an error, even
-/// if the file exists on the filesystem.
-///
-/// Any `part` declarations found in [sources] must refer to part files which
-/// are also listed in [sources], otherwise an error results. (It is not
-/// permitted to refer to a part file declared in another build unit).
-@deprecated
-Future<ResolvedAsts> resolvedAstsFor(
- List<Uri> sources, CompilerOptions options) =>
- throw new UnimplementedError();
-
-/// Representation of the resolved ASTs of a build unit.
-///
-/// Not intended to be implemented or extended by clients.
-@deprecated
-abstract class ResolvedAsts {
- /// The resolved ASTs of the build unit's source libraries.
- ///
- /// There is one sub-list per source library; each sub-list consists of the
- /// resolved AST for the library's defining compilation unit, followed by the
- /// resolved ASTs for any of the library's part files.
- List<List<CompilationUnit>> get compilationUnits;
-
- /// Given a [LibraryElement] referred to by [compilationUnits], determine the
- /// path to the summary that the library originated from. If the
- /// [LibraryElement] did not originate from a summary (i.e. because it
- /// originated from one of the source files of *this* build unit), return
- /// `null`.
- ///
- /// This can be used by the client to determine which build unit any
- /// referenced element originated from.
- String getOriginatingSummary(LibraryElement element);
-}
diff --git a/pub/front_end/lib/src/async_dependency_walker.dart b/pub/front_end/lib/src/async_dependency_walker.dart
deleted file mode 100644
index b0c6535..0000000
--- a/pub/front_end/lib/src/async_dependency_walker.dart
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-
-/**
- * An instance of [AsyncDependencyWalker] contains the core algorithms for
- * walking a dependency graph and evaluating nodes in a safe order.
- *
- * Computation of dependencies and evaluation of nodes may be asynchronous.
- */
-abstract class AsyncDependencyWalker<NodeType extends Node<NodeType>> {
- /**
- * Called by [walk] to evaluate a single non-cyclical node, after
- * all that node's dependencies have been evaluated.
- */
- Future<Null> evaluate(NodeType v);
-
- /**
- * Called by [walk] to evaluate a strongly connected component
- * containing one or more nodes. All dependencies of the strongly
- * connected component have been evaluated.
- */
- Future<Null> evaluateScc(List<NodeType> scc);
-
- /**
- * Walk the dependency graph starting at [startingPoint], finding
- * strongly connected components and evaluating them in a safe order
- * by calling [evaluate] and [evaluateScc].
- *
- * This is an implementation of Tarjan's strongly connected
- * components algorithm
- * (https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm).
- *
- * TODO(paulberry): Consider switching to an algorithm that allows
- * dependencies to be computed in parallel, and nodes to be evaluated in
- * parallel.
- */
- Future<Null> walk(NodeType startingPoint) async {
- // TODO(paulberry): consider rewriting in a non-recursive way so
- // that long dependency chains don't cause stack overflow.
-
- // TODO(paulberry): in the event that an exception occurs during
- // the walk, restore the state of the [Node] data structures so
- // that further evaluation will be safe.
-
- // The index which will be assigned to the next node that is
- // freshly visited.
- int index = 1;
-
- // Stack of nodes which have been seen so far and whose strongly
- // connected component is still being determined. Nodes are only
- // popped off the stack when they are evaluated, so sometimes the
- // stack contains nodes that were visited after the current node.
- List<NodeType> stack = <NodeType>[];
-
- Future strongConnect(NodeType node) async {
- bool hasTrivialCycle = false;
-
- // Assign the current node an index and add it to the stack. We
- // haven't seen any of its dependencies yet, so set its lowLink
- // to its index, indicating that so far it is the only node in
- // its strongly connected component.
- node._index = node._lowLink = index++;
- stack.add(node);
-
- // Consider the node's dependencies one at a time.
- var dependencies =
- node._dependencies ??= await node.computeDependencies();
- for (NodeType dependency in dependencies) {
- // If the dependency has already been evaluated, it can't be
- // part of this node's strongly connected component, so we can
- // skip it.
- if (dependency._isEvaluated) {
- continue;
- }
- if (identical(node, dependency)) {
- // If a node includes itself as a dependency, there is no need to
- // explore the dependency further.
- hasTrivialCycle = true;
- } else if (dependency._index == 0) {
- // The dependency hasn't been seen yet, so recurse on it.
- await strongConnect(dependency);
- // If the dependency's lowLink refers to a node that was
- // visited before the current node, that means that the
- // current node, the dependency, and the node referred to by
- // the dependency's lowLink are all part of the same
- // strongly connected component, so we need to update the
- // current node's lowLink accordingly.
- if (dependency._lowLink < node._lowLink) {
- node._lowLink = dependency._lowLink;
- }
- } else {
- // The dependency has already been seen, so it is part of
- // the current node's strongly connected component. If it
- // was visited earlier than the current node's lowLink, then
- // it is a new addition to the current node's strongly
- // connected component, so we need to update the current
- // node's lowLink accordingly.
- if (dependency._index < node._lowLink) {
- node._lowLink = dependency._index;
- }
- }
- }
-
- // If the current node's lowLink is the same as its index, then
- // we have finished visiting a strongly connected component, so
- // pop the stack and evaluate it before moving on.
- if (node._lowLink == node._index) {
- // The strongly connected component has only one node. If there is a
- // cycle, it's a trivial one.
- if (identical(stack.last, node)) {
- stack.removeLast();
- node._isEvaluated = true;
- if (hasTrivialCycle) {
- await evaluateScc(<NodeType>[node]);
- } else {
- await evaluate(node);
- }
- } else {
- // There are multiple nodes in the strongly connected
- // component.
- List<NodeType> scc = <NodeType>[];
- while (true) {
- NodeType otherNode = stack.removeLast();
- scc.add(otherNode);
- otherNode._isEvaluated = true;
- if (identical(otherNode, node)) {
- break;
- }
- }
- await evaluateScc(scc);
- }
- }
- }
-
- // Kick off the algorithm starting with the starting point.
- await strongConnect(startingPoint);
- }
-}
-
-/**
- * Instances of [Node] represent nodes in a dependency graph. The
- * type parameter, [NodeType], is the derived type (this affords some
- * extra type safety by making it difficult to accidentally construct
- * bridges between unrelated dependency graphs).
- */
-abstract class Node<NodeType> {
- /**
- * Index used by Tarjan's strongly connected components algorithm.
- * Zero means the node has not been visited yet; a nonzero value
- * counts the order in which the node was visited.
- */
- int _index = 0;
-
- /**
- * Low link used by Tarjan's strongly connected components
- * algorithm. This represents the smallest [_index] of all the nodes
- * in the strongly connected component to which this node belongs.
- */
- int _lowLink = 0;
-
- List<NodeType> _dependencies;
-
- bool _isEvaluated = false;
-
- /**
- * Compute the dependencies of this node.
- */
- Future<List<NodeType>> computeDependencies();
-}
diff --git a/pub/front_end/lib/src/base/analysis_target.dart b/pub/front_end/lib/src/base/analysis_target.dart
deleted file mode 100644
index ab50efd..0000000
--- a/pub/front_end/lib/src/base/analysis_target.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:front_end/src/base/source.dart';
-
-/**
- * An object with which an analysis result can be associated.
- *
- * Clients may implement this class when creating new kinds of targets.
- * Instances of this type are used in hashed data structures, so subtypes are
- * required to correctly implement [==] and [hashCode].
- */
-abstract class AnalysisTarget {
- /**
- * If this target is associated with a library, return the source of the
- * library's defining compilation unit; otherwise return `null`.
- */
- Source get librarySource;
-
- /**
- * Return the source associated with this target, or `null` if this target is
- * not associated with a source.
- */
- Source get source;
-}
diff --git a/pub/front_end/lib/src/base/errors.dart b/pub/front_end/lib/src/base/errors.dart
deleted file mode 100644
index d39953f..0000000
--- a/pub/front_end/lib/src/base/errors.dart
+++ /dev/null
@@ -1,282 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/**
- * An error code associated with an [AnalysisError].
- *
- * Generally, we want to provide messages that consist of three sentences. From
- * the user's perspective these sentences should explain:
- *
- * 1. what is wrong,
- * 2. why is it wrong, and
- * 3. how do I fix it.
- *
- * However, we combine the first two in the [message] and the last in the
- * [correction].
- *
- * When composing messages (including correction messages) keep the following
- * guidelines in mind.
- *
- * 1. The message should be a complete sentence starting with an uppercase
- * letter, and ending with a period.
- *
- * 2. Reserved words and embedded identifiers should be in single quotes, so
- * prefer double quotes for the complete message. For example,
- * ```
- * "The class '{0}' can't use 'super'."
- * ```
- * Notice that the word 'class' in the preceding message is not quoted as it
- * refers to the concept 'class', not the reserved word. On the other hand,
- * 'super' refers to the reserved word. Do not quote 'null' and numeric literals.
- *
- * 3. Do not try to compose messages, as it can make translating them hard.
- *
- * 4. Try to keep the error messages short, but informative.
- *
- * 5. Use simple words and terminology, assume the reader of the message doesn't
- * have an advanced degree in math, and that English is not the reader's native
- * language. Do not assume any formal computer science training. For example, do
- * not use Latin abbreviations (prefer "that is" over "i.e.", and "for example"
- * over "e.g."). Also avoid phrases such as "if and only if" and "iff"; that
- * level of precision is unnecessary.
- *
- * 6. Prefer contractions when they are in common use, for example, prefer
- * "can't" over "cannot". Using "cannot", "must not", "shall not", etc. is
- * off-putting to people new to programming.
- *
- * 7. Use common terminology, preferably from the Dart Language Specification.
- * This increases the user's chance of finding a good explanation on the web.
- *
- * 8. Do not try to be cute or funny. It is extremely frustrating to work on a
- * product that crashes with a "tongue-in-cheek" message, especially if you did
- * not want to use this product to begin with.
- *
- * 9. Do not lie, that is, do not write error messages containing phrases like
- * "can't happen". If the user ever saw this message, it would be a lie. Prefer
- * messages like: "Internal error: This function should not be called when 'x'
- * is null.".
- *
- * 10. Prefer to not use the imperative tone. That is, the message should not
- * sound accusing or like it is ordering the user around. The computer should
- * describe the problem, not criticize the user for violating the specification.
- */
-abstract class ErrorCode {
- /**
- * The name of the error code.
- */
- final String name;
-
- /**
- * The template used to create the message to be displayed for this error. The
- * message should indicate what is wrong and why it is wrong.
- */
- final String message;
-
- /**
- * The template used to create the correction to be displayed for this error,
- * or `null` if there is no correction information for this error. The
- * correction should indicate how the user can fix the error.
- */
- final String correction;
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const ErrorCode(this.name, this.message, [this.correction]);
-
- /**
- * The severity of the error.
- */
- ErrorSeverity get errorSeverity;
-
- /**
- * The type of the error.
- */
- ErrorType get type;
-
- /**
- * The unique name of this error code.
- */
- String get uniqueName => "$runtimeType.$name";
-
- @override
- String toString() => uniqueName;
-}
-
-/**
- * The severity of an [ErrorCode].
- */
-class ErrorSeverity implements Comparable<ErrorSeverity> {
- /**
- * The severity representing a non-error. This is never used for any error
- * code, but is useful for clients.
- */
- static const ErrorSeverity NONE = const ErrorSeverity('NONE', 0, " ", "none");
-
- /**
- * The severity representing an informational level analysis issue.
- */
- static const ErrorSeverity INFO = const ErrorSeverity('INFO', 1, "I", "info");
-
- /**
- * The severity representing a warning. Warnings can become errors if the `-Werror` command
- * line flag is specified.
- */
- static const ErrorSeverity WARNING =
- const ErrorSeverity('WARNING', 2, "W", "warning");
-
- /**
- * The severity representing an error.
- */
- static const ErrorSeverity ERROR =
- const ErrorSeverity('ERROR', 3, "E", "error");
-
- static const List<ErrorSeverity> values = const [NONE, INFO, WARNING, ERROR];
-
- /**
- * The name of this error code.
- */
- final String name;
-
- /**
- * The ordinal value of the error code.
- */
- final int ordinal;
-
- /**
- * The name of the severity used when producing machine output.
- */
- final String machineCode;
-
- /**
- * The name of the severity used when producing readable output.
- */
- final String displayName;
-
- /**
- * Initialize a newly created severity with the given names.
- */
- const ErrorSeverity(
- this.name, this.ordinal, this.machineCode, this.displayName);
-
- @override
- int get hashCode => ordinal;
-
- @override
- int compareTo(ErrorSeverity other) => ordinal - other.ordinal;
-
- /**
- * Return the severity constant that represents the greatest severity.
- */
- ErrorSeverity max(ErrorSeverity severity) =>
- this.ordinal >= severity.ordinal ? this : severity;
-
- @override
- String toString() => name;
-}
-
-/**
- * The type of an [ErrorCode].
- */
-class ErrorType implements Comparable<ErrorType> {
- /**
- * Task (todo) comments in user code.
- */
- static const ErrorType TODO = const ErrorType('TODO', 0, ErrorSeverity.INFO);
-
- /**
- * Extra analysis run over the code to follow best practices, which are not in
- * the Dart Language Specification.
- */
- static const ErrorType HINT = const ErrorType('HINT', 1, ErrorSeverity.INFO);
-
- /**
- * Compile-time errors are errors that preclude execution. A compile time
- * error must be reported by a Dart compiler before the erroneous code is
- * executed.
- */
- static const ErrorType COMPILE_TIME_ERROR =
- const ErrorType('COMPILE_TIME_ERROR', 2, ErrorSeverity.ERROR);
-
- /**
- * Checked mode compile-time errors are errors that preclude execution in
- * checked mode.
- */
- static const ErrorType CHECKED_MODE_COMPILE_TIME_ERROR = const ErrorType(
- 'CHECKED_MODE_COMPILE_TIME_ERROR', 3, ErrorSeverity.ERROR);
-
- /**
- * Static warnings are those warnings reported by the static checker. They
- * have no effect on execution. Static warnings must be provided by Dart
- * compilers used during development.
- */
- static const ErrorType STATIC_WARNING =
- const ErrorType('STATIC_WARNING', 4, ErrorSeverity.WARNING);
-
- /**
- * Many, but not all, static warnings relate to types, in which case they are
- * known as static type warnings.
- */
- static const ErrorType STATIC_TYPE_WARNING =
- const ErrorType('STATIC_TYPE_WARNING', 5, ErrorSeverity.WARNING);
-
- /**
- * Syntactic errors are errors produced as a result of input that does not
- * conform to the grammar.
- */
- static const ErrorType SYNTACTIC_ERROR =
- const ErrorType('SYNTACTIC_ERROR', 6, ErrorSeverity.ERROR);
-
- /**
- * Lint warnings describe style and best practice recommendations that can be
- * used to formalize a project's style guidelines.
- */
- static const ErrorType LINT = const ErrorType('LINT', 7, ErrorSeverity.INFO);
-
- static const List<ErrorType> values = const [
- TODO,
- HINT,
- COMPILE_TIME_ERROR,
- CHECKED_MODE_COMPILE_TIME_ERROR,
- STATIC_WARNING,
- STATIC_TYPE_WARNING,
- SYNTACTIC_ERROR,
- LINT
- ];
-
- /**
- * The name of this error type.
- */
- final String name;
-
- /**
- * The ordinal value of the error type.
- */
- final int ordinal;
-
- /**
- * The severity of this type of error.
- */
- final ErrorSeverity severity;
-
- /**
- * Initialize a newly created error type to have the given [name] and
- * [severity].
- */
- const ErrorType(this.name, this.ordinal, this.severity);
-
- String get displayName => name.toLowerCase().replaceAll('_', ' ');
-
- @override
- int get hashCode => ordinal;
-
- @override
- int compareTo(ErrorType other) => ordinal - other.ordinal;
-
- @override
- String toString() => name;
-}
diff --git a/pub/front_end/lib/src/base/file_repository.dart b/pub/front_end/lib/src/base/file_repository.dart
deleted file mode 100644
index d4d4f7c..0000000
--- a/pub/front_end/lib/src/base/file_repository.dart
+++ /dev/null
@@ -1,100 +0,0 @@
-// 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.
-
-/// Data structure storing an association between URI and file contents.
-///
-/// Each URI is also associated with a unique arbitrary path ending in ".dart".
-/// This allows interfacing with analyzer code that expects to manipulate paths
-/// rather than URIs.
-class FileRepository {
- /// Regular expression matching the arbitrary file paths generated by
- /// [_pathForIndex].
- static final _pathRegexp = new RegExp(r'^/[0-9]+\.dart$');
-
- /// The URIs currently stored in the repository.
- final _uris = <Uri>[];
-
- /// Map from a URI to its index in [_uris].
- final _uriToIndexMap = <Uri, int>{};
-
- /// The file contents associated with the URIs in [_uris].
- final _contents = <String>[];
-
- /// Clear any contents stored in the file repository. The association between
- /// URI and arbitrary path is preserved.
- ///
- /// Subsequent calls to [contentsForPath] will have undefined results until
- /// new contents are stored using [store].
- void clearContents() {
- for (var i = 0; i < _contents.length; i++) {
- _contents[i] = null;
- }
- }
-
- /// Return the contents of the file whose arbitary path is [path].
- ///
- /// The path must have been returned by a previous call to [store] or
- /// [pathForUri].
- String contentsForPath(String path) {
- var contents = _contents[_indexForPath(path)];
- assert(contents != null);
- return contents;
- }
-
- /// For testing purposes, return the contents of all files stored in the file
- /// repository, as a map from path to contents string.
- Map<String, String> getContentsForTesting() {
- var result = <String, String>{};
- for (var i = 0; i < _contents.length; i++) {
- if (_contents[i] != null) result[_pathForIndex(i)] = _contents[i];
- }
- return result;
- }
-
- /// Return the arbitrary path associated with [uri].
- ///
- /// If [allocate] is `false` (the default), the uri must have previously been
- /// allocated a corresponding path, e.g. via a call to [store]. If [allocate]
- /// is `true`, then a new path will be allocated if necessary.
- String pathForUri(Uri uri, {bool allocate: false}) {
- return _pathForIndex(_indexForUri(uri, allocate));
- }
-
- /// Associate the given [uri] with file [contents].
- ///
- /// The arbitrary path associated with the file is returned.
- String store(Uri uri, String contents) {
- int index = _indexForUri(uri, true);
- _contents[index] = contents;
- return _pathForIndex(index);
- }
-
- /// Return the URI for the file whose arbitrary path is [path].
- ///
- /// The path must have been returned by a previous call to [store] or
- /// [pathForUri].
- Uri uriForPath(String path) => _uris[_indexForPath(path)];
-
- /// Return the index into [_uris] and [_contents] matching the arbitrary path
- /// [path].
- int _indexForPath(String path) {
- assert(_pathRegexp.hasMatch(path));
- return int.parse(path.substring(1, path.length - 5));
- }
-
- int _indexForUri(Uri uri, bool allocate) {
- int index = _uriToIndexMap[uri];
- assert(allocate || index != null);
- if (index == null) {
- index = _uris.length;
- _uris.add(uri);
- _uriToIndexMap[uri] = index;
- _contents.add(null);
- }
- return index;
- }
-
- /// Return the arbitrary path associated with the given index.
- String _pathForIndex(int index) => '/$index.dart';
-}
diff --git a/pub/front_end/lib/src/base/jenkins_smi_hash.dart b/pub/front_end/lib/src/base/jenkins_smi_hash.dart
deleted file mode 100644
index 8901ba4..0000000
--- a/pub/front_end/lib/src/base/jenkins_smi_hash.dart
+++ /dev/null
@@ -1,53 +0,0 @@
-// 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.
-
-/// Jenkins hash function, optimized for small integers.
-///
-/// Static methods borrowed from sdk/lib/math/jenkins_smi_hash.dart. Non-static
-/// methods are an enhancement for the "front_end" package.
-///
-/// Where performance is critical, use [hash2], [hash3], or [hash4], or the
-/// pattern `finish(combine(combine(...combine(0, a), b)..., z))`, where a..z
-/// are hash codes to be combined.
-///
-/// For ease of use, you may also use this pattern:
-/// `(new JenkinsSmiHash()..add(a)..add(b)....add(z)).hashCode`, where a..z are
-/// the sub-objects whose hashes should be combined. This pattern performs the
-/// same operations as the performance critical variant, but allocates an extra
-/// object.
-class JenkinsSmiHash {
- /// Accumulates the hash code [value] into the running hash [hash].
- static int combine(int hash, int value) {
- hash = 0x1fffffff & (hash + value);
- hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
- return hash ^ (hash >> 6);
- }
-
- /// Finalizes a running hash produced by [combine].
- static int finish(int hash) {
- hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
- hash = hash ^ (hash >> 11);
- return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
- }
-
- /// Combines together two hash codes.
- static int hash2(a, b) => finish(combine(combine(0, a), b));
-
- /// Combines together three hash codes.
- static int hash3(a, b, c) => finish(combine(combine(combine(0, a), b), c));
-
- /// Combines together four hash codes.
- static int hash4(a, b, c, d) =>
- finish(combine(combine(combine(combine(0, a), b), c), d));
-
- int _hash = 0;
-
- /// Accumulates the object [o] into the hash.
- void add(Object o) {
- _hash = combine(_hash, o.hashCode);
- }
-
- /// Finalizes the hash and return the resulting hashcode.
- int get hashCode => finish(_hash);
-}
diff --git a/pub/front_end/lib/src/base/library_info.dart b/pub/front_end/lib/src/base/library_info.dart
deleted file mode 100644
index a66b6d5..0000000
--- a/pub/front_end/lib/src/base/library_info.dart
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// A bit flag used by [LibraryInfo] indicating that a library is used by
-/// dart2js.
-///
-/// This declaration duplicates the declaration in the SDK's "libraries.dart".
-const int DART2JS_PLATFORM = 1;
-
-/// A bit flag used by [LibraryInfo] indicating that a library is used by the
-/// VM.
-///
-/// This declaration duplicates the declaration in the SDK's "libraries.dart".
-const int VM_PLATFORM = 2;
-
-/// Parse a category string in the SDK's "libraries.dart".
-///
-/// This declaration duplicates the declaration in the SDK's "libraries.dart".
-Category parseCategory(String name) {
- switch (name) {
- case 'Client':
- return Category.client;
- case 'Server':
- return Category.server;
- case 'Embedded':
- return Category.embedded;
- }
- return null;
-}
-
-/// The contexts that a library can be used from.
-///
-/// This declaration duplicates the declaration in the SDK's "libraries.dart".
-enum Category {
- /// Indicates that a library can be used in a browser context.
- client,
-
- /// Indicates that a lbirary can be used in a command line context.
- server,
-
- /// Indicates that a library can be used from embedded devices.
- embedded
-}
-
-/// Information about a "dart:" library gleaned from the SDK's "libraries.dart"
-/// file.
-///
-/// This declaration duplicates the declaration in "libraries.dart".
-class LibraryInfo {
- /// Path to the library's *.dart file relative to the SDK's "lib" directory.
- final String path;
-
- /// The categories in which the library can be used, encoded as a
- /// comma-separated String.
- final String _categories;
-
- /// Path to the dart2js library's *.dart file relative to the SDK's "lib"
- /// directory, or null if dart2js uses the common library path defined above.
- final String dart2jsPath;
-
- /// Path to the dart2js library's patch file relative to the SDK's "lib"
- /// directory, or null if no dart2js patch file associated with this library.
- final String dart2jsPatchPath;
-
- /// True if this library is documented and should be shown to the user.
- final bool documented;
-
- /// Bit flags indicating which platforms consume this library. See
- /// [DART2JS_LIBRARY] and [VM_LIBRARY].
- final int platforms;
-
- /// True if the library contains implementation details for another library.
- /// The implication is that these libraries are less commonly used and that
- /// tools like the analysis server should not show these libraries in a list
- /// of all libraries unless the user specifically asks the tool to do so.
- final bool implementation;
-
- /// States the current maturity of this library.
- final Maturity maturity;
-
- const LibraryInfo(this.path,
- {String categories: "",
- this.dart2jsPath,
- this.dart2jsPatchPath,
- this.implementation: false,
- this.documented: true,
- this.maturity: Maturity.UNSPECIFIED,
- this.platforms: DART2JS_PLATFORM | VM_PLATFORM})
- : _categories = categories;
-
- /// The categories in which the library can be used.
- ///
- /// If no categories are specified, the library is internal and cannot be
- /// loaded by user code.
- List<Category> get categories {
- // `''.split(',')` returns [''], not [], so we handle that case separately.
- if (_categories.isEmpty) return const <Category>[];
- return _categories.split(',').map(parseCategory).toList();
- }
-
- /// The original "categories" String that was passed to the constructor.
- ///
- /// Can be used to construct a slightly modified copy of this LibraryInfo.
- String get categoriesString {
- return _categories;
- }
-
- bool get isDart2jsLibrary => (platforms & DART2JS_PLATFORM) != 0;
-
- bool get isInternal => categories.isEmpty;
-
- bool get isVmLibrary => (platforms & VM_PLATFORM) != 0;
-}
-
-/// Abstraction to capture the maturity of a library.
-class Maturity {
- static const Maturity DEPRECATED = const Maturity(0, "Deprecated",
- "This library will be remove before next major release.");
- static const Maturity EXPERIMENTAL = const Maturity(
- 1,
- "Experimental",
- "This library is experimental and will likely change or be removed\n"
- "in future versions.");
- static const Maturity UNSTABLE = const Maturity(
- 2,
- "Unstable",
- "This library is in still changing and have not yet endured\n"
- "sufficient real-world testing.\n"
- "Backwards-compatibility is NOT guaranteed.");
-
- static const Maturity WEB_STABLE = const Maturity(
- 3,
- "Web Stable",
- "This library is tracking the DOM evolution as defined by WC3.\n"
- "Backwards-compatibility is NOT guaranteed.");
-
- static const Maturity STABLE = const Maturity(
- 4,
- "Stable",
- "The library is stable. API backwards-compatibility is guaranteed.\n"
- "However implementation details might change.");
-
- static const Maturity LOCKED = const Maturity(5, "Locked",
- "This library will not change except when serious bugs are encountered.");
-
- static const Maturity UNSPECIFIED = const Maturity(-1, "Unspecified",
- "The maturity for this library has not been specified.");
-
- final int level;
-
- final String name;
-
- final String description;
-
- const Maturity(this.level, this.name, this.description);
-
- String toString() => "$name: $level\n$description\n";
-}
diff --git a/pub/front_end/lib/src/base/processed_options.dart b/pub/front_end/lib/src/base/processed_options.dart
deleted file mode 100644
index 60ef2ec..0000000
--- a/pub/front_end/lib/src/base/processed_options.dart
+++ /dev/null
@@ -1,136 +0,0 @@
-// 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';
-
-import 'package:analyzer/src/summary/idl.dart';
-import 'package:front_end/compiler_options.dart';
-import 'package:front_end/file_system.dart';
-import 'package:front_end/src/base/uri_resolver.dart';
-import 'package:package_config/packages_file.dart' as package_config;
-
-/// Wrapper around [CompilerOptions] which exposes the options in a form useful
-/// to the front end implementation.
-///
-/// The intent is that the front end should immediately wrap any incoming
-/// [CompilerOptions] object in this class before doing further processing, and
-/// should thereafter access all options via the wrapper. This ensures that
-/// options are interpreted in a consistent way and that data derived from
-/// options is not unnecessarily recomputed.
-class ProcessedOptions {
- /// The raw [CompilerOptions] which this class wraps.
- final CompilerOptions _raw;
-
- /// The package map derived from the options, or `null` if the package map has
- /// not been computed yet.
- Map<String, Uri> _packages;
-
- /// A URI resolver based on the options, or `null` if the URI resolver has not
- /// been computed yet.
- UriResolver _uriResolver;
-
- /// The summary bundle for the SDK, or `null` if it has not been read yet.
- PackageBundle _sdkSummary;
-
- /// The location of the SDK, or `null` if the location hasn't been determined
- /// yet.
- Uri _sdkRoot;
-
- /// Initializes a [ProcessedOptions] object wrapping the given [rawOptions].
- ProcessedOptions(CompilerOptions rawOptions) : this._raw = rawOptions;
-
- /// Determine whether to generate code for the SDK when compiling a
- /// whole-program.
- bool get compileSdk => _raw.compileSdk;
-
- /// Get the [FileSystem] which should be used by the front end to access
- /// files.
- ///
- /// If the client supplied roots using [CompilerOptions.multiRoots], the
- /// returned [FileSystem] will automatically perform the appropriate mapping.
- FileSystem get fileSystem {
- // TODO(paulberry): support multiRoots.
- assert(_raw.multiRoots.isEmpty);
- return _raw.fileSystem;
- }
-
- /// Get the summary bundle for the SDK.
- ///
- /// This is an asynchronous getter since file system operations are required.
- Future<PackageBundle> getSdkSummary() async {
- if (_sdkSummary == null) {
- Uri summaryLocation;
- if (_raw.sdkSummary != null) {
- // Options sdkSummary and sdkRoot are mutually exclusive.
- assert(_raw.sdkRoot == null);
- // No need to look for the SDK; we were told where the SDK summary is.
- summaryLocation = _raw.sdkSummary;
- } else {
- // Need to look for the SDK summary inside the SDK.
- var sdkRoot = await _getSdkRoot();
- summaryLocation = sdkRoot.resolve(
- 'lib/_internal/' + (_raw.strongMode ? 'strong.sum' : 'spec.sum'));
- }
- var summaryBytes =
- await fileSystem.entityForUri(summaryLocation).readAsBytes();
- _sdkSummary = new PackageBundle.fromBuffer(summaryBytes);
- }
- return _sdkSummary;
- }
-
- /// Get the [UriResolver] which resolves "package:" and "dart:" URIs.
- ///
- /// This is an asynchronous getter since file system operations may be
- /// required to locate/read the packages file as well as SDK metadata.
- Future<UriResolver> getUriResolver() async {
- if (_uriResolver == null) {
- await _getPackages();
- var sdkLibraries =
- <String, Uri>{}; // TODO(paulberry): support SDK libraries
- _uriResolver = new UriResolver(_packages, sdkLibraries);
- }
- return _uriResolver;
- }
-
- /// Get the package map which maps package names to URIs.
- ///
- /// This is an asynchronous getter since file system operations may be
- /// required to locate/read the packages file.
- Future<Map<String, Uri>> _getPackages() async {
- if (_packages == null) {
- if (_raw.packagesFileUri == null) {
- throw new UnimplementedError(); // TODO(paulberry): search for .packages
- } else if (_raw.packagesFileUri.path.isEmpty) {
- _packages = {};
- } else {
- var contents =
- await fileSystem.entityForUri(_raw.packagesFileUri).readAsBytes();
- _packages = package_config.parse(contents, _raw.packagesFileUri);
- }
- }
- return _packages;
- }
-
- /// Get the location of the SDK.
- ///
- /// This is an asynchronous getter since file system operations may be
- /// required to locate the SDK.
- Future<Uri> _getSdkRoot() async {
- if (_sdkRoot == null) {
- // If an SDK summary location was provided, the SDK itself should not be
- // needed.
- assert(_raw.sdkSummary == null);
- if (_raw.sdkRoot == null) {
- // TODO(paulberry): implement the algorithm for finding the SDK
- // automagically.
- throw new UnimplementedError();
- }
- _sdkRoot = _raw.sdkRoot;
- if (!_sdkRoot.path.endsWith('/')) {
- _sdkRoot = _sdkRoot.replace(path: _sdkRoot.path + '/');
- }
- }
- return _sdkRoot;
- }
-}
diff --git a/pub/front_end/lib/src/base/resolve_relative_uri.dart b/pub/front_end/lib/src/base/resolve_relative_uri.dart
deleted file mode 100644
index cafcbf2..0000000
--- a/pub/front_end/lib/src/base/resolve_relative_uri.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/**
- * Resolve the [containedUri] against [baseUri] using Dart rules.
- *
- * This function behaves similarly to [Uri.resolveUri], except that it properly
- * handles situations like the following:
- *
- * resolveRelativeUri(dart:core, bool.dart) -> dart:core/bool.dart
- * resolveRelativeUri(package:a/b.dart, ../c.dart) -> package:a/c.dart
- */
-Uri resolveRelativeUri(Uri baseUri, Uri containedUri) {
- if (containedUri.isAbsolute) {
- return containedUri;
- }
- String scheme = baseUri.scheme;
- // dart:core => dart:core/core.dart
- if (scheme == 'dart') {
- String part = baseUri.path;
- if (part.indexOf('/') < 0) {
- baseUri = Uri.parse('$scheme:$part/$part.dart');
- }
- }
- return baseUri.resolveUri(containedUri);
-}
diff --git a/pub/front_end/lib/src/base/source.dart b/pub/front_end/lib/src/base/source.dart
deleted file mode 100644
index a87f933..0000000
--- a/pub/front_end/lib/src/base/source.dart
+++ /dev/null
@@ -1,175 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:front_end/src/base/analysis_target.dart';
-import 'package:front_end/src/base/timestamped_data.dart';
-import 'package:front_end/src/base/uri_kind.dart';
-import 'package:path/path.dart' as pathos;
-
-/// Base class providing implementations for the methods in [Source] that don't
-/// require filesystem access.
-abstract class BasicSource extends Source {
- final Uri uri;
-
- BasicSource(this.uri);
-
- @override
- String get encoding => uri.toString();
-
- @override
- String get fullName => encoding;
-
- @override
- int get hashCode => uri.hashCode;
-
- @override
- bool get isInSystemLibrary => uri.scheme == 'dart';
-
- @override
- String get shortName => pathos.basename(fullName);
-
- @override
- bool operator ==(Object object) => object is Source && object.uri == uri;
-}
-
-/**
- * The interface `Source` defines the behavior of objects representing source code that can be
- * analyzed by the analysis engine.
- *
- * Implementations of this interface need to be aware of some assumptions made by the analysis
- * engine concerning sources:
- * * Sources are not required to be unique. That is, there can be multiple instances representing
- * the same source.
- * * Sources are long lived. That is, the engine is allowed to hold on to a source for an extended
- * period of time and that source must continue to report accurate and up-to-date information.
- * Because of these assumptions, most implementations will not maintain any state but will delegate
- * to an authoritative system of record in order to implement this API. For example, a source that
- * represents files on disk would typically query the file system to determine the state of the
- * file.
- *
- * If the instances that implement this API are the system of record, then they will typically be
- * unique. In that case, sources that are created that represent non-existent files must also be
- * retained so that if those files are created at a later date the long-lived sources representing
- * those files will know that they now exist.
- */
-abstract class Source implements AnalysisTarget {
- /**
- * An empty list of sources.
- */
- static const List<Source> EMPTY_LIST = const <Source>[];
-
- /**
- * Get the contents and timestamp of this source.
- *
- * Clients should consider using the method [AnalysisContext.getContents]
- * because contexts can have local overrides of the content of a source that the source is not
- * aware of.
- *
- * @return the contents and timestamp of the source
- * @throws Exception if the contents of this source could not be accessed
- */
- TimestampedData<String> get contents;
-
- /**
- * Return an encoded representation of this source that can be used to create a source that is
- * equal to this source.
- *
- * @return an encoded representation of this source
- * See [SourceFactory.fromEncoding].
- */
- String get encoding;
-
- /**
- * Return the full (long) version of the name that can be displayed to the user to denote this
- * source. For example, for a source representing a file this would typically be the absolute path
- * of the file.
- *
- * @return a name that can be displayed to the user to denote this source
- */
- String get fullName;
-
- /**
- * Return a hash code for this source.
- *
- * @return a hash code for this source
- * See [Object.hashCode].
- */
- @override
- int get hashCode;
-
- /**
- * Return `true` if this source is in one of the system libraries.
- *
- * @return `true` if this is in a system library
- */
- bool get isInSystemLibrary;
-
- @override
- Source get librarySource => null;
-
- /**
- * Return the modification stamp for this source, or a negative value if the
- * source does not exist. A modification stamp is a non-negative integer with
- * the property that if the contents of the source have not been modified
- * since the last time the modification stamp was accessed then the same value
- * will be returned, but if the contents of the source have been modified one
- * or more times (even if the net change is zero) the stamps will be different.
- *
- * Clients should consider using the method
- * [AnalysisContext.getModificationStamp] because contexts can have local
- * overrides of the content of a source that the source is not aware of.
- */
- int get modificationStamp;
-
- /**
- * Return a short version of the name that can be displayed to the user to denote this source. For
- * example, for a source representing a file this would typically be the name of the file.
- *
- * @return a name that can be displayed to the user to denote this source
- */
- String get shortName;
-
- @override
- Source get source => this;
-
- /**
- * Return the URI from which this source was originally derived.
- *
- * @return the URI from which this source was originally derived
- */
- Uri get uri;
-
- /**
- * Return the kind of URI from which this source was originally derived. If this source was
- * created from an absolute URI, then the returned kind will reflect the scheme of the absolute
- * URI. If it was created from a relative URI, then the returned kind will be the same as the kind
- * of the source against which the relative URI was resolved.
- *
- * @return the kind of URI from which this source was originally derived
- */
- UriKind get uriKind;
-
- /**
- * Return `true` if the given object is a source that represents the same source code as
- * this source.
- *
- * @param object the object to be compared with this object
- * @return `true` if the given object is a source that represents the same source code as
- * this source
- * See [Object.==].
- */
- @override
- bool operator ==(Object object);
-
- /**
- * Return `true` if this source exists.
- *
- * Clients should consider using the method [AnalysisContext.exists] because
- * contexts can have local overrides of the content of a source that the source is not aware of
- * and a source with local content is considered to exist even if there is no file on disk.
- *
- * @return `true` if this source exists
- */
- bool exists();
-}
diff --git a/pub/front_end/lib/src/base/syntactic_entity.dart b/pub/front_end/lib/src/base/syntactic_entity.dart
deleted file mode 100644
index b21a503..0000000
--- a/pub/front_end/lib/src/base/syntactic_entity.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/**
- * Interface representing a syntactic entity (either a token or an AST node)
- * which has a location and extent in the source file.
- */
-abstract class SyntacticEntity {
- /**
- * Return the offset from the beginning of the file to the character after the
- * last character of the syntactic entity.
- */
- int get end;
-
- /**
- * Return the number of characters in the syntactic entity's source range.
- */
- int get length;
-
- /**
- * Return the offset from the beginning of the file to the first character in
- * the syntactic entity.
- */
- int get offset;
-}
diff --git a/pub/front_end/lib/src/base/timestamped_data.dart b/pub/front_end/lib/src/base/timestamped_data.dart
deleted file mode 100644
index 4c76dc5..0000000
--- a/pub/front_end/lib/src/base/timestamped_data.dart
+++ /dev/null
@@ -1,24 +0,0 @@
-// 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.
-
-/**
- * Analysis data for which we have a modification time.
- */
-class TimestampedData<E> {
- /**
- * The modification time of the source from which the data was created.
- */
- final int modificationTime;
-
- /**
- * The data that was created from the source.
- */
- final E data;
-
- /**
- * Initialize a newly created holder to associate the given [data] with the
- * given [modificationTime].
- */
- TimestampedData(this.modificationTime, this.data);
-}
diff --git a/pub/front_end/lib/src/base/uri_kind.dart b/pub/front_end/lib/src/base/uri_kind.dart
deleted file mode 100644
index 0e6d007..0000000
--- a/pub/front_end/lib/src/base/uri_kind.dart
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/**
- * The enumeration `UriKind` defines the different kinds of URI's that are known to the
- * analysis engine. These are used to keep track of the kind of URI associated with a given source.
- */
-class UriKind implements Comparable<UriKind> {
- /**
- * A 'dart:' URI.
- */
- static const UriKind DART_URI = const UriKind('DART_URI', 0, 0x64);
-
- /**
- * A 'file:' URI.
- */
- static const UriKind FILE_URI = const UriKind('FILE_URI', 1, 0x66);
-
- /**
- * A 'package:' URI.
- */
- static const UriKind PACKAGE_URI = const UriKind('PACKAGE_URI', 2, 0x70);
-
- static const List<UriKind> values = const [DART_URI, FILE_URI, PACKAGE_URI];
-
- /**
- * The name of this URI kind.
- */
- final String name;
-
- /**
- * The ordinal value of the URI kind.
- */
- final int ordinal;
-
- /**
- * The single character encoding used to identify this kind of URI.
- */
- final int encoding;
-
- /**
- * Initialize a newly created URI kind to have the given encoding.
- */
- const UriKind(this.name, this.ordinal, this.encoding);
-
- @override
- int get hashCode => ordinal;
-
- @override
- int compareTo(UriKind other) => ordinal - other.ordinal;
-
- @override
- String toString() => name;
-
- /**
- * Return the URI kind represented by the given [encoding], or `null` if there
- * is no kind with the given encoding.
- */
- static UriKind fromEncoding(int encoding) {
- while (true) {
- if (encoding == 0x64) {
- return DART_URI;
- } else if (encoding == 0x66) {
- return FILE_URI;
- } else if (encoding == 0x70) {
- return PACKAGE_URI;
- }
- break;
- }
- return null;
- }
-
- /**
- * Return the URI kind corresponding to the given scheme string.
- */
- static UriKind fromScheme(String scheme) {
- if (scheme == 'package') {
- return UriKind.PACKAGE_URI;
- } else if (scheme == 'dart') {
- return UriKind.DART_URI;
- } else if (scheme == 'file') {
- return UriKind.FILE_URI;
- }
- return UriKind.FILE_URI;
- }
-}
diff --git a/pub/front_end/lib/src/base/uri_resolver.dart b/pub/front_end/lib/src/base/uri_resolver.dart
deleted file mode 100644
index 0c6a420..0000000
--- a/pub/front_end/lib/src/base/uri_resolver.dart
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// The class `UriResolver` implements the rules for resolving "dart:" and
-/// "package:" URIs.
-class UriResolver {
- /// The URI scheme used for "package" URIs.
- static const PACKAGE_SCHEME = 'package';
-
- /// The URI scheme used for "dart" URIs.
- static const DART_SCHEME = 'dart';
-
- /// A map from package name to the file URI of the "lib" directory of the
- /// corresponding package. This is equivalent to the format returned by
- /// the "package_config" package's parse() function.
- final Map<String, Uri> packages;
-
- /// A map from SDK library name (e.g. `core` for `dart:core`) to the file URI
- /// of the defining compilation unit of the SDK library.
- final Map<String, Uri> sdkLibraries;
-
- UriResolver(this.packages, this.sdkLibraries);
-
- /// Converts "package:" and "dart:" URIs to the locations of the corresponding
- /// files.
- ///
- /// If the given URI is a "package:" or "dart:" URI, is well formed, and names
- /// a package or dart library that is recognized, returns the URI it resolves
- /// to. If the given URI is a "package:" or "dart:" URI, and is ill-formed
- /// or names a package or dart library that is not recognized, returns `null`.
- ///
- /// If the given URI has any scheme other than "package:" or "dart:", it is
- /// returned unchanged.
- ///
- /// It is not necessary for the URI to be absolute (relative URIs will be
- /// passed through unchanged).
- ///
- /// Note that no I/O is performed; the URI that is returned will be
- /// independent of whether or not any particular file exists on the file
- /// system.
- Uri resolve(Uri uri) {
- if (uri.scheme == DART_SCHEME || uri.scheme == PACKAGE_SCHEME) {
- var path = uri.path;
- var slashIndex = path.indexOf('/');
- String prefix;
- String rest;
- if (slashIndex >= 0) {
- prefix = path.substring(0, slashIndex);
- rest = path.substring(slashIndex + 1);
- } else {
- prefix = path;
- rest = '';
- }
- Uri libUri;
- if (uri.scheme == PACKAGE_SCHEME) {
- if (slashIndex < 0) return null;
- libUri = packages[prefix];
- } else if (uri.scheme == DART_SCHEME) {
- libUri = sdkLibraries[prefix];
- }
- if (libUri == null) return null;
- return libUri.resolve(rest);
- } else {
- return uri;
- }
- }
-}
diff --git a/pub/front_end/lib/src/dependency_grapher_impl.dart b/pub/front_end/lib/src/dependency_grapher_impl.dart
deleted file mode 100644
index 66aa443..0000000
--- a/pub/front_end/lib/src/dependency_grapher_impl.dart
+++ /dev/null
@@ -1,151 +0,0 @@
-// 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';
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/error/listener.dart';
-import 'package:analyzer/src/dart/scanner/reader.dart';
-import 'package:analyzer/src/generated/parser.dart';
-import 'package:front_end/dependency_grapher.dart';
-import 'package:front_end/src/async_dependency_walker.dart';
-import 'package:front_end/src/base/processed_options.dart';
-import 'package:front_end/src/base/uri_resolver.dart';
-import 'package:front_end/src/scanner/scanner.dart';
-
-/// Generates a representation of the dependency graph of a program.
-///
-/// Given the Uri of one or more files, this function follows `import`,
-/// `export`, and `part` declarations to discover a graph of all files involved
-/// in the program.
-///
-/// If a [fileReader] is supplied, it is used to read file contents; otherwise
-/// they are read directly from `options.fileSystem`.
-///
-/// This is intended for internal use by the front end. Clients should use
-/// package:front_end/dependency_grapher.dart.
-Future<Graph> graphForProgram(List<Uri> sources, ProcessedOptions options,
- {FileReader fileReader}) async {
- var uriResolver = await options.getUriResolver();
- fileReader ??= (originalUri, resolvedUri) =>
- options.fileSystem.entityForUri(resolvedUri).readAsString();
- var walker = new _Walker(fileReader, uriResolver, options.compileSdk);
- var startingPoint = new _StartingPoint(walker, sources);
- await walker.walk(startingPoint);
- return walker.graph;
-}
-
-/// Type of the callback function used by [graphForProgram] to read file
-/// contents.
-typedef Future<String> FileReader(Uri originalUri, Uri resolvedUri);
-
-class _Scanner extends Scanner {
- _Scanner(String contents) : super(new CharSequenceReader(contents)) {
- preserveComments = false;
- }
-
- @override
- void reportError(errorCode, int offset, List<Object> arguments) {
- // TODO(paulberry): report errors.
- }
-}
-
-class _StartingPoint extends _WalkerNode {
- final List<Uri> sources;
-
- _StartingPoint(_Walker walker, this.sources) : super(walker, null);
-
- @override
- Future<List<_WalkerNode>> computeDependencies() async =>
- sources.map(walker.nodeForUri).toList();
-}
-
-class _Walker extends AsyncDependencyWalker<_WalkerNode> {
- final FileReader fileReader;
- final UriResolver uriResolver;
- final _nodesByUri = <Uri, _WalkerNode>{};
- final graph = new Graph();
- final bool compileSdk;
-
- _Walker(this.fileReader, this.uriResolver, this.compileSdk);
-
- @override
- Future<Null> evaluate(_WalkerNode v) {
- if (v is _StartingPoint) return new Future.value();
- return evaluateScc([v]);
- }
-
- @override
- Future<Null> evaluateScc(List<_WalkerNode> scc) {
- var cycle = new LibraryCycleNode();
- for (var walkerNode in scc) {
- cycle.libraries[walkerNode.uri] = walkerNode.library;
- }
- graph.topologicallySortedCycles.add(cycle);
- return new Future.value();
- }
-
- _WalkerNode nodeForUri(Uri referencedUri) {
- var dependencyNode = _nodesByUri.putIfAbsent(
- referencedUri, () => new _WalkerNode(this, referencedUri));
- return dependencyNode;
- }
-}
-
-class _WalkerNode extends Node<_WalkerNode> {
- static final dartCoreUri = Uri.parse('dart:core');
- final _Walker walker;
- final Uri uri;
- final LibraryNode library;
-
- _WalkerNode(this.walker, Uri uri)
- : uri = uri,
- library = new LibraryNode(uri);
-
- @override
- Future<List<_WalkerNode>> computeDependencies() async {
- var dependencies = <_WalkerNode>[];
- // TODO(paulberry): add error recovery if the file can't be read.
- var resolvedUri = walker.uriResolver.resolve(uri);
- if (resolvedUri == null) {
- // TODO(paulberry): If an error reporter was provided, report the error
- // in the proper way and continue.
- throw new StateError('Invalid URI: $uri');
- }
- var contents = await walker.fileReader(uri, resolvedUri);
- var scanner = new _Scanner(contents);
- var token = scanner.tokenize();
- // TODO(paulberry): report errors.
- var parser = new Parser(null, AnalysisErrorListener.NULL_LISTENER);
- var unit = parser.parseDirectives(token);
- bool coreUriFound = false;
- void handleDependency(Uri referencedUri) {
- _WalkerNode dependencyNode = walker.nodeForUri(referencedUri);
- library.dependencies.add(dependencyNode.library);
- if (referencedUri.scheme != 'dart' || walker.compileSdk) {
- dependencies.add(dependencyNode);
- }
- if (referencedUri == dartCoreUri) {
- coreUriFound = true;
- }
- }
-
- for (var directive in unit.directives) {
- if (directive is UriBasedDirective) {
- // TODO(paulberry): when we support SDK libraries, we'll need more
- // complex logic here to find SDK parts correctly.
- var referencedUri = uri.resolve(directive.uri.stringValue);
- if (directive is PartDirective) {
- library.parts.add(referencedUri);
- } else {
- handleDependency(referencedUri);
- }
- }
- }
- if (!coreUriFound) {
- handleDependency(dartCoreUri);
- }
- return dependencies;
- }
-}
diff --git a/pub/front_end/lib/src/dependency_walker.dart b/pub/front_end/lib/src/dependency_walker.dart
deleted file mode 100644
index 7a27acb..0000000
--- a/pub/front_end/lib/src/dependency_walker.dart
+++ /dev/null
@@ -1,168 +0,0 @@
-// 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.
-
-/**
- * Instances of [Node] represent nodes in a dependency graph. The
- * type parameter, [NodeType], is the derived type (this affords some
- * extra type safety by making it difficult to accidentally construct
- * bridges between unrelated dependency graphs).
- */
-abstract class Node<NodeType> {
- /**
- * Index used by Tarjan's strongly connected components algorithm.
- * Zero means the node has not been visited yet; a nonzero value
- * counts the order in which the node was visited.
- */
- int _index = 0;
-
- /**
- * Low link used by Tarjan's strongly connected components
- * algorithm. This represents the smallest [_index] of all the nodes
- * in the strongly connected component to which this node belongs.
- */
- int _lowLink = 0;
-
- List<NodeType> _dependencies;
-
- /**
- * Retrieve the dependencies of this node.
- */
- List<NodeType> get dependencies => _dependencies ??= computeDependencies();
-
- /**
- * Indicates whether this node has been evaluated yet.
- */
- bool get isEvaluated;
-
- /**
- * Compute the dependencies of this node.
- */
- List<NodeType> computeDependencies();
-}
-
-/**
- * An instance of [DependencyWalker] contains the core algorithms for
- * walking a dependency graph and evaluating nodes in a safe order.
- */
-abstract class DependencyWalker<NodeType extends Node<NodeType>> {
- /**
- * Called by [walk] to evaluate a single non-cyclical node, after
- * all that node's dependencies have been evaluated.
- */
- void evaluate(NodeType v);
-
- /**
- * Called by [walk] to evaluate a strongly connected component
- * containing one or more nodes. All dependencies of the strongly
- * connected component have been evaluated.
- */
- void evaluateScc(List<NodeType> scc);
-
- /**
- * Walk the dependency graph starting at [startingPoint], finding
- * strongly connected components and evaluating them in a safe order
- * by calling [evaluate] and [evaluateScc].
- *
- * This is an implementation of Tarjan's strongly connected
- * components algorithm
- * (https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm).
- */
- void walk(NodeType startingPoint) {
- // TODO(paulberry): consider rewriting in a non-recursive way so
- // that long dependency chains don't cause stack overflow.
-
- // TODO(paulberry): in the event that an exception occurs during
- // the walk, restore the state of the [Node] data structures so
- // that further evaluation will be safe.
-
- // The index which will be assigned to the next node that is
- // freshly visited.
- int index = 1;
-
- // Stack of nodes which have been seen so far and whose strongly
- // connected component is still being determined. Nodes are only
- // popped off the stack when they are evaluated, so sometimes the
- // stack contains nodes that were visited after the current node.
- List<NodeType> stack = <NodeType>[];
-
- void strongConnect(NodeType node) {
- bool hasTrivialCycle = false;
-
- // Assign the current node an index and add it to the stack. We
- // haven't seen any of its dependencies yet, so set its lowLink
- // to its index, indicating that so far it is the only node in
- // its strongly connected component.
- node._index = node._lowLink = index++;
- stack.add(node);
-
- // Consider the node's dependencies one at a time.
- for (NodeType dependency in node.dependencies) {
- // If the dependency has already been evaluated, it can't be
- // part of this node's strongly connected component, so we can
- // skip it.
- if (dependency.isEvaluated) {
- continue;
- }
- if (identical(node, dependency)) {
- // If a node includes itself as a dependency, there is no need to
- // explore the dependency further.
- hasTrivialCycle = true;
- } else if (dependency._index == 0) {
- // The dependency hasn't been seen yet, so recurse on it.
- strongConnect(dependency);
- // If the dependency's lowLink refers to a node that was
- // visited before the current node, that means that the
- // current node, the dependency, and the node referred to by
- // the dependency's lowLink are all part of the same
- // strongly connected component, so we need to update the
- // current node's lowLink accordingly.
- if (dependency._lowLink < node._lowLink) {
- node._lowLink = dependency._lowLink;
- }
- } else {
- // The dependency has already been seen, so it is part of
- // the current node's strongly connected component. If it
- // was visited earlier than the current node's lowLink, then
- // it is a new addition to the current node's strongly
- // connected component, so we need to update the current
- // node's lowLink accordingly.
- if (dependency._index < node._lowLink) {
- node._lowLink = dependency._index;
- }
- }
- }
-
- // If the current node's lowLink is the same as its index, then
- // we have finished visiting a strongly connected component, so
- // pop the stack and evaluate it before moving on.
- if (node._lowLink == node._index) {
- // The strongly connected component has only one node. If there is a
- // cycle, it's a trivial one.
- if (identical(stack.last, node)) {
- stack.removeLast();
- if (hasTrivialCycle) {
- evaluateScc(<NodeType>[node]);
- } else {
- evaluate(node);
- }
- } else {
- // There are multiple nodes in the strongly connected
- // component.
- List<NodeType> scc = <NodeType>[];
- while (true) {
- NodeType otherNode = stack.removeLast();
- scc.add(otherNode);
- if (identical(otherNode, node)) {
- break;
- }
- }
- evaluateScc(scc);
- }
- }
- }
-
- // Kick off the algorithm starting with the starting point.
- strongConnect(startingPoint);
- }
-}
diff --git a/pub/front_end/lib/src/incremental_kernel_generator_impl.dart b/pub/front_end/lib/src/incremental_kernel_generator_impl.dart
deleted file mode 100644
index efd4ddd..0000000
--- a/pub/front_end/lib/src/incremental_kernel_generator_impl.dart
+++ /dev/null
@@ -1,147 +0,0 @@
-// 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';
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/ast/standard_resolution_map.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/error/error.dart';
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:front_end/incremental_kernel_generator.dart';
-import 'package:front_end/incremental_resolved_ast_generator.dart';
-import 'package:front_end/src/base/processed_options.dart';
-import 'package:front_end/src/base/source.dart';
-import 'package:front_end/src/incremental_resolved_ast_generator_impl.dart';
-import 'package:kernel/analyzer/loader.dart';
-import 'package:kernel/kernel.dart' hide Source;
-import 'package:kernel/repository.dart';
-
-dynamic unimplemented() {
- // TODO(paulberry): get rid of this.
- throw new UnimplementedError();
-}
-
-DartOptions _convertOptions(ProcessedOptions options) {
- // TODO(paulberry): make sure options.compileSdk is handled correctly.
- return new DartOptions(
- strongMode: true, // TODO(paulberry): options.strongMode,
- sdk: null, // TODO(paulberry): _uriToPath(options.sdkRoot, options),
- sdkSummary:
- null, // TODO(paulberry): options.compileSdk ? null : _uriToPath(options.sdkSummary, options),
- packagePath:
- null, // TODO(paulberry): _uriToPath(options.packagesFileUri, options),
- declaredVariables: null // TODO(paulberry): options.declaredVariables
- );
-}
-
-/// Implementation of [IncrementalKernelGenerator].
-///
-/// Theory of operation: an instance of [IncrementalResolvedAstGenerator] is
-/// used to obtain resolved ASTs, and these are fed into kernel code generation
-/// logic.
-///
-/// Note that the kernel doesn't expect to take resolved ASTs as a direct input;
-/// it expects to request resolved ASTs from an [AnalysisContext]. To deal with
-/// this, we create [_AnalysisContextProxy] which returns the resolved ASTs when
-/// requested. TODO(paulberry): Make this unnecessary.
-class IncrementalKernelGeneratorImpl implements IncrementalKernelGenerator {
- final IncrementalResolvedAstGenerator _resolvedAstGenerator;
- final ProcessedOptions _options;
-
- IncrementalKernelGeneratorImpl(Uri source, ProcessedOptions options)
- : _resolvedAstGenerator =
- new IncrementalResolvedAstGeneratorImpl(source, options),
- _options = options;
-
- @override
- Future<DeltaProgram> computeDelta(
- {Future<Null> watch(Uri uri, bool used)}) async {
- var deltaLibraries = await _resolvedAstGenerator.computeDelta();
- var kernelOptions = _convertOptions(_options);
- var packages = null; // TODO(paulberry)
- var kernels = <Uri, Program>{};
- for (Uri uri in deltaLibraries.newState.keys) {
- // The kernel generation code doesn't currently support building a kernel
- // directly from resolved ASTs--it wants to query an analysis context. So
- // we provide it with a proxy analysis context that feeds it the resolved
- // ASTs.
- var strongMode = true; // TODO(paulberry): set this correctly
- var analysisOptions = new _AnalysisOptionsProxy(strongMode);
- var context =
- new _AnalysisContextProxy(deltaLibraries.newState, analysisOptions);
- var repository = new Repository();
- var loader =
- new DartLoader(repository, kernelOptions, packages, context: context);
- loader.loadLibrary(uri);
- kernels[uri] = new Program(repository.libraries);
- // TODO(paulberry) rework watch invocation to eliminate race condition,
- // include part source files, and prevent watch from being a bottleneck
- if (watch != null) await watch(uri, true);
- }
- // TODO(paulberry) invoke watch with used=false for each unused source
- return new DeltaProgram(kernels);
- }
-
- @override
- void invalidate(String path) => _resolvedAstGenerator.invalidate(path);
-
- @override
- void invalidateAll() => _resolvedAstGenerator.invalidateAll();
-}
-
-class _AnalysisContextProxy implements AnalysisContext {
- final Map<Uri, Map<Uri, CompilationUnit>> _resolvedLibraries;
-
- @override
- final _SourceFactoryProxy sourceFactory = new _SourceFactoryProxy();
-
- @override
- final AnalysisOptions analysisOptions;
-
- _AnalysisContextProxy(this._resolvedLibraries, this.analysisOptions);
-
- List<AnalysisError> computeErrors(Source source) {
- // TODO(paulberry): do we need to return errors sometimes?
- return [];
- }
-
- LibraryElement computeLibraryElement(Source source) {
- assert(_resolvedLibraries.containsKey(source.uri));
- return resolutionMap
- .elementDeclaredByCompilationUnit(
- _resolvedLibraries[source.uri][source.uri])
- .library;
- }
-
- noSuchMethod(Invocation invocation) => unimplemented();
-
- CompilationUnit resolveCompilationUnit(
- Source unitSource, LibraryElement library) {
- var unit = _resolvedLibraries[library.source.uri][unitSource.uri];
- assert(unit != null);
- return unit;
- }
-}
-
-class _AnalysisOptionsProxy implements AnalysisOptions {
- final bool strongMode;
-
- _AnalysisOptionsProxy(this.strongMode);
-
- noSuchMethod(Invocation invocation) => unimplemented();
-}
-
-class _SourceFactoryProxy implements SourceFactory {
- Source forUri2(Uri absoluteUri) => new _SourceProxy(absoluteUri);
-
- noSuchMethod(Invocation invocation) => unimplemented();
-}
-
-class _SourceProxy extends BasicSource {
- _SourceProxy(Uri uri) : super(uri);
-
- noSuchMethod(Invocation invocation) => unimplemented();
-}
diff --git a/pub/front_end/lib/src/incremental_resolved_ast_generator_impl.dart b/pub/front_end/lib/src/incremental_resolved_ast_generator_impl.dart
deleted file mode 100644
index d0b093b..0000000
--- a/pub/front_end/lib/src/incremental_resolved_ast_generator_impl.dart
+++ /dev/null
@@ -1,302 +0,0 @@
-// 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';
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/context/context.dart';
-import 'package:analyzer/src/dart/analysis/byte_store.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart' as driver;
-import 'package:analyzer/src/dart/analysis/file_state.dart';
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/sdk.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/summary/idl.dart';
-import 'package:analyzer/src/util/absolute_path.dart';
-import 'package:front_end/incremental_resolved_ast_generator.dart';
-import 'package:front_end/src/base/file_repository.dart';
-import 'package:front_end/src/base/processed_options.dart';
-import 'package:front_end/src/base/resolve_relative_uri.dart';
-import 'package:front_end/src/base/source.dart';
-import 'package:front_end/src/dependency_grapher_impl.dart';
-import 'package:path/src/context.dart';
-
-dynamic unimplemented() {
- // TODO(paulberry): get rid of this.
- throw new UnimplementedError();
-}
-
-/// Implementation of [IncrementalKernelGenerator].
-///
-/// Theory of operation: this class is a thin wrapper around
-/// [driver.AnalysisDriver]. When the client requests a new delta, we forward
-/// the request to the analysis driver. When the client calls an invalidate
-/// method, we ensure that the proper files will be re-read next time a delta is
-/// requested.
-///
-/// Note that the analysis driver expects to be able to read file contents
-/// synchronously based on filesystem path rather than asynchronously based on
-/// URI, so the file contents are first read into memory using the asynchronous
-/// FileSystem API, and then these are fed into the analysis driver using a
-/// proxy implementation of [ResourceProvider]. TODO(paulberry): make this (and
-/// other proxies in this file) unnecessary.
-class IncrementalResolvedAstGeneratorImpl
- implements IncrementalResolvedAstGenerator {
- driver.AnalysisDriverScheduler _scheduler;
- final _fileRepository = new FileRepository();
- _ResourceProviderProxy _resourceProvider;
- driver.AnalysisDriver _driver;
- bool _isInitialized = false;
- final ProcessedOptions _options;
- final Uri _source;
- bool _schedulerStarted = false;
- final _fileState = <Uri, String>{};
-
- IncrementalResolvedAstGeneratorImpl(this._source, this._options);
-
- @override
- Future<DeltaLibraries> computeDelta() async {
- if (!_isInitialized) {
- await init();
- }
- // The analysis driver doesn't currently support an asynchronous file API,
- // so we have to find all the files first to read their contents.
- // TODO(paulberry): this is an unnecessary source of duplicate work and
- // should be eliminated ASAP.
- var graph =
- await graphForProgram([_source], _options, fileReader: _fileReader);
- // TODO(paulberry): collect no-longer-referenced files from _fileState and
- // _fileRepository.
- var libraries = <Uri, Map<Uri, CompilationUnit>>{};
- if (!_schedulerStarted) {
- _scheduler.start();
- _schedulerStarted = true;
- }
- for (var libraryCycle in graph.topologicallySortedCycles) {
- for (var libraryUri in libraryCycle.libraries.keys) {
- var libraryNode = libraryCycle.libraries[libraryUri];
- for (var partUri in libraryNode.parts) {
- // TODO(paulberry): resolve the part URI.
- _fileReader(partUri, partUri);
- }
- }
- for (var libraryUri in libraryCycle.libraries.keys) {
- var libraryNode = libraryCycle.libraries[libraryUri];
- var result =
- await _driver.getResult(_fileRepository.pathForUri(libraryUri));
- // TODO(paulberry): handle errors.
- var units = {libraryUri: result.unit};
- for (var partUri in libraryNode.parts) {
- // Really we ought to have a driver API that lets us request a
- // specific part of a given library. Otherwise we will run into
- // problems if a part is included in multiple libraries.
- // TODO(paulberry): address this.
- var partResult =
- await _driver.getResult(_fileRepository.pathForUri(partUri));
- // TODO(paulberry): handle errors.
- units[partUri] = partResult.unit;
- }
- libraries[libraryUri] = units;
- }
- }
- _driver.addFile(_fileRepository.pathForUri(_source));
- // TODO(paulberry): stop the scheduler
- return new DeltaLibraries(libraries);
- }
-
- Future<Null> init() async {
- // TODO(paulberry): can we just use null?
- var performanceLog = new driver.PerformanceLog(new _NullStringSink());
- _scheduler = new driver.AnalysisDriverScheduler(performanceLog);
- _resourceProvider = new _ResourceProviderProxy(_fileRepository);
- // TODO(paulberry): MemoryByteStore leaks memory (it never discards data).
- // Do something better here.
- var byteStore = new MemoryByteStore();
- // TODO(paulberry): can we just use null?
- var fileContentOverlay = new FileContentOverlay();
- var sdkContext = new AnalysisContextImpl();
- var sdkBundle = await _options.getSdkSummary();
- var dartSdk = new _DartSdkProxy(sdkBundle, sdkContext, _fileRepository);
- sdkContext.sourceFactory =
- new SourceFactory([new DartUriResolver(dartSdk)]);
-
- var sourceFactory = new _SourceFactoryProxy(dartSdk, _fileRepository);
- var analysisOptions = new AnalysisOptionsImpl();
- _driver = new driver.AnalysisDriver(
- _scheduler,
- performanceLog,
- _resourceProvider,
- byteStore,
- fileContentOverlay,
- 'front_end',
- sourceFactory,
- analysisOptions,
- sdkBundle: sdkBundle);
- _isInitialized = true;
- }
-
- @override
- void invalidate(String path) {
- throw new UnimplementedError();
- }
-
- @override
- void invalidateAll() {
- _fileState.clear();
- _fileRepository.clearContents();
- // TODO(paulberry): verify that this has an effect (requires a multi-file
- // test).
- if (_isInitialized) {
- _driver.knownFiles.forEach(_driver.changeFile);
- }
- }
-
- Future<String> _fileReader(Uri originalUri, Uri resolvedUri) async {
- String contents = _fileState[resolvedUri] ??=
- await _options.fileSystem.entityForUri(resolvedUri).readAsString();
- _fileRepository.store(originalUri, contents);
- return contents;
- }
-}
-
-class _DartSdkProxy implements DartSdk {
- final PackageBundle summary;
-
- final AnalysisContext context;
-
- final FileRepository _fileRepository;
-
- _DartSdkProxy(this.summary, this.context, this._fileRepository);
-
- @override
- PackageBundle getLinkedBundle() => summary;
-
- @override
- Source mapDartUri(String uriString) {
- var uri = Uri.parse(uriString);
- return new _SourceProxy(
- uri, _fileRepository.pathForUri(uri, allocate: true));
- }
-
- noSuchMethod(Invocation invocation) => unimplemented();
-}
-
-class _FileProxy implements File {
- final _SourceProxy _source;
-
- final _ResourceProviderProxy _resourceProvider;
-
- _FileProxy(this._source, this._resourceProvider);
-
- @override
- String get path => _source.fullName;
-
- @override
- String get shortName => path;
-
- @override
- Source createSource([Uri uri]) {
- assert(uri == null);
- return _source;
- }
-
- noSuchMethod(Invocation invocation) => unimplemented();
-
- @override
- String readAsStringSync() {
- return _resourceProvider._fileRepository.contentsForPath(path);
- }
-}
-
-/// A string sink that ignores everything written to it.
-class _NullStringSink implements StringSink {
- void write(Object obj) {}
- void writeAll(Iterable objects, [String separator = ""]) {}
- void writeCharCode(int charCode) {}
- void writeln([Object obj = ""]) {}
-}
-
-class _ResourceProviderProxy implements ResourceProvider {
- final FileRepository _fileRepository;
-
- _ResourceProviderProxy(this._fileRepository);
-
- @override
- AbsolutePathContext get absolutePathContext => throw new UnimplementedError();
-
- @override
- Context get pathContext => throw new UnimplementedError();
-
- @override
- File getFile(String path) {
- return new _FileProxy(
- new _SourceProxy(_fileRepository.uriForPath(path), path), this);
- }
-
- @override
- Folder getFolder(String path) => throw new UnimplementedError();
-
- @override
- Future<List<int>> getModificationTimes(List<Source> sources) =>
- throw new UnimplementedError();
-
- @override
- Resource getResource(String path) => throw new UnimplementedError();
-
- @override
- Folder getStateLocation(String pluginId) => throw new UnimplementedError();
-}
-
-class _SourceFactoryProxy implements SourceFactory {
- @override
- final DartSdk dartSdk;
-
- final FileRepository _fileRepository;
-
- @override
- AnalysisContext context;
-
- _SourceFactoryProxy(this.dartSdk, this._fileRepository);
-
- @override
- SourceFactory clone() => new _SourceFactoryProxy(dartSdk, _fileRepository);
-
- @override
- Source forUri(String absoluteUri) {
- Uri uri = Uri.parse(absoluteUri);
- return forUri2(uri);
- }
-
- @override
- Source forUri2(Uri absoluteUri) {
- return new _SourceProxy(
- absoluteUri, _fileRepository.pathForUri(absoluteUri, allocate: true));
- }
-
- noSuchMethod(Invocation invocation) => unimplemented();
-
- Source resolveUri(Source containingSource, String containedUri) {
- // TODO(paulberry): re-use code from dependency_grapher_impl, and support
- // SDK URI resolution logic.
- String absoluteUri =
- resolveRelativeUri(containingSource?.uri, Uri.parse(containedUri))
- .toString();
- return forUri(absoluteUri);
- }
-
- @override
- Uri restoreUri(Source source) => source.uri;
-}
-
-class _SourceProxy extends BasicSource {
- @override
- final String fullName;
-
- _SourceProxy(Uri uri, this.fullName) : super(uri);
-
- int get modificationStamp => 0;
-
- noSuchMethod(Invocation invocation) => unimplemented();
-}
diff --git a/pub/front_end/lib/src/libraries_reader.dart b/pub/front_end/lib/src/libraries_reader.dart
deleted file mode 100644
index ded5d9f..0000000
--- a/pub/front_end/lib/src/libraries_reader.dart
+++ /dev/null
@@ -1,201 +0,0 @@
-import 'package:analyzer/src/summary/idl.dart';
-import 'package:front_end/src/base/library_info.dart';
-
-/// Decodes the contents of the SDK's "libraries.dart" file.
-///
-/// Caller should pass in the unlinked summary of the libraries.dart file. This
-/// function will materialize the "libraries" constant based on information in
-/// the summary.
-///
-/// Note that this code is not intended to be fully general; it makes some
-/// assumptions about the structure of the "libraries.dart" file (such as what
-/// declarations are expected to be present in it, and the types of those
-/// declarations).
-Map<String, LibraryInfo> readLibraries(UnlinkedUnit librariesUnit) {
- var constContext = new _ConstContext(librariesUnit.references);
- for (var variable in librariesUnit.variables) {
- if (!variable.isConst) continue;
- constContext.topLevelConstants[variable.name] =
- new _ConstVariable(variable.initializer.bodyExpr, constContext);
- }
- for (var cls in librariesUnit.classes) {
- if (cls.name == 'Maturity') {
- for (var field in cls.fields) {
- if (!field.isConst) continue;
- constContext.maturityConstants[field.name] =
- new _ConstVariable(field.initializer.bodyExpr, constContext);
- }
- }
- }
- return constContext.topLevelConstants['libraries'].value;
-}
-
-/// Function type used to invoke a constructor based on dynamic information.
-///
-/// Caller supplies two callbacks ([positional] and [named]) which can be used
-/// to query the arguments passed to the constructor. These callbacks will
-/// return the requested argument if it was provided; otherwise they will return
-/// the supplied default value.
-typedef dynamic _Constructor(dynamic positional(int i, [dynamic defaultValue]),
- dynamic named(String name, [dynamic defaultValue]));
-
-/// Contextual information used to evaluate constants in the "libraries.dart"
-/// file.
-class _ConstContext {
- /// Top level constants in the "libraries.dart" file.
- final topLevelConstants = <String, _ConstVariable>{};
-
- /// Static constants in "libraries.dart"'s "Maturity" class.
- final maturityConstants = <String, _ConstVariable>{};
-
- /// References from the unlinked summary of the "libraries.dart" file.
- final List<UnlinkedReference> references;
-
- _ConstContext(this.references);
-}
-
-/// Information necessary to evaluate a single constant from the
-/// "libraries.dart" file.
-class _ConstVariable {
- /// The constant expression from the unlinked summary.
- final UnlinkedExpr expr;
-
- /// Contextual information necessary to evaluate the constant.
- final _ConstContext context;
-
- /// The evaluated value, or `null` if it hasn't been evaluated yet.
- dynamic _value;
-
- _ConstVariable(this.expr, this.context);
-
- /// Evaluate the constant (if necessary) and return it.
- dynamic get value => _value ??= _materialize();
-
- /// Find the constructor referred to by [entityRef] and return a function
- /// which may be used to invoke it.
- _Constructor _findConstructor(EntityRef entityRef) {
- // This method is not fully general; we only support the constructor
- // invocations that we expect to find in LibraryInfo.
- assert(entityRef.implicitFunctionTypeIndices.isEmpty);
- assert(entityRef.paramReference == 0);
- assert(entityRef.syntheticParams.isEmpty);
- assert(entityRef.syntheticReturnType == null);
- assert(entityRef.typeArguments.isEmpty);
- var reference = context.references[entityRef.reference];
- assert(reference.prefixReference == 0);
- switch (reference.name) {
- case 'LibraryInfo':
- return (dynamic positional(int i, [dynamic defaultValue]),
- dynamic named(String name, [dynamic defaultValue])) =>
- new LibraryInfo(positional(0),
- categories: named('categories', ''),
- dart2jsPath: named('dart2jsPath'),
- dart2jsPatchPath: named('dart2jsPatchPath'),
- implementation: named('implementation', false),
- documented: named('documented', true),
- maturity: named('maturity', Maturity.UNSPECIFIED),
- platforms: named('platforms', DART2JS_PLATFORM | VM_PLATFORM));
- case 'Maturity':
- return (dynamic positional(int i, [dynamic defaultValue]),
- dynamic named(String name, [dynamic defaultValue])) =>
- new Maturity(positional(0), positional(1), positional(2));
- default:
- throw new UnimplementedError(
- 'Unexpected constructor reference: ${reference.name}');
- }
- }
-
- /// Compute the value referred to by [entityRef].
- dynamic _findReference(EntityRef entityRef) {
- // This method is not fully general; we only support the references that we
- // expect to find in LibraryInfo.
- assert(entityRef.implicitFunctionTypeIndices.isEmpty);
- assert(entityRef.paramReference == 0);
- assert(entityRef.syntheticParams.isEmpty);
- assert(entityRef.syntheticReturnType == null);
- assert(entityRef.typeArguments.isEmpty);
- var reference = context.references[entityRef.reference];
- if (reference.prefixReference == 0) {
- return context.topLevelConstants[reference.name].value;
- } else {
- assert(reference.prefixReference != 0);
- var prefixReference = context.references[reference.prefixReference];
- assert(prefixReference.name == 'Maturity');
- assert(prefixReference.prefixReference == 0);
- return context.maturityConstants[reference.name].value;
- }
- }
-
- /// Compute the value of the constant.
- dynamic _materialize() {
- var stack = [];
- var stringIndex = 0;
- var intIndex = 0;
- var referenceIndex = 0;
- List popItems(int count) {
- var items = stack.sublist(stack.length - count, stack.length);
- stack.length -= count;
- return items;
- }
-
- for (var operation in expr.operations) {
- switch (operation) {
- case UnlinkedExprOperation.pushString:
- stack.add(expr.strings[stringIndex++]);
- break;
- case UnlinkedExprOperation.invokeConstructor:
- var namedArgumentList = popItems(expr.ints[intIndex++]);
- var namedArguments = <String, dynamic>{};
- for (var namedArgument in namedArgumentList) {
- namedArguments[expr.strings[stringIndex++]] = namedArgument;
- }
- var positionalArguments = popItems(expr.ints[intIndex++]);
- stack.add(_findConstructor(expr.references[referenceIndex++])(
- (i, [defaultValue]) => i < positionalArguments.length
- ? positionalArguments[i]
- : defaultValue,
- (name, [defaultValue]) => namedArguments.containsKey(name)
- ? namedArguments[name]
- : defaultValue));
- break;
- case UnlinkedExprOperation.makeUntypedMap:
- var map = {};
- var numKeyValuePairs = expr.ints[intIndex++];
- var keyValueList = popItems(numKeyValuePairs * 2);
- for (var i = 0; i < numKeyValuePairs; i++) {
- map[keyValueList[2 * i]] = keyValueList[2 * i + 1];
- }
- stack.add(map);
- break;
- case UnlinkedExprOperation.pushReference:
- stack.add(_findReference(expr.references[referenceIndex++]));
- break;
- case UnlinkedExprOperation.pushInt:
- stack.add(expr.ints[intIndex++]);
- break;
- case UnlinkedExprOperation.pushFalse:
- stack.add(false);
- break;
- case UnlinkedExprOperation.pushTrue:
- stack.add(true);
- break;
- case UnlinkedExprOperation.bitOr:
- var y = stack.removeLast();
- var x = stack.removeLast();
- stack.add(x | y);
- break;
- default:
- throw new UnimplementedError(
- 'Unexpected expression in libraries.dart: $operation');
- }
- }
- assert(stringIndex == expr.strings.length);
- assert(intIndex == expr.ints.length);
- assert(referenceIndex == expr.references.length);
- assert(stack.length == 1);
- if (stack[0] == null) {
- throw new StateError('Unexpected null constant in libraries.dart');
- }
- return stack[0];
- }
-}
diff --git a/pub/front_end/lib/src/scanner/errors.dart b/pub/front_end/lib/src/scanner/errors.dart
deleted file mode 100644
index bcf0c56..0000000
--- a/pub/front_end/lib/src/scanner/errors.dart
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:front_end/src/base/errors.dart';
-
-/**
- * The error codes used for errors detected by the scanner.
- */
-class ScannerErrorCode extends ErrorCode {
- /**
- * Parameters:
- * 0: the illegal character
- */
- static const ScannerErrorCode ILLEGAL_CHARACTER =
- const ScannerErrorCode('ILLEGAL_CHARACTER', "Illegal character '{0}'.");
-
- static const ScannerErrorCode MISSING_DIGIT =
- const ScannerErrorCode('MISSING_DIGIT', "Decimal digit expected.");
-
- static const ScannerErrorCode MISSING_HEX_DIGIT = const ScannerErrorCode(
- 'MISSING_HEX_DIGIT', "Hexidecimal digit expected.");
-
- static const ScannerErrorCode MISSING_QUOTE =
- const ScannerErrorCode('MISSING_QUOTE', "Expected quote (' or \").");
-
- /**
- * Parameters:
- * 0: the path of the file that cannot be read
- */
- static const ScannerErrorCode UNABLE_GET_CONTENT = const ScannerErrorCode(
- 'UNABLE_GET_CONTENT', "Unable to get content of '{0}'.");
-
- static const ScannerErrorCode UNTERMINATED_MULTI_LINE_COMMENT =
- const ScannerErrorCode(
- 'UNTERMINATED_MULTI_LINE_COMMENT',
- "Unterminated multi-line comment.",
- "Try terminating the comment with '*/', or "
- "removing any unbalanced occurances of '/*' (because comments nest in Dart).");
-
- static const ScannerErrorCode UNTERMINATED_STRING_LITERAL =
- const ScannerErrorCode(
- 'UNTERMINATED_STRING_LITERAL', "Unterminated string literal.");
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const ScannerErrorCode(String name, String message, [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorSeverity.ERROR;
-
- @override
- ErrorType get type => ErrorType.SYNTACTIC_ERROR;
-}
diff --git a/pub/front_end/lib/src/scanner/interner.dart b/pub/front_end/lib/src/scanner/interner.dart
deleted file mode 100644
index 9f248c9..0000000
--- a/pub/front_end/lib/src/scanner/interner.dart
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/**
- * The interface `Interner` defines the behavior of objects that can intern
- * strings.
- */
-abstract class Interner {
- /**
- * Return a string that is identical to all of the other strings that have
- * been interned that are equal to the given [string].
- */
- String intern(String string);
-}
-
-/**
- * The class `NullInterner` implements an interner that does nothing (does not
- * actually intern any strings).
- */
-class NullInterner implements Interner {
- @override
- String intern(String string) => string;
-}
diff --git a/pub/front_end/lib/src/scanner/reader.dart b/pub/front_end/lib/src/scanner/reader.dart
deleted file mode 100644
index b079139..0000000
--- a/pub/front_end/lib/src/scanner/reader.dart
+++ /dev/null
@@ -1,133 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/**
- * An object used by the scanner to read the characters to be scanned.
- */
-abstract class CharacterReader {
- /**
- * The current offset relative to the beginning of the source. Return the
- * initial offset if the scanner has not yet scanned the source code, and one
- * (1) past the end of the source code if the entire source code has been
- * scanned.
- */
- int get offset;
-
- /**
- * Set the current offset relative to the beginning of the source to the given
- * [offset]. The new offset must be between the initial offset and one (1)
- * past the end of the source code.
- */
- void set offset(int offset);
-
- /**
- * Advance the current position and return the character at the new current
- * position.
- */
- int advance();
-
- /**
- * Return the substring of the source code between the [start] offset and the
- * modified current position. The current position is modified by adding the
- * [endDelta], which is the number of characters after the current location to
- * be included in the string, or the number of characters before the current
- * location to be excluded if the offset is negative.
- */
- String getString(int start, int endDelta);
-
- /**
- * Return the character at the current position without changing the current
- * position.
- */
- int peek();
-}
-
-/**
- * A [CharacterReader] that reads characters from a character sequence.
- */
-class CharSequenceReader implements CharacterReader {
- /**
- * The sequence from which characters will be read.
- */
- final String _sequence;
-
- /**
- * The number of characters in the string.
- */
- int _stringLength;
-
- /**
- * The index, relative to the string, of the next character to be read.
- */
- int _charOffset;
-
- /**
- * Initialize a newly created reader to read the characters in the given
- * [_sequence].
- */
- CharSequenceReader(this._sequence) {
- this._stringLength = _sequence.length;
- this._charOffset = 0;
- }
-
- @override
- int get offset => _charOffset - 1;
-
- @override
- void set offset(int offset) {
- _charOffset = offset + 1;
- }
-
- @override
- int advance() {
- if (_charOffset >= _stringLength) {
- return -1;
- }
- return _sequence.codeUnitAt(_charOffset++);
- }
-
- @override
- String getString(int start, int endDelta) =>
- _sequence.substring(start, _charOffset + endDelta);
-
- @override
- int peek() {
- if (_charOffset >= _stringLength) {
- return -1;
- }
- return _sequence.codeUnitAt(_charOffset);
- }
-}
-
-/**
- * A [CharacterReader] that reads characters from a character sequence, but adds
- * a delta when reporting the current character offset so that the character
- * sequence can be a subsequence from a larger sequence.
- */
-class SubSequenceReader extends CharSequenceReader {
- /**
- * The offset from the beginning of the file to the beginning of the source
- * being scanned.
- */
- final int _offsetDelta;
-
- /**
- * Initialize a newly created reader to read the characters in the given
- * [sequence]. The [_offsetDelta] is the offset from the beginning of the file
- * to the beginning of the source being scanned
- */
- SubSequenceReader(String sequence, this._offsetDelta) : super(sequence);
-
- @override
- int get offset => _offsetDelta + super.offset;
-
- @override
- void set offset(int offset) {
- super.offset = offset - _offsetDelta;
- }
-
- @override
- String getString(int start, int endDelta) =>
- super.getString(start - _offsetDelta, endDelta);
-}
diff --git a/pub/front_end/lib/src/scanner/scanner.dart b/pub/front_end/lib/src/scanner/scanner.dart
deleted file mode 100644
index be259fc..0000000
--- a/pub/front_end/lib/src/scanner/scanner.dart
+++ /dev/null
@@ -1,1341 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:charcode/ascii.dart';
-import 'package:front_end/src/scanner/errors.dart';
-import 'package:front_end/src/scanner/reader.dart';
-import 'package:front_end/src/scanner/string_utilities.dart';
-import 'package:front_end/src/scanner/token.dart';
-
-/**
- * A state in a state machine used to scan keywords.
- */
-class KeywordState {
- /**
- * An empty transition table used by leaf states.
- */
- static List<KeywordState> _EMPTY_TABLE = new List<KeywordState>(26);
-
- /**
- * The initial state in the state machine.
- */
- static final KeywordState KEYWORD_STATE = _createKeywordStateTable();
-
- /**
- * A table mapping characters to the states to which those characters will
- * transition. (The index into the array is the offset from the character
- * `'a'` to the transitioning character.)
- */
- final List<KeywordState> _table;
-
- /**
- * The keyword that is recognized by this state, or `null` if this state is
- * not a terminal state.
- */
- Keyword _keyword;
-
- /**
- * Initialize a newly created state to have the given transitions and to
- * recognize the keyword with the given [syntax].
- */
- KeywordState(this._table, String syntax) {
- this._keyword = (syntax == null) ? null : Keyword.keywords[syntax];
- }
-
- /**
- * Return the keyword that was recognized by this state, or `null` if this
- * state does not recognized a keyword.
- */
- Keyword keyword() => _keyword;
-
- /**
- * Return the state that follows this state on a transition of the given
- * [character], or `null` if there is no valid state reachable from this state
- * with such a transition.
- */
- KeywordState next(int character) => _table[character - $a];
-
- /**
- * Create the next state in the state machine where we have already recognized
- * the subset of strings in the given array of [strings] starting at the given
- * [offset] and having the given [length]. All of these strings have a common
- * prefix and the next character is at the given [start] index.
- */
- static KeywordState _computeKeywordStateTable(
- int start, List<String> strings, int offset, int length) {
- List<KeywordState> result = new List<KeywordState>(26);
- assert(length != 0);
- int chunk = $nul;
- int chunkStart = -1;
- bool isLeaf = false;
- for (int i = offset; i < offset + length; i++) {
- if (strings[i].length == start) {
- isLeaf = true;
- }
- if (strings[i].length > start) {
- int c = strings[i].codeUnitAt(start);
- if (chunk != c) {
- if (chunkStart != -1) {
- result[chunk - $a] = _computeKeywordStateTable(
- start + 1, strings, chunkStart, i - chunkStart);
- }
- chunkStart = i;
- chunk = c;
- }
- }
- }
- if (chunkStart != -1) {
- assert(result[chunk - $a] == null);
- result[chunk - $a] = _computeKeywordStateTable(
- start + 1, strings, chunkStart, offset + length - chunkStart);
- } else {
- assert(length == 1);
- return new KeywordState(_EMPTY_TABLE, strings[offset]);
- }
- if (isLeaf) {
- return new KeywordState(result, strings[offset]);
- } else {
- return new KeywordState(result, null);
- }
- }
-
- /**
- * Create and return the initial state in the state machine.
- */
- static KeywordState _createKeywordStateTable() {
- List<Keyword> values = Keyword.values;
- List<String> strings = new List<String>(values.length);
- for (int i = 0; i < values.length; i++) {
- strings[i] = values[i].syntax;
- }
- strings.sort();
- return _computeKeywordStateTable(0, strings, 0, strings.length);
- }
-}
-
-/**
- * The class `Scanner` implements a scanner for Dart code.
- *
- * The lexical structure of Dart is ambiguous without knowledge of the context
- * in which a token is being scanned. For example, without context we cannot
- * determine whether source of the form "<<" should be scanned as a single
- * left-shift operator or as two left angle brackets. This scanner does not have
- * any context, so it always resolves such conflicts by scanning the longest
- * possible token.
- */
-abstract class Scanner {
- /**
- * The reader used to access the characters in the source.
- */
- final CharacterReader _reader;
-
- /**
- * The flag specifying whether documentation comments should be parsed.
- */
- bool _preserveComments = true;
-
- /**
- * The token pointing to the head of the linked list of tokens.
- */
- Token _tokens;
-
- /**
- * The last token that was scanned.
- */
- Token _tail;
-
- /**
- * The first token in the list of comment tokens found since the last
- * non-comment token.
- */
- Token _firstComment;
-
- /**
- * The last token in the list of comment tokens found since the last
- * non-comment token.
- */
- Token _lastComment;
-
- /**
- * The index of the first character of the current token.
- */
- int _tokenStart = 0;
-
- /**
- * A list containing the offsets of the first character of each line in the
- * source code.
- */
- List<int> _lineStarts = new List<int>();
-
- /**
- * A list, treated something like a stack, of tokens representing the
- * beginning of a matched pair. It is used to pair the end tokens with the
- * begin tokens.
- */
- List<BeginToken> _groupingStack = new List<BeginToken>();
-
- /**
- * The index of the last item in the [_groupingStack], or `-1` if the stack is
- * empty.
- */
- int _stackEnd = -1;
-
- /**
- * A flag indicating whether any unmatched groups were found during the parse.
- */
- bool _hasUnmatchedGroups = false;
-
- /**
- * A flag indicating whether to parse generic method comments, of the form
- * `/*=T*/` and `/*<T>*/`.
- */
- bool scanGenericMethodComments = false;
-
- /**
- * A flag indicating whether the lazy compound assignment operators '&&=' and
- * '||=' are enabled.
- */
- bool scanLazyAssignmentOperators = false;
-
- /**
- * Initialize a newly created scanner to scan characters from the given
- * character [_reader].
- */
- Scanner(this._reader) {
- _tokens = new Token(TokenType.EOF, -1);
- _tokens.setNext(_tokens);
- _tail = _tokens;
- _tokenStart = -1;
- _lineStarts.add(0);
- }
-
- /**
- * Return the first token in the token stream that was scanned.
- */
- Token get firstToken => _tokens.next;
-
- /**
- * Return `true` if any unmatched groups were found during the parse.
- */
- bool get hasUnmatchedGroups => _hasUnmatchedGroups;
-
- /**
- * Return an array containing the offsets of the first character of each line
- * in the source code.
- */
- List<int> get lineStarts => _lineStarts;
-
- /**
- * Set whether documentation tokens should be preserved.
- */
- void set preserveComments(bool preserveComments) {
- this._preserveComments = preserveComments;
- }
-
- /**
- * Return the last token that was scanned.
- */
- Token get tail => _tail;
-
- /**
- * Append the given [token] to the end of the token stream being scanned. This
- * method is intended to be used by subclasses that copy existing tokens and
- * should not normally be used because it will fail to correctly associate any
- * comments with the token being passed in.
- */
- void appendToken(Token token) {
- _tail = _tail.setNext(token);
- }
-
- int bigSwitch(int next) {
- _beginToken();
- if (next == $cr) {
- // '\r'
- next = _reader.advance();
- if (next == $lf) {
- // '\n'
- next = _reader.advance();
- }
- recordStartOfLine();
- return next;
- } else if (next == $lf) {
- // '\n'
- next = _reader.advance();
- recordStartOfLine();
- return next;
- } else if (next == $tab || next == $space) {
- // '\t' || ' '
- return _reader.advance();
- }
- if (next == $r) {
- // 'r'
- int peek = _reader.peek();
- if (peek == $double_quote || peek == $single_quote) {
- // '"' || "'"
- int start = _reader.offset;
- return _tokenizeString(_reader.advance(), start, true);
- }
- }
- if ($a <= next && next <= $z) {
- // 'a'-'z'
- return _tokenizeKeywordOrIdentifier(next, true);
- }
- if (($A <= next && next <= $Z) || next == $_ || next == $$) {
- // 'A'-'Z' || '_' || '$'
- return _tokenizeIdentifier(next, _reader.offset, true);
- }
- if (next == $lt) {
- // '<'
- return _tokenizeLessThan(next);
- }
- if (next == $gt) {
- // '>'
- return _tokenizeGreaterThan(next);
- }
- if (next == $equal) {
- // '='
- return _tokenizeEquals(next);
- }
- if (next == $exclamation) {
- // '!'
- return _tokenizeExclamation(next);
- }
- if (next == $plus) {
- // '+'
- return _tokenizePlus(next);
- }
- if (next == $minus) {
- // '-'
- return _tokenizeMinus(next);
- }
- if (next == $asterisk) {
- // '*'
- return _tokenizeMultiply(next);
- }
- if (next == $percent) {
- // '%'
- return _tokenizePercent(next);
- }
- if (next == $ampersand) {
- // '&'
- return _tokenizeAmpersand(next);
- }
- if (next == $bar) {
- // '|'
- return _tokenizeBar(next);
- }
- if (next == $caret) {
- // '^'
- return _tokenizeCaret(next);
- }
- if (next == $open_bracket) {
- // '['
- return _tokenizeOpenSquareBracket(next);
- }
- if (next == $tilde) {
- // '~'
- return _tokenizeTilde(next);
- }
- if (next == $backslash) {
- // '\\'
- _appendTokenOfType(TokenType.BACKSLASH);
- return _reader.advance();
- }
- if (next == $hash) {
- // '#'
- return _tokenizeTag(next);
- }
- if (next == $open_paren) {
- // '('
- _appendBeginToken(TokenType.OPEN_PAREN);
- return _reader.advance();
- }
- if (next == $close_paren) {
- // ')'
- _appendEndToken(TokenType.CLOSE_PAREN, TokenType.OPEN_PAREN);
- return _reader.advance();
- }
- if (next == $comma) {
- // ','
- _appendTokenOfType(TokenType.COMMA);
- return _reader.advance();
- }
- if (next == $colon) {
- // ':'
- _appendTokenOfType(TokenType.COLON);
- return _reader.advance();
- }
- if (next == $semicolon) {
- // ';'
- _appendTokenOfType(TokenType.SEMICOLON);
- return _reader.advance();
- }
- if (next == $question) {
- // '?'
- return _tokenizeQuestion();
- }
- if (next == $close_bracket) {
- // ']'
- _appendEndToken(
- TokenType.CLOSE_SQUARE_BRACKET, TokenType.OPEN_SQUARE_BRACKET);
- return _reader.advance();
- }
- if (next == $backquote) {
- // '`'
- _appendTokenOfType(TokenType.BACKPING);
- return _reader.advance();
- }
- if (next == $lbrace) {
- // '{'
- _appendBeginToken(TokenType.OPEN_CURLY_BRACKET);
- return _reader.advance();
- }
- if (next == $rbrace) {
- // '}'
- _appendEndToken(
- TokenType.CLOSE_CURLY_BRACKET, TokenType.OPEN_CURLY_BRACKET);
- return _reader.advance();
- }
- if (next == $slash) {
- // '/'
- return _tokenizeSlashOrComment(next);
- }
- if (next == $at) {
- // '@'
- _appendTokenOfType(TokenType.AT);
- return _reader.advance();
- }
- if (next == $double_quote || next == $single_quote) {
- // '"' || "'"
- return _tokenizeString(next, _reader.offset, false);
- }
- if (next == $dot) {
- // '.'
- return _tokenizeDotOrNumber(next);
- }
- if (next == $0) {
- // '0'
- return _tokenizeHexOrNumber(next);
- }
- if ($1 <= next && next <= $9) {
- // '1'-'9'
- return _tokenizeNumber(next);
- }
- if (next == -1) {
- // EOF
- return -1;
- }
- _reportError(ScannerErrorCode.ILLEGAL_CHARACTER, [next]);
- return _reader.advance();
- }
-
- /**
- * Record the fact that we are at the beginning of a new line in the source.
- */
- void recordStartOfLine() {
- _lineStarts.add(_reader.offset);
- }
-
- /**
- * Report an error at the given offset. The [errorCode] is the error code
- * indicating the nature of the error. The [arguments] are any arguments
- * needed to complete the error message
- */
- void reportError(
- ScannerErrorCode errorCode, int offset, List<Object> arguments);
-
- /**
- * Record that the source begins on the given [line] and [column] at the
- * current offset as given by the reader. Both the line and the column are
- * one-based indexes. The line starts for lines before the given line will not
- * be correct.
- *
- * This method must be invoked at most one time and must be invoked before
- * scanning begins. The values provided must be sensible. The results are
- * undefined if these conditions are violated.
- */
- void setSourceStart(int line, int column) {
- int offset = _reader.offset;
- if (line < 1 || column < 1 || offset < 0 || (line + column - 2) >= offset) {
- return;
- }
- for (int i = 2; i < line; i++) {
- _lineStarts.add(1);
- }
- _lineStarts.add(offset - column + 1);
- }
-
- /**
- * Scan the source code to produce a list of tokens representing the source,
- * and return the first token in the list of tokens that were produced.
- */
- Token tokenize() {
- int next = _reader.advance();
- while (next != -1) {
- next = bigSwitch(next);
- }
- _appendEofToken();
- return firstToken;
- }
-
- void _appendBeginToken(TokenType type) {
- BeginToken token;
- if (_firstComment == null) {
- token = new BeginToken(type, _tokenStart);
- } else {
- token = new BeginTokenWithComment(type, _tokenStart, _firstComment);
- _firstComment = null;
- _lastComment = null;
- }
- _tail = _tail.setNext(token);
- _groupingStack.add(token);
- _stackEnd++;
- }
-
- void _appendCommentToken(TokenType type, String value) {
- CommentToken token = null;
- TokenType genericComment = _matchGenericMethodCommentType(value);
- if (genericComment != null) {
- token = new CommentToken(genericComment, value, _tokenStart);
- } else if (!_preserveComments) {
- // Ignore comment tokens if client specified that it doesn't need them.
- return;
- } else {
- // OK, remember comment tokens.
- if (_isDocumentationComment(value)) {
- token = new DocumentationCommentToken(type, value, _tokenStart);
- } else {
- token = new CommentToken(type, value, _tokenStart);
- }
- }
- if (_firstComment == null) {
- _firstComment = token;
- _lastComment = _firstComment;
- } else {
- _lastComment = _lastComment.setNext(token);
- }
- }
-
- void _appendEndToken(TokenType type, TokenType beginType) {
- Token token;
- if (_firstComment == null) {
- token = new Token(type, _tokenStart);
- } else {
- token = new TokenWithComment(type, _tokenStart, _firstComment);
- _firstComment = null;
- _lastComment = null;
- }
- _tail = _tail.setNext(token);
- if (_stackEnd >= 0) {
- BeginToken begin = _groupingStack[_stackEnd];
- if (begin.type == beginType) {
- begin.endToken = token;
- _groupingStack.removeAt(_stackEnd--);
- }
- }
- }
-
- void _appendEofToken() {
- Token eofToken;
- if (_firstComment == null) {
- eofToken = new Token(TokenType.EOF, _reader.offset + 1);
- } else {
- eofToken = new TokenWithComment(
- TokenType.EOF, _reader.offset + 1, _firstComment);
- _firstComment = null;
- _lastComment = null;
- }
- // The EOF token points to itself so that there is always infinite
- // look-ahead.
- eofToken.setNext(eofToken);
- _tail = _tail.setNext(eofToken);
- if (_stackEnd >= 0) {
- _hasUnmatchedGroups = true;
- // TODO(brianwilkerson) Fix the ungrouped tokens?
- }
- }
-
- void _appendKeywordToken(Keyword keyword) {
- if (_firstComment == null) {
- _tail = _tail.setNext(new KeywordToken(keyword, _tokenStart));
- } else {
- _tail = _tail.setNext(
- new KeywordTokenWithComment(keyword, _tokenStart, _firstComment));
- _firstComment = null;
- _lastComment = null;
- }
- }
-
- void _appendStringToken(TokenType type, String value) {
- if (_firstComment == null) {
- _tail = _tail.setNext(new StringToken(type, value, _tokenStart));
- } else {
- _tail = _tail.setNext(
- new StringTokenWithComment(type, value, _tokenStart, _firstComment));
- _firstComment = null;
- _lastComment = null;
- }
- }
-
- void _appendStringTokenWithOffset(TokenType type, String value, int offset) {
- if (_firstComment == null) {
- _tail = _tail.setNext(new StringToken(type, value, _tokenStart + offset));
- } else {
- _tail = _tail.setNext(new StringTokenWithComment(
- type, value, _tokenStart + offset, _firstComment));
- _firstComment = null;
- _lastComment = null;
- }
- }
-
- void _appendTokenOfType(TokenType type) {
- if (_firstComment == null) {
- _tail = _tail.setNext(new Token(type, _tokenStart));
- } else {
- _tail =
- _tail.setNext(new TokenWithComment(type, _tokenStart, _firstComment));
- _firstComment = null;
- _lastComment = null;
- }
- }
-
- void _appendTokenOfTypeWithOffset(TokenType type, int offset) {
- if (_firstComment == null) {
- _tail = _tail.setNext(new Token(type, offset));
- } else {
- _tail = _tail.setNext(new TokenWithComment(type, offset, _firstComment));
- _firstComment = null;
- _lastComment = null;
- }
- }
-
- void _beginToken() {
- _tokenStart = _reader.offset;
- }
-
- /**
- * Return the beginning token corresponding to a closing brace that was found
- * while scanning inside a string interpolation expression. Tokens that cannot
- * be matched with the closing brace will be dropped from the stack.
- */
- BeginToken _findTokenMatchingClosingBraceInInterpolationExpression() {
- while (_stackEnd >= 0) {
- BeginToken begin = _groupingStack[_stackEnd];
- if (begin.type == TokenType.OPEN_CURLY_BRACKET ||
- begin.type == TokenType.STRING_INTERPOLATION_EXPRESSION) {
- return begin;
- }
- _hasUnmatchedGroups = true;
- _groupingStack.removeAt(_stackEnd--);
- }
- //
- // We should never get to this point because we wouldn't be inside a string
- // interpolation expression unless we had previously found the start of the
- // expression.
- //
- return null;
- }
-
- /**
- * Checks if [value] is the start of a generic method type annotation comment.
- *
- * This can either be of the form `/*<T>*/` or `/*=T*/`. The token type is
- * returned, or null if it was not a generic method comment.
- */
- TokenType _matchGenericMethodCommentType(String value) {
- if (scanGenericMethodComments) {
- // Match /*< and >*/
- if (StringUtilities.startsWith3(value, 0, $slash, $asterisk, $lt) &&
- StringUtilities.endsWith3(value, $gt, $asterisk, $slash)) {
- return TokenType.GENERIC_METHOD_TYPE_LIST;
- }
- // Match /*=
- if (StringUtilities.startsWith3(value, 0, $slash, $asterisk, $equal)) {
- return TokenType.GENERIC_METHOD_TYPE_ASSIGN;
- }
- }
- return null;
- }
-
- /**
- * Report an error at the current offset. The [errorCode] is the error code
- * indicating the nature of the error. The [arguments] are any arguments
- * needed to complete the error message
- */
- void _reportError(ScannerErrorCode errorCode, [List<Object> arguments]) {
- reportError(errorCode, _reader.offset, arguments);
- }
-
- int _select(int choice, TokenType yesType, TokenType noType) {
- int next = _reader.advance();
- if (next == choice) {
- _appendTokenOfType(yesType);
- return _reader.advance();
- } else {
- _appendTokenOfType(noType);
- return next;
- }
- }
-
- int _selectWithOffset(
- int choice, TokenType yesType, TokenType noType, int offset) {
- int next = _reader.advance();
- if (next == choice) {
- _appendTokenOfTypeWithOffset(yesType, offset);
- return _reader.advance();
- } else {
- _appendTokenOfTypeWithOffset(noType, offset);
- return next;
- }
- }
-
- int _tokenizeAmpersand(int next) {
- // &&= && &= &
- next = _reader.advance();
- if (next == $ampersand) {
- next = _reader.advance();
- if (scanLazyAssignmentOperators && next == $equal) {
- _appendTokenOfType(TokenType.AMPERSAND_AMPERSAND_EQ);
- return _reader.advance();
- }
- _appendTokenOfType(TokenType.AMPERSAND_AMPERSAND);
- return next;
- } else if (next == $equal) {
- _appendTokenOfType(TokenType.AMPERSAND_EQ);
- return _reader.advance();
- } else {
- _appendTokenOfType(TokenType.AMPERSAND);
- return next;
- }
- }
-
- int _tokenizeBar(int next) {
- // ||= || |= |
- next = _reader.advance();
- if (next == $bar) {
- next = _reader.advance();
- if (scanLazyAssignmentOperators && next == $equal) {
- _appendTokenOfType(TokenType.BAR_BAR_EQ);
- return _reader.advance();
- }
- _appendTokenOfType(TokenType.BAR_BAR);
- return next;
- } else if (next == $equal) {
- _appendTokenOfType(TokenType.BAR_EQ);
- return _reader.advance();
- } else {
- _appendTokenOfType(TokenType.BAR);
- return next;
- }
- }
-
- int _tokenizeCaret(int next) =>
- _select($equal, TokenType.CARET_EQ, TokenType.CARET);
-
- int _tokenizeDotOrNumber(int next) {
- int start = _reader.offset;
- next = _reader.advance();
- if ($0 <= next && next <= $9) {
- return _tokenizeFractionPart(next, start);
- } else if ($dot == next) {
- return _select(
- $dot, TokenType.PERIOD_PERIOD_PERIOD, TokenType.PERIOD_PERIOD);
- } else {
- _appendTokenOfType(TokenType.PERIOD);
- return next;
- }
- }
-
- int _tokenizeEquals(int next) {
- // = == =>
- next = _reader.advance();
- if (next == $equal) {
- _appendTokenOfType(TokenType.EQ_EQ);
- return _reader.advance();
- } else if (next == $gt) {
- _appendTokenOfType(TokenType.FUNCTION);
- return _reader.advance();
- }
- _appendTokenOfType(TokenType.EQ);
- return next;
- }
-
- int _tokenizeExclamation(int next) {
- // ! !=
- next = _reader.advance();
- if (next == $equal) {
- _appendTokenOfType(TokenType.BANG_EQ);
- return _reader.advance();
- }
- _appendTokenOfType(TokenType.BANG);
- return next;
- }
-
- int _tokenizeExponent(int next) {
- if (next == $plus || next == $minus) {
- next = _reader.advance();
- }
- bool hasDigits = false;
- while (true) {
- if ($0 <= next && next <= $9) {
- hasDigits = true;
- } else {
- if (!hasDigits) {
- _reportError(ScannerErrorCode.MISSING_DIGIT);
- }
- return next;
- }
- next = _reader.advance();
- }
- }
-
- int _tokenizeFractionPart(int next, int start) {
- bool done = false;
- bool hasDigit = false;
- LOOP:
- while (!done) {
- if ($0 <= next && next <= $9) {
- hasDigit = true;
- } else if ($e == next || $E == next) {
- hasDigit = true;
- next = _tokenizeExponent(_reader.advance());
- done = true;
- continue LOOP;
- } else {
- done = true;
- continue LOOP;
- }
- next = _reader.advance();
- }
- if (!hasDigit) {
- _appendStringToken(TokenType.INT, _reader.getString(start, -2));
- if ($dot == next) {
- return _selectWithOffset($dot, TokenType.PERIOD_PERIOD_PERIOD,
- TokenType.PERIOD_PERIOD, _reader.offset - 1);
- }
- _appendTokenOfTypeWithOffset(TokenType.PERIOD, _reader.offset - 1);
- return bigSwitch(next);
- }
- _appendStringToken(
- TokenType.DOUBLE, _reader.getString(start, next < 0 ? 0 : -1));
- return next;
- }
-
- int _tokenizeGreaterThan(int next) {
- // > >= >> >>=
- next = _reader.advance();
- if ($equal == next) {
- _appendTokenOfType(TokenType.GT_EQ);
- return _reader.advance();
- } else if ($gt == next) {
- next = _reader.advance();
- if ($equal == next) {
- _appendTokenOfType(TokenType.GT_GT_EQ);
- return _reader.advance();
- } else {
- _appendTokenOfType(TokenType.GT_GT);
- return next;
- }
- } else {
- _appendTokenOfType(TokenType.GT);
- return next;
- }
- }
-
- int _tokenizeHex(int next) {
- int start = _reader.offset - 1;
- bool hasDigits = false;
- while (true) {
- next = _reader.advance();
- if (($0 <= next && next <= $9) ||
- ($A <= next && next <= $F) ||
- ($a <= next && next <= $f)) {
- hasDigits = true;
- } else {
- if (!hasDigits) {
- _reportError(ScannerErrorCode.MISSING_HEX_DIGIT);
- }
- _appendStringToken(
- TokenType.HEXADECIMAL, _reader.getString(start, next < 0 ? 0 : -1));
- return next;
- }
- }
- }
-
- int _tokenizeHexOrNumber(int next) {
- int x = _reader.peek();
- if (x == $x || x == $X) {
- _reader.advance();
- return _tokenizeHex(x);
- }
- return _tokenizeNumber(next);
- }
-
- int _tokenizeIdentifier(int next, int start, bool allowDollar) {
- while (($a <= next && next <= $z) ||
- ($A <= next && next <= $Z) ||
- ($0 <= next && next <= $9) ||
- next == $_ ||
- (next == $$ && allowDollar)) {
- next = _reader.advance();
- }
- _appendStringToken(
- TokenType.IDENTIFIER, _reader.getString(start, next < 0 ? 0 : -1));
- return next;
- }
-
- int _tokenizeInterpolatedExpression(int next, int start) {
- _appendBeginToken(TokenType.STRING_INTERPOLATION_EXPRESSION);
- next = _reader.advance();
- while (next != -1) {
- if (next == $rbrace) {
- BeginToken begin =
- _findTokenMatchingClosingBraceInInterpolationExpression();
- if (begin == null) {
- _beginToken();
- _appendTokenOfType(TokenType.CLOSE_CURLY_BRACKET);
- next = _reader.advance();
- _beginToken();
- return next;
- } else if (begin.type == TokenType.OPEN_CURLY_BRACKET) {
- _beginToken();
- _appendEndToken(
- TokenType.CLOSE_CURLY_BRACKET, TokenType.OPEN_CURLY_BRACKET);
- next = _reader.advance();
- _beginToken();
- } else if (begin.type == TokenType.STRING_INTERPOLATION_EXPRESSION) {
- _beginToken();
- _appendEndToken(TokenType.CLOSE_CURLY_BRACKET,
- TokenType.STRING_INTERPOLATION_EXPRESSION);
- next = _reader.advance();
- _beginToken();
- return next;
- }
- } else {
- next = bigSwitch(next);
- }
- }
- return next;
- }
-
- int _tokenizeInterpolatedIdentifier(int next, int start) {
- _appendStringTokenWithOffset(
- TokenType.STRING_INTERPOLATION_IDENTIFIER, "\$", 0);
- if (($A <= next && next <= $Z) ||
- ($a <= next && next <= $z) ||
- next == $_) {
- _beginToken();
- next = _tokenizeKeywordOrIdentifier(next, false);
- }
- _beginToken();
- return next;
- }
-
- int _tokenizeKeywordOrIdentifier(int next, bool allowDollar) {
- KeywordState state = KeywordState.KEYWORD_STATE;
- int start = _reader.offset;
- while (state != null && $a <= next && next <= $z) {
- state = state.next(next);
- next = _reader.advance();
- }
- if (state == null || state.keyword() == null) {
- return _tokenizeIdentifier(next, start, allowDollar);
- }
- if (($A <= next && next <= $Z) ||
- ($0 <= next && next <= $9) ||
- next == $_ ||
- next == $$) {
- return _tokenizeIdentifier(next, start, allowDollar);
- } else if (next < 128) {
- _appendKeywordToken(state.keyword());
- return next;
- } else {
- return _tokenizeIdentifier(next, start, allowDollar);
- }
- }
-
- int _tokenizeLessThan(int next) {
- // < <= << <<=
- next = _reader.advance();
- if ($equal == next) {
- _appendTokenOfType(TokenType.LT_EQ);
- return _reader.advance();
- } else if ($lt == next) {
- return _select($equal, TokenType.LT_LT_EQ, TokenType.LT_LT);
- } else {
- _appendTokenOfType(TokenType.LT);
- return next;
- }
- }
-
- int _tokenizeMinus(int next) {
- // - -- -=
- next = _reader.advance();
- if (next == $minus) {
- _appendTokenOfType(TokenType.MINUS_MINUS);
- return _reader.advance();
- } else if (next == $equal) {
- _appendTokenOfType(TokenType.MINUS_EQ);
- return _reader.advance();
- } else {
- _appendTokenOfType(TokenType.MINUS);
- return next;
- }
- }
-
- int _tokenizeMultiLineComment(int next) {
- int nesting = 1;
- next = _reader.advance();
- while (true) {
- if (-1 == next) {
- _reportError(ScannerErrorCode.UNTERMINATED_MULTI_LINE_COMMENT);
- _appendCommentToken(
- TokenType.MULTI_LINE_COMMENT, _reader.getString(_tokenStart, 0));
- return next;
- } else if ($asterisk == next) {
- next = _reader.advance();
- if ($slash == next) {
- --nesting;
- if (0 == nesting) {
- _appendCommentToken(TokenType.MULTI_LINE_COMMENT,
- _reader.getString(_tokenStart, 0));
- return _reader.advance();
- } else {
- next = _reader.advance();
- }
- }
- } else if ($slash == next) {
- next = _reader.advance();
- if ($asterisk == next) {
- next = _reader.advance();
- ++nesting;
- }
- } else if (next == $cr) {
- next = _reader.advance();
- if (next == $lf) {
- next = _reader.advance();
- }
- recordStartOfLine();
- } else if (next == $lf) {
- next = _reader.advance();
- recordStartOfLine();
- } else {
- next = _reader.advance();
- }
- }
- }
-
- int _tokenizeMultiLineRawString(int quoteChar, int start) {
- int next = _reader.advance();
- outer:
- while (next != -1) {
- while (next != quoteChar) {
- if (next == -1) {
- break outer;
- } else if (next == $cr) {
- next = _reader.advance();
- if (next == $lf) {
- next = _reader.advance();
- }
- recordStartOfLine();
- } else if (next == $lf) {
- next = _reader.advance();
- recordStartOfLine();
- } else {
- next = _reader.advance();
- }
- }
- next = _reader.advance();
- if (next == quoteChar) {
- next = _reader.advance();
- if (next == quoteChar) {
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- return _reader.advance();
- }
- }
- }
- _reportError(ScannerErrorCode.UNTERMINATED_STRING_LITERAL);
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- return _reader.advance();
- }
-
- int _tokenizeMultiLineString(int quoteChar, int start, bool raw) {
- if (raw) {
- return _tokenizeMultiLineRawString(quoteChar, start);
- }
- int next = _reader.advance();
- while (next != -1) {
- if (next == $$) {
- _appendStringToken(TokenType.STRING, _reader.getString(start, -1));
- next = _tokenizeStringInterpolation(start);
- _beginToken();
- start = _reader.offset;
- continue;
- }
- if (next == quoteChar) {
- next = _reader.advance();
- if (next == quoteChar) {
- next = _reader.advance();
- if (next == quoteChar) {
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- return _reader.advance();
- }
- }
- continue;
- }
- if (next == $backslash) {
- next = _reader.advance();
- if (next == -1) {
- break;
- }
- if (next == $cr) {
- next = _reader.advance();
- if (next == $lf) {
- next = _reader.advance();
- }
- recordStartOfLine();
- } else if (next == $lf) {
- recordStartOfLine();
- next = _reader.advance();
- } else {
- next = _reader.advance();
- }
- } else if (next == $cr) {
- next = _reader.advance();
- if (next == $lf) {
- next = _reader.advance();
- }
- recordStartOfLine();
- } else if (next == $lf) {
- recordStartOfLine();
- next = _reader.advance();
- } else {
- next = _reader.advance();
- }
- }
- _reportError(ScannerErrorCode.UNTERMINATED_STRING_LITERAL);
- if (start == _reader.offset) {
- _appendStringTokenWithOffset(TokenType.STRING, "", 1);
- } else {
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- }
- return _reader.advance();
- }
-
- int _tokenizeMultiply(int next) =>
- _select($equal, TokenType.STAR_EQ, TokenType.STAR);
-
- int _tokenizeNumber(int next) {
- int start = _reader.offset;
- while (true) {
- next = _reader.advance();
- if ($0 <= next && next <= $9) {
- continue;
- } else if (next == $dot) {
- return _tokenizeFractionPart(_reader.advance(), start);
- } else if (next == $e || next == $E) {
- return _tokenizeFractionPart(next, start);
- } else {
- _appendStringToken(
- TokenType.INT, _reader.getString(start, next < 0 ? 0 : -1));
- return next;
- }
- }
- }
-
- int _tokenizeOpenSquareBracket(int next) {
- // [ [] []=
- next = _reader.advance();
- if (next == $close_bracket) {
- return _select($equal, TokenType.INDEX_EQ, TokenType.INDEX);
- } else {
- _appendBeginToken(TokenType.OPEN_SQUARE_BRACKET);
- return next;
- }
- }
-
- int _tokenizePercent(int next) =>
- _select($equal, TokenType.PERCENT_EQ, TokenType.PERCENT);
-
- int _tokenizePlus(int next) {
- // + ++ +=
- next = _reader.advance();
- if ($plus == next) {
- _appendTokenOfType(TokenType.PLUS_PLUS);
- return _reader.advance();
- } else if ($equal == next) {
- _appendTokenOfType(TokenType.PLUS_EQ);
- return _reader.advance();
- } else {
- _appendTokenOfType(TokenType.PLUS);
- return next;
- }
- }
-
- int _tokenizeQuestion() {
- // ? ?. ?? ??=
- int next = _reader.advance();
- if (next == $dot) {
- // '.'
- _appendTokenOfType(TokenType.QUESTION_PERIOD);
- return _reader.advance();
- } else if (next == $question) {
- // '?'
- next = _reader.advance();
- if (next == $equal) {
- // '='
- _appendTokenOfType(TokenType.QUESTION_QUESTION_EQ);
- return _reader.advance();
- } else {
- _appendTokenOfType(TokenType.QUESTION_QUESTION);
- return next;
- }
- } else {
- _appendTokenOfType(TokenType.QUESTION);
- return next;
- }
- }
-
- int _tokenizeSingleLineComment(int next) {
- while (true) {
- next = _reader.advance();
- if (-1 == next) {
- _appendCommentToken(
- TokenType.SINGLE_LINE_COMMENT, _reader.getString(_tokenStart, 0));
- return next;
- } else if ($lf == next || $cr == next) {
- _appendCommentToken(
- TokenType.SINGLE_LINE_COMMENT, _reader.getString(_tokenStart, -1));
- return next;
- }
- }
- }
-
- int _tokenizeSingleLineRawString(int next, int quoteChar, int start) {
- next = _reader.advance();
- while (next != -1) {
- if (next == quoteChar) {
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- return _reader.advance();
- } else if (next == $cr || next == $lf) {
- _reportError(ScannerErrorCode.UNTERMINATED_STRING_LITERAL);
- _appendStringToken(TokenType.STRING, _reader.getString(start, -1));
- return _reader.advance();
- }
- next = _reader.advance();
- }
- _reportError(ScannerErrorCode.UNTERMINATED_STRING_LITERAL);
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- return _reader.advance();
- }
-
- int _tokenizeSingleLineString(int next, int quoteChar, int start) {
- while (next != quoteChar) {
- if (next == $backslash) {
- next = _reader.advance();
- } else if (next == $$) {
- _appendStringToken(TokenType.STRING, _reader.getString(start, -1));
- next = _tokenizeStringInterpolation(start);
- _beginToken();
- start = _reader.offset;
- continue;
- }
- if (next <= $cr && (next == $lf || next == $cr || next == -1)) {
- _reportError(ScannerErrorCode.UNTERMINATED_STRING_LITERAL);
- if (start == _reader.offset) {
- _appendStringTokenWithOffset(TokenType.STRING, "", 1);
- } else if (next == -1) {
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- } else {
- _appendStringToken(TokenType.STRING, _reader.getString(start, -1));
- }
- return _reader.advance();
- }
- next = _reader.advance();
- }
- _appendStringToken(TokenType.STRING, _reader.getString(start, 0));
- return _reader.advance();
- }
-
- int _tokenizeSlashOrComment(int next) {
- next = _reader.advance();
- if ($asterisk == next) {
- return _tokenizeMultiLineComment(next);
- } else if ($slash == next) {
- return _tokenizeSingleLineComment(next);
- } else if ($equal == next) {
- _appendTokenOfType(TokenType.SLASH_EQ);
- return _reader.advance();
- } else {
- _appendTokenOfType(TokenType.SLASH);
- return next;
- }
- }
-
- int _tokenizeString(int next, int start, bool raw) {
- int quoteChar = next;
- next = _reader.advance();
- if (quoteChar == next) {
- next = _reader.advance();
- if (quoteChar == next) {
- // Multiline string.
- return _tokenizeMultiLineString(quoteChar, start, raw);
- } else {
- // Empty string.
- _appendStringToken(TokenType.STRING, _reader.getString(start, -1));
- return next;
- }
- }
- if (raw) {
- return _tokenizeSingleLineRawString(next, quoteChar, start);
- } else {
- return _tokenizeSingleLineString(next, quoteChar, start);
- }
- }
-
- int _tokenizeStringInterpolation(int start) {
- _beginToken();
- int next = _reader.advance();
- if (next == $lbrace) {
- return _tokenizeInterpolatedExpression(next, start);
- } else {
- return _tokenizeInterpolatedIdentifier(next, start);
- }
- }
-
- int _tokenizeTag(int next) {
- // # or #!.*[\n\r]
- if (_reader.offset == 0) {
- if (_reader.peek() == $exclamation) {
- do {
- next = _reader.advance();
- } while (next != $lf && next != $cr && next > 0);
- _appendStringToken(
- TokenType.SCRIPT_TAG, _reader.getString(_tokenStart, 0));
- return next;
- }
- }
- _appendTokenOfType(TokenType.HASH);
- return _reader.advance();
- }
-
- int _tokenizeTilde(int next) {
- // ~ ~/ ~/=
- next = _reader.advance();
- if (next == $slash) {
- return _select($equal, TokenType.TILDE_SLASH_EQ, TokenType.TILDE_SLASH);
- } else {
- _appendTokenOfType(TokenType.TILDE);
- return next;
- }
- }
-
- /**
- * Checks if [value] is a single-line or multi-line comment.
- */
- static bool _isDocumentationComment(String value) {
- return StringUtilities.startsWith3(value, 0, $slash, $slash, $slash) ||
- StringUtilities.startsWith3(value, 0, $slash, $asterisk, $asterisk);
- }
-}
diff --git a/pub/front_end/lib/src/scanner/string_utilities.dart b/pub/front_end/lib/src/scanner/string_utilities.dart
deleted file mode 100644
index 8387923..0000000
--- a/pub/front_end/lib/src/scanner/string_utilities.dart
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:front_end/src/scanner/interner.dart';
-
-class StringUtilities {
- static Interner INTERNER = new NullInterner();
-
- static bool endsWith3(String str, int c1, int c2, int c3) {
- var length = str.length;
- return length >= 3 &&
- str.codeUnitAt(length - 3) == c1 &&
- str.codeUnitAt(length - 2) == c2 &&
- str.codeUnitAt(length - 1) == c3;
- }
-
- static String intern(String string) => INTERNER.intern(string);
-
- static bool startsWith3(String str, int start, int c1, int c2, int c3) {
- return str.length - start >= 3 &&
- str.codeUnitAt(start) == c1 &&
- str.codeUnitAt(start + 1) == c2 &&
- str.codeUnitAt(start + 2) == c3;
- }
-}
diff --git a/pub/front_end/lib/src/scanner/token.dart b/pub/front_end/lib/src/scanner/token.dart
deleted file mode 100644
index abd0194..0000000
--- a/pub/front_end/lib/src/scanner/token.dart
+++ /dev/null
@@ -1,1297 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/**
- * Defines the tokens that are produced by the scanner, used by the parser, and
- * referenced from the [AST structure](ast.dart).
- */
-import 'dart:collection';
-
-import 'package:front_end/src/base/syntactic_entity.dart';
-import 'package:front_end/src/scanner/string_utilities.dart';
-
-/**
- * The opening half of a grouping pair of tokens. This is used for curly
- * brackets ('{'), parentheses ('('), and square brackets ('[').
- */
-class BeginToken extends SimpleToken {
- /**
- * The token that corresponds to this token.
- */
- Token endToken;
-
- /**
- * Initialize a newly created token to have the given [type] at the given
- * [offset].
- */
- BeginToken(TokenType type, int offset) : super(type, offset) {
- assert(type == TokenType.OPEN_CURLY_BRACKET ||
- type == TokenType.OPEN_PAREN ||
- type == TokenType.OPEN_SQUARE_BRACKET ||
- type == TokenType.STRING_INTERPOLATION_EXPRESSION);
- }
-
- @override
- Token copy() => new BeginToken(type, offset);
-}
-
-/**
- * A begin token that is preceded by comments.
- */
-class BeginTokenWithComment extends BeginToken implements TokenWithComment {
- /**
- * The first comment in the list of comments that precede this token.
- */
- @override
- CommentToken _precedingComment;
-
- /**
- * Initialize a newly created token to have the given [type] at the given
- * [offset] and to be preceded by the comments reachable from the given
- * [_precedingComment].
- */
- BeginTokenWithComment(TokenType type, int offset, this._precedingComment)
- : super(type, offset) {
- _setCommentParent(_precedingComment);
- }
-
- @override
- CommentToken get precedingComments => _precedingComment;
-
- @override
- void set precedingComments(CommentToken comment) {
- _precedingComment = comment;
- _setCommentParent(_precedingComment);
- }
-
- @override
- void applyDelta(int delta) {
- super.applyDelta(delta);
- Token token = precedingComments;
- while (token != null) {
- token.applyDelta(delta);
- token = token.next;
- }
- }
-
- @override
- Token copy() =>
- new BeginTokenWithComment(type, offset, copyComments(precedingComments));
-}
-
-/**
- * A token representing a comment.
- */
-class CommentToken extends StringToken {
- /**
- * The token that contains this comment.
- */
- TokenWithComment parent;
-
- /**
- * Initialize a newly created token to represent a token of the given [type]
- * with the given [value] at the given [offset].
- */
- CommentToken(TokenType type, String value, int offset)
- : super(type, value, offset);
-
- @override
- CommentToken copy() => new CommentToken(type, _value, offset);
-
- /**
- * Remove this comment token from the list.
- *
- * This is used when we decide to interpret the comment as syntax.
- */
- void remove() {
- if (previous != null) {
- previous.setNextWithoutSettingPrevious(next);
- next?.previous = previous;
- } else {
- assert(parent.precedingComments == this);
- parent.precedingComments = next;
- }
- }
-}
-
-/**
- * A documentation comment token.
- */
-class DocumentationCommentToken extends CommentToken {
- /**
- * The references embedded within the documentation comment.
- * This list will be empty unless this is a documentation comment that has
- * references embedded within it.
- */
- final List<Token> references = <Token>[];
-
- /**
- * Initialize a newly created token to represent a token of the given [type]
- * with the given [value] at the given [offset].
- */
- DocumentationCommentToken(TokenType type, String value, int offset)
- : super(type, value, offset);
-
- @override
- CommentToken copy() {
- DocumentationCommentToken copy =
- new DocumentationCommentToken(type, _value, offset);
- references.forEach((ref) => copy.references.add(ref.copy()));
- return copy;
- }
-}
-
-/**
- * The keywords in the Dart programming language.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Keyword {
- static const Keyword ABSTRACT = const Keyword._('ABSTRACT', "abstract", true);
-
- static const Keyword AS = const Keyword._('AS', "as", true);
-
- static const Keyword ASSERT = const Keyword._('ASSERT', "assert");
-
- static const Keyword BREAK = const Keyword._('BREAK', "break");
-
- static const Keyword CASE = const Keyword._('CASE', "case");
-
- static const Keyword CATCH = const Keyword._('CATCH', "catch");
-
- static const Keyword CLASS = const Keyword._('CLASS', "class");
-
- static const Keyword CONST = const Keyword._('CONST', "const");
-
- static const Keyword CONTINUE = const Keyword._('CONTINUE', "continue");
-
- static const Keyword COVARIANT =
- const Keyword._('COVARIANT', "covariant", true);
-
- static const Keyword DEFAULT = const Keyword._('DEFAULT', "default");
-
- static const Keyword DEFERRED = const Keyword._('DEFERRED', "deferred", true);
-
- static const Keyword DO = const Keyword._('DO', "do");
-
- static const Keyword DYNAMIC = const Keyword._('DYNAMIC', "dynamic", true);
-
- static const Keyword ELSE = const Keyword._('ELSE', "else");
-
- static const Keyword ENUM = const Keyword._('ENUM', "enum");
-
- static const Keyword EXPORT = const Keyword._('EXPORT', "export", true);
-
- static const Keyword EXTENDS = const Keyword._('EXTENDS', "extends");
-
- static const Keyword EXTERNAL = const Keyword._('EXTERNAL', "external", true);
-
- static const Keyword FACTORY = const Keyword._('FACTORY', "factory", true);
-
- static const Keyword FALSE = const Keyword._('FALSE', "false");
-
- static const Keyword FINAL = const Keyword._('FINAL', "final");
-
- static const Keyword FINALLY = const Keyword._('FINALLY', "finally");
-
- static const Keyword FOR = const Keyword._('FOR', "for");
-
- static const Keyword GET = const Keyword._('GET', "get", true);
-
- static const Keyword IF = const Keyword._('IF', "if");
-
- static const Keyword IMPLEMENTS =
- const Keyword._('IMPLEMENTS', "implements", true);
-
- static const Keyword IMPORT = const Keyword._('IMPORT', "import", true);
-
- static const Keyword IN = const Keyword._('IN', "in");
-
- static const Keyword IS = const Keyword._('IS', "is");
-
- static const Keyword LIBRARY = const Keyword._('LIBRARY', "library", true);
-
- static const Keyword NEW = const Keyword._('NEW', "new");
-
- static const Keyword NULL = const Keyword._('NULL', "null");
-
- static const Keyword OPERATOR = const Keyword._('OPERATOR', "operator", true);
-
- static const Keyword PART = const Keyword._('PART', "part", true);
-
- static const Keyword RETHROW = const Keyword._('RETHROW', "rethrow");
-
- static const Keyword RETURN = const Keyword._('RETURN', "return");
-
- static const Keyword SET = const Keyword._('SET', "set", true);
-
- static const Keyword STATIC = const Keyword._('STATIC', "static", true);
-
- static const Keyword SUPER = const Keyword._('SUPER', "super");
-
- static const Keyword SWITCH = const Keyword._('SWITCH', "switch");
-
- static const Keyword THIS = const Keyword._('THIS', "this");
-
- static const Keyword THROW = const Keyword._('THROW', "throw");
-
- static const Keyword TRUE = const Keyword._('TRUE', "true");
-
- static const Keyword TRY = const Keyword._('TRY', "try");
-
- static const Keyword TYPEDEF = const Keyword._('TYPEDEF', "typedef", true);
-
- static const Keyword VAR = const Keyword._('VAR', "var");
-
- static const Keyword VOID = const Keyword._('VOID', "void");
-
- static const Keyword WHILE = const Keyword._('WHILE', "while");
-
- static const Keyword WITH = const Keyword._('WITH', "with");
-
- static const List<Keyword> values = const <Keyword>[
- ABSTRACT,
- AS,
- ASSERT,
- BREAK,
- CASE,
- CATCH,
- CLASS,
- CONST,
- CONTINUE,
- COVARIANT,
- DEFAULT,
- DEFERRED,
- DO,
- DYNAMIC,
- ELSE,
- ENUM,
- EXPORT,
- EXTENDS,
- EXTERNAL,
- FACTORY,
- FALSE,
- FINAL,
- FINALLY,
- FOR,
- GET,
- IF,
- IMPLEMENTS,
- IMPORT,
- IN,
- IS,
- LIBRARY,
- NEW,
- NULL,
- OPERATOR,
- PART,
- RETHROW,
- RETURN,
- SET,
- STATIC,
- SUPER,
- SWITCH,
- THIS,
- THROW,
- TRUE,
- TRY,
- TYPEDEF,
- VAR,
- VOID,
- WHILE,
- WITH,
- ];
-
- /**
- * A table mapping the lexemes of keywords to the corresponding keyword.
- */
- static final Map<String, Keyword> keywords = _createKeywordMap();
-
- /**
- * The name of the keyword type.
- */
- final String name;
-
- /**
- * The lexeme for the keyword.
- */
- final String syntax;
-
- /**
- * A flag indicating whether the keyword is a pseudo-keyword. Pseudo keywords
- * can be used as identifiers.
- */
- final bool isPseudoKeyword;
-
- /**
- * Initialize a newly created keyword to have the given [name] and [syntax].
- * The keyword is a pseudo-keyword if the [isPseudoKeyword] flag is `true`.
- */
- const Keyword._(this.name, this.syntax, [this.isPseudoKeyword = false]);
-
- @override
- String toString() => name;
-
- /**
- * Create a table mapping the lexemes of keywords to the corresponding keyword
- * and return the table that was created.
- */
- static Map<String, Keyword> _createKeywordMap() {
- LinkedHashMap<String, Keyword> result =
- new LinkedHashMap<String, Keyword>();
- for (Keyword keyword in values) {
- result[keyword.syntax] = keyword;
- }
- return result;
- }
-}
-
-/**
- * A token representing a keyword in the language.
- */
-class KeywordToken extends SimpleToken {
- @override
- final Keyword keyword;
-
- /**
- * Initialize a newly created token to represent the given [keyword] at the
- * given [offset].
- */
- KeywordToken(this.keyword, int offset) : super(TokenType.KEYWORD, offset);
-
- @override
- String get lexeme => keyword.syntax;
-
- @override
- Token copy() => new KeywordToken(keyword, offset);
-
- @override
- Keyword value() => keyword;
-}
-
-/**
- * A keyword token that is preceded by comments.
- */
-class KeywordTokenWithComment extends KeywordToken implements TokenWithComment {
- /**
- * The first comment in the list of comments that precede this token.
- */
- @override
- CommentToken _precedingComment;
-
- /**
- * Initialize a newly created token to to represent the given [keyword] at the
- * given [offset] and to be preceded by the comments reachable from the given
- * [_precedingComment].
- */
- KeywordTokenWithComment(Keyword keyword, int offset, this._precedingComment)
- : super(keyword, offset) {
- _setCommentParent(_precedingComment);
- }
-
- @override
- CommentToken get precedingComments => _precedingComment;
-
- void set precedingComments(CommentToken comment) {
- _precedingComment = comment;
- _setCommentParent(_precedingComment);
- }
-
- @override
- void applyDelta(int delta) {
- super.applyDelta(delta);
- Token token = precedingComments;
- while (token != null) {
- token.applyDelta(delta);
- token = token.next;
- }
- }
-
- @override
- Token copy() => new KeywordTokenWithComment(
- keyword, offset, copyComments(precedingComments));
-}
-
-/**
- * A token that was scanned from the input. Each token knows which tokens
- * precede and follow it, acting as a link in a doubly linked list of tokens.
- */
-class SimpleToken implements Token {
- /**
- * The type of the token.
- */
- @override
- final TokenType type;
-
- /**
- * The offset from the beginning of the file to the first character in the
- * token.
- */
- @override
- int offset = 0;
-
- /**
- * The previous token in the token stream.
- */
- @override
- Token previous;
-
- /**
- * The next token in the token stream.
- */
- Token _next;
-
- /**
- * Initialize a newly created token to have the given [type] and [offset].
- */
- SimpleToken(this.type, this.offset);
-
- @override
- int get end => offset + length;
-
- @override
- bool get isOperator => type.isOperator;
-
- @override
- bool get isSynthetic => length == 0;
-
- @override
- bool get isUserDefinableOperator => type.isUserDefinableOperator;
-
- @override
- Keyword get keyword => null;
-
- @override
- int get length => lexeme.length;
-
- @override
- String get lexeme => type.lexeme;
-
- @override
- Token get next => _next;
-
- @override
- CommentToken get precedingComments => null;
-
- @override
- void applyDelta(int delta) {
- offset += delta;
- }
-
- @override
- Token copy() => new Token(type, offset);
-
- @override
- Token copyComments(Token token) {
- if (token == null) {
- return null;
- }
- Token head = token.copy();
- Token tail = head;
- token = token.next;
- while (token != null) {
- tail = tail.setNext(token.copy());
- token = token.next;
- }
- return head;
- }
-
- @override
- bool matchesAny(List<TokenType> types) {
- for (TokenType type in types) {
- if (this.type == type) {
- return true;
- }
- }
- return false;
- }
-
- @override
- Token setNext(Token token) {
- _next = token;
- token.previous = this;
- return token;
- }
-
- @override
- Token setNextWithoutSettingPrevious(Token token) {
- _next = token;
- return token;
- }
-
- @override
- String toString() => lexeme;
-
- @override
- Object value() => type.lexeme;
-
- /**
- * Sets the `parent` property to `this` for the given [comment] and all the
- * next tokens.
- */
- void _setCommentParent(CommentToken comment) {
- while (comment != null) {
- comment.parent = this;
- comment = comment.next;
- }
- }
-}
-
-/**
- * A token whose value is independent of it's type.
- */
-class StringToken extends SimpleToken {
- /**
- * The lexeme represented by this token.
- */
- String _value;
-
- /**
- * Initialize a newly created token to represent a token of the given [type]
- * with the given [value] at the given [offset].
- */
- StringToken(TokenType type, String value, int offset) : super(type, offset) {
- this._value = StringUtilities.intern(value);
- }
-
- @override
- String get lexeme => _value;
-
- @override
- Token copy() => new StringToken(type, _value, offset);
-
- @override
- String value() => _value;
-}
-
-/**
- * A string token that is preceded by comments.
- */
-class StringTokenWithComment extends StringToken implements TokenWithComment {
- /**
- * The first comment in the list of comments that precede this token.
- */
- CommentToken _precedingComment;
-
- /**
- * Initialize a newly created token to have the given [type] at the given
- * [offset] and to be preceded by the comments reachable from the given
- * [comment].
- */
- StringTokenWithComment(
- TokenType type, String value, int offset, this._precedingComment)
- : super(type, value, offset) {
- _setCommentParent(_precedingComment);
- }
-
- @override
- CommentToken get precedingComments => _precedingComment;
-
- void set precedingComments(CommentToken comment) {
- _precedingComment = comment;
- _setCommentParent(_precedingComment);
- }
-
- @override
- void applyDelta(int delta) {
- super.applyDelta(delta);
- Token token = precedingComments;
- while (token != null) {
- token.applyDelta(delta);
- token = token.next;
- }
- }
-
- @override
- Token copy() => new StringTokenWithComment(
- type, lexeme, offset, copyComments(precedingComments));
-}
-
-/**
- * A token that was scanned from the input. Each token knows which tokens
- * precede and follow it, acting as a link in a doubly linked list of tokens.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class Token implements SyntacticEntity {
- /**
- * Initialize a newly created token to have the given [type] and [offset].
- */
- factory Token(TokenType type, int offset) = SimpleToken;
-
- @override
- int get end;
-
- /**
- * Return `true` if this token represents an operator.
- */
- bool get isOperator;
-
- /**
- * Return `true` if this token is a synthetic token. A synthetic token is a
- * token that was introduced by the parser in order to recover from an error
- * in the code.
- */
- bool get isSynthetic;
-
- /**
- * Return `true` if this token represents an operator that can be defined by
- * users.
- */
- bool get isUserDefinableOperator;
-
- /**
- * Return the keyword, if a keyword token, or `null` otherwise.
- */
- Keyword get keyword;
-
- @override
- int get length;
-
- /**
- * Return the lexeme that represents this token.
- */
- String get lexeme;
-
- /**
- * Return the next token in the token stream.
- */
- Token get next;
-
- @override
- int get offset;
-
- /**
- * Set the offset from the beginning of the file to the first character in
- * the token to the given [offset].
- */
- void set offset(int offset);
-
- /**
- * Return the first comment in the list of comments that precede this token,
- * or `null` if there are no comments preceding this token. Additional
- * comments can be reached by following the token stream using [next] until
- * `null` is returned.
- *
- * For example, if the original contents were `/* one */ /* two */ id`, then
- * the first preceding comment token will have a lexeme of `/* one */` and
- * the next comment token will have a lexeme of `/* two */`.
- */
- Token get precedingComments;
-
- /**
- * Return the previous token in the token stream.
- */
- Token get previous;
-
- /**
- * Set the previous token in the token stream to the given [token].
- */
- void set previous(Token token);
-
- /**
- * Return the type of the token.
- */
- TokenType get type;
-
- /**
- * Apply (add) the given [delta] to this token's offset.
- */
- void applyDelta(int delta);
-
- /**
- * Return a newly created token that is a copy of this token but that is not a
- * part of any token stream.
- */
- Token copy();
-
- /**
- * Copy a linked list of comment tokens identical to the given comment tokens.
- */
- Token copyComments(Token token);
-
- /**
- * Return `true` if this token has any one of the given [types].
- */
- bool matchesAny(List<TokenType> types);
-
- /**
- * Set the next token in the token stream to the given [token]. This has the
- * side-effect of setting this token to be the previous token for the given
- * token. Return the token that was passed in.
- */
- Token setNext(Token token);
-
- /**
- * Set the next token in the token stream to the given token without changing
- * which token is the previous token for the given token. Return the token
- * that was passed in.
- */
- Token setNextWithoutSettingPrevious(Token token);
-
- /**
- * Return the value of this token. For keyword tokens, this is the keyword
- * associated with the token, for other tokens it is the lexeme associated
- * with the token.
- */
- Object value();
-
- /**
- * Compare the given [tokens] to find the token that appears first in the
- * source being parsed. That is, return the left-most of all of the tokens.
- * The list must be non-`null`, but the elements of the list are allowed to be
- * `null`. Return the token with the smallest offset, or `null` if the list is
- * empty or if all of the elements of the list are `null`.
- */
- static Token lexicallyFirst(List<Token> tokens) {
- Token first = null;
- int offset = -1;
- int length = tokens.length;
- for (int i = 0; i < length; i++) {
- Token token = tokens[i];
- if (token != null && (offset < 0 || token.offset < offset)) {
- first = token;
- offset = token.offset;
- }
- }
- return first;
- }
-}
-
-/**
- * The classes (or groups) of tokens with a similar use.
- */
-class TokenClass {
- /**
- * A value used to indicate that the token type is not part of any specific
- * class of token.
- */
- static const TokenClass NO_CLASS = const TokenClass('NO_CLASS');
-
- /**
- * A value used to indicate that the token type is an additive operator.
- */
- static const TokenClass ADDITIVE_OPERATOR =
- const TokenClass('ADDITIVE_OPERATOR', 13);
-
- /**
- * A value used to indicate that the token type is an assignment operator.
- */
- static const TokenClass ASSIGNMENT_OPERATOR =
- const TokenClass('ASSIGNMENT_OPERATOR', 1);
-
- /**
- * A value used to indicate that the token type is a bitwise-and operator.
- */
- static const TokenClass BITWISE_AND_OPERATOR =
- const TokenClass('BITWISE_AND_OPERATOR', 11);
-
- /**
- * A value used to indicate that the token type is a bitwise-or operator.
- */
- static const TokenClass BITWISE_OR_OPERATOR =
- const TokenClass('BITWISE_OR_OPERATOR', 9);
-
- /**
- * A value used to indicate that the token type is a bitwise-xor operator.
- */
- static const TokenClass BITWISE_XOR_OPERATOR =
- const TokenClass('BITWISE_XOR_OPERATOR', 10);
-
- /**
- * A value used to indicate that the token type is a cascade operator.
- */
- static const TokenClass CASCADE_OPERATOR =
- const TokenClass('CASCADE_OPERATOR', 2);
-
- /**
- * A value used to indicate that the token type is a conditional operator.
- */
- static const TokenClass CONDITIONAL_OPERATOR =
- const TokenClass('CONDITIONAL_OPERATOR', 3);
-
- /**
- * A value used to indicate that the token type is an equality operator.
- */
- static const TokenClass EQUALITY_OPERATOR =
- const TokenClass('EQUALITY_OPERATOR', 7);
-
- /**
- * A value used to indicate that the token type is an if-null operator.
- */
- static const TokenClass IF_NULL_OPERATOR =
- const TokenClass('IF_NULL_OPERATOR', 4);
-
- /**
- * A value used to indicate that the token type is a logical-and operator.
- */
- static const TokenClass LOGICAL_AND_OPERATOR =
- const TokenClass('LOGICAL_AND_OPERATOR', 6);
-
- /**
- * A value used to indicate that the token type is a logical-or operator.
- */
- static const TokenClass LOGICAL_OR_OPERATOR =
- const TokenClass('LOGICAL_OR_OPERATOR', 5);
-
- /**
- * A value used to indicate that the token type is a multiplicative operator.
- */
- static const TokenClass MULTIPLICATIVE_OPERATOR =
- const TokenClass('MULTIPLICATIVE_OPERATOR', 14);
-
- /**
- * A value used to indicate that the token type is a relational operator.
- */
- static const TokenClass RELATIONAL_OPERATOR =
- const TokenClass('RELATIONAL_OPERATOR', 8);
-
- /**
- * A value used to indicate that the token type is a shift operator.
- */
- static const TokenClass SHIFT_OPERATOR =
- const TokenClass('SHIFT_OPERATOR', 12);
-
- /**
- * A value used to indicate that the token type is a unary operator.
- */
- static const TokenClass UNARY_POSTFIX_OPERATOR =
- const TokenClass('UNARY_POSTFIX_OPERATOR', 16);
-
- /**
- * A value used to indicate that the token type is a unary operator.
- */
- static const TokenClass UNARY_PREFIX_OPERATOR =
- const TokenClass('UNARY_PREFIX_OPERATOR', 15);
-
- /**
- * The name of the token class.
- */
- final String name;
-
- /**
- * The precedence of tokens of this class, or `0` if the such tokens do not
- * represent an operator.
- */
- final int precedence;
-
- /**
- * Initialize a newly created class of tokens to have the given [name] and
- * [precedence].
- */
- const TokenClass(this.name, [this.precedence = 0]);
-
- @override
- String toString() => name;
-}
-
-/**
- * The types of tokens that can be returned by the scanner.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class TokenType {
- /**
- * The type of the token that marks the start or end of the input.
- */
- static const TokenType EOF = const _EndOfFileTokenType();
-
- static const TokenType DOUBLE = const TokenType._('DOUBLE');
-
- static const TokenType HEXADECIMAL = const TokenType._('HEXADECIMAL');
-
- static const TokenType IDENTIFIER = const TokenType._('IDENTIFIER');
-
- static const TokenType INT = const TokenType._('INT');
-
- static const TokenType KEYWORD = const TokenType._('KEYWORD');
-
- static const TokenType MULTI_LINE_COMMENT =
- const TokenType._('MULTI_LINE_COMMENT');
-
- static const TokenType SCRIPT_TAG = const TokenType._('SCRIPT_TAG');
-
- static const TokenType SINGLE_LINE_COMMENT =
- const TokenType._('SINGLE_LINE_COMMENT');
-
- static const TokenType STRING = const TokenType._('STRING');
-
- static const TokenType AMPERSAND =
- const TokenType._('AMPERSAND', TokenClass.BITWISE_AND_OPERATOR, '&');
-
- static const TokenType AMPERSAND_AMPERSAND = const TokenType._(
- 'AMPERSAND_AMPERSAND', TokenClass.LOGICAL_AND_OPERATOR, '&&');
-
- static const TokenType AMPERSAND_AMPERSAND_EQ = const TokenType._(
- 'AMPERSAND_AMPERSAND_EQ', TokenClass.ASSIGNMENT_OPERATOR, '&&=');
-
- static const TokenType AMPERSAND_EQ =
- const TokenType._('AMPERSAND_EQ', TokenClass.ASSIGNMENT_OPERATOR, '&=');
-
- static const TokenType AT = const TokenType._('AT', TokenClass.NO_CLASS, '@');
-
- static const TokenType BANG =
- const TokenType._('BANG', TokenClass.UNARY_PREFIX_OPERATOR, '!');
-
- static const TokenType BANG_EQ =
- const TokenType._('BANG_EQ', TokenClass.EQUALITY_OPERATOR, '!=');
-
- static const TokenType BAR =
- const TokenType._('BAR', TokenClass.BITWISE_OR_OPERATOR, '|');
-
- static const TokenType BAR_BAR =
- const TokenType._('BAR_BAR', TokenClass.LOGICAL_OR_OPERATOR, '||');
-
- static const TokenType BAR_BAR_EQ =
- const TokenType._('BAR_BAR_EQ', TokenClass.ASSIGNMENT_OPERATOR, '||=');
-
- static const TokenType BAR_EQ =
- const TokenType._('BAR_EQ', TokenClass.ASSIGNMENT_OPERATOR, '|=');
-
- static const TokenType COLON =
- const TokenType._('COLON', TokenClass.NO_CLASS, ':');
-
- static const TokenType COMMA =
- const TokenType._('COMMA', TokenClass.NO_CLASS, ',');
-
- static const TokenType CARET =
- const TokenType._('CARET', TokenClass.BITWISE_XOR_OPERATOR, '^');
-
- static const TokenType CARET_EQ =
- const TokenType._('CARET_EQ', TokenClass.ASSIGNMENT_OPERATOR, '^=');
-
- static const TokenType CLOSE_CURLY_BRACKET =
- const TokenType._('CLOSE_CURLY_BRACKET', TokenClass.NO_CLASS, '}');
-
- static const TokenType CLOSE_PAREN =
- const TokenType._('CLOSE_PAREN', TokenClass.NO_CLASS, ')');
-
- static const TokenType CLOSE_SQUARE_BRACKET =
- const TokenType._('CLOSE_SQUARE_BRACKET', TokenClass.NO_CLASS, ']');
-
- static const TokenType EQ =
- const TokenType._('EQ', TokenClass.ASSIGNMENT_OPERATOR, '=');
-
- static const TokenType EQ_EQ =
- const TokenType._('EQ_EQ', TokenClass.EQUALITY_OPERATOR, '==');
-
- static const TokenType FUNCTION =
- const TokenType._('FUNCTION', TokenClass.NO_CLASS, '=>');
-
- static const TokenType GT =
- const TokenType._('GT', TokenClass.RELATIONAL_OPERATOR, '>');
-
- static const TokenType GT_EQ =
- const TokenType._('GT_EQ', TokenClass.RELATIONAL_OPERATOR, '>=');
-
- static const TokenType GT_GT =
- const TokenType._('GT_GT', TokenClass.SHIFT_OPERATOR, '>>');
-
- static const TokenType GT_GT_EQ =
- const TokenType._('GT_GT_EQ', TokenClass.ASSIGNMENT_OPERATOR, '>>=');
-
- static const TokenType HASH =
- const TokenType._('HASH', TokenClass.NO_CLASS, '#');
-
- static const TokenType INDEX =
- const TokenType._('INDEX', TokenClass.UNARY_POSTFIX_OPERATOR, '[]');
-
- static const TokenType INDEX_EQ =
- const TokenType._('INDEX_EQ', TokenClass.UNARY_POSTFIX_OPERATOR, '[]=');
-
- static const TokenType IS =
- const TokenType._('IS', TokenClass.RELATIONAL_OPERATOR, 'is');
-
- static const TokenType LT =
- const TokenType._('LT', TokenClass.RELATIONAL_OPERATOR, '<');
-
- static const TokenType LT_EQ =
- const TokenType._('LT_EQ', TokenClass.RELATIONAL_OPERATOR, '<=');
-
- static const TokenType LT_LT =
- const TokenType._('LT_LT', TokenClass.SHIFT_OPERATOR, '<<');
-
- static const TokenType LT_LT_EQ =
- const TokenType._('LT_LT_EQ', TokenClass.ASSIGNMENT_OPERATOR, '<<=');
-
- static const TokenType MINUS =
- const TokenType._('MINUS', TokenClass.ADDITIVE_OPERATOR, '-');
-
- static const TokenType MINUS_EQ =
- const TokenType._('MINUS_EQ', TokenClass.ASSIGNMENT_OPERATOR, '-=');
-
- static const TokenType MINUS_MINUS =
- const TokenType._('MINUS_MINUS', TokenClass.UNARY_PREFIX_OPERATOR, '--');
-
- static const TokenType OPEN_CURLY_BRACKET =
- const TokenType._('OPEN_CURLY_BRACKET', TokenClass.NO_CLASS, '{');
-
- static const TokenType OPEN_PAREN =
- const TokenType._('OPEN_PAREN', TokenClass.UNARY_POSTFIX_OPERATOR, '(');
-
- static const TokenType OPEN_SQUARE_BRACKET = const TokenType._(
- 'OPEN_SQUARE_BRACKET', TokenClass.UNARY_POSTFIX_OPERATOR, '[');
-
- static const TokenType PERCENT =
- const TokenType._('PERCENT', TokenClass.MULTIPLICATIVE_OPERATOR, '%');
-
- static const TokenType PERCENT_EQ =
- const TokenType._('PERCENT_EQ', TokenClass.ASSIGNMENT_OPERATOR, '%=');
-
- static const TokenType PERIOD =
- const TokenType._('PERIOD', TokenClass.UNARY_POSTFIX_OPERATOR, '.');
-
- static const TokenType PERIOD_PERIOD =
- const TokenType._('PERIOD_PERIOD', TokenClass.CASCADE_OPERATOR, '..');
-
- static const TokenType PLUS =
- const TokenType._('PLUS', TokenClass.ADDITIVE_OPERATOR, '+');
-
- static const TokenType PLUS_EQ =
- const TokenType._('PLUS_EQ', TokenClass.ASSIGNMENT_OPERATOR, '+=');
-
- static const TokenType PLUS_PLUS =
- const TokenType._('PLUS_PLUS', TokenClass.UNARY_PREFIX_OPERATOR, '++');
-
- static const TokenType QUESTION =
- const TokenType._('QUESTION', TokenClass.CONDITIONAL_OPERATOR, '?');
-
- static const TokenType QUESTION_PERIOD = const TokenType._(
- 'QUESTION_PERIOD', TokenClass.UNARY_POSTFIX_OPERATOR, '?.');
-
- static const TokenType QUESTION_QUESTION =
- const TokenType._('QUESTION_QUESTION', TokenClass.IF_NULL_OPERATOR, '??');
-
- static const TokenType QUESTION_QUESTION_EQ = const TokenType._(
- 'QUESTION_QUESTION_EQ', TokenClass.ASSIGNMENT_OPERATOR, '??=');
-
- static const TokenType SEMICOLON =
- const TokenType._('SEMICOLON', TokenClass.NO_CLASS, ';');
-
- static const TokenType SLASH =
- const TokenType._('SLASH', TokenClass.MULTIPLICATIVE_OPERATOR, '/');
-
- static const TokenType SLASH_EQ =
- const TokenType._('SLASH_EQ', TokenClass.ASSIGNMENT_OPERATOR, '/=');
-
- static const TokenType STAR =
- const TokenType._('STAR', TokenClass.MULTIPLICATIVE_OPERATOR, '*');
-
- static const TokenType STAR_EQ =
- const TokenType._('STAR_EQ', TokenClass.ASSIGNMENT_OPERATOR, "*=");
-
- static const TokenType STRING_INTERPOLATION_EXPRESSION = const TokenType._(
- 'STRING_INTERPOLATION_EXPRESSION', TokenClass.NO_CLASS, '\${');
-
- static const TokenType STRING_INTERPOLATION_IDENTIFIER = const TokenType._(
- 'STRING_INTERPOLATION_IDENTIFIER', TokenClass.NO_CLASS, '\$');
-
- static const TokenType TILDE =
- const TokenType._('TILDE', TokenClass.UNARY_PREFIX_OPERATOR, '~');
-
- static const TokenType TILDE_SLASH = const TokenType._(
- 'TILDE_SLASH', TokenClass.MULTIPLICATIVE_OPERATOR, '~/');
-
- static const TokenType TILDE_SLASH_EQ = const TokenType._(
- 'TILDE_SLASH_EQ', TokenClass.ASSIGNMENT_OPERATOR, '~/=');
-
- static const TokenType BACKPING =
- const TokenType._('BACKPING', TokenClass.NO_CLASS, '`');
-
- static const TokenType BACKSLASH =
- const TokenType._('BACKSLASH', TokenClass.NO_CLASS, '\\');
-
- static const TokenType PERIOD_PERIOD_PERIOD =
- const TokenType._('PERIOD_PERIOD_PERIOD', TokenClass.NO_CLASS, '...');
-
- static const TokenType GENERIC_METHOD_TYPE_LIST =
- const TokenType._('GENERIC_METHOD_TYPE_LIST');
-
- static const TokenType GENERIC_METHOD_TYPE_ASSIGN =
- const TokenType._('GENERIC_METHOD_TYPE_ASSIGN');
-
- /**
- * The class of the token.
- */
- final TokenClass _tokenClass;
-
- /**
- * The name of the token type.
- */
- final String name;
-
- /**
- * The lexeme that defines this type of token, or `null` if there is more than
- * one possible lexeme for this type of token.
- */
- final String lexeme;
-
- /**
- * Initialize a newly created token type to have the given [name],
- * [_tokenClass] and [lexeme].
- */
- const TokenType._(this.name,
- [this._tokenClass = TokenClass.NO_CLASS, this.lexeme = null]);
-
- /**
- * Return `true` if this type of token represents an additive operator.
- */
- bool get isAdditiveOperator => _tokenClass == TokenClass.ADDITIVE_OPERATOR;
-
- /**
- * Return `true` if this type of token represents an assignment operator.
- */
- bool get isAssignmentOperator =>
- _tokenClass == TokenClass.ASSIGNMENT_OPERATOR;
-
- /**
- * Return `true` if this type of token represents an associative operator. An
- * associative operator is an operator for which the following equality is
- * true: `(a * b) * c == a * (b * c)`. In other words, if the result of
- * applying the operator to multiple operands does not depend on the order in
- * which those applications occur.
- *
- * Note: This method considers the logical-and and logical-or operators to be
- * associative, even though the order in which the application of those
- * operators can have an effect because evaluation of the right-hand operand
- * is conditional.
- */
- bool get isAssociativeOperator =>
- this == AMPERSAND ||
- this == AMPERSAND_AMPERSAND ||
- this == BAR ||
- this == BAR_BAR ||
- this == CARET ||
- this == PLUS ||
- this == STAR;
-
- /**
- * Return `true` if this type of token represents an equality operator.
- */
- bool get isEqualityOperator => _tokenClass == TokenClass.EQUALITY_OPERATOR;
-
- /**
- * Return `true` if this type of token represents an increment operator.
- */
- bool get isIncrementOperator =>
- identical(lexeme, '++') || identical(lexeme, '--');
-
- /**
- * Return `true` if this type of token represents a multiplicative operator.
- */
- bool get isMultiplicativeOperator =>
- _tokenClass == TokenClass.MULTIPLICATIVE_OPERATOR;
-
- /**
- * Return `true` if this token type represents an operator.
- */
- bool get isOperator =>
- _tokenClass != TokenClass.NO_CLASS &&
- this != OPEN_PAREN &&
- this != OPEN_SQUARE_BRACKET &&
- this != PERIOD;
-
- /**
- * Return `true` if this type of token represents a relational operator.
- */
- bool get isRelationalOperator =>
- _tokenClass == TokenClass.RELATIONAL_OPERATOR;
-
- /**
- * Return `true` if this type of token represents a shift operator.
- */
- bool get isShiftOperator => _tokenClass == TokenClass.SHIFT_OPERATOR;
-
- /**
- * Return `true` if this type of token represents a unary postfix operator.
- */
- bool get isUnaryPostfixOperator =>
- _tokenClass == TokenClass.UNARY_POSTFIX_OPERATOR;
-
- /**
- * Return `true` if this type of token represents a unary prefix operator.
- */
- bool get isUnaryPrefixOperator =>
- _tokenClass == TokenClass.UNARY_PREFIX_OPERATOR;
-
- /**
- * Return `true` if this token type represents an operator that can be defined
- * by users.
- */
- bool get isUserDefinableOperator =>
- identical(lexeme, '==') ||
- identical(lexeme, '~') ||
- identical(lexeme, '[]') ||
- identical(lexeme, '[]=') ||
- identical(lexeme, '*') ||
- identical(lexeme, '/') ||
- identical(lexeme, '%') ||
- identical(lexeme, '~/') ||
- identical(lexeme, '+') ||
- identical(lexeme, '-') ||
- identical(lexeme, '<<') ||
- identical(lexeme, '>>') ||
- identical(lexeme, '>=') ||
- identical(lexeme, '>') ||
- identical(lexeme, '<=') ||
- identical(lexeme, '<') ||
- identical(lexeme, '&') ||
- identical(lexeme, '^') ||
- identical(lexeme, '|');
-
- /**
- * Return the precedence of the token, or `0` if the token does not represent
- * an operator.
- */
- int get precedence => _tokenClass.precedence;
-
- @override
- String toString() => name;
-}
-
-/**
- * A normal token that is preceded by comments.
- */
-class TokenWithComment extends SimpleToken {
- /**
- * The first comment in the list of comments that precede this token.
- */
- CommentToken _precedingComment;
-
- /**
- * Initialize a newly created token to have the given [type] at the given
- * [offset] and to be preceded by the comments reachable from the given
- * [comment].
- */
- TokenWithComment(TokenType type, int offset, this._precedingComment)
- : super(type, offset) {
- _setCommentParent(_precedingComment);
- }
-
- @override
- CommentToken get precedingComments => _precedingComment;
-
- void set precedingComments(CommentToken comment) {
- _precedingComment = comment;
- _setCommentParent(_precedingComment);
- }
-
- @override
- Token copy() =>
- new TokenWithComment(type, offset, copyComments(precedingComments));
-}
-
-/**
- * A token representing the end (either the head or the tail) of a stream of
- * tokens.
- */
-class _EndOfFileTokenType extends TokenType {
- /**
- * Initialize a newly created token.
- */
- const _EndOfFileTokenType() : super._('EOF', TokenClass.NO_CLASS, '');
-
- @override
- String toString() => '-eof-';
-}
diff --git a/pub/front_end/lib/summary_generator.dart b/pub/front_end/lib/summary_generator.dart
deleted file mode 100644
index 0c494c4..0000000
--- a/pub/front_end/lib/summary_generator.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// Defines the front-end API for converting source code to summaries.
-library front_end.summary_generator;
-
-import 'dart:async';
-import 'compiler_options.dart';
-
-/// Creates a summary representation of the build unit whose source files are in
-/// [sources].
-///
-/// Intended to be a part of a modular compilation process.
-///
-/// [sources] should be the complete set of source files for a build unit
-/// (including both library and part files).
-///
-/// The summarization process is hermetic, meaning that the only files which
-/// will be read are those listed in [sources],
-/// [CompilerOptions.inputSummaries], and [CompilerOptions.sdkSummary]. If a
-/// source file attempts to refer to a file which is not obtainable from these
-/// paths, that will result in an error, even if the file exists on the
-/// filesystem.
-///
-/// Any `part` declarations found in [sources] must refer to part files which
-/// are also listed in [sources], otherwise an error results. (It is not
-/// permitted to refer to a part file declared in another build unit).
-///
-/// The return value is a list of bytes to write to the summary file.
-Future<List<int>> summaryFor(List<Uri> sources, CompilerOptions options) =>
- throw new UnimplementedError();
diff --git a/pub/front_end/pubspec.yaml b/pub/front_end/pubspec.yaml
deleted file mode 100644
index 5f15860..0000000
--- a/pub/front_end/pubspec.yaml
+++ /dev/null
@@ -1,18 +0,0 @@
-name: front_end
-version: 0.1.0-alpha.1
-author: Dart Team <misc@dartlang.org>
-description: Front end for compilation of Dart code.
-homepage: https://github.com/dart-lang/sdk/tree/master/pkg/front_end
-environment:
- sdk: '>=1.12.0 <2.0.0'
-dependencies:
- analyzer: 0.30.0-alpha.1
- path: '^1.3.9'
- source_span: '^1.2.3'
-dev_dependencies:
- # TODO(sigmund): update to a version constraint once we roll the latest kernel
- # to the repo.
- kernel: {path: ../../pkg/kernel}
- package_config: '^1.0.0'
- test: ^0.12.0
- test_reflective_loader: ^0.1.0
diff --git a/pub/front_end/tool/example.dart b/pub/front_end/tool/example.dart
deleted file mode 100644
index d81f437..0000000
--- a/pub/front_end/tool/example.dart
+++ /dev/null
@@ -1,29 +0,0 @@
-import 'dart:async';
-
-import 'package:front_end/kernel_generator.dart';
-import 'package:front_end/compiler_options.dart';
-import 'package:kernel/binary/ast_to_binary.dart';
-import 'package:kernel/kernel.dart' show Program;
-
-Future dumpToSink(Program program, StreamSink<List<int>> sink) {
- new BinaryPrinter(sink).writeProgramFile(program);
- return sink.close();
-}
-
-Future kernelToSink(Uri entry, StreamSink<List<int>> sink) async {
- var program = await kernelForProgram(
- entry,
- new CompilerOptions()
- ..sdkRoot = new Uri.file('sdk')
- ..packagesFileUri = new Uri.file('.packages')
- ..onError = (e) => print(e.message));
-
- await dumpToSink(program, sink);
-}
-
-main(args) async {
- kernelToSink(
- Uri.base.resolve(args[0]),
- // TODO(sigmund,hausner): define memory type where to dump binary data.
- new StreamController<List<int>>.broadcast().sink);
-}
diff --git a/pub/front_end/tool/perf.dart b/pub/front_end/tool/perf.dart
deleted file mode 100644
index 7c4e4cd..0000000
--- a/pub/front_end/tool/perf.dart
+++ /dev/null
@@ -1,349 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// An entrypoint used to run portions of front_end and measure its performance.
-library front_end.tool.perf;
-
-import 'dart:async';
-import 'dart:io' show exit;
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/error/listener.dart';
-import 'package:analyzer/file_system/file_system.dart' show ResourceUriResolver;
-import 'package:analyzer/file_system/physical_file_system.dart'
- show PhysicalResourceProvider;
-import 'package:analyzer/source/package_map_resolver.dart';
-import 'package:analyzer/src/context/builder.dart';
-import 'package:analyzer/src/dart/sdk/sdk.dart' show FolderBasedDartSdk;
-import 'package:analyzer/src/generated/parser.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/generated/source_io.dart';
-import 'package:analyzer/src/summary/format.dart';
-import 'package:analyzer/src/summary/idl.dart';
-import 'package:analyzer/src/summary/link.dart';
-import 'package:analyzer/src/summary/summarize_ast.dart';
-import 'package:front_end/compiler_options.dart';
-import 'package:front_end/kernel_generator.dart';
-import 'package:front_end/src/scanner/reader.dart';
-import 'package:front_end/src/scanner/scanner.dart';
-import 'package:front_end/src/scanner/token.dart';
-import 'package:kernel/kernel.dart' hide Source;
-import 'package:package_config/discovery.dart';
-
-main(List<String> args) async {
- // TODO(sigmund): provide sdk folder as well.
- if (args.length < 2) {
- print('usage: perf.dart <bench-id> <entry.dart>');
- exit(1);
- }
-
- var bench = args[0];
- var entryUri = Uri.base.resolve(args[1]);
-
- await setup(entryUri);
-
- Set<Source> files = scanReachableFiles(entryUri);
- var handlers = {
- 'scan': () async => scanFiles(files),
- 'parse': () async => parseFiles(files),
- 'kernel_gen_e2e': () async {
- await generateKernel(entryUri, useSdkSummary: false);
- },
- 'kernel_gen_e2e_sum': () async {
- await generateKernel(entryUri, useSdkSummary: true, compileSdk: false);
- },
- 'unlinked_summarize': () async => summarize(files),
- 'unlinked_summarize_from_sources': () async => summarize(files),
- 'prelinked_summarize': () async => summarize(files, prelink: true),
- 'linked_summarize': () async => summarize(files, link: true),
- };
-
- var handler = handlers[bench];
- if (handler == null) {
- print('unsupported bench-id: $bench. Please specify one of the following: '
- '${handlers.keys.join(", ")}');
- exit(1);
- }
-
- // TODO(sigmund): replace the warmup with instrumented snapshots.
- int iterations = bench.contains('kernel_gen') ? 2 : 10;
- for (int i = 0; i < iterations; i++) {
- var totalTimer = new Stopwatch()..start();
- print('== iteration $i');
- await handler();
- totalTimer.stop();
- report('total', totalTimer.elapsedMicroseconds);
- }
-}
-
-/// Cumulative time spent parsing.
-Stopwatch parseTimer = new Stopwatch();
-
-/// Cumulative time spent building unlinked summaries.
-Stopwatch unlinkedSummarizeTimer = new Stopwatch();
-
-/// Cumulative time spent scanning.
-Stopwatch scanTimer = new Stopwatch();
-
-/// Size of all sources.
-int inputSize = 0;
-
-/// Factory to load and resolve app, packages, and sdk sources.
-SourceFactory sources;
-
-/// Add to [files] all sources reachable from [start].
-void collectSources(Source start, Set<Source> files) {
- if (!files.add(start)) return;
- var unit = parseDirectives(start);
- for (var directive in unit.directives) {
- if (directive is UriBasedDirective) {
- var next = sources.resolveUri(start, directive.uri.stringValue);
- collectSources(next, files);
- }
- }
-}
-
-Future<Program> generateKernel(Uri entryUri,
- {bool useSdkSummary: false, bool compileSdk: true}) async {
- // TODO(sigmund): this is here only to compute the input size,
- // we should extract the input size from the frontend instead.
- scanReachableFiles(entryUri);
-
- var dartkTimer = new Stopwatch()..start();
- // TODO(sigmund): add a constructor with named args to compiler options.
- var options = new CompilerOptions()
- ..strongMode = false
- ..compileSdk = compileSdk
- ..packagesFileUri = new Uri.file('.packages')
- ..onError = ((e) => print('${e.message}'));
- if (useSdkSummary) {
- // TODO(sigmund): adjust path based on the benchmark runner architecture.
- // Possibly let the runner make the file available at an architecture
- // independent location.
- options.sdkSummary =
- new Uri.file('out/ReleaseX64/dart-sdk/lib/_internal/spec.sum');
- } else {
- options.sdkRoot = new Uri.file('sdk');
- }
- Program program = await kernelForProgram(entryUri, options);
- dartkTimer.stop();
- var suffix = useSdkSummary ? '_sum' : '';
- report('kernel_gen_e2e${suffix}', dartkTimer.elapsedMicroseconds);
- return program;
-}
-
-/// Generates unlinkmed summaries for all files in [files], and returns them in
-/// an [_UnlinkedSummaries] container.
-_UnlinkedSummaries generateUnlinkedSummaries(Set<Source> files) {
- var unlinkedSummaries = new _UnlinkedSummaries();
- for (var source in files) {
- unlinkedSummaries.summariesByUri[source.uri.toString()] =
- unlinkedSummarize(source);
- }
- return unlinkedSummaries;
-}
-
-/// Generates unlinked summaries for every file in [files] and, if requested via
-/// [prelink] or [link], generates the pre-linked and linked summaries as well.
-///
-/// This function also prints a report of the time spent on each action.
-void summarize(Set<Source> files, {bool prelink: false, bool link: false}) {
- scanTimer = new Stopwatch();
- parseTimer = new Stopwatch();
- unlinkedSummarizeTimer = new Stopwatch();
- var unlinkedSummaries = generateUnlinkedSummaries(files);
- report('scan', scanTimer.elapsedMicroseconds);
- report('parse', parseTimer.elapsedMicroseconds);
- report('unlinked_summarize', unlinkedSummarizeTimer.elapsedMicroseconds);
- report(
- 'unlinked_summarize_from_sources',
- unlinkedSummarizeTimer.elapsedMicroseconds +
- parseTimer.elapsedMicroseconds +
- scanTimer.elapsedMicroseconds);
-
- if (prelink || link) {
- var prelinkTimer = new Stopwatch()..start();
- var prelinkedLibraries = prelinkSummaries(files, unlinkedSummaries);
- prelinkTimer.stop();
- report('prelinked_summarize', prelinkTimer.elapsedMicroseconds);
-
- if (link) {
- var linkTimer = new Stopwatch()..start();
- LinkedLibrary getDependency(String uri) {
- // getDependency should never be called because all dependencies are
- // present in [prelinkedLibraries].
- print('Warning: getDependency called for: $uri');
- return null;
- }
-
- relink(prelinkedLibraries, getDependency, unlinkedSummaries.getUnit,
- true /*strong*/);
- linkTimer.stop();
- report('linked_summarize', linkTimer.elapsedMicroseconds);
- }
- }
-}
-
-/// Uses the diet-parser to parse only directives in [source].
-CompilationUnit parseDirectives(Source source) {
- var token = tokenize(source);
- var parser = new Parser(source, AnalysisErrorListener.NULL_LISTENER);
- return parser.parseDirectives(token);
-}
-
-/// Parses every file in [files] and reports the time spent doing so.
-void parseFiles(Set<Source> files) {
- scanTimer = new Stopwatch();
- parseTimer = new Stopwatch();
- for (var source in files) {
- parseFull(source);
- }
-
- report('scan', scanTimer.elapsedMicroseconds);
- report('parse', parseTimer.elapsedMicroseconds);
-}
-
-/// Parse the full body of [source] and return it's compilation unit.
-CompilationUnit parseFull(Source source) {
- var token = tokenize(source);
- parseTimer.start();
- var parser = new Parser(source, AnalysisErrorListener.NULL_LISTENER);
- var unit = parser.parseCompilationUnit(token);
- parseTimer.stop();
- return unit;
-}
-
-/// Prelinks all the summaries for [files], using [unlinkedSummaries] to obtain
-/// their unlinked summaries.
-///
-/// The return value is suitable for passing to the summary linker.
-Map<String, LinkedLibraryBuilder> prelinkSummaries(
- Set<Source> files, _UnlinkedSummaries unlinkedSummaries) {
- Set<String> libraryUris = files.map((source) => '${source.uri}').toSet();
-
- String getDeclaredVariable(String s) => null;
- var prelinkedLibraries =
- setupForLink(libraryUris, unlinkedSummaries.getUnit, getDeclaredVariable);
- return prelinkedLibraries;
-}
-
-/// Report that metric [name] took [time] micro-seconds to process
-/// [inputSize] characters.
-void report(String name, int time) {
- var sb = new StringBuffer();
- var padding = ' ' * (20 - name.length);
- sb.write('$name:$padding $time us, ${time ~/ 1000} ms');
- var invSpeed = (time * 1000 / inputSize).toStringAsFixed(2);
- sb.write(', $invSpeed ns/char');
- print('$sb');
-}
-
-/// Scans every file in [files] and reports the time spent doing so.
-void scanFiles(Set<Source> files) {
- // `tokenize` records how many chars are scanned and how long it takes to scan
- // them. As this function is called repeatedly when running as a benchmark, we
- // make sure to clear the data and compute it again every time.
- scanTimer = new Stopwatch();
- for (var source in files) {
- tokenize(source);
- }
-
- report('scan', scanTimer.elapsedMicroseconds);
-}
-
-/// Load and scans all files we need to process: files reachable from the
-/// entrypoint and all core libraries automatically included by the VM.
-Set<Source> scanReachableFiles(Uri entryUri) {
- var files = new Set<Source>();
- var loadTimer = new Stopwatch()..start();
- scanTimer = new Stopwatch();
- collectSources(sources.forUri2(entryUri), files);
-
- var libs = [
- 'dart:async',
- 'dart:collection',
- 'dart:convert',
- 'dart:core',
- 'dart:developer',
- 'dart:_internal',
- 'dart:isolate',
- 'dart:math',
- 'dart:mirrors',
- 'dart:typed_data',
- 'dart:io'
- ];
-
- for (var lib in libs) {
- collectSources(sources.forUri(lib), files);
- }
-
- loadTimer.stop();
-
- inputSize = 0;
- for (var s in files) inputSize += s.contents.data.length;
- print('input size: ${inputSize} chars');
- var loadTime = loadTimer.elapsedMicroseconds - scanTimer.elapsedMicroseconds;
- report('load', loadTime);
- report('scan', scanTimer.elapsedMicroseconds);
- return files;
-}
-
-/// Sets up analyzer to be able to load and resolve app, packages, and sdk
-/// sources.
-Future setup(Uri entryUri) async {
- var provider = PhysicalResourceProvider.INSTANCE;
- var packageMap = new ContextBuilder(provider, null, null)
- .convertPackagesToMap(await findPackages(entryUri));
- sources = new SourceFactory([
- new ResourceUriResolver(provider),
- new PackageMapUriResolver(provider, packageMap),
- new DartUriResolver(
- new FolderBasedDartSdk(provider, provider.getFolder('sdk'))),
- ]);
-}
-
-/// Scan [source] and return the first token produced by the scanner.
-Token tokenize(Source source) {
- scanTimer.start();
- // TODO(sigmund): is there a way to scan from a random-access-file without
- // first converting to String?
- var scanner = new _Scanner(source.contents.data);
- var token = scanner.tokenize();
- scanTimer.stop();
- return token;
-}
-
-UnlinkedUnitBuilder unlinkedSummarize(Source source) {
- var unit = parseFull(source);
- unlinkedSummarizeTimer.start();
- var unlinkedUnit = serializeAstUnlinked(unit);
- unlinkedSummarizeTimer.stop();
- return unlinkedUnit;
-}
-
-/// Simple container for a mapping from URI string to an unlinked summary.
-class _UnlinkedSummaries {
- final summariesByUri = <String, UnlinkedUnit>{};
-
- /// Get the unlinked summary for the given URI, and report a warning if it
- /// can't be found.
- UnlinkedUnit getUnit(String uri) {
- var result = summariesByUri[uri];
- if (result == null) {
- print('Warning: no summary found for: $uri');
- }
- return result;
- }
-}
-
-class _Scanner extends Scanner {
- _Scanner(String contents) : super(new CharSequenceReader(contents)) {
- preserveComments = false;
- }
-
- @override
- void reportError(errorCode, int offset, List<Object> arguments) {
- // ignore errors.
- }
-}
diff --git a/pub/front_end/tool/perf_test.dart b/pub/front_end/tool/perf_test.dart
deleted file mode 100644
index 66093ed..0000000
--- a/pub/front_end/tool/perf_test.dart
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-/// The only purpose of this file is to enable analyzer tests on `perf.dart`,
-/// the code here just has a dummy import to the rest of the code.
-library front_end.tool.perf_test;
-
-import 'perf.dart' as m;
-
-main() => print('done ${m.inputSize}');